in order to find the sum of n numbers given by user,suppose our program is to find the sum of any 4 numbers given by user (using while loop such that (while(i<=4))and incrementing each value of i by 1),if the user give any 2 inputs instead of four then the total sum should be the summation of that two inputs..but the program shows the sum something else,why it is so?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

in order to find the sum of n numbers given by user,suppose our program is to find the sum of any 4 numbers given by user (using while loop such that (while(i<=4))and incrementing each value of i by 1),if the user give any 2 inputs instead of four then the total sum should be the summation of that two inputs..but the program shows the sum something else,why it is so??

using while loop

12th Jan 2017, 4:40 AM
Pragya Priya
Pragya Priya - avatar
3 Answers
+ 4
If found your code in your profile ( spaces and indentation are useful for improve readability ;) ): #include<iostream> using namespace std; int main() { int sum=0; int x,y; int i=1; while( i<=5) { cin>>x; i++; sum+=x; } cout<<"sum is"<<sum<<endl; return 0; } Your 'while' loop block will be executed 5 times, even if you input only 2 values... In real life of program ( somewhere else than in code playground, locally ) the loop would be waiting for next entries, but in Sololearn code playground, these entries are emulated/virtualized: so it seems to be like the last entry is still used for the next if buffer is empty ( user not giving as much number of lines than the code is required ): Tell we only input 1 and 2... - 1st loop: sum = 0 + 1 = 1 - 2nd loop: sum = 1 + 2 = 3 - 3rd, 4th and 5th: no more entry, as if repeat the last entry : 3 + 2 = 5 + 2 = 7 + 2 = 9...
12th Jan 2017, 5:41 AM
visph
visph - avatar
0
thanks a lot :)
12th Jan 2017, 7:40 AM
Pragya Priya
Pragya Priya - avatar
0
Thank you
15th Jan 2017, 6:26 AM
Himanshu Choudhary
Himanshu Choudhary - avatar