What's new

Phc robot

PHC-Rafael

Ice 4 sale
Contributor
Joined
Mar 19, 2017
Posts
20,374
Solutions
11,198
Reaction
23,177
Points
16,575
Declaring and Initializing C++ Variables



Summary
In this lab, you declare and initialize variables in a C++ program. The program, which is saved in a file named NewAge.cpp, calculates your age in the year 2050.



Instructions
  1. Declare an integer variable named myNewAge.
  2. Declare and initialize an integer variable named myCurrentAge. Initialize this variable with your current age.
  3. Declare and initialize an integer variable named currentYear. Initialize this variable with the value of the current year. Use four digits for the year.
  4. Execute the program by clicking the "Run Code" button at the bottom of the screen.
Sample program execution:

My Current Age is 29.
I will be 65 in 2050.
 
Here's the code for the program:

Code:
#include <iostream>

using namespace std;

int main() {
    int myNewAge;
    int myCurrentAge = 29;
    int currentYear = 2021;
    
    myNewAge = 2050 - (currentYear - myCurrentAge);
    
    cout << "My Current Age is " << myCurrentAge << "." << endl;
    cout << "I will be " << myNewAge << " in 2050." << endl;
    
    return 0;
}

Explanation:
  • Line 4: Declare an integer variable named myNewAge.
  • Line 5: Declare and initialize an integer variable named myCurrentAge with a value of 29.
  • Line 6: Declare and initialize an integer variable named currentYear with the current year, 2021.
  • Line 8: Calculate the value of myNewAge by subtracting the difference between the current year and myCurrentAge from the year 2050.
  • Line 10: Output the message "My Current Age is " followed by the value of myCurrentAge and a period.
  • Line 11: Output the message "I will be " followed by the value of myNewAge, a space, and the year "in 2050.".
  • Line 13: End the program and return the value 0 (which indicates successful execution).
 

Similar threads

Back
Top