Lesson # 3. For Loops and While Loops. References briefly

Дата изменения: 7 октября 2020

Theory

Note about for loop

The for loop allows you to use several counters: the initialization and increment sections can contain several operators connected by the operator «,» (comma)

int a = 0, b = 0;
for (a = 1, b = 8; a < b; ++a, --b) {
    // empty body
}
cout << a << " " << b << endl; // output 5   4

References

References are not objects; they do not necessarily occupy storage:

void double_numb(int& numb) {
	numb *= numb; // 'numb' is the same as main()'s 'x'
}
void main(){
int x = 2;
	double_numb(x);
	cout << x << '\n';
	system("pause");
}
  • References are the other name of the variable:
  • int main(){
      int a = 5;
      int& ra = a;
      ra = 3;
      std::cout << a; // output 3!
      system("pause");
    }

    Labs and tasks

    • Create an empty application with a name Lesson_3. All the tasks and labs must be done within this application. When one task is ready, exclude the .cpp file of the task and add a new file to the application to do the next task.
    • Or you can do all tasks within the same header and source file. But you should put comments with the task number and explanation of what to do.
    • Every task has to be done using user function. For example, if the task is to find the sum of a sequence of 5 entered numbers, you must create a function within .cpp file to do this task:
    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
      #include <iostream>
      using namespace std;
       
      int sumSeq() {
      	cout << "enter a sequence"<<endl;
      	int numb;
      	int sum = 0;
      	for (int i = 0; i < 5; i++) {
      		cin >> numb;
      		sum += numb;
      	}
      	return sum;
      }
      void main(){
      	int result = sumSeq();
      	cout << result;
      	system("pause");
      }
    • Try to pass arguments of the functions by reference (in the tasks where it is needed).
    Passing parameters by reference:
    For loop:
    Task 1:
    To do: Create a function to output the sequence: -3 0 3 6 9 12 15 18 21 24. Make the task with FOR loop. An iterator of the loop has a step equaled 3.

    Note 1: To make a step equal to 3 see syntax:

    for ([initializers]; [condition]; [iterator]) 

    instead of the iterator you’ll have the variable counter +=3
    Note 2: The signature of the function must be void printSeq(int & a, int & b), where a = -3 and b = 24.
    Expected output:

    The sequence: -3 0 3 6 9 12 15 18 21 24

    [Solution and Project name: Lesson_3, file name L3Task1main.cpp]

    Task 2:

    To do: 10 integers are input. Create a function (findPosNeg) to output the quantity of positive and negative among them.

    Note 1: Create for loop to input the numbers. Within the loop, check each number whether it is positive or negative. Use two counters to find the quantity.
    Note 2: The signature of the function must be:

    void findPosNeg(int & pos, int & neg){
      //TODO
    }

    Expected output:

    the sequence:
    1  -5  -12   2   3   9   -1  9   5   -8    
    counter_positive = 6, counter_negative = 4

    [Solution and Project name: Lesson_3, file name L3Task2main.cpp]

    Task 3:

    To do: Create a function to calculate the addition of 10 numbers of the sequence: 1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19 (numbers are NOT input, they must be created using a loop).

    Note: To calculate the addition, use a variable named sum.

    Expected output:

    the sequence:
    1 + 3 + 5 + 7 + 9 + 11 + 13 + 15 + 17 + 19   
    sum = 100
    

    [Solution and Project name: Lesson_3, file name L3Task3main.cpp]

    Task 4:

    To do: For every x changing in the interval [x1;x2] (x1 and x2 values are entered), calculate the value of the function z(x,y) = xy. The variable y changes in the interval [y1;y2] (y1 and y2 values are entered). You must create a function.
    Note 1: Create two for loops (nested loop): one loop within the other. Variable x has to be modified in the outer loop; variable y has to be modified in the inner loop.
    Note 2: To output the power of a number, use pow function and #include directive: f = pow(base number, exponent);

    Expected output:

    enter x1 and x2:
    >>>2 >>>8
    enter y1 and y2:
    >>>2 >>>4
    z(x,y) = 2^2 = 4
    z(x,y) = 2^3 = 8
    z(x,y) = 2^4 = 16
    z(x,y) = 3^2 = 9
    z(x,y) = 3^3 = 27
    z(x,y) = 3^4 = 81
    z(x,y) = 4^2 = 16
    z(x,y) = 4^3 = 64
    z(x,y) = 4^4 = 256
    z(x,y) = 5^2 = 25
    z(x,y) = 5^3 = 125
    z(x,y) = 5^4 = 625
    ... etc.

    [Solution and Project name: Lesson_3, file name L3Task4main.cpp]

    While loop:
    Task 5:

    To do: Create a function to output the sequence 15 12 9 6 3 0 (from 15 down to 0 with a step = -3). Use while loop.

    Note: The signature of the function must be:

    void printSeqTask5(int & a, int & b){}

    Where a = 15 and b = 0

    Expected output:

    the sequence:
    15 12 9 6 3 0
    

    [Solution and Project name: Lesson_3, file name L3Task5main.cpp]

    Task 6:

    To do: Create a function to calculate a multiplication of 2-digit even integers in the interval [10;20] (10 * 12 * 14 * 16 * 18 * 20). Make the task using a while loop.
    Note 1: To calculate a multiplication you should use a variable with the name product. Start with product = 1.

    Note 2: The signature of the function must be:

    void findMult(int & a, int & b){}

    where a = 10 and b = 20

    Expected output:

    10 * 12 * 14 * 16 * 18 * 20  
    the product: 9676800

    [Solution and Project name: Lesson_3, file name L3Task6main.cpp]

    Task 7:

    To do: Two two-digit integers are input. Create a BitwiseSum() function that computes their bitwise sum modulo 10. For example, the bitwise sum of the numbers 34 and 59 is the number 83 (3 + 5 = 8; 4 + 9 = 13; 13%10 = 3). Use while loop.

    Note: The BitwiseSum() method must accept two integers arguments passed by reference.

    Expected output:

    Please enter two two-digit numbers:
    >>> 34   >>> 59
    The bitwise sum of 34 and 59 is: 83

    [Solution and Project name: Lesson_3, file name L3Task7main.cpp]

    Task 8:

    To do: A sequence of integers (entered) is given. The last element of the sequence is 0. Calculate the sum of all positive elements of this sequence and the number of its negative elements. While loop must be used.

    Note 1: In the task, you should use the endless loop with an exit from the middle:

    while (true)
    	{
    		cin >> num;
    		if (num == 0)
    			break;
                    ...
                    // calculalete pos and neg, as it is in the task
                    //
            }

    Note 2: To return two values from the function Use function parameters by reference (&):

    void sumPosCountNeg( int& pos_sum, int& neg) {}

    Expected output:

    Please enter the sequence, the last element is 0:
    >>> 3   5   -1   2  -3   0
    The sum of positive numbers is: 10
    The number of negatives is: 2
    

    [Solution and Project name: Lesson_3, file name L3Task8main.cpp]

    Task 9:

    To do: A sequence of integers (entered) is given. The last element of the sequence is 0. Find the minimum and maximum elements. While loop must be used.

    Note 1: In the task, you should use the endless loop with an exit from the middle:

    while (true)
    	{
    		cin >> num;
    		if (num == 0)
    			break;
                    ...
                    // calculalete min and max, as it is in the task
                    //
            }

    Note 2: To return two values from the function Use function parameters by reference (&):

    void minMax( int& min, int& max) {}

    Expected output:

    Please enter the sequence, the last element is 0:
    >>> 3   5   -1   2  -3   0
    The minimum is: -3
    The maximum is: 5
    

    [Solution and Project name: Lesson_3, file name L3Task9main.cpp]

    EXTRA TASKS

    ExtraTask 1 (for loop):

    The Pell numbers PN are given recursively:

    P0 = 0, P1 = 1, PN = 2 PN – 1 + PN – 2

    To do: Create a function to calculate the N-th Pell number (N ≥ 0). Be sure to check that for large N the expression (PN – 1 + PN) / PN is close enough to √2.

    Note: Do not use recursion.

    Expected output:

    Please enter n: 
    >>> 5
    Pell = 70

    [Solution and Project name: Lesson_3, file name L3ExTask1.cpp]

    ExtraTask 2 (while loop):

    To do: An integer is given. Find the number of its digits and their sum.

    Note: The function signature should look like this:

    void digitsCountAndSum (int n, int& count, int& sum)

    Expected output:

    Enter number: 
    >>> 12345
    The number of digits = 5, the sum = 15

    [Solution and Project name: Lesson_3, file name L3ExTask2.cpp]

    ExtraTask 3:

    To do: An integer is given. Generate a new number, the odd (in order) digits of which coincide with the corresponding digits of the original number, and the even ones are equal to zero.

    Note: Create a function with an argument passed by reference.

    Expected output:

    Enter an integer, please: 
    >>> 3627
    Result: 3020

    [Solution and Project name: Lesson_3, file name L3ExTask3.cpp]

    ExtraTask 4 (passing parameters by reference):

    To do: An integer N and a set of N positive real numbers are given. Calculate the sum of all integer parts, as well as the sum of all fractional parts of the sequence. Some of the standard header functions may be helpful.

    Expected output:

    Enter N: 
    >>> 4
    12,4  11,7  8,5  1,1
    Sum of integer parts is: 32 
    Sum of fractional parts is: 1.7

    [Solution and Project name: Lesson_3, file name L3ExTask4.cpp]

    Hometasks

    For loop
    Hometask1:

    To do: 10 integers are input. Create a function to output the addition (sum) of entered numbers.

    Note: Create for loop to input the numbers. To calculate the addition, use a variable named sum.

    Expected output:

    1  -5  -12   2   3   9   -1  9   5   -8   
    sum = 3

    [Solution and Project name: Lesson_3, file name L3HomeTask1.cpp]

    Hometask2:

    To do: 10 real numbers are input. Create a function to output the multiplication of the entered numbers.
    Note 1: Create for loop to input the numbers. To calculate the multiplication, use a variable named product.
    Note 2: Don’t forget to initialize the product variable with a double type value.

    double product = 1.0; 

    Expected output:

    1,1  2,4  5,1  7,2  6,4  8,1  6,7  3,2  3,3  2,4  
    product = 853338,921998746

    [Solution and Project name: Lesson_3, file name L3HomeTask2.cpp]

    Hometask3:

    To do: For every x changing in the interval [30;33], calculate the value of the function z(x,y) = x - y. The variable y changes in the interval [1;5]. You must create a function.

    Note: Create two for loops (nested loop): one loop within the other. The variable x has to be modified in the outer loop; the variable y has to be modified in the inner loop.

    Expected output:

    z(x,y) = 30-1=29
    z(x,y) = 30-2=28
    z(x,y) = 30-3=27
    z(x,y) = 30-4=26
    z(x,y) = 30-5=25
    z(x,y) = 31-1=30
    ... etc.

    [Solution and Project name: Lesson_3, file name L3HomeTask3.cpp]

    While loop
    Hometask4:

    To do: Create a function to output the sequence 3 5 7 9 ... 21 (from 3 to 21 with a step = 2).

    Note: the signature of the function must be void seq(int & a, int & b), where a = 3 and b = 21.

    Expected output:

    3 5 7 9 11 13 15 17 19 21

    [Solution and Project name: Lesson_3, file name L3HomeTask4.cpp]

    Hometask5:

    To do: 5 real numbers are input. Create a function to calculate an addition (sum) of entered numbers. Make the task using a while loop.

    Note: Double type must be used for real numbers and for variable sum:

    double sum = 0;
    double numb;

    Please enter 5 numbers and press Enter

    1.1 4.2 2.1 9.3 2.5
    The sum of inputted numbers = 19.2

    [Solution and Project name: Lesson_3, file name L3HomeTask5.cpp]

    Добавить комментарий

    Ваш адрес email не будет опубликован. Обязательные поля помечены *

    *
    *


    Вставить формулу как
    Блок
    Строка
    Дополнительные настройки
    Цвет формулы
    Цвет текста
    #333333
    Используйте LaTeX для набора формулы
    Предпросмотр
    \({}\)
    Формула не набрана
    Вставить