I have a question on how to program my nested loops. This is the output i am supposed to have.

Enter the number you want to sum to: 8

0 = 0

0 + 1 = 1

0 + 1 + 2 = 3

0 + 1 + 2 + 3 = 6

0 + 1 + 2 + 3 + 4 = 10

0 + 1 + 2 + 3 + 4 + 5 = 15

0 + 1 + 2 + 3 + 4 + 5 + 6 = 21

0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28

0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36

I understand enough to get the last line where just the number 8 if summed. However i am having a real hard time thinking of how to do the loop to get the previous ones. Any help is really appreciated. btw I looked through the code snippets and didnt find any help there.

2
Contributors
3
Replies
5
Views
13 Years
Discussion Span
Last Post by jillas

Hello,

This is quite simple in fact. We will run one loop through 8 times for simplicity. Each loop around we will increase a single variable that will tell us where to stop. Here is our example:

``````#include <stdio.h>

int main() {
int i, j, k, temp;

/* initialize j */
j = 0;
/* loop 8 times */
for (i = 0; i <= 8; i++) {
/* reset variables */
temp = k = 0;
/* loop until k hits j */
while (k <= j) {
/* print number */
printf("%d ", k);
/* print plus sign except for last time */
if (k != j)
printf("+ ");
/* add to our temporary variable */
temp += k;
/* increment k */
k++;
}
/* print result */
printf("= %d\n", temp);
/* increment j */
j++;
}

return 0;
}``````

- Stack Overflow

Here is my code that still doesnt give me the output that i need. I dont know how to capture the output from my screen to post on here.

``````#include <iostream>
using namespace std;

int main()
{

//Variables
int number;
int count = 0;
int count2;
int  sum = 0;
char q;

cout << "Programmed by";
do {
cout  <<endl << endl << "Enter the number you want to sum: ";
cin >> number;

for (int count = 0; count <= number; count ++)
{ for (int count2 = 0; count2 <= count; count2 ++) {
cout << count << " + ";

}
cout << endl;
}

cout << endl ;
cout << "Do you want to do this again (y/n): ";
cin >> q;
}
while (q == 'y' || q == 'Y');

return 0;
}``````

Thanks for the help i will look at that and you guys can disregard my feeble first attempt at it.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.