I'm new to C and I'm having some problems in this code where I'm getting these errors.
sum2.c: In function 'main':
sum2.c:22:6: warning: 'z' is used uninitialized in this function [-Wuninitialized]
int z = twice(x, z);
On my code I needed to add a fuction twice, which, given a number, calculates its double, using only the elementary operations and the sum function. And I don't know if the way I put the function is correct.
//USER
//3532
#include <stdio.h>
int sum(int x, int y){
return y == 0 ? x : sum(x+1, y-1);
}
int twice(int x, int z){
z = x * x;
return 0;
}
int main(void){
int x;
int y;
scanf("%d%d", &x, &y);
int z = twice(x, z);
printf("%d\n", z);
return 0;
}
The instructions say that twice is "given a number", but you've defined it as taking two numbers. It only needs one parameter.
And you're supposed to use your sum() function. There's no need to multiply x*x (that's the square of the number, not twice the number), nor is there any point in assigning a variable in the return statement.
You only need to read one number as input to test this.
#include <stdio.h>
int sum(int x, int y)
{
return y == 0 ? x : sum(x+1, y-1);
}
int twice(int x)
{
return sum(x, x);
}
int main(void)
{
int x;
int w;
scanf("%d", &x);
int w = twice(x);
printf("%d\n", w);
return 0;
}
According to your description the function twice should accept only one argument.
So this function definition
int twice(int x, int z)
{
z = x * x;
return 0;
}
does not make sense. Moreover the function always returns 0.
Also take into account that the type int is a signed integer type. The user can input a negative number. In this case your function sum will yield a wrong result.
The sum of two integers of the type int can be too big to fit in an object of the type int. That is there can be for example an overflow.
The functions can be defined the following way as it is shown in a demonstrative program.
#include <stdio.h>
long long int sum( int x, int y )
{
return y == 0 ? ( long long int )x
: sum( y < 0 ? x - 1 : x + 1, y < 0 ? y + 1 : y - 1 );
}
long long int twice( int x)
{
return sum( x, x );
}
int main(void)
{
int x;
printf( "Enter a number: " );
scanf("%d", &x);
long long int result = twice( x );
printf("The sum is %lld\n", result );
return 0;
}
Its output might look like
Enter a number: -5
The sum is -10
Or
Enter a number: 5
The sum is 10
Related
#include<stdio.h>
const char *author ="Alexandre Santos";
int succ(int x)
{
return x+1;
}
int pred(int x)
{
return x-1;
}
int is_zero(int x)
{
return x == 0;
}
int is_pos(int x)
{
return x >= 0;
}
int sum(int x, int y)
{
return is_zero(y)? x: sum(succ(x),pred(y));
}
int twice(int x)
{
return sum(succ(x), pred(x));
}
int main(void)
{
int x;
scanf("%d", &x);
int z = twice(x);
printf("%d\n", z);
return 0;
}
I am in the first year of university and this is one of the exercises that a professor gave. I need to calculate the double of a number just using the given functions(succ, pred, is_zero, is_pos). I tried to do it and managed to come up with a solution but to be honest I don't understand how this is working. My main doubt is how the sum function is working since it uses the variable y and in this program this variable doesn't even exist/is not inserted in the input. Any tip?
In your code, you called the function twice() with the parameter x, and in the function twice() you called the function sum() with the parameters succ(x) and pred(x), the value of succ(x) is assigned to x in sum, and the value of pred(x) is assigned to y in sum.
So for example; you passed the value 10 to x in the input, we will call the function twice with a value 10, and twice(10) returns the sum of succ(10) and pred(10) which are 11 and 9, so the values 11 and 9 are passed to the function sum like this: sum(11, 9), so in the function sum, the parameter x gets the value 11, and the parameter y gets the value 9.
I am not able to find out why my function returns the user input only rather then the factorial of the input.
#include <stdio.h>
#include <math.h>
int factorial(int x)
{
//int x;
int sum = 1;
while (x!=0){
sum = sum * x;
x--;
}
return sum;
}
int main(){
int x;
printf("Enter value of x: ");
scanf("%i",&x);
factorial(x);
printf("sum is %i", x);
return 0;
}
Your factorial function does return a new value, but then you don't actually use that value.
printf("sum is %i\n", factorial(x));
Because you are printing x which is the variable that you have stored the user input in. Your factorial function returns the result, but you are not saving it.
I think the variable names were not proper and you printed x instead of printing factorial.
#include <stdio.h>
int factorial(int x)
{
int fact = 1;
while (x!=0){
fact = fact * x;
x--;
}
return fact;
}
int main(){
int x;
printf("Enter value of x: ");
scanf("%i",&x);
printf("Factorial is %i",factorial(x));
return 0;
}
For starters the function as is
int factorial(int x)
{
//int x;
int sum = 1;
while (x!=0){
sum = sum * x;
x--;
}
return sum;
}
can invoke undefined behavior if the user will pass a negative value, and the function accepts negative values.
The function argument should have an unsigned integer type instead of the signed integer type int
For non-negative values the maximum value of the types int or unsigned int for which the factorial can be calculated is equal to 12.
So to be able to calculate the factorial for greater values you should use the type unsigned long long int. In this case the maximum value for which the factorial can be calculated correctly is equal to 20.
The function can look the following way
unsigned long long int factorial( unsigned long long int x )
{
unsigned long long int product = 1;
for ( ; 1 < x; --x )
{
product *= x;
}
return product;
}
In your program you are not using the returned value of the function.
factorial(x);
The function main can look the following way
int main( void )
{
unsigned int x;
printf( "Enter value of x: " );
if ( scanf( "%u",&x ) == 1 )
{
printf("The factorial of %u is equal to %llu\n, x, factorial( x ) );
}
return 0;
}
Now try the program by entering the value for x equal to 20 and see the program output.:)
You could check in the if statement that the user did not enter a value greater than 20 as for example
if ( scanf( "%u",&x ) == 1 && !( 20 < x ) )
Though it would be better if the function itself will check the value of the passed argument.
Failure to use function return value
As others have said:
//factorial(x);
//printf("sum is %i", x);
printf("sum is %i", factorial(x));
To improve factorial()
Since factorial is a product, change the sum name.
Cope with pathologic inputs like values less than 0 or very large. Code code exit, but maybe instead return a error value. Determination of the upper limit could be done beforehand (as below), at run time or with makefile magic.
Use a wider type to handle large values. Maybe even use an unsigned type. uintmax_t has the greatest max value. It is at least 64 bits.
Example
#include <limits.h>
#include <stdint.h>
#if UINTMAX_MAX == 0xFFFFFFFFFFFFFFFFu
#define FACTORIAL_MAX 20
#elif (UINTMAX_MAX >> 64) == 0xFFFFFFFFFFFFFFFFu
#define FACTORIAL_MAX 34
#else
#error TBD FACTORIAL_MAX
#endif
// Compute factorial.
// Return 0 on error.
uintmax_t factorial(int x) {
if (x < 0 || x > FACTORIAL_MAX) {
return 0;
}
uintmax_t product = 1;
while (x > 0) {
product = product * x;
x--;
}
return product;
}
so I have to write a recursive algorithm for exponentiation and I have to use this to make the algorithm faster: and then I'd have to figure out how many time multiplication is happening. I wrote it, but I am not sure if I am right - also I need some help with figuring out the multiplication part.
#include <stdio.h>
#include <math.h>
double intpower(double x, int n)
{
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2);}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2);}
if(n==1) return x;
else return result;
}
int main()
{
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
printf("result = %.2f\n", intpower(x,n));
return 0;
}
The inductive definitions are saying
If k is even, then x^k = [ x^(k/2) ] ^ 2
If k is odd, then x^k = x * [ x^(floor(k)/2) ] ^ 2
With these it's a bit easier to see how to arrange the recursion:
#include <stdio.h>
double int_pwr(double x, unsigned k)
{
if (k == 0) return 1;
if (k == 1) return x; // This line can be omitted.
double y = int_pwr(x, k/2);
return (k & 1) ? x * y * y : y * y;
}
int main(void)
{
double x;
unsigned k;
scanf("%lf%u", &x, &k);
printf("x^k=%lg\n", int_pwr(x, k));
return 0;
}
I've changed types to be a bit more logical and saved an exponential (in k) amount of work that the OP's solution does by making two recursive calls at each level.
As to the number of multiplications, it's pretty easy to see that if k's highest order bit is 2^p (i.e. at position p), then you'll need p multiplications for the repeated squarings. Another way of saying this is p = floor(log_2(k)). For example if k=4=2^2, you'll square the square to get the answer: 2 multiplications. Additionally you'll need q-1 more, where q is the number of 1's in k's binary rep. This is the number of times the check for "odd" will be true. I.e. if k = 5 (which has 2 bits that are 1's), you'll square the square and then multiply the result by x one more time. To summarize, the number of multiplications is p + q - 1 with p and q as defined above.
To figure out how many times multiplication is happening, you could count them in intpower().
static int count = 0;
double intpower(double x, int n) {
double result;
if(n>1&&n%2!=0) {result=x*intpower(x,(n-1)/2)*intpower(x,(n-1)/2); count += 2;}
if(n>1&&n%2==0) {result=intpower(x,n/2)*intpower(x,n/2); count++;}
if(n==1) return x;
else return result;
}
int main() {
int n;
double x,result;
printf("x\n");
scanf("%lf", &x);
printf("n\n");
scanf("%d", &n);
mcount = 0;
printf("result = %.2f\n", intpower(x,n));
printf("multiplcations = %d\n", mcount);
return 0;
}
Try this
double intpower(double x, int n)
{
if(n == 0) return 1;
if(n == 1) return x;
if(n%2!=0)
{
return x*intpower(x,(n-1));
}
else
{
x = intpower(x,n/2);
return x*x;
}
}
or you can reduce your function to one line
double intpower(double x, int n)
{
return n == 0 ? 1 : n%2 != 0 ? x*intpower( x, (n-1) ) : (x = intpower(x, n/2), x*x);
}
So I had to write a program that used the Pythagorean Threes concept where if you entered a number it would give you all the combinations less than that number that would produce a correct a^2 + b^2 = c^2 output.
Not sure if I explained the assignment well, but basically I understand the logic or at least I think I do I was wondering if you guys could help me find out why I am getting this error....
For the last line of my code it gives me, "warning: control reaches end of non-void function [-Wreturn-type]," As the error any idea what I am doing wrong?
#include <stdio.h>
int main(void){
int x = 0, y = 0, z = 0, n;
int count = 0;
printf("Please Enter A Positive Integer: \n");
scanf("%d", &n);
while(z <= n){
while(y < z){
while(x < y){
if(x * x + y * y == z * z)
printf("%d: \t%d %d %d\n", ++count, x, y, z);
x += 1; }
y += 1; }
z += 1;
}
}
int main(void){
Your function header indicates that you're looking to return an int. To fix this, return a number (0 usually indicates a normal termination) at the end of your function.
To break it down a little,
int indicates the return type,
main is the method name, and
void indicates that there are no parameters for this method.
Your main function is declared to return an int, but you don't return anything.
put return 0; before the closing brace of your main.
int main( void )
{
// ... code ...
return 0;
}
I have:
#include <stdio.h>
int sum ( int x, int y );
main ()
{
int theSum = sum (10, 11);
printf ( "Sum of %i and %i is: %i\n", x, y, theSum );
}
int sum ( int x, int y )
{
return x + y;
}
However, when I compile and run it says x and y are undeclared? Any help greatly appreciated. Thanks
In line three all you have done is declare a function sum which takes two parameters, both integers, called x and y. You haven't declared any variables. Those parameters can only be referred to inside the function itself. Below is a simplification which will help you at this stage, but you should try to read a basic programming book. "The C Programming Language" by Kernighan and Ritchie is a fine place to start.
Variables are chunks of memory that you refer to by name. They can take on any value (of their type) during the life of your program - hence the name 'variable'. They must be declared before you use them; you do this by telling the compiler their type and their name. int a means 'reserve me a block of memory big enough to hold any integer, and let me refer to it later with the name a'. You can assign values to it: a = 10 and you can make use of it: a + 20.
You need to understand the difference between parameters and variables to get what's going on here. A function's parameters are basically variables which exist only during the life of that function. Here's your sum again:
int sum(int x, int y) {
return x + y;
}
Notice how the top line looks just like a variable declaration int x. That's because it is. x and y are variables you can use in the function.
You call sum by passing in values. The compiler, in effect, replaces x and y in your function with the values you pass in. In your case, you're passing literals: 10 and 11. When the program reaches the call to sum, the parameters x and y take on the values 10 and 11, so the return becomes return 10 + 11; which is of course 21.
Just remember that the parameters x and y only exist in that function. You may only refer to them within your function. Why? Because each pair of curly braces { and } define a scope, and anything declared within that scope can only be used within that scope. That includes variables and parameters.
So, here is a more complete example. I have changed the letters so you can see the different ways you use variables and parameters:
#include <stdio.h>
int sum ( int x, int y );
main ()
{
/* We declare our variables */
int a;
int b;
/* We assign values to them */
a = 10;
b = 11;
/* We pass them as parameters to your sum function */
int theSum = sum (a, b);
/* And we use them as parameters again, in a call to the printf function */
printf ( "Sum of %i and %i is: %i\n", a, b, theSum );
}
int sum ( int x, int y )
{
return x + y;
}
declare x and y right before the call to sum:
main ()
{
int x = 10;
int y = 11;
int theSum = sum (x, y);
printf ( "Sum of %i and %i is: %i\n", x, y, theSum );
}
You would have to declare x and y in main, so that you call sum(x,y) rather than calling it on 2 literals. At the moment, x and y are only defined in the function sum.
No, you haven't. You just told the compiler that the function sum takes two ints. You could have written that as
int sum ( int , int );
Therefore you should write:
#include <stdio.h>
int sum ( int , int );
main ()
{
int x = 10;
int y = 11;
int theSum = sum (x, y);
printf ( "Sum of %i and %i is: %i\n", x, y, theSum );
}
int sum ( int x, int y )
{
return x + y;
}
The x and y variables are only passed as arguments to the function. You would not be able to reference those in the main function. If you wanted to, it would be like this:
#include <stdio.h>
int sum ( int x, int y );
main ()
{
int x = 10;
int y = 11;
int theSum = sum (x, y);
printf ( "Sum of %i and %i is: %i\n", x, y, theSum );
}
int sum ( int x, int y )
{
return x + y;
}
This should work. I hope this helps!
In your main you’re declaring neither x nor y—you’re just passing in the literal values 10 and 11. Outside the scope of the sum method, neither name has any meaning. Quick fix:
main()
{
int x = 10;
int y = 11;
int theSum = sum(x, y);
// etc.