You are here:

C++/nested looping

Advertisement


Question
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

Answer
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  

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


vijayan

Expertise

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.

Experience

about 15 years or so

Education/Credentials
post graduate engineer

©2016 About.com. All rights reserved.