I'm currently in college in a C language class. I always like to make the assignments given to me to be programmed user-friendly and neatly. So, keep in mind I'm beginner level at this stuff.
Although this is basic, I just need help with this:
1 int count, sum, max, input;
2 count = 1;
3 sum = 0;
4 input = 0;
5 printf("This program will find the sum of your given
6 input of an integer.\n");
7 printf("Please enter the number you would like the sum
8 of: ");
9 scanf("%d", &max, &input);
10 while (count <= max){
11 sum = sum count;
12 count ;
13 }
14 printf("The sum of %d is %d.\n", input, sum);
15 printf("==To exit the program, please enter anything,
16 then press enter==");
17 scanf("%d");
18 return;
}
I want to let the user know on line 14 of what they entered firstly while also giving them the sum of what they entered. How can I do this?
EDIT: I know that line 9 makes no sense, but that's where I am having the issue. I have seen scanf("%d%d", &var, &var);, but that requires the user to have 2 inputs. I only want 1 input. In other words, if a user inputs a number, I want that only 1 input to go into both max
and input
.
EDIT 2: For example, if you input to want to have the sum of 10
, I want line 14 to show the input you entered as well as show the sum of 10
.
CodePudding user response:
scanf()
will only assign to as many variables as there are format operators in the format string. The extra variable you provide is ignored, it doesn't get a copy of the same input value.
Use an ordinary assignment to copy the entered value into the second variable.
scanf("%d", &max);
input = max;
CodePudding user response:
I think you dont need to declare an extra variable "input".(Since the value of max never changes in your code.)
Just check the below code:
1 int count, sum, max; //removed input
2 count = 1;
3 sum = 0;
4 //removed input
5 printf("This program will find the sum of your given
6 input of an integer.\n");
7 printf("Please enter the number you would like the sum
8 of: ");
9 scanf("%d", &max);
10 while (count <= max){
11 sum = sum count;
12 count ;
13 }
14 printf("The sum of %d is %d.\n", max, sum); //replaced input by max
15 printf("==To exit the program, please enter anything,
16 then press enter==");
17 scanf("%d");
18 return;
}