Showing posts with label WHILE. Show all posts
Showing posts with label WHILE. Show all posts

Multiplication Table with Loopings in C++

Let's solve the repetition structure list exercise:


  • Make a C++ program that asks the user for an integer and displays their multiplication table.


Multiplication table with FOR in C++

First, we ask the user for a number and store it in the num variable.
Let's also use an aux control variable.

This variable, inside the FOR loop, goes from 1 to 10, to build the multiplication table.
Then just multiply one by aux in each iteration and display the result.

See how our code looked:
#include <iostream>

using namespace std;

int main()
{
    int num, aux;

    cout << "Number: ";
    cin >> num;

    for(aux=1 ; aux<=10 ; aux++)
        cout<<num<<" * "<<aux<<" = " << num*aux <<endl;

    return 0;
}

Multiplication table with WHILE and DO WHILE

You can also do the same with WHILE looping, see:
#include <iostream>

using namespace std;

int main()
{
    int num, aux=1;

    cout << "Number: ";
    cin >> num;

    while(aux<=10){
        cout<<num<<" * "<<aux<<" = " << num*aux <<endl;
        aux++;
    }

    return 0;
}
Note that we must first initialize the aux variable and increment it inside WHILE, just as we do in the FOR structure header.

We can also increment our code and use while, to display as many tables as the user wants, just for when they type 0:




#include <iostream>

using namespace std;

int main()
{
    int num, aux;

    do{
        cout << "Number: ";
        cin >> num;

        for(aux=1; aux<=10 ; aux++)
            cout<<num<<" * "<<aux<<" = " << num*aux <<endl;
        cout<<endl;
    }while(num);

    return 0;
}

+30 C++ Loop Exercise

Congratulations on completing the C++ Repetition Statements section, famous loops, one of the most important topics in any programming language.

Now is the time to put your knowledge into practice, this is where you will evolve, become a real programmer.

Solve the exercises, try, try, try again and again, before you see the solution, combined?
Just reading or watching videos will never make you a programmer, even the worser.

It is in the race, trying, struggling, breaking one's head, sweeping nights, and crying in a fetal position that one forges a true C++ Progressive programmer.

Left? Say goodbye to friends, girlfriend or boyfriend, family, social networks ... time to hide from society and exercise!

Ah ... and post there in the comments your solutions!

WHILE, DO WHILE, and FOR exercises in C++

0. Make a C++ program that asks the user for an integer, and displays their multiplication table.
Multiplication table with FOR, WHILE and DO WHILE

1. Make a program that takes two integers and generates the integers that fall within their range.

2. Make a program that asks for a grade between zero and ten. Show a message if the value is invalid and keep asking until the user enters a valid value.

3. Make a program that prints numbers 1 to 20 on the screen, one below the other. Then modify the program so that it shows the numbers next to each other.

4. Write programs that display the following patterns on the screen according to the number you provide, which will always be the number of lines:
(Solutions in e-book)
4.1

** 
*** 
**** 
*****

4.2
1
12 
123 
1234 
12345

4.3
1                                                                                                             
22                                                                                                      
333                                                                                                         
4444                                                                                                         
55555 


4.4
1                                                                                  
2 3                                                                                                         
4 5 6                                                                                                       
7 8 9 10 


4.5
       1                                                           
      2 3                                                           
     4 5 6                                                         
    7 8 9 10

4.6
        *                                                           
       * *                                                         
      * * *                                                         
     * * * *                                                       
    * * * * *

4.7
1                                                                      
01                                                                     
101                                                                    
0101                                                                   
10101

4.8
    *                                                                  
   ***                                                                 
  *****                                                                
 *******                                                               
*********                                                              
 *******                                                               
  *****                                                                
   ***                                                                 
    *


4.9
          1                                                            
        1   1                                                          
      1   2   1                                                        
    1   3   3   1                                                      
  1   4   6   4   1 

4.10                                                                      
1   1                                                                  
1   2   1                                                              
1   3   3   1                                                          
1   4   6   4   1                                                      
1   5   10   10   5   1                                                
1   6   15   20   15   6   1

4.11
12345                                                                                                         
2345                                                                                                          
345                                                                                                           
45                                                                                                            
5

4.12
12345                                                                                                         
 1234                                                                                                         
  123                                                                                                         
   12                                                                                                         
    1

4.13
5 4 3 2 1                                                              
4 3 2 1                                                                
3 2 1                                                                  
2 1                                                                    
1

4.14
    1                                                                  
   21                                                                  
  321                                                                  
 4321                                                                  
54321

4.15
     1234567654321                                                                                            
      12345654321                                                                                             
       123454321                                                                                              
        1234321                                                                                               
         12321                                                                                                
          121                                                                                                 
           1

5. Make a program that reads 5 numbers and reports the largest number.

6. Make a program that reads 5 numbers and gives the sum and average of the numbers.

7. Make a program that calculates the show the arithmetic average of N grades.

8. Make a program that prints only odd numbers between 1 and 50 on the screen. At the end, also show the sum of the numbers.

9. Create a program that asks the user for a number and calculates the summation to that value.

10. Create a program that asks the user for a number, and calculates its factorial. Ex .: 5! = 5.4.3.2.1 = 120
Summation and Factorial

11. The Fibonacci series is formed by the sequence 0,1,1,2,3,5,8,13,21,34,55, ... where the next term is always the sum of the previous two. Make a program capable of generating the series to the nth term that the user must supply.
Fibonacci in C++ with loopings

12. Make a program that asks for two numbers, base and exponent, calculate and display the first number raised to the second number. Do not use the power function of language.
Exponentiation with loopings in C++

13. Make a program that asks for an integer and determines whether or not it is a prime number. A prime number is one that is divisible only by itself and by 1.

14. Make a program that shows all primes between 1 and N where N is a user-supplied integer.
Prime numbers with C++

15. Make a program that displays all possible Powerball game combinations.
Powerball lottery in C++

16. Program software that receives a user number and tells you if it is a perfect number or not. Search Google for a perfect number.

17. Program software that receives two integers from the user, and tell them the greatest common divisor of these numbers.

18. Program a software that receives a number less than 1000, and say the value of the unit, the dozen, and the hundred digits.

19. Program software that calculates the sum of the digits of a number.

20. Make a program that shows the following Series terms:

  S = 1/1 + 2/3 + 3/5 + 4/7 + 5/9 + ... + n / m.

Print at the end the sum of the series.


21. Let the harmonic series H = 1 + 1/2 + 1/3 + 1/4 + ... + 1 / N, Make a program that calculates the value of H with N terms, where N is input by the user.

22. Make a program that shows the following terms of the Series:

  S = 1/1 + 2/3 + 3/5 + 4/7 + 5/9 + ... + n / m.

Print at the end the sum of the series.


23. The value of PI can be approximated by the following infinite sequence:
Infinite series to calculate pi
Create a program that calculates the value of this series with 10 terms, then 100 terms, and finally using a thousand terms. What values did you get?

DO ... WHILE C++ looping

In this C++ tutorial, we will learn how to use do ... while looping in C++, through ready-made examples with commented code.

DO ... WHILE Looping

To recap: loop is a certain piece of code that can be repeated as many times as we wish. We have already studied WHILE looping in C++, now let's know DO WHILE.

Remembering that in the WHILE loop, the conditional test occurs before the loop executes.

This is the main difference for the DO WHILE loop, in this, the conditional test will only happen after each iteration (loop internal code repetition).

The loop structure of WHILE is:
do
{
   // code
   // code
} while (condition) ; 

That is, the code is executed first (DO this).
Then the conditional test occurs within the parentheses of while.

If true, the code is repeated again and again as long as the condition is true.

See the flow chart:
How to use DO WHILE loop in C++ tutorial

How to use DO WHILE in C++

The first thing to keep in mind when deciding to use DO WHILE is that it will execute the code at least once! That is, always performs an iteration of the loop!

A very common use is in menus. A menu is always displayed at least once (either in a game or in your banking system).
Let's create a menu of a bank.

See our code:
#include <iostream>
using namespace std;

int main()
{
    int op;

    do
    {
        cout << "Choose an option:\n";
        cout << "0. Exit\n";
        cout << "1. Balance\n";
        cout << "2. Extract\n";
        cout << "3. Withdraw\n";
        cout << "4. Transfer\n";
        cin >> op;

    } while(op);

    return 0;
}
Each time you type an option, it can go to a different section of the system (we'll learn how to do that using functions), and only comes out if you type 0 (ie as long as the op value is different from 0, the loop occurs, because any value other than 0 is true, only 0 is False).

Note that we do not even need to initialize the variable (if we were to use the while loop, we would need to initialize, to ensure that the loop occurred at least once).

DO WHILE example usage

We use the while looping too when we want to do something at least once, and we want to give it the option of repeating itself again.

For example, the code below calculates the average of two grades the user provides.
At the end, he asks if you want to calculate another average:
#include <iostream>
using namespace std;

int main()
{
    float grade1, grade2;
    int op;

    do
    {
        cout << "First grade: ";
        cin >> grade1;

        cout << "Second grade: ";
        cin >> grade2;

        cout <<"Average: " << (grade1+grade2)/2 << endl;
        cout <<"Calculate again ?\n";
        cout <<"1. Yes\n";
        cout <<"2. No\n";
        cin >> op;

    } while(op!=2);

    return 0;
}
That is, the person using this program can calculate as many averages as he or she wants, infinitely, thanks to the do while looping.

So whenever you need to run code at least once (but you don't know how many times, it depends on the user), use DO WHILE looping.

For example:
do
{
   cout << "Blablabla (or type 0 to exit): ";
   //code
   //códe
} while(op);
Cool, isn't?

The WHILE Loop in C++: How to Use the Repetition Structure

In this looping tutorial, we will introduce the while repetition structure in C++.

WHILE Loop: Repetition Structure

As the name may suggest in the introduction, it is a structure that allows us to repeat certain pieces of code in C++.

The structure of C ++ is as follows:
while(test){
   // Statement in case of 
   // test expression be true
}

So it starts with the while statement, then parentheses, and within these must have some boolean value, usually an expression, a conditional test that will return true or false.

While that value within parentheses is true, the code inside the while statement will run.

Each repetition is called an iteration. There can be none, one, one thousand, one million or infinite iterations in a loop (infinite loopings), it will depend on how the conditional test behaves.

See the WHILE loop flowchart:
WHILE looping in C++ tutorial

WHILE Example - Repetition Structure

Let's go to the examples, so we learn better.

Let's create a program that displays numbers from 1 to 10 on the screen.
For this, let's use a control variable, let's call count, because it will be our counter.

We start with value 1.
The conditional test is: as long as count is less than or equal to 10
Inside WHILE we give cout to print the number.

Then we have to increment the counter by one, see the code:
#include <iostream>
using namespace std;

int main()
{
    int count=1;

    while(count<=10){
        cout << count << endl;
        count++;
    }
    return 0;
}
What happens is as follows. The code arrives in WHILE, and there it tests if the variable is less than or equal to 10.

As it is worth 1, the test is true and enters the code. There we print the variable, and increment the counter.

Then the test occurs again, now our variable is worth 2 and gives true to the test, running its code.
Then the test occurs with the counter worth 3, and so on, until the counter is 10.

In this case, the test is still true.
But within the code, the counter increments and turns 11.

When retesting, the result is false, so the repeat structure stops the iterations and ends the loop.

Here's what the code would look like, displaying from 10 to 1:
#include <iostream>
using namespace std;

int main()
{
    int count=10;

    while(count>0){
        cout << count << endl;
        count--;
    }
    return 0;
}

How to use WHILE loop in C ++

The example below is infinite looping, but the test inside the WHILE loop is always true, so he would be printing the message endlessly ...
#include <iostream>
using namespace std;

int main()
{
    while(1)
        cout << "Progressive C++ course\n";

    return 0;
}
We can also do an infinite count:
#include <iostream>
using namespace std;

int main()
{
    int count=1;

    while(count++)
        cout << count << endl;

    return 0;
}
Note that we place the increment operator directly inside the while loop.
We also do not use braces, this is allowed as the while code has only one line.

WHILE in C ++: Validating Entries

One of the features of the WHILE command is to validate user input.
For example, let's ask the user for a grade from 0 to 10.

If it type less than 0 or greater than 10, it will enter WHILE.
Within the repeating structure, we warn him that he entered a wrong note and we ask him to insert the note again.

The while loop is a stubborn loop ... it repeats as many times as necessary.
Want to see? Test placing notes less than 0 or greater than 10, it will only stop when the entered note is between 0 and 10:
#include <iostream>
using namespace std;

int main()
{
    int grade;

    cout << "Type a grade: ";
    cin >> grade;

    while(grade<0 || grade>10){
        cout <<"Invalid grade, try again: ";
        cin >> grade;
    }

    return 0;
}
Very simple, but powerful, this control structure.

Example of using WHILE in C ++

Create a program that prompts the user for a number and displays the multiplication table of that number.
Let's store the number entered in variable num. Our control variable is aux, which will range from 1 to 10.

See how our code looks:
#include <iostream>
using namespace std;

int main()
{
    int num, aux=1;

    cout << "Type a number: ";
    cin >> num;

    while(aux<=10){
        cout <<num<<" x "<<aux<<" = "<<num*aux<<endl;
        aux++;
    }

    return 0;
}