Browse by Domains

Simple C++ Programs

Table of contents

Practice makes a man perfect. Meaning the more you practice something, the more you get good at it. Practising programming that has different difficulty levels on a daily basis is very important to improve your coding skills. C++ is a very simple language, given that you practice it daily. Following are some C++ programs that you can practice to have a strong grasp of the language.

Check out Great Learning academy’s free course on C /C++Programming to upskill yourself and stay ahead of the curve.

  • C++ Program: The program prints “Hello, this is my first attempt.”
  • C++ Program: The program prints the number that is entered by the user. 
  • C++ Program: The program is used to add two numbers that are entered by the user. 
  • C++ Program: The program is used to find quotients and remainders. 
  • C++ Program: The program is used to find the size of the different data types: int, float, char, and double in the C++ language. 
  • C++ Program: The program is used to swap any two numbers. 
  • C++ Program: The program is used to find if the given number is odd or even 
  • C++ Program: The program is used to find if the given character is a vowel or a consonant

C++ Program: “Hello, this is my first attempt.”

Introduction:

The respective program provides an output: “Hello, this is my first attempt.”. It is one of the fundamental programs that is taught when you start to learn to code in the C++ language. The simplicity of the program allows any beginner to understand the program. 

Code:

The following is the code that can be used for the C++ Program: “Hello, this is my first attempt.”. 

//C++ Program: “Hello, this is my first attempt.”

#include <iostream>

int main() {
    std::cout << "Hello, this is my first attempt.";
    return 0;
}

Output:

Hello, this is my first attempt.

Explanation: 

Let us now understand how the following code works.

  1. //C++ Program: “Hello, this is my first attempt.”: Your code needs to have a proper structure, and the person studying your program should understand it. C++ eliminates the respective problem by providing you with the ability to write comments in your code. Any line starting with // will be considered as a comment by the C++ compiler. These comments can be used to structure your code and to explain your code properly (for any reader). These comments do not interfere with the actual code as the C++ compiler ignores them. 
  2. #include <iostream>: The way to include files in your program is to use a preprocessor directive which in this case is #include. It can be concluded that the respective code is making use of the contents of the iostream file. As you want to print the output, the above preprocessor: #include makes it happen by using cout. In simple words, #include<iostream> allows you to use cout to print any output on the screen. 
  3. int main() {…..}: If you want any of your C++ programs to be valid it is important to make use of the main() function. The opening curly bracket indicates the start of the function and the closing curly bracket indicates the end of the function. The process of execution of the code starts from the function: main(). 
  4. std::cout << “Hello, this is my first attempt.”;: If you want to print any output on the screen, you can simply type the output within the quotation marks of the std::cout<<“…”;. It is important to maintain the order first std::cout then << and finally the format string. In the following case the format string is “Hello, this is my first program.”. For ending any statement in C++, ; is used. 
  5. return 0;: For indicating the end of a particular C ++ program return 0; statement is used. It is an “Exit Status” of a C++ Program. 

Conclusion:

  1. For printing any output on the screen you can make use of the std::cout.
  2. It is important to include iostream, if you desire to make use of std::cout.
  3. For any valid C++ program, it is important to make use of the main() function. In simple words, it is mandatory. 

C++ Program: Prints the number, entered by the user. 

Introduction:

The respective program is used to print any number that the user enters. It is a simple program to understand as it is based on the basics of the C++ language. It is a very useful program as you learn to print an output that you enter, which allows you to be more interactive with the C++ code. 

Code:

The following is the code that can be used for the C++ Program: Prints the number entered by the user. 

#include <iostream>
using namespace std;

int main() {    
    int number;

    cout << "Input number: ";
    cin >> number;

    cout << "Number provided:" << number;    
    return 0;
}

Output:

Input value: 15

Number provided: 15

Explanation: 

Let us now understand how the following code works.

  1. int number;: int, is a short for integers. In C++ or any other programming language, data (variables) can’t be randomly fed into the system, as the compiler will not know what to do with the respective data. To eliminate this problem, datatypes are used, and int is also a fundamental data type that is already built into the C++ compiler. For defining any numeric variables that hold integers, you can make use of int data type. In the following case, the variable is the number. 
  2. cin>>number;: In C++, iostream, which is a class that has cin as its object. In the respective code, you have to provide input to the C++ program, but for the compiler to understand the input provided by you, the cin object is used. It accepts input (from standard input devices), allowing the compiler to accurately understand the input data. It is important to maintain the order first the cin object, then the extraction operator >> and finally the variable defined for the input data, which in this case is number.
  3. When the respective code is compiled, the program will ask you for the input value, and you can provide any integer as your Input number. 
  4. cout << “Number provided:” << number;: This is used to print the integer value provided by you. It is important to maintain the order first cout, then <<, following the text you want to print which in this case is “Number provided:”, then again << and finally the variable that you have defined in the beginning which in this case is number. End the statement by using ;. 

Conclusion:

  1. You can use different data types depending upon what you need—for example, int, float, char, long int, double, long double, etc. Remember to always provide input data that is accepted by the data type that you have used; otherwise, the program will prompt an error. 
  2. If you want your program to accept input from the user, you can use the cin object, but always remember to include the iostream class. 

C++ Program: Adds two numbers, entered by the user. 

Introduction:

The respective program is used to add the two numbers that are entered by the user. This is an important program as it teaches us to incorporate mathematics into C++ programming. This program is the base for the more complex mathematical problems that can be solved using the C++ program. Beginners can easily understand the code and can explore more. The program requires two variables for assigning them to the input values provided by the user and another variable for computing the value of the addition of the two input values.

Code:

The following is the code that can be used for the C++ Program: Adds two numbers, entered by the user. 

#include <iostream>
using namespace std;

int main()
{
    int valueone, valuetwo, sumofbothvalues;
    
    cout << "Enter two value: ";
    cin >> valueone >> valuetwo;

   // sumofbothvalues stores the actual sum of the two input values provided by the user
    sumofbothvalues = valueone+valuetwo;

    // Prints sum 
    cout << valueone << " + " << valuetwo << " = " << sumofbothvalues;     

    return 0;
}

Output:

Enter two values: 2

6

2 + 6 = 8 

Explanation: 

Let us now understand how the following code works.

  1. int valueone, valuetwo, sumofbothvalues;: As you want the user to provide the input values for the addition, it is first important to define the variable that can later be used to store the input values provided by the user. As the user provides two input values two variables named variableone and the variabletwo are defined. The addition of the respective variables is also a data that needs to be stored, so sumofbothvalues a third variable is also defined. 
  2. cin >> valueone >> valuetwo;: cin object, which is the object of class iostream is used for accepting the input provided by the user. It is important to maintain the order because the order defines the order in which the input values are assigned to the defined  variables. First cin object, then followed by extraction operator >>, followed by the defined variable for the first input value which in this case is valueone, then again extraction operator >>, now the defined variable for the second input value which in this case is valuetwo and ginally end the statement using ;. 
  3. sumofbothvalues = valueone+valuetwo;: It is important to define the equation for the variable sumofbothvalues. The compiler reads the equation and then properly executes it. If the equation for the variable sumofbothvalues is not defined the value of the respective variable hangs nowhere and the program prompts error. 
  4. cout << valueone << ” + ” << valuetwo << ” = ” << sumofbothvalues;: To print the final solution the following statement is used. It is important to maintain the defined order. 

Conclusion:

  1. The respective code can be used to create and explore many other mathematical solutions. Different operators such as addition +, subtraction -, multiplication *, etc. can be used. 
  2. Pay extra attention while ordering the statements as any error made in order cin object statements will lead to misassignment of the input values to the defined variables. 
  3. Also, pay attention while assigning the data types for the variables. Make sure the input values that are provided are accepted by the respective data types that are being used by you. 

C++ Program: To find quotients and remainders

Introduction:

The respective program is used to find quotients and remainders. This is also a C++ program that is an addition to the possible mathematical equations that can be solved with the help of the C++ language. The program is designed in such a way that it can be easily understood by a beginner. It is also one of the basic C++ programs that are taught to a newbie and can be explored more. The program requires two variables for assigning them to the two input values from the user and two other variables for computing the values of quotient and remainder. 

Code:

The following is the code that can be used for the C++ Program: To find quotients and remainders

#include <iostream>
using namespace std;

int main()
{    
    int divisor, dividend, quotient, remainder;

    cout << "Enter input value for dividend: ";
    cin >> dividend;

    cout << "Enter input value for divisor: ";
    cin >> divisor;

   // Following are the equations for the values of quotient and remainder. 
    quotient = dividend / divisor;
    remainder = dividend % divisor;

    // Always check if the order is maintained. 
    cout << "Quotient Value= " << quotient << endl;
    cout << "Remainder Value= " << remainder;

    return 0;
}

Output:

Enter input value for dividend: 15

Enter input value for divisor: 2

Quotient Value: 7

Remainder Value: 1

Explanation: 

Let us now understand how the following code works.

  1. int divisor, dividend, quotient, remainder;: For any division equation, there is a need for four values that are divisor, dividend, quotient, and remainder. These values are important, and it is important to assign a unique variable to each value. When the user provides the input value for each variable, the input value gets stored in the assigned variables.
  2. Instead of asking the inputs for the two variables divisor and dividend at the same time, you can also separate the process by mentioning separate statements for the two variables. When the cin object statements are mentioned separately, then they can be mentioned in any manner as there is only one variable string assigned to a particular cin object statement. In the following case, the dividend and divisor are mentioned separately. 
  3. Mention the equation for the quotient and the remaining variables. These equations are important because, without them, the C++ compiler won’t be able to compute the values for the variables quotient and remainder. 
  4. The / operator is known as a division operator and is used for calculating the quotient, whereas the % operator is known as a modulus operator and is used for calculating the remainder. 

Conclusion:

  1. The respective code can be used to create and explore many other mathematical solutions. Different operators such as addition +, subtraction -, multiplication *, etc. can be used. 
  2. Pay extra attention while ordering the statements as any error made in order cin object statements will lead to misassignment of the input values to the defined variables. 
  3. Also, pay attention while assigning the data types for the variables. Make sure the input values that are provided are accepted by the respective data types that are being used by you. 

C++ Program: To find the size of the different data types: int, float, char and double in the C++ language

Introduction:

The respective program is used to find the size of the different data types such as int, float, char, and double in C++ language. It is a useful program that can be grasped easily. It is also one of the fundamental programmes that are taught to a newbie. Knowing the size of different data types allows you to experiment with different values. The size of the data types (variables) is found out with the help of the a operator known as the sizeof operator. 

Code:

The following is the code that can be used for the C++ Program: To find the size of the different data types: int, float, char and double in the C++ language

#include <iostream>
using namespace std;

int main() 
{    
   cout << "Size of int: " << sizeof(int) << " bytes" << endl;
   cout << "Size of float: " << sizeof(float) << " bytes" << endl;
   cout << "Size of char: " << sizeof(char) << " byte" << endl;
   cout << "Size of double: " << sizeof(double) << " bytes" << endl;

    return 0;
}

Output:

Size of int: 4 byte

Size of float: 4 bytes

Size of char: 1 bytes

Size of double: 8 bytes

Explanation: 

Let us now understand how the following code works.

  1. cout << “Size of int: ” << sizeof(int) << ” bytes” << endl;: In C++, a cout object is an object of the iostream class. The header file of iostream is where the cout object is defined. There is a lot of data (strings) that you want to display or print on the screen; the cout object is used for printing the string value defined inside the quotation marks “” on the screen. << are known as the insertion operator. The sizeof operator is the operator that is used to find the size of the variable data types. The sizeof operator is a compile-time operator. It is mainly used to find the size of any variables or data types in bytes. The syntax for the sizeof operator is sizeof(data type). The endl is a function that is used for manipulating C++. The endl function is mainly used to insert a new line, meaning the output for the next statement is printed in the next line instead of continuing in the same line. In simple words, it breaks the line character and flushes the stream. 
  1. It is very important to maintain the order of the statement starting with the cout object (object of class iostream, mentioned in the header file), then comes the insertion operators <<, followed by the string inside the quotation marks, which in this case is the “Size of the name of the data type”, then again insertion operators <<, followed by the sizeof operator were inside the brackets datatype is mentioned, then insertion operators and finally endl to break the line and insert a new line before mentioning the string “byte/bytes”. 

Conclusion:

  1. Use insertion operators properly as it is confusing for the beginners.

C++ Program: To swap any two numbers 

Introduction:

The respective program is used to swap any two numbers that are given to the program. This program is an interesting program to learn and can be applied in many other important programs. It is also a fundamental program and has hidden potential. The program can be executed in two forms where in the first, the values that are swapped are temporary values, and in the second, the values swapped are not temporary values. 

Code: 

The following is the code that can be used for the C++ Program: To swap any two numbers (temporary numbers)

//temporary variables
#include <iostream>
using namespace std;

int main()
{
    int x =2, y =3, new;

    cout << "Initial case" << endl;
    cout << "x = " << x << ", y = " << y << endl;

    new = x;
    x = y;
    y = new;

    cout << "\nFinal case" << endl;
    cout << "x = " << x << ", y = " << y << endl;

    return 0;
}

Output: 

Initial case

x = 2, y = 3

Final case

x = 3, y = 2

The following is the code that can be used for the C++ Program: To swap any two numbers (not temporary numbers) 

//values that are not temporary 
#include <iostream>
using namespace std;

int main()
{
    
    int x =2, y =3;

    cout << "Initial value" << endl;
    cout << "x = " << x << ", y = " << y << endl;

    x = x + y;
    y = x - y;
    x = x - y;

    cout << "\nFinal Value" << endl;
    cout << " x  = " << x << ", y = " << y << endl;

    return 0;
}

Output:

Initial case

x = 2, y = 3

Final case

x = 3, y = 2

Explanation: 

Let us now understand how the following code works.

  1. C++ Program: To swap any two temporary numbers
    1. The program requires variables for which appropriate data types are declared. The following code makes use of three variables to be specific but requires the value for any two variables. The third variable in the following case is used to store the value of the first variable, which in the respective code is declared by a and has a value of 2. Then the value of the second variable is copied to the first variable. Now in order to complete the swapping process, the value of the new variable is copied back to the second variable. If the above three steps are analyzed properly, you can observe that the values of the two variables, x, and y, are interchanged or, in simple words, swapped. 
    2. The respective code uses simple definitions instead of making use of any arithmetic equation. It is a simpler process and can be implemented by a beginner. 
    3. Remember to maintain the order of the cout object statements, as any error made while defining these statements will result in a failed execution of the respective code. 
  2. C++ Program: To swap any two numbers that are not temporary
    1. The respective program only requires the two varthat are needed to be swapped. The program makes use of arithmetic equations to carry the swapping process. The first equation defines a new value for the variable x where the respective variable is equal to the sum of the first variable x and the second variable y. Then the second equation is where the variable y is assigned with the value of the variable x. The following result is achieved by equating y with the subtraction of the variable x (where x = x + y) and the variable y resulting in the output y = x. Finally, the process of swapping is completed by defining the third equation where the variable x is assigned with the value of the variable y. This is achieved by equating the variable x with the difference of the variable x (where x = x + y) and the variable y (where y = x – y), resulting in the output x = y. 
    2. The respective code makes use of simple arithmetic manipulating equations that can be easily explained to any beginner. Such programs have hidden potential and can be explored and experimented with once you have a good grasp of C++ programming. 
    3. Remember to maintain the order of the cout object statements, as any error made while defining these statements will result in a failed execution of the respective code.

Conclusion:

  1. Pay attention while defining statements and arithmetic equations. As any error made will result in a failed execution of the respective code. 
  2. Try to explore these programs as they will provide you with a better understanding of C++ programming. 

C++ Program: To find if the given number is odd or even

Introduction:

The respective program is used to find if the given number is either odd or even. It is a C++ program that makes use of if-else statements to check if the number provided by you is either odd or even. Now, how to tell a C++ program to identify even and odd numbers from each other. We can make use of the definitions for the following terms: even number and odd number, even number is a number which is perfectly divisible by two and has zero has its remainder, whereas the odd number is a number which is not perfectly divisible by two and has remainder other than zero. 

To check whether the provided number is even or odd, a modulus operator is used. If the remainder value is zero, then the respective number is an even number, and if the value of the remainder is non-zero, then the respective number is an odd number. 

Code:

The following is the code that can be used for the C++ Program: To find if the given number is odd or even (using if else statements)

//using if else statement
#include <iostream>
using namespace std;

int main() {
  int x;

  cout << "Input Value: ";
  cin >> x;

  if ( x % 2 == 0)
    cout << x << " the number is even.";
  else
    cout << x << " the number is odd.";

  return 0;
}

Output:

Input Value: 34

34 the number is even.

The following is the code that can be used for the C++ Program: To find if the given number is odd or even (using ternary operators)

//using ternary operators
#include <iostream>
using namespace std;

int main() {
  int x;

  cout << "Input Value: ";
  cin >> x;
    
  (x % 2 == 0) ? cout << x << "the number is even." :  cout << x << "the number is odd.";
    
  return 0;
}

Output:

Input Value: 34

34 the number is even.

Explanation: 

Let us now understand how the following code works.

  1. C++ Program: To find if the given number is odd or even (using if else statements)
    1. If statement: To evaluate any expression, whether it is true or false, you can use C++ if statements. When the provided expression is true, the program is executed according to the condition of the expression or, also known as the conditional statement. And when the provided expression is false, the program is not executed according to the condition of the expression. These statements are very important as they are used in various programs including some complex programs. 
  2. Syntax for If statements
if (the expression) {
	// Code here
}

  1. If else statement: When the expression or the conditional statement provided in the if statement is true, then there is no problem, the program is executed smoothly, and the required result is obtained. But in situations when the conditional statement provided is false, the program does nothing. In reality, there is always something that you want the program to do when the if statement is false. You can make use of the else statements. When the value of the if statement is false, then the program is executed according to the expression defined in the else statement. This provides you with a more range of motion in the sense that you can use two separate situations to work where the latter situation is dependent on a specific value of the former situation. 
  2. Syntax for If else statements
if (the expression) {
	// Execute code
} else {
	//Execute other code
}

  1. Nested Else if statements: The above two statements can be used for single conditions but cannot be exploited for multiple conditions. If you want to execute your program for multiple conditions and want to eliminate long scripts of coding, you can use nested else if statements. Syntax for Nested Else if statements: 
if (the first expression) {
	// When the condition for the if statement is true, write the code to be executed for the respective situation
} else if (the second expression) {
	// When the condition for the if statement is false and the condition for the else if statement is true, write the code to be executed for the respective situation
} else {
	// When the condition for all the above mentioned statements are false, write the code to execute for the respective situation
}

  1. if ( x % 2 == 0): The expression of the respective if situations states that if the number provided by the user has the value of remainder equal to zero when it is divided by 2, then the input number is even. 
  2. C++ Program: To find if the given number is odd or even (using ternary operators)
    1. If statements, If else statements, and Nested else if statements are great tools, but in some cases, the syntax for the respective statements can become lengthy and also confusing for beginners. This can give rise to big issues such as wastage of time in writing the syntax for such lengthy programs or finding the error, or making sure each and every statement is written properly. The respective problem can be eliminated with the help of ternary operators. 

Ternary operators have similar functions to that of if-else statements but have much simpler syntax when compared to the syntax of if-else statements. The ternary operator uses the condition ( depending upon the result of the respective condition) provided by you to execute the block of code. The ternary operator is made up of three operands. The first is the condition; then it is the first expression: expression 1, and finally the second expression: expression 2. If the value of the condition statement provided by you is true, then the first expression: expression 1, is executed. And, when the value of the conditional statement provided by you is false, then the second expression: expression 2, is executed. 

  • Syntax for Ternary Operators:
    1. condition ? expression1 : expression2;

Conclusion:

  1. There are multiple ways to solve conditional situation-based problems. Try to experiment with all the possibilities of the if-else statements. The more you practice these statements, the more you get better at implementing these statements. 
  2. Remember to make your code simple. Overcomplicating the syntax can lead to a wastage of time. The more complicated the syntax gets, the probability of making errors difficult to identify increases. 
  3. Remember to switch between if-else statements and the ternary operators. Use them appropriately to save you time and energy. 

C++ Program: To find if the given character is a vowel or a consonant 

Introduction:

The respective code is used to find if the given character is a vowel or a consonant. It is also a C++ program that makes use of if-else statements to achieve the above-stated task. But how can a program identify if the character provided by the user is a vowel or a consonant, and also how does the program know how to differentiate between lowercase and uppercase characters as the input provided by the user can be capital or in lowercase? To achieve this, you can make use of if-else statements. But first, the program should know what the alphabets that are considered to be vowels are. A, E, I, O, U are the five alphabets that are known as vowels. The remaining alphabets are called consonants. With the basic information, we can write expressions using if-else statements to tell the program to differentiate between vowels and consonants. 

Code:

The following is the code that can be used for the C++ Program: To find if the given character is a vowel or a consonant 

#include <iostream>
using namespace std;

int main() {
    char x;
    bool LowercaseVowel, UppercaseVowel;

    cout << "Input character: ";
    cin >> x;

    // If the character (vowel)  is in lowercase then the value evaluates to 1 also considered to be true. 
    LowercaseVowel = (x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u');

    // If the character (vowel) is in uppercase then the value evaluates to 1 also considered to be true.
    UppercaseVowel = (x == 'A' || x == 'E' || x == 'I' || x == 'O' || c == 'U');

    //If the input character is not an alphabet then the error message is printed. 
    if (!isalpha(x))
      printf("Input character non alphabetic");
    else if (LowercaseVowel || UppercaseVowel)
        cout << x << " is considered to be a vowel.";
    else
        cout << x << " is considered to be a consonant.";

    return 0;
}

Output: 

Input character: i

i is considered to be a vowel. 

Explanation: 

Let us now understand how the following code works.

  1. char x;: The above program requires the input value to be a character. As we already know, there are different data types, and each data type has its own specific acceptable value inputs. The data type char will be used because the input value demanded by the program to execute smoothly is a character value, and the char data type accepts character input values. The variable defined for the character input value is x, meaning any character input value provided by the user will be stored in the variable x. 
  2. bool LowercaseVowel, UppercaseVowel;: bool is data type in C++. These data types are defined to hold boolean values such as true and false. The true value is defined by the number 1, and the false value is defined by the number 0. The two variables that are defined are LowercaseVowel and UppercaseVowel. Meaning any character input independent of the case will be considered to be a true value. 
  3. LowercaseVowel = (x == ‘a’ || x == ‘e’ || x == ‘i’ || x == ‘o’ || x == ‘u’);/ UppercaseVowel = (x == ‘A’ || x == ‘E’ || x == ‘I’ || x == ‘O’ || c == ‘U’);: the bool variable ls are defined in the respective statements. Meaning if the input character provided by the user is one of a, e, i, o, u or A, E, I, O, U, then the input character value will be considered to be a vowel, and if the input char is not one of the above-mentioned alphabets, then the input character value will be considered to be consonant. 
  4. if (!isalpha(x)): The question arises how will the program know whether the input character value provided by the user is an alphabet or not. For this isalpha() function is used. The isalpha() function is used to identify if the input character is an alphabet or some other, not acceptable character. The error message is printed if the character value is not an alphabet. 

Conclusion:

  1. Pay close attention while writing the syntax as beginners make many errors resulting in a failed execution of the code.
  2. You can experiment with if-else statements and also try to explore other ways the following problem can be solved. 

We hope you are able to grasp the basic concepts of C++ programming and also simultaneously practice a few simple C++ programs. Always remember to study the concepts before implementing them, as having a stronghold on the concepts of the C++ program allows you to experiment with the code and also makes C++ programming interesting and enjoyable. Visit the Great Learning website to learn the C++ language through our free online courses: Great Learning. If you want to learn C++ in Hindi, visit: C++ Programming in Hindi – Great Learning.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top