+ 2
Write a program to print 1-2+3-4+5-6........n terms using while loop
7 odpowiedzi
+ 4
Simple, since it will always be subtracted by even numbers.
int x = 2;
int y = 1;
int z = 100; /*or use cin to get input, this will be our 'n' aka the max range*/
int sum = 0;
while ( y < z){
if ( y%x != 0) {
sum = sum + y; }
else {
sum = sum - y;
}
y++;
}
cout << sum;
+ 3
even you can calculate this without loop:
int sum = (n * (n + 1)) / 2;
n = n % 2 == 0 ? n / 2 : (n / 2) + 1;
double sumOdds = (n * 1d / 2) * (2 + ((n - 1) * 2));
sum -= sumOdds;
int result = (int) sumOdds - sum;
+ 2
You just need to loop from 1 to n. If the value if divid by 2 it's mean you substract and in the oposit way you just add. I didn't test the code but it's should work.
int i;
int val = 0;
for (i = 1; i <= n; i++) {
if ((i % 2) == 0) {
val -= i;
}
else {
val += i;
}
}
+ 1
1-2/3+4/5-6/7 tracing using while loop with flow chart
+ 1
Write a program in C++ to print 1 - 2 + 3 - 4 + 5 - 6 ......n terms
aj
using while loop.
0
Write a program in C++ to print 1 - 2 + 3 - 4 + 5 - 6 ......n terms using while loop.
0
Write a program in C++ to print 1 - 2 + 3 - 4 + 5 - 6 ......n terms using while loop.