Write a program to print 1-2+3-4+5-6........n terms using while loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Write a program to print 1-2+3-4+5-6........n terms using while loop

30th Dec 2016, 8:22 AM
Ayush Jain
Ayush Jain - avatar
7 Answers
+ 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;
30th Dec 2016, 8:44 AM
Wen Qin
Wen Qin - avatar
+ 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;
30th Dec 2016, 10:31 AM
Nima Moradi
Nima Moradi - avatar
+ 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; } }
30th Dec 2016, 8:47 AM
Florian Castelain
Florian Castelain - avatar
+ 1
1-2/3+4/5-6/7 tracing using while loop with flow chart
10th Sep 2020, 1:26 PM
Madhu
+ 1
Write a program in C++ to print 1 - 2 + 3 - 4 + 5 - 6 ......n terms aj using while loop.
13th Feb 2023, 4:17 PM
Narendra Kumar
Narendra Kumar - avatar
0
Write a program in C++ to print 1 - 2 + 3 - 4 + 5 - 6 ......n terms using while loop.
13th Feb 2023, 4:18 PM
Narendra Kumar
Narendra Kumar - avatar
0
Write a program in C++ to print 1 - 2 + 3 - 4 + 5 - 6 ......n terms using while loop.
2nd Mar 2023, 7:23 AM
ᗩᖽᐸᗩSᕼ ᖽᐸᑘᘻᗩᖇ
ᗩᖽᐸᗩSᕼ ᖽᐸᑘᘻᗩᖇ - avatar