C++ Basics

Print your name and age with variables

Description: Create a std::string for your name and an int for your age. Print My name is Riya and I am 21 years old. with your own values.

Hint:

  • Join the parts with << on std::cout.

Solution

#include <iostream>
#include <print>
#include <string>

int main() {
    std::string name = "Riya";
    int age = 21;
    std::cout << "My name is " << name << " and I am " << age << " years old.\n";
    std::println("My name is {} and I am {} years old.", name, age);
}
Output

My name is Riya and I am 21 years old.
My name is Riya and I am 21 years old.

How it works

  • << sends each part to the output stream, one after the other.
  • std::println (C++23) uses {} placeholders.

Read C++ Variables.

Swap two numbers using a reference function

Description: Write a function swap_values(int& a, int& b) which swaps two variables. Test it with 10 and 25, and compare it with std::swap.

Hint:

  • A reference parameter works on the original variable.

Solution

#include <iostream>
#include <utility>

void swap_values(int& a, int& b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int x = 10, y = 25;
    swap_values(x, y);
    std::cout << x << ' ' << y << '\n';
    std::swap(x, y);
    std::cout << x << ' ' << y << '\n';
}
Output

25 10
10 25

How it works

  • Because the parameters are references, the function changes x and y of main, not copies.

Read C++ References.

Convert Celsius to Fahrenheit

Description: Convert 0, 37 and 100 degrees Celsius to Fahrenheit with F = C * 9 / 5 + 32, and print one digit after the decimal point.

Hint:

  • Use double and 9.0 / 5.

Solution

#include <print>

double to_fahrenheit(double c) {
    return c * 9.0 / 5 + 32;
}

int main() {
    for (double c : {0.0, 37.0, 100.0}) {
        std::println("{:.1f} C = {:.1f} F", c, to_fahrenheit(c));
    }
}
Output

0.0 C = 32.0 F
37.0 C = 98.6 F
100.0 C = 212.0 F

How it works

  • 9.0 / 5 is a decimal division. 9 / 5 would be 1 (integer division).
  • {:.1f} prints one digit after the point.

Read C++ Functions.