C++ is one of the world’s most widely embraced programming languages. In this article, we will delve into some fundamental C++ programs ideal for newcomers to the language. Emerging in the early 1980s as an extension of the C programming language, C++ has garnered immense popularity for its versatility. It is extensively employed in crafting various applications, from system software, game development, and embedded systems to high-performance applications and beyond.
The strength of C++ lies in its ability to seamlessly blend high-level and low-level programming features, thereby striking an optimal equilibrium between performance and abstraction. Developers relish its support for procedural, object-oriented, and generic programming paradigms, which affords them the creative freedom to design and implement solutions as per their specific requirements.
1. Print Number Entered by User
#include <iostream> using namespace std; int main() { int number; cout << "Enter an integer: "; cin >> number; Cout << nunber; return 0;
}
2. C++ program to Check if a number is even or odd.
TO Check if a given number is even or odd in C++, we simply divide the given number by 2, if the remainder is 0 then it is even otherwise odd.
#include <iostream>
using namespace std;
int main() {
int a ;
cin>>a;
if(a%2 == 0) // if remainder is zero then even number
cout<<”even”;
else
cout<<”odd”;
return 0;
}
Input: 8
Output: even
3. Write a program to swap two numbers in C++.
We will use a temporary variable to store one of the numbers to perform the swap operation.
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
cout<<a<<" "<<b<<endl;
int temp = a;
a = b;
b = temp;
cout<<a<<" "<<b<<endl;
return 0;
}
Output: 10 20
20 10
4. Here is the source code of C++ Program to Check if a Number is Even.
#include<iostream>
using namespace std;
int main ()
{
int num;
cout << "Enter the number to be checked : ";
cin >> num;
if (num % 2 == 0)
cout << num << " is Even.";
else
cout << num << " is Not Even ";
return 0;
}
5. Write a program to swap two numbers in C++.
We will use a temporary variable to store one of the numbers to perform the swap operation.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
cout<<a<<” “<<b<<endl;
int temp = a;
a = b;
b = temp;
cout<<a<<” “<<b<<endl;
return 0;
}
Output: 10 20
20 10
Sample C++ Programs for Beginners
Basic Computer Engineering – Study Material
Lecture – 1
Lecture – 2
Lecture – 3
Lecture – 4
Lecture – 5
Lecture – 6