Here is my program
#include <bits/stdc++.h>
using namespace std;
// Function to return gcd of a and b
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to find gcd of input2ay of
// numbers
int findGCD(int input2[], int n)
{
int result = input2[0];
for (int i = 1; i < n; i++)
{
result = gcd(input2[i], result);
if(result == 1)
{
return 1;
}
}
return result;
}
// Driver code
int main(int input1,int input2[40])
{
int n = sizeof(input2) / sizeof(input2[0]);
cout << findGCD(input2, n) << endl;
return 0;
}
The input has to go in following format
3 2 4 8
where 3 is size of array and 2 4 8 are elements of array.
Now I am getting following errors
main.cpp:40:5: warning: second argument of ‘int main(int, int*)’ should be ‘char **’ [-Wmain]
int main(int input1,int input2[40])
^~~~
main.cpp: In function ‘int main(int, int*)’:
main.cpp:43:23: warning: ‘sizeof’ on array function parameter ‘input2’ will return size of ‘int*’ [-Wsizeof-array-argument]
int n = sizeof(input2) / sizeof(input2[0]);
^
main.cpp:40:34: note: declared here
int main(int input1,int input2[40])
^
What is the problem here?
my question is mostly code adding more details.
edit
based on suggestions I came up with using atoi.
#include <stdio.h>
unsigned gcd(unsigned x, unsigned y){
unsigned wk;
if(x<y){ wk=x;x=y;y=wk; }
while(y){
wk = x%y;
x=y;
y=wk;
}
return x;
}
int gcd_a(int n, int a[n]){
if(n==1) return a[0];
if(n==2) return gcd(a[0], a[1]);
int h = n / 2;
return gcd(gcd_a(h, &a[0]), gcd_a(n - h, &a[h]));
}
int main(int argc ,char *argv[]){
// argc is number of arguments given including a.out in command line
// argv is a list of string containing command line arguments
int total = 0;
int i,input1;
int *value;
for(i = 1; i < argc; i++)
{
// The integers given is read as (char *)
value[i] = atoi(argv[i]);
total++;
}
input1 = total;
int gcd = gcd_a(input1, value);
printf("%d\n", gcd);
return 0;
}
But still this is not giving me desired result.
I compiled it online but it did not give any error but it did not took any arguments also.
The post can not be submitted because it looks mostly code java script programming error in SO.
The main method declaration must be int main(int ,char**);
Here you will get array of c-strings. i.e (["10","20","40"....]).
So you need to convert char* to integer using below methods
using atoi() method ==> read this
sscanf() method ==> read this
see the below code
int findGCD(char* input2[], int n)
{
int result = atoi(input2[1]); /*Here first argument is fileName itself ,so we are taking from second.i.e input2[1]*/
for (int i = 2; i < n; i++)
{
int a = atoi(input2[i]);
result = gcd(a, result);
if(result == 1)
{
return 1;
}
}
return result;
}
// Driver code
int main(int args,char** argv)
{
// for(int i = 0;i < args;i++)
// {
// cout <<"argv["<<i<<"] = "<<argv[i]<<endl;
// }
cout << "GCD::"<<findGCD(argv, args) << endl;
return 0;
}
Related
I have the following pieces of code and I am getting a bunch of same error of undeclared identifier. According to other codes I have written, the #include "rec_fun.h" on the main file should enable the use of functions in that file. Since I am compiling both rec_fun.cpp and main.cpp, this should generate an executable name FINAL.
erros:
MaryMcBeth#unknown88665a207c1a Recursion_Program % g++ -std=c++14 rec_fun.cpp main.cpp -o FINAL
main.cpp:17:12: error: use of undeclared identifier 'fib_recursion'
fib_recursion(i);// Replace with call to your function.
^
main.cpp:18:12: error: use of undeclared identifier 'fib_iterative'
fib_iterative(i);
^
main.cpp:28:6: error: use of undeclared identifier 'triangle'
triangle(cout, 3, 5);
^
main.cpp:31:6: error: use of undeclared identifier 'numbers'
numbers(cout, "THERBLIG", 2);
^
4 errors generated.
MaryMcBeth#unknown88665a207c1a Recursion_Program %
main.cpp:
#include <iostream>
#include <chrono>
#include "rec_fun.h"
using namespace std;
using namespace std::chrono;
int main()
{
high_resolution_clock::time_point startTime = high_resolution_clock::now();
int i;
for (i = 0; i < 1000000; i++)
{
fib_recursion(i);// Replace with call to your function.
fib_iterative(i);
}
high_resolution_clock::time_point endTime = high_resolution_clock::now();
duration<float> time_span = endTime - startTime;
std::cout << fixed;
std::cout << "It took " << time_span.count() << " seconds.";
std::cout << std::endl;
cout<<"---------------"<<endl;
triangle(cout, 3, 5);
return 0;
cout<<"------------------"<<endl;
numbers(cout, "THERBLIG", 2);
cout<<"-------------------------"<<endl;
}
rec_fun.cpp:
#include<iostream>
#include <chrono>
#include "rec_fun.h"
#include <string>
using namespace savitch2;
using namespace std;
using namespace std::chrono;
void recursion::numbers(ostream &outs, const string& prefix, unsigned int levels)
{
if(levels == 0)
outs << prefix << endl;
else
{
for(char c = '1'; c <= '9'; c++)
{
s = prefix + c + '.';
numbers(outs, s, levels-1);
}
}
}
bool recursion::bears(int n)
{
if (n < 42) return false;
if (n == 42) return true;
if ((n%2) == 0)
if (bears(n/2)) return true;
if (((n%3)==0) || ((n%4)==0))
{
ones = n % 10;
tens = (n % 100)/10;
if ((ones != 0) && (tens != 0) && (bears(n-ones*tens)))
return true;
}
if ((n%5) == 0)
if (bears(n-42)) return true;
return false;
}
//recursive helper method to return a string containing count number of '*'
string recursion::asterisks(int count)
{
//if count is above 0, returning one '*' followed by the value returned
//from recursive call to asterisks passing count-1 as argument
if(count>0){
return "*"+asterisks(count-1);
}
//else, if count is 0 or negative, returning empty string
else{
return "";
}
}
//required method
void recursion::triangle(ostream &outs, unsigned int m, unsigned int n)
{
//proceeding only if m<=n.
//if m>n, recursion stops (base case)
if(m<=n){
//making a string containing m number of asterisks
string ast=asterisks(m);
//printing it to outs
outs<<ast<<endl;
//making a recursive call passing m+1 as new m
triangle(outs,m+1,n);
//printing ast to outs once again
outs<<ast<<endl;
}
}
int recursion::fib_iterative(int n) {
if(n == 1 || n == 2)
return 1;
int A[2][2] = { { 1, 1 },{ 1, 0 } };
int B[2][2] = { { 1, 1 },{ 1, 0 } };
int temp[2][2];
while (n >= 2) {
for (int i = 0; i < 2; i++)
for (int k = 0; k < 2; k++) {
temp[i][k] = 0;
for (int j = 0; j < 2; j++)
temp[i][k] += A[i][j] * B[j][k];
}
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
B[i][j] = temp[i][j];
n--;
}
return B[0][1];
}
int recursion::fib_recursion(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fib_recursion(n-1) + fib_recursion(n-2);
}
rec_fun.h:
#include<iostream>
#include <string>
using namespace std;
namespace savitch2
{
class recursion
{
public:
bool bears(int n);
void triangle(ostream &outs, unsigned int m, unsigned int n);
string asterisks(int count);
void numbers(ostream &outs, const string& prefix, unsigned int levels);
int fib_iterative(int n);
int fib_recursion(int n);
private:
int ones;
int tens;
string s;
};
}
Expected Output:
It took 8 seconds
...
You need to do
int i;
recursion rec;
for (i = 0; i < 1000000; i++)
{
rec.fib_recursion(i);// Replace with call to your function.
rec.fib_iterative(i);
Since your functions are class methods, you have to create an instance of the class to use them
You will need to create a class instance. Essentially, the functions in your program are not independent functions, they are the methods of a class(in your case, class=recursion), so getting the error: 'use of undeclared identifier' does make sense.
Create an instance of class recursion in the main.cpp file and call those functions via that instance inside the for loop.
I'm trying to find the sum of the numbers in a char array.
My code works for most cases. Example : a=dasn344wee22ee, the output is:366 - which is good
But when my char is,for example : andre54e5 the output should be 59, but the program displays: 108.
Can anybody tell me what the issue is?
#include <iostream>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
using namespace std;
int getnr(char a[], int i, int j)
{
int counter = 0;
char sir[1000];
for (int x = i; x<j; x++)
{
sir[counter] = a[x];
counter++;
}
return atoi(sir);
}
int main()
{
char a[1000];
int s = 0, inceput, finals;
cin.getline(a, 255);
for (int i = 0; i<strlen(a); i++)
{
if (isdigit(a[i]) )
{
if (i == strlen(a) - 1)
{
s += getnr(a, i, strlen(a));
}
for (int j = i + 1; j<strlen(a); j++)
{
if (!isdigit(a[j]) || j == strlen(a) - 1)
{
s += getnr(a, i, j + 1);
i = j;
break;
}
}
}
}
cout << s;
return 0;
}
In your function int getnr(char a[], int i, int j), you forgot to null-terminate string sir, such that atoi(sir) might yield a garbage value (actually the behaviour is undefined). The following should help:
int getnr(char a[], int i, int j)` {
...
sir[counter] = '\0';
return atoi(sir);
}
The problem is that getnr() doesn't add a null terminator to the sir array, so you're getting undefined behavior when you call atoi(sir).
int getnr(char a[], int i, int j)
{
int counter = 0;
char sir[1000];
for (int x = i; x<j; x++)
{
sir[counter] = a[x];
counter++;
}
sir[counter] = '\0';
return atoi(sir);
}
The issue is within this part of code:
if (i == strlen(a) - 1)
{
s += getnr(a, i, strlen(a));
}
Specifically, if your last number is a single digit (which it is), it will always return junk.
So, I would change to only convert the single char of the char array as a digit and at it to the int s.
Edit:
For some reason when doing s+= a[i], I return junk.
But, doing the following, does the trick:
if (i == strlen(a) - 1)
{
string x;
x[0] = a[i];
int l = stoi(x);
s += l;
}
I know that there's a much more effective way, but I'm not sure why s+= a[i] itself returns false numbers.
I am constantly getting a missing subscript and unknown size problem. So, I am guessing this is a beginner problem but I can't get my head around it. How do I get my function to work and outputted to the screen?
I am trying to have two columns be filled with numbers. Column[0] is inputted by rand() and then have Column[1] be converted into a new number through an equation. I am expecting 1-10 rows to be inputted.
// function prototypes
void arrayProgram(double ma[][2], int xSize);
int main()
{
const int arraySize = 5;
double ma[arraySize][arraySize];
// if I change double ma[1][2];
// I get an argument of type 'int' is incompatible of type "double(*)[2]
arrayProgram(ma, arraySize);
}//end main
void arrayProgram(double ma[][2], int xSize)
{
int i = 0;
for (i = 0; i < xSize; ++i)
{
ma[i][0] = rand();
ma[i][1] = (ma[i][0] * (20 / 25.0) + 64);
}
}
It works:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
// function prototypes
void arrayProgram(double ma[][2], int xSize);
int main()
{
const int arraySize = 1;
double ma[arraySize][2];
srand ( time(NULL) ); // setting seed value
rand(); // first random number
arrayProgram(ma, arraySize);
}//end main
void arrayProgram(double ma[][2], int xSize)
{
int i = 0;
for (i = 0; i < xSize; ++i)
{
ma[i][0] = rand();
ma[i][1] = (ma[i][0] * (20 / 25.0) + 64);
std::cout << ma[i][0] << '\t' << ma[i][1] << std::endl;
}
}
I have a problem with variable number of arguments in C++. I write my code using Xcode.
Here is my code:
#include <iostream>
int sum(int n, ...)
{
int *p = &n;
p++;
int res = 0;
for(int i=0; i<n; i++){
res+=(*p);
p++;
}
return res;
}
int main(int argc, const char * argv[]) {
std::cout << sum(4, 1, 2, 3, 4);
return 0;
}
sum(4, 1, 2, 3, 4) should return a value of 10, but it returns 1606452732.
In C++ you use a template metafunction to do that. It's pretty straight forward:
int sum(int u)
{return u;} // Recursion-End
template<typename... Args>
int sum(int u, Args... rest)
{
return u + sum(rest...);
}
Try it online!
However there is a, as I consider it, depreciated C-way using va_start and va_end. You need to include cstdarg and on function call you need to provide the total parameter count. It would look like this:
int sum(int argnum, ...)
{
va_list arguments;
int i;
int sum = 0;
va_start(arguments, argnum); /* Needs last known character to calculate
the address of the other parameters */
for(i = 0; i < argnum; ++i)
sum += va_arg(arguments, int); /* use next argument */
va_end(arguments);
return sum;
}
Try it online!
From: http://en.cppreference.com/w/cpp/utility/variadic/va_start
#include <iostream>
#include <cstdarg>
int add_nums(int count, ...)
{
int result = 0;
va_list args;
va_start(args, count);
for (int i = 0; i < count; ++i) {
result += va_arg(args, int);
}
va_end(args);
return result;
}
int main()
{
std::cout << add_nums(4, 25, 25, 50, 50) << '\n';
return 0;
}
I'm having trouble with returning an array from a function to the main function. The array is also used as a parameter for another function.
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
void ran(int list[]);
void guess(int list[]);
int black_marker(int num1[], int num2[]);
int main(){
int r[4];
int g[4];
cout << black_marker(ran(r), guess(g));
}
void ran(int list[]){ //random number generator
srand (time(NULL));
int a = rand() % 6 + 1;
int b = rand() % 7 + 1;
while(a == b)
b = rand() % 7 + 1;
int c = rand() % 8 + 1;
while(a == c || b == c)
c = rand() % 8 + 1;
int d = rand() % 9 + 1;
while(a == d || b == d || c == d)
d = rand() % 9 + 1;
int num_random[4] = {a, b, c, d};
}
void guess(int list[]){ //takes user input for a guess
int random_no[4];
for(int i = 0; i < 4; i++){
cin >> random_no[i];
}
}
int black_marker(int num1[], int num2[]){ //Counts how many digits from random number
int black_count = 0; //is similar to the user's guess
for(int i = 0; i < 4; i++){
if(num1[i] == num2[i]){
black_count += 1;
}
}
return black_count;
}
Basically, this is an incomplete number-guessing game where the user is given a hint such as the number of digits that are common to the randomly generated number and the user input guess. I get a void type error for cout << black_marker(ran(r), guess(g)); which is unusual since this pass-by-reference method works otherwise when I have a cout statement in the void function's body.
black_marker(ran(r), guess(g)) black_marker takes two arrays, but ran() and guess(g) return void, so you end up with black_marker(void, void) and that won't work.
What you wanna do is
#include <cmath>
#include <iostream>
using namespace std;
void ran(int list[]){ //random number generator
srand (time(NULL));
int a = rand() % 6 + 1;
int b = rand() % 7 + 1;
while(a == b)
b = rand() % 7 + 1;
int c = rand() % 8 + 1;
while(a == c || b == c)
c = rand() % 8 + 1;
int d = rand() % 9 + 1;
while(a == d || b == d || c == d)
d = rand() % 9 + 1;
list[0] = a;
list[1] = b;
list[2] = c;
list[3] = d;
}
void guess(int list[]){ //takes user input for a guess
int random_no[4];
for(int i = 0; i < 4; i++){
cin >> list[i];
}
}
int black_marker(int num1[], int num2[]){ //Counts how many digits from random number
int black_count = 0; //is similar to the user's guess
for(int i = 0; i < 4; i++){
if(num1[i] == num2[i]){
black_count += 1;
}
}
return black_count;
}
int main(){
int r[4];
int g[4];
ran(r);
guess(g);
cout << black_marker(r, g) << endl;
}
however you should drop the C-style arrays and use std::vector or std::array instead.
When you use
black_marker(ran(r), guess(g))
black_marker is called by using the return values of ran(r) and guess(g). The return types of those functions are void. The argument types to black_marker are declared to be int []. That's the argument type mismatch the compiler is complaining about.
Use
ran(r);
guess(g);
cout << black_marker(r, g);
Just a quick note:
Your function
int black_marker(int num1[], int num2[]);
takes integer arrays (references) as input arguments however you provide them with void using the function call :
black_marker(ran(r), guess(g));
since ran(r) and guess(g) returns void (nothing) as Pablo pointed.
Sahu`s solution will work well.
Additionally, if you want to insist on the original function call:
black_marker(ran(r), guess(g));
Then you may return the int pointers from the functions "ran" and "guess" as follows:
int* ran(int list[]) {
...
return list;
}
int* guess(int list[]) {
...
return list;
}
then your function call would work fine since the size is known (=4).
Alternatively, you may use array references:
int ( &ran( int (&list)[4] ) )[4] {
return list;
}
and
int ( &guess( int (&list)[4] ) )[4] {
return list;
}