C/C++ variable initialization process question

Asked 2 years ago, Updated 2 years ago, 66 views

#include <iostream>
using namespace std;

int main() 

{ 

int num1, num2; // variable to store two digits from the user 

inti; // variables for repetition 

int oddSum = 0; // Variable to store odd sum 

evenSum = 0; // variable to store even sums 

cout << "Please enter two numbers" << endl;
cin >> num1 >> num2;


if (num1 > num2)

{ 

i = num1; 

num1 = num2; 

num2 = i; 

} 

// i is repeated by increasing by 1 from num1 to num2. 

For (i = num1; i < = num2; i++)// i has values from num1 to num2. 

{ 

If (i%2 == 1) // i divided by 2 and the remainder is 1, that is, odd 

Accumulates the value of i corresponding to odSum += i; // oddSum. oddSum = oddSum + i; 

If else // i is divided by 2 and the rest is not 1, that is, if it is an even number, 

Accumulates the value of i corresponding to evenSum += i; // evenSum. evenSum = evenSum + i; 

} 

\n" from cout <<num1 <<" to "<<num2 <<";

cout <<"oddSum <<endl;"
cout << "Even number:" << evenSum << endl;
cout << "The sum of odd and even numbers: << odSum + evenSum << endl;

return 0; 

}

If num1 is larger in the if statement, the variable values of num1 and num2 are changed, so why do you put num1 in the i variable? Can't you just say num1 = num2;? I wonder if I have to create an i variable and save the value. Also, is inti in the for statement different from i = num2; previously stored?

Thank you for reading.

c c++ variable initialization

2022-09-20 19:50

1 Answers

For example, when saved as below,

num1=1;
num2=2;`

In order to exchange two numbers, if you do it as below as you said,

num1=num2;    // num1: 2, num2: 2
num2=num1;    // num1: 2, num2: 2

In the first line, num1 is stored with 2 which is the value of num2 In the second line, num1 is now 2, so num2 stores 2. So the two numbers don't change and they all go to 2.

So when you want to change the value of two variables, you usually use a separate variable. The question code used i, which usually uses a variable named temp.

When saved again as below,

num1=1;
num2=2;`

The code below replaces the values of num1 and num2.

temp=num1;    // temp: 1, num1: 1
num1=num2;    // num1: 2, num2: 2
num2=temp;    // num2: 1, temp: 1

If you look at the code one line at a time, finally, num1 is 2 and num2 is 1 and the original number is changed. Because these three lines are typical of changing the values of two variables, you can memorize them and use them.

For reference, the variable i in the for loop is also the same variable as the variable i used to change. I think the code writer just recycled it. However, it is recommended to make and use variable names such as temp (meaning temporary) so that you can know the meaning as much as possible.


2022-09-20 19:50

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.