C++ Basic tutorial
1. Write a program in C++ to print welcome text on a
separate line.
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Print a welcome text in a separate line
:\n";
cout << "----------------------------------------------\n";
cout << " Welcome to \n" ;
cout << " w3resource.com "<<endl ;
}
2. Write a program in C++ to print the sum of two numbers.
Sample Output:
Print the sum of two numbers :
-----------------------------------
The sum of 29 and 30 is : 59
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Print the sum of two numbers :\n";
cout << "-----------------------------------\n";
cout << " The sum of 29 and 30 is : "<< 29+30 <<"\n\n" ;
}
3. Write a in C++ program to find the size of fundamental
data types.
Sample Output:
Find Size of fundamental data types :
------------------------------------------
The sizeof(char) is : 1 bytes
The sizeof(short) is : 2 bytes
The sizeof(int) is : 4 bytes
The sizeof(long) is : 8 bytes
The sizeof(long long) is : 8 bytes
The sizeof(float) is : 4 bytes
The sizeof(double) is : 8 bytes
The sizeof(long double) is : 16 bytes
The sizeof(bool) is : 1 bytes
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Find Size of fundamental data types :\n";
cout << "------------------------------------------\n";
cout << " The sizeof(char) is : " << sizeof(char)
<< " bytes \n" ;
cout << " The sizeof(short) is : " << sizeof(short)
<< " bytes \n" ;
cout << " The sizeof(int) is : " << sizeof(int) << "
bytes \n" ;
cout << " The sizeof(long) is : " << sizeof(long)
<< " bytes \n" ;
cout << " The sizeof(long long) is : " << sizeof(long
long) << " bytes \n";
cout << " The sizeof(float) is : " << sizeof(float)
<< " bytes \n" ;
cout << " The sizeof(double) is : " <<
sizeof(double) << " bytes \n";
cout << " The sizeof(long double) is : " << sizeof(long
double) << " bytes \n";
cout << " The sizeof(bool) is : " << sizeof(bool)
<< " bytes \n\n";
return 0;
}
4. Write a program in C++ to print the sum of two numbers
using variables.
Print the sum of two numbers :
-----------------------------------
The sum of 29 and 30 is : 59
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Print the sum of two numbers :\n";
cout << "-----------------------------------\n";
int a;
int b;
int sum;
a=29;
b=30;
sum=a+b;
cout << " The sum of "<< a << " and "<<b <<" is : "<<
sum <<"\n\n" ;
}
5. Write a C++ program that checks whether primitive
values cross the limit.
Check whether the primitive values crossing the limits or
not:
--------------------------------------------------------------------
The Gender is : F
Is she married? : 1
Number of sons she has : 2
Year of her appointment : 2009
Salary for a year : 1500000
Height is : 79.48
GPA is 4.69
Salary drawn upto : 12047235
Balance till : 995324987
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Check whether the primitive values crossing
the limits or not :\n";
cout << "---------------------------------------------------------
-----------\n";
char gender = 'F'; // char is single-quoted
bool isEmployed = true; // true(non-zero) or false(0)
unsigned short numOfsons = 2; // [0, 255]
short yearOfAppt = 2009; // [-32767, 32768]
unsigned int YearlyPackage = 1500000; // [0,
4294967295]
double height = 79.48; // With fractional part
float gpa = 4.69f; // Need suffix 'f' for float
long totalDrawan = 12047235L; // Suffix 'L' for long
long long balance = 995324987LL; // Need suffix 'LL' for
long long int
cout << " The Gender is : " << gender << endl;
cout << " Is she married? : " << isEmployed << endl;
cout << " Number of sons she has : " << numOfsons <<
endl;
cout << " Year of her appointment : " << yearOfAppt <<
endl;
cout << " Salary for a year : " << YearlyPackage << endl;
cout << " Height is : " << height << endl;
cout << " GPA is " << gpa << endl;
cout << " Salary drawn upto : " << totalDrawan << endl;
cout << " Balance till : " << balance << endl;
return 0;
}
13. Write a C++ program that swaps two numbers.
Sample Output:
Swap two numbers :
-----------------------
Input 1st number : 25
Input 2nd number : 39
After swapping the 1st number is : 39
After swapping the 2nd number is : 25
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Swap two numbers :\n";
cout << "-----------------------\n";
int num1, num2, temp;
cout << " Input 1st number : ";
cin >> num1 ;
cout << " Input 2nd number : ";
cin >> num2;
temp=num2;
num2=num1;
num1=temp;
cout << " After swapping the 1st number is : "<< num1
<<"\n" ;
cout << " After swapping the 2nd number is : "<< num2
<<"\n\n" ;
}
14. Write a C++ program that calculates the volume of a
sphere.
Sample Output:
Calculate the volume of a sphere :
---------------------------------------
Input the radius of a sphere : 6
The volume of a sphere is : 904.32
#include <iostream>
using namespace std;
int main()
{
int rad1;
float volsp;
cout << "\n\n Calculate the volume of a sphere
:\n";
cout << "---------------------------------------\n";
cout<<" Input the radius of a sphere : ";
cin>>rad1;
volsp=(4*3.14*rad1*rad1*rad1)/3;
cout<<" The volume of a sphere is : "<< volsp << endl;
cout << endl;
return 0;
}
17. Write a C++ program to find the Area and Perimeter of a
Rectangle.
Sample Output:
Find the Area and Perimeter of a Rectangle :
-------------------------------------------------
Input the length of the rectangle : 10
Input the width of the rectangle : 15
The area of the rectangle is : 150
The perimeter of the rectangle is : 50
#include <iostream>
using namespace std;
int main()
{
int width, lngth, area, peri;
cout << "\n\n Find the Area and Perimeter of a
Rectangle :\n";
cout << "-------------------------------------------------
\n";
cout<<" Input the length of the rectangle : ";
cin>>lngth;
cout<<" Input the width of the rectangle : ";
cin>>width;
area=(lngth*width);
peri=2*(lngth+width);
cout<<" The area of the rectangle is : "<< area <<
endl;
cout<<" The perimeter of the rectangle is : "<< peri <<
endl;
cout << endl;
return 0;
}
20. Write a C++ program to convert temperature in Celsius to
Fahrenheit.
Sample Output:
Convert temperature in Celsius to Fahrenheit :
---------------------------------------------------
Input the temperature in Celsius : 35
The temperature in Celsius : 35
The temperature in Fahrenheit : 95
#include <iostream>
using namespace std;
int main()
{
float frh, cel;
cout << "\n\n Convert temperature in Celsius to
Fahrenheit :\n";
cout << "---------------------------------------------------
\n";
cout << " Input the temperature in Celsius : ";
cin >> cel;
frh = (cel * 9.0) / 5.0 + 32;
cout << " The temperature in Celsius : " << cel << endl;
cout << " The temperature in Fahrenheit : " << frh <<
endl;
cout << endl;
return 0;
}
21. Write a C++ program to convert temperature in Fahrenheit
to Celsius.
Sample Output:
Convert temperature in Fahrenheit to Celsius :
---------------------------------------------------
Input the temperature in Fahrenheit : 95
The temperature in Fahrenheit : 95
The temperature in Celsius : 35
#include <iostream>
using namespace std;
int main()
{
float frh, cel;
cout << "\n\n Convert temperature in Fahrenheit to
Celsius :\n";
cout << "---------------------------------------------------\n";
cout << " Input the temperature in Fahrenheit : ";
cin >> frh;
cel = ((frh * 5.0)-(5.0 * 32))/9;
cout << " The temperature in Fahrenheit : " << frh << endl;
cout << " The temperature in Celsius : " << cel << endl;
cout << endl;
return 0;
}
23. Write a program in C++ that converts kilometers per hour
to miles per hour.
Sample Output:
Convert kilometers per hour to miles per hour :
----------------------------------------------------
Input the distance in kilometer : 25
The 25 Km./hr. means 15.5343 Miles/hr.
#include <iostream>
using namespace std;
int main()
{
float kmph, miph;
cout << "\n\n Convert kilometers per hour to miles per
hour :\n";
cout << "----------------------------------------------------\n";
cout << " Input the distance in kilometer : ";
cin >> kmph;
miph = (kmph * 0.6213712);
cout << " The "<< kmph <<" Km./hr. means "<< miph
<< " Miles/hr." << endl;
cout << endl;
return 0;
}
32. Write a program in C++ to check whether a number is
positive, negative or zero.
Sample Output:
Check whether a number is positive, negative or zero :
-----------------------------------------------------------
Input a number : 8
The entered number is positive.
#include <iostream>
using namespace std;
int main()
{
signed long num1 = 0;
cout << "\n\n Check whether a number is positive,
negative or zero :\n";
cout << "---------------------------------------------------------\n";
cout << " Input a number : ";
cin >> num1;
if(num1 > 0)
{
cout << " The entered number is positive.\n\n";
}
else if(num1 < 0)
{
cout << " The entered number is negative.\n\n";
}
else
{
std::cout << " The number is zero.\n\n";
}
return 0;
}
34. Write a C++ program to display the current date and time.
Sample Output:
Display the Current Date and Time :
----------------------------------------
seconds = 57
minutes = 33
hours = 12
day of month = 6
month of year = 7
year = 2017
weekday = 4
day of year = 186
daylight savings = 0
Current Date: 6/7/2017
Current Time: 12:33:57
#include<iostream>
#include<cmath>
#include <ctime>
using namespace std;
int main()
{
time_t t = time(NULL);
tm* tPtr = localtime(&t);
cout << "\n\n Display the Current Date and Time :\n";
cout << "----------------------------------------\n";
cout << " seconds = " << (tPtr->tm_sec) << endl;
cout << " minutes = " << (tPtr->tm_min) << endl;
cout << " hours = " << (tPtr->tm_hour) << endl;
cout << " day of month = " << (tPtr->tm_mday) << endl;
cout << " month of year = " << (tPtr->tm_mon)+1 << endl;
cout << " year = " << (tPtr->tm_year)+1900 << endl;
cout << " weekday = " << (tPtr->tm_wday )<< endl;
cout << " day of year = " << (tPtr->tm_yday )<< endl;
cout << " daylight savings = " <<(tPtr->tm_isdst )<< endl;
cout << endl;
cout << endl;
cout << " Current Date: " <<(tPtr->tm_mday)<<"/"<<
(tPtr->tm_mon)+1 <<"/"<< (tPtr->tm_year)+1900<< endl;
cout << " Current Time: " << (tPtr->tm_hour)<<":"<<
(tPtr->tm_min)<<":"<< (tPtr->tm_sec) << endl;
cout << endl;
return 0;
}
37. Write a C++ program to print a mystery series from 1 to
50.
Sample Output:
Print a mystery series:
-------------------------
The series are:
5 4 2 7 11 10 8 13 17 16 14 19 23 22 20 25 29 28 26 31 35 34
32 37 41 4 0 38 43 47 46 44 49
#include <iostream>
using namespace std;
int main()
cout << "\n\n Print a mystery series:\n";
cout << "-------------------------\n";
cout << " The series are: \n";
int nm1 = 1;
while (true)
++nm1;
if ((nm1 % 3) == 0)
continue;
if (nm1 == 50)
break;
if ((nm1 % 2) == 0)
nm1 += 3;
else
nm1 -= 3;
cout << nm1 << " ";
cout << endl;
return 0;
}
38. Write a C++ program that takes a number as input and
prints its multiplication table up to 10.
Sample Output:
Print the multiplication table of a number upto 10:
--------------------------------------------------------
Input a number: 5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
#include <iostream>
using namespace std;
int main()
int a,i=0;
cout << "\n\n Print the multiplication table of a number upto 10:\n";
cout << "--------------------------------------------------------\n";
cout << " Input a number: ";
cin>> a;
for (i=1;i<=10;i++)
{
cout << a<<" x "<< i << " = "<<a*i<<"\n" ;
39. Write a C++ program to print the following pattern.
Sample Output:
xxxxx
x x x x
x x x
x xxxxxxx xxxxxxx
x x x
x x x x
xxxxx
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Print the following pattern:\n";
cout << "--------------------------------\n";
cout << " xxxxx\n";
cout << "x x x x\n";
cout << "x x x\n";
cout << "x xxxxxxx xxxxxxx\n";
cout << "x x x\n";
cout << "x x x x\n";
cout << " xxxxx\n";
}
41. Write a C++ program to print an American flag on the
screen.
Sample Output:
Print the American flag:
-----------------------------
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
* * * * * ==================================
* * * * * * ==================================
==============================================
==============================================
==============================================
==============================================
==============================================
==============================================
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Print the American flag:\n";
cout << "-----------------------------\n";
cout <<"* * * * * * =================================="<<"\n";
cout <<" * * * * * =================================="<<"\n";
cout <<"* * * * * * =================================="<<"\n";
cout <<" * * * * * =================================="<<"\n";
cout <<"* * * * * * =================================="<<"\n";
cout <<" * * * * * =================================="<<"\n";
cout <<"* * * * * * =================================="<<"\n";
cout <<" * * * * * =================================="<<"\n";
cout <<"* * * * * * =================================="<<"\n";
cout <<"=============================================="<<"\n";
cout <<"=============================================="<<"\n";
cout <<"=============================================="<<"\n";
cout <<"=============================================="<<"\n";
cout <<"=============================================="<<"\n";
cout
<<"=============================================="<<"\n";
}
42. Write a C++ program that accepts the user's first and last
name and prints them in reverse order with a space between
them.
Sample Output:
Print the name in reverse where last name comes first:
-----------------------------------------------------------
Input First Name: Alexandra
Input Last Name: Abramov
Name in reverse is: Abramov Alexandra
# include <iostream>
# include <string>
using namespace std;
int main()
{
char fname[30], lname [30];
cout << "\n\n Print the name in reverse where last name comes
first:\n";
cout << "-----------------------------------------------------------\n";
cout << " Input First Name: ";
cin >> fname;
cout << " Input Last Name: ";
cin >> lname;
cout << " Name in reverse is: "<< lname << " "<< fname <<endl;
cout << endl;
return 0;
}
54. Write a C++ program to enter P, T, R and calculate Simple
Interest.
Sample Output:
Calculate the Simple Interest :
-----------------------------------
Input the Principle: 20000
Input the Rate of Interest: 10
Input the Time: 1.5
The Simple interest for the amount 20000 for 1 years @ 10 %
is: 2000
#include<iostream>
using namespace std;
int main()
int p,r,t,i;
cout << "\n\n Calculate the Simple Interest :\n";
cout << " -----------------------------------\n";
cout<<" Input the Principle: ";
cin>>p;
cout<<" Input the Rate of Interest: ";
cin>>r;
cout<<" Input the Time: ";
cin>>t;
i=(p*r*t)/100;
cout<<" The Simple interest for the amount "<<p<<" for
"<<t<<" years @ "<<r<<" % is: "<<i;
cout << endl;
return 0;
56. Write a C++ program to show the manipulation of a string.
Sample Output:
Show the manipulation of a string:
-------------------------------------
The string:: welcome, w3resource
The length of the string:: 19
The char at index 1 of the string:: e
The char at index 1 of the string [using array ]:: e
Is the string empty:: 0
Retrieve the sub-string from 3rd position for 4 characters:: come
The sub-string replace by 'went':: welwent, w3resource
Append a string 'end' at last of the string:: welwent, w3resource end
Append a string 'end' at last of the string using operator:: welwent,
w3resource end end
The string 'insert' inserting at 3rd position of the string:: wel inse rt
went, w3resource end
The new string is:: wel insert went, w3resource end
Input a sentence:: The quick brown fox jumps over the lazy dog.
The quick brown fox jumps over the lazy dog.
#include <iostream>
#include <string>
using namespace std;
int main()
cout << "\n\n Show the manipulation of a string:\n";
cout << " -------------------------------------\n";
string txt = "welcome, w3resource";
cout <<" The string:: "<< txt << endl;
cout <<" The length of the string:: "<< txt.length() << endl;
cout <<" The char at index 1 of the string:: "<< txt.at(1) << endl;
cout <<" The char at index 1 of the string [using array ]:: "<< txt[1] <<
endl;
cout <<" Is the string empty:: "<< txt.empty() << endl;
cout <<" Retrieve the sub-string from 3rd position for 4 characters:: "<<
txt.substr(3, 4) << endl;
cout <<" The sub-string replace by 'went':: "<< txt.replace(3, 4, "went") <<
endl;
cout <<" Append a string ' end' at last of the string:: "<< txt.append("
end") << endl;
cout <<" Append a string ' end' at last of the string using operator:: "<< txt
+ " end" << endl;
cout <<" The string ' insert ' inserting at 3rd position of the string:: "<<
txt.insert(3, " insert ") << endl;
string txt1;
txt1 = txt;
cout <<" The new string is:: "<< txt1 << endl;
cout << " Input a sentence:: ";
getline(cin, txt);
cout << txt << endl<< endl;
59. Write a C++ program to compute the distance between
two points on the surface of the earth.
Sample Output:
Print the the distance between two points on the surface of
earth:
-----------------------------------------------------------------------
Input the latitude of coordinate 1: 25
Input the longitude of coordinate 1: 35
Input the latitude of coordinate 2: 35.5
Input the longitude of coordinate 2: 25.5
The distance between those points is: 1480.08
#include <iostream>
#include <math.h>
using namespace std;
int main()
double d,la1,la2,lo1,lo2,er,r;
cout << "\n\n Print the the distance between two points on the
surface of earth:\n";
cout << "------------------------------------------------------------\n";
cout << " Input the latitude of coordinate 1: ";
cin>> la1;
cout << " Input the longitude of coordinate 1: ";
cin>> lo1;
cout << " Input the latitude of coordinate 2: ";
cin>> la2;
cout << " Input the longitude of coordinate 2: ";
cin>> lo2;
r=0.01745327; //Pi/180=3.14159/180
la1=la1*r;
la2=la2*r;
lo1=lo1*r;
lo2=lo2*r;
er=6371.01; //Kilometers
d=er * acos((sin(la1)*sin(la2)) + (cos(la1)*cos(la2)*cos(lo1 -
lo2)));
cout<<" The distance between those points is: "<<d<<"\n";
62. Write a C++ program that reads the integer n and prints a
twin prime that has the maximum size among twin primes less
than or equal to n.
According to wikipedia "A twin prime is a prime number that
is either 2 less or 2 more than another prime number" for
example, either member of the twin prime pair (41, 43). In
other words, a twin prime is a prime that has a prime gap of
two".
#include <iostream>
#include <cmath>
using namespace std;
int main() {
const int num_primes = 10005;
bool primes[num_primes];
for (int i = 2; i != num_primes; ++i) {
primes[i] = true;
for (int i = 2; i != int(sqrt(num_primes)); ++i) {
if (primes[i]) {
for (int j = 2; i * j < num_primes; ++j) {
primes[i*j] = false;
int n;
cout << "Input an integer:\n";
cin >> n;
cout << "Twin primes are:\n";
for (int i = n; i - 2 >= 0; --i) {
if (primes[i] && primes[i-2]) {
cout << i-2 << " " << i << endl;
break;
return 0;