C++: Learning the Basics – WHILE LOOP

Situation #1: The program gives the sum of the first ten numbers.

You can change the number of numbers to add.

#include
#include
void main()

{
   clrscr(); 
   int sum1=0, i=0; 
   while(i<=10) #change the number of numbers to add

   {
       //cout//i//endl; 
       sum1=sum1+i; 
       i++;
   }

   cout<<"sum= "<<sum1; 
   getch();
}

Situation #2: User enters any ten numbers and the program displays the sum.

#include
#include
void main()
{
   clrscr(); 
   int sum1=0, i=0, num; 
   while(i<10)
 
   { 

       cout<<"\n\t Enter number: ";         
       cin>>num; 
       //cout//i//endl; 
       sum1=sum1+num; 
       i++;
 
    }
    cout<<"\n\t Sum of 10 numbers = "<<sum1<<endl; 
    getch();
}

Situation #3: User enters ten numbers and the program displays the number of odd and even numbers:

#include 
#include 
void main() 
{ 
   clrscr(); 
   int odd=0, even=0, i=0, num; 

   while(i<10)
   { 
        cout<<"\n\t Enter a number: ";         cin>>num;
 
        if (num%2==0)
        {
            even++; #aka even=even+1
        }
        else 
        {
            odd++;
        }
        counter++;
   }
   cout<<"\n\t Number of odd nos.: "<<odd;
   cout<<"\n\t Number of even nos.: "<<even;
   getch();
}

Want to try something more challenging?

Situation #4: User enters ten numbers and the program displays the largest.

The code will be revealed in the next post!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s