You are here:

- Home
- Computing/Technology
- C/C++
- C++
- nested looping

Advertisement

hi! i forgot to tell you,

this is the code i came up with..

--

#include <iostream.h>

#include <conio.h>

int main()

{

clrscr();

int n,s,x=0,sum=0,num=0,num1;

cin>>n;

do

{

s=1;

sum=0;

while ((s<=4)&&(num<=n))

{

num=x+s;

cout<<num;

sum+=num;

s++;

}

cout<<" "<<sum<<" ";

x=num;

}

while (num<=n);

getch();

return 0;

}

---

my problem now is,

when i input let's say 5,

its output looks something like this..

1234 10 56 11

or

input 10

1234 10 5678 26 91011 30

--

it should stop when num becomes equal to the input "n" right? (atleast thats what i thought) what am i doing wrong here?

thank you so much

Use standard headers; <iostream> and not <iostream.h>, and no <conio.h>

The code can be greatly simplified:

#include <iostream>

using namespace std ;

int main()

{

int n ;

cout << "n? " ;

cin >> n ;

int sum = 0 ; // sum of last 4 numbers

for( int number = 1 ; number <= n ; ++number ) // for 1 .. n

{

cout << number ; // print the number

sum += number ; // add number to sum

if( number%4 == 0 ) // if number is a multiple of 4

{

std::cout << ' ' << sum << ' ' ; // print the sum of four numbers

sum = 0 ; // reset sum to zero

}

}

if( sum > 0 ) cout << ' ' << sum ; // print sum of what is left

cout << '\n' ; // and a new line at the end

}

Online IDE: http://liveworkspace.org/code/3HoohD$0

- Add to this Answer
- Ask a Question

Rating(1-10) | Knowledgeability = 10 | Clarity of Response = 10 | Politeness = 10 |

Comment | thank you so much.. i have just realized my mistake when i reviewed the email sent to me confirming the question i have posted.. but thank you very much.. this is a great help.. i get to have an alternative solution aside from what i came up with.. :) |

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

about 15 years or so**Education/Credentials**

post graduate engineer