Showing posts with label FOR. Show all posts
Showing posts with label FOR. Show all posts

Powerball Lottery with C++

In this C ++ tutorial, we will learn how to count all possible Powerball guesses, as well as how to display all these numbers using the nested repeating structures technique;

The Powerball lottery

Most likely you already played at the Powerball right?
It works like this: You must choose 5 numbers from a universe of 69 numbers, from 1 to 69 and one number of 26.


In the end, they display the result in ascending order of values, ie from the smallest to the largest.

The 'lowest' guess is:
1 2 3 4 5  - 1

Already the 'biggest' guess is:
65 66 67 68 69 - 26

Here comes the secret:

The first dozen goes from 1 to 65
The second dozen goes from 2 to 66
The third dozen goes from 3 to 67
The fourth dozen goes from 4 to 68
The fifth dozen goes from 5 to 69
The last goes from 1 to 26

How many guesses are possible in Powerball

So, come on.
Let's use 6 variables for the numbers: ten1, ten2, ten3, ten4, ten5, and ten6.

The accumulator variable, to count how many iterations (hence, how many guesses are possible in the Powerball), is the sum.

Now just make FOR nested with FOR and count how many possibilities there are, always being careful about the interval each dozen can take.

Another important secret is that the variable ten1 starts from 1, and the following starts from the previous decade plus 1, since the tens are larger than the others, since we are assuming they are in ascending order. The last one, don't.

The code:
#include <iostream>
using namespace std;

int main()
{
    int dez1, dez2, dez3, dez4,
        dez5, dez6, sum=0;

    for(dez1=1; dez1<=65 ; dez1++)
        for(dez2=dez1+1; dez2<=66 ; dez2++)
            for(dez3=dez2+1; dez3<=67 ; dez3++)
                for(dez4=dez3+1; dez4<=68 ; dez4++)
                    for(dez5=dez4+1; dez5<=69 ; dez5++)
                        for(dez6=1; dez6<=26 ; dez6++)
                            sum++;
    cout << "Total: "<<sum<<endl;

    return 0;
}

The result
C++ tutorial

It took 0.821s here to run over 292 million iterations, and then on your machine?

Display all guesses from Powerball

Let's print all possibles results:
#include <iostream>
using namespace std;

int main()
{
    int dez1, dez2, dez3, dez4,
        dez5, dez6;

    for(dez1=1; dez1<=65 ; dez1++)
        for(dez2=dez1+1; dez2<=66 ; dez2++)
            for(dez3=dez2+1; dez3<=67 ; dez3++)
                for(dez4=dez3+1; dez4<=68 ; dez4++)
                    for(dez5=dez4+1; dez5<=69 ; dez5++)
                        for(dez6=1; dez6<=26 ; dez6++)
                            cout<<dez1<<"-"<<dez2<<"-"<<dez3<<"-"
                                <<dez4<<"-"<<dez5<<"--"<<dez6<<endl;

    return 0;
}




Note that now is waaaay longer, and this is because the cout function is slower, it takes time to display things on your screen, if the machine was just doing the calculations, as in the previous example, would be much faster. But here we have to show the results of the iterations, so it takes longer.

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?

FOR Repetition Statement - C++ controlled loop

Concluding the presentation of the repetition structures of our C ++ Course, we will present the FOR statement, the controlled loop.

FOR repetition statement in C++

The FOR repetition statement has the following syntax:
for(inicialization ; conditional_test ; update){
   // codes that run if
   // the conditional test
   // is true
}
Come on.
The FOR repetition statement has three expressions within it, separated by semicolons.

The loop begins with some kind of initialization, usually a count variable, with some initial value.

After this initialization, conditional testing occurs. If true, the code inside the FOR loop braces is executed.
After each iteration, the 'update' occurs, where we usually update the counter value, most commonly it is a variable that will increment or decrement.

Then again the conditional test is performed, if true, again the FOR code is executed. After this iteration, the update occurs again.

FOR loop usage example

In programming, an example is worth a thousand words.
Let's count from 1 to 10, using the for loop, the code is as follows:
#include <iostream>
using namespace std;

int main()
{
    int count;

    for(count=1; count<=10 ; count++){
        cout << count << endl;
    }

    return 0;
}
Our control variable is count, which starts at 1.
Let's print it on screen as long as its value is less than or equal to 10.

At each iteration, we increment it by one (count++) because we want it to go from 1 to 10.

Note that we already did that in the WHILE loop, but we initialized the variables before the loop, inside that we updated the variable with each loop and the conditional test occurred inside the WHILE parentheses.

It occurs the same way in the FOR loop, but in a more organized way.

Using the FOR Repetition Statement

Let's do the opposite now, a countdown, which counts from 100 to 1.
For this, we initialize our control variable to 100.

The test to be performed is: count> 0
That is, as long as the variable has a value above 0, iterations of the FOR loop will occur.

And with each iteration we have to decrease the count, because it goes from 100 to 1, one by one.
See how our code looked:

#include <iostream>
using namespace std;

int main()
{
    int count;

    for(count=100; count>0 ; count--){
        cout << count << endl;
    }

    return 0;
}
Not always, however, we will increment or decrement by 1 in 1.
We can update our variables as we wish.

For example, let's print all even numbers from 1 to 1000 on the screen.
The first even is 2, so we initialize our variable with this value.

Let's increment by 2: count += 2

And the test is as long as the variable is less than or equal to one thousand: count <= 1000
#include <iostream>
using namespace std;

int main()
{
    int count;

    for(count=2; count<=1000 ; count+=2){
        cout << count << endl;
    }

    return 0;
} 
See the incredible speed with which this code executes.
Do you doubt the ability of C ++? Put 1 million.

When to use the FOR loop

Often we want to loop with a certain number of iterations.
For example, when asking for a student's grades, let's ask for as many grades as there are to average.

To calculate your income tax, we need to add up your entire salary of the year, ie 12 salaries.

The FOR loop is ideal when you know exactly the number of iterations you are going to do: "oh, I want to calculate this in this range from x to y", so bang, use the FOR repetition statement.

When you don't know when looping should end or have less control over how many iterations to occur, then use the WHILE loop.

Remembering that, deep down, they are absolutely the same thing.

It will only be easier to work with FOR sometimes and WHILE at other times.

FOR Repetition Statement

Create a program that asks how many grades you want to average, then asks each of those grades and finally displays the average.

Let's store the number of notes we will ask for in variable n.
The next step is to ask for grade by grade, and here comes the ace in the hole: calculate the sum of all grades.

Within the FOR, the control variable aux goes from grade 1 to the grade n, asking one by one and storing the grade in the variable grade.

Let's store in the sum variable, the sum of all these grades.
Finally, we display sum/n to display the average.

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

int main()
{
    int aux, n;
    float grade, sum=0;

    cout <<"How many topics: ";
    cin >> n;

    for(aux=1; aux<=n ; aux++){
        cout <<"Grade "<<aux<<": ";
        cin >> grade;
        sum += grade;
    }

    cout << "Average: "<<(sum/n)<<endl;

    return 0;
}
Notice how this repetition statement is controlled: it will always run 'n' iterations, whatever the value of 'n' (obviously, the number of grade must be a positive integer value).

You can fill in 2 grades, 3 grades, a thousand grades, a million grades ...
Powerful, isn't this FOR command?