Real-Life Examples of Variables in C++

Understanding variables becomes easier with practical examples. Let's consider a program that calculates the area of a circle.

Example: Calculating the Area of a Circle

Code Example

#include <iostream>
#define PI 3.14159

int main() {
    double radius, area;
    std::cout << "Enter the radius of the circle: ";
    std::cin >> radius;
    area = PI * radius * radius;
    std::cout << "Area of the circle is: " << area << std::endl;
    return 0;
}

Sample Output

Output:

Enter the radius of the circle: 5

Area of the circle is: 78.5397

Code Explanation: The program defines a constant PI and uses variables radius and area to calculate the area of a circle based on user input.

Example: Storing User Information

Code Example

#include <iostream>
#include <string>

int main() {
    std::string name;
    int age;
    char grade;
    
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);
    
    std::cout << "Enter your age: ";
    std::cin >> age;
    
    std::cout << "Enter your grade: ";
    std::cin >> grade;
    
    std::cout << "Student Information:\n";
    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Grade: " << grade << std::endl;
    
    return 0;
}

Sample Output

Output:

Enter your name: Akila

Enter your age: 22

Enter your grade: A

Student Information:

Name: Akila

Age: 22

Grade: A

Code Explanation: This program collects user information and stores it in variables. It demonstrates the use of std::string, int, and char data types.

Key Takeaways:

  • Variables are essential for storing and manipulating data.
  • Real-life examples help in understanding the practical use of variables.
  • User input can be stored in variables for further processing.