+ 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
3 Respuestas
+ 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...
0
thanks a lot :)
0
Thank you