A Journey to
C++ Programming
Learning with Examples
Dr. Budditha Hettige
BSc, MPhil, PhD
A Journey to
C++ Programming
Learning with Examples
Dr. Budditha Hettige
i|Page
A Journey to
C++ Programming
Learning with Examples
Dr. Budditha Hettige
ii| C++ Programming with Examples
Table of Contents
Input Output and Data Types ...................................................... 1
Example 01: Input and Output ................................................ 1
Example 02: Input and Output ................................................ 3
Example 03: print the biggest number .................................... 4
Example 04: biggest number of the 3 given numbers ............. 6
Example 05: print the grade for a given mark ......................... 8
Example 06: print the name of a month ................................ 11
Example 07: print the name of the day ................................. 13
Example 08: display a given date .......................................... 17
Example 09: print the bill for an item ................................... 22
For, while, do-while Loops ....................................................... 25
Example 10: find the factorial ............................................... 25
Example 11: accept numbers until the user enters ................ 26
Example 12: check given number is Palindrome .................. 28
Example 13: read N number of integers................................ 29
Example 14: find the total and average ................................. 32
Example 15: Compute the gross pay ..................................... 35
iii| C++ Programming with Examples
1
Input Output and Data Types
Example 01: Input and Output
Write a C++ program to calculate and display total amount of the given
unit price and quantity of an item.
#include <iostream>
using namespace std;
int main() {
double unitPrice;
int quantity;
double totalAmount;
// Get the unit price from the user
cout << "Enter the unit price of the item: ";
cin >> unitPrice;
1| C++ Programming with Examples
// Get the quantity from the user
cout << "Enter the quantity of the item: ";
cin >> quantity;
// Calculate the total amount
totalAmount = unitPrice * quantity;
// Display the total amount
cout << "Total amount: $" << totalAmount << endl;
return 0;
}
Output of the Program
2| C++ Programming with Examples
Example 02: Input and Output
Write a C++ program to read an examination mark from keyboard and
print “pass” if mark >= 40.
#include <iostream>
using namespace std;
int main() {
int mark;
// Read the examination mark from the keyboard
cout << "Enter the examination mark: ";
cin >> mark;
// Check if the mark is greater than or equal to 40
if (mark >= 40) {
cout << "pass" << endl;
} else {
cout << "fail" << endl;
}
return 0;
}
3| C++ Programming with Examples
Example 03: Print the biggest number
Write a C++ program to print the biggest number of the two given
numbers
4| C++ Programming with Examples
int main() {
int num1, num2;
// Read two numbers from the keyboard
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
// Determine and print the biggest number
if (num1 > num2) {
cout << "The biggest number is: " << num1 << endl;
} else if (num2 > num1) {
cout << "The biggest number is: " << num2 << endl;
} else {
cout << "Both numbers are equal." << endl;
}
return 0;
}
5| C++ Programming with Examples
Example 04: Piggest number of the 3 given numbers
Write a C++ program to print the biggest number of the 3 given numbers
#include <iostream>
using namespace std;
6| C++ Programming with Examples
int main() {
// Declare variables to hold the three numbers
int num1, num2, num3;
// Ask the user to input the three numbers
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
cout << "Enter the third number: ";
cin >> num3;
// Determine the biggest number and print it
if (num1 >= num2 && num1 >= num3) {
cout << "The biggest number is: " << num1 << endl;
} else if (num2 >= num1 && num2 >= num3) {
cout << "The biggest number is: " << num2 << endl;
} else {
cout << "The biggest number is: " << num3 << endl;
}
return 0;
7| C++ Programming with Examples
}
Example 05: Print the grade for a given mark
Write a C++ program to print the grade for a given mark.
#include <iostream>
using namespace std;
8| C++ Programming with Examples
int main() {
// Declare a variable to hold the mark
int mark;
// Ask the user to input the mark
cout << "Enter the mark: ";
cin >> mark;
// Determine the grade and print it
if (mark >= 90 && mark <= 100) {
cout << "Grade: A" << endl;
} else if (mark >= 80 && mark < 90) {
cout << "Grade: B" << endl;
} else if (mark >= 70 && mark < 80) {
cout << "Grade: C" << endl;
} else if (mark >= 60 && mark < 70) {
cout << "Grade: D" << endl;
} else if (mark >= 0 && mark < 60) {
cout << "Grade: F" << endl;
} else {
cout << "Invalid mark. Please enter a mark between 0 and 100." <<
endl;
}
9| C++ Programming with Examples
return 0;
}
10| C++ Programming with Examples
Example 06: Print the name of a month
Write a C++ program that reads month as an integer and print the name
of a month.
#include <iostream>
using namespace std;
int main() {
// Declare a variable to hold the month number
int month;
// Ask the user to input the month number
cout << "Enter the month number (1-12): ";
cin >> month;
// Determine the month name and print it
switch (month) {
case 1:
cout << "January" << endl;
break;
case 2:
cout << "February" << endl;
11| C++ Programming with Examples
break;
case 3:
cout << "March" << endl;
break;
case 4:
cout << "April" << endl;
break;
case 5:
cout << "May" << endl;
break;
case 6:
cout << "June" << endl;
break;
case 7:
cout << "July" << endl;
break;
case 8:
cout << "August" << endl;
break;
case 9:
cout << "September" << endl;
break;
case 10:
12| C++ Programming with Examples
cout << "October" << endl;
break;
case 11:
cout << "November" << endl;
break;
case 12:
cout << "December" << endl;
break;
default:
cout << "Invalid month number. Please enter a number between
1 and 12." << endl;
break;
}
return 0;
}
Example 07: Print the name of the day
Write a C++ program that reads day as an integer (1-7)and print the name
Use only if-else statement and implement your solution Use switch
statement and implement your solution
#include <iostream>
using namespace std;
13| C++ Programming with Examples
int main() {
// Declare a variable to hold the day number
int day;
// Ask the user to input the day number
cout << "Enter the day number (1-7): ";
cin >> day;
// Determine the day name and print it using if-else statements
if (day == 1) {
cout << "Sunday" << endl;
} else if (day == 2) {
cout << "Monday" << endl;
} else if (day == 3) {
cout << "Tuesday" << endl;
} else if (day == 4) {
cout << "Wednesday" << endl;
} else if (day == 5) {
cout << "Thursday" << endl;
} else if (day == 6) {
cout << "Friday" << endl;
} else if (day == 7) {
14| C++ Programming with Examples
cout << "Saturday" << endl;
} else {
cout << "Invalid day number. Please enter a number between 1 and
7." << endl;
}
return 0;
}
Sample 2
#include <iostream>
using namespace std;
int main() {
// Declare a variable to hold the day number
int day;
// Ask the user to input the day number
cout << "Enter the day number (1-7): ";
cin >> day;
// Determine the day name and print it using switch statement
15| C++ Programming with Examples
switch (day) {
case 1:
cout << "Sunday" << endl;
break;
case 2:
cout << "Monday" << endl;
break;
case 3:
cout << "Tuesday" << endl;
break;
case 4:
cout << "Wednesday" << endl;
break;
case 5:
cout << "Thursday" << endl;
break;
case 6:
cout << "Friday" << endl;
break;
case 7:
cout << "Saturday" << endl;
break;
default:
16| C++ Programming with Examples
cout << "Invalid day number. Please enter a number between 1
and 7." << endl;
break;
}
return 0;
}
Example 08: Display a given date
Write a C++ program to display a given date as the following formats.
Your program should read date as the three inputs (day, month and year)
and generates the output forms.
Option 1: 21.05.2001
Option 2: 21.05.01
Option 3: 21 st May 2001
#include <iostream>
#include <string>
using namespace std;
// Function to get the suffix for the day
string getDaySuffix(int day) {
if (day >= 11 && day <= 13)
17| C++ Programming with Examples
return "th";
else if (day % 10 == 1)
return "st";
else if (day % 10 == 2)
return "nd";
else if (day % 10 == 3)
return "rd";
else
return "th";
}
int main() {
// Declare variables to hold day, month, and year
int day, month, year;
// Ask the user to input the date components
cout << "Enter day: ";
cin >> day;
cout << "Enter month: ";
cin >> month;
cout << "Enter year: ";
18| C++ Programming with Examples
cin >> year;
// Option 1: 21.05.2001
cout << "Option 1: " << (day < 10 ? "0" : "") << day << "." << (month
< 10 ? "0" : "") << month << "." << year << endl;
// Option 2: 21.05.01
cout << "Option 2: " << (day < 10 ? "0" : "") << day << "." << (month
< 10 ? "0" : "") << month << "." << (year % 100) << endl;
// Option 3: 21 st May 2001
string suffix = getDaySuffix(day);
string monthName;
switch(month) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
19| C++ Programming with Examples
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
20| C++ Programming with Examples
break;
case 12:
monthName = "December";
break;
default:
monthName = "Invalid Month";
}
cout << "Option 3: " << day << suffix << " " << monthName << " "
<< year << endl;
return 0;
}
21| C++ Programming with Examples
Example 09: Print the bill for an item
Write a C++ program to print the bill for an item bought by a customer
from a shop.
The program should ask unit price and quantity of an item and calculate
the total cost
If item quantity greater than 10 give one item free
Add 3.5 % discount for the total if total cost grater than 2500.
The bill should contain all the above information and amount of money
tendered and the correct amount of change.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Constants
const double DISCOUNT_THRESHOLD = 2500;
const double DISCOUNT_RATE = 0.035;
// Variables
double unitPrice, totalCost, discount, amountTendered, change;
int quantity, freeItems = 0;
// Input
22| C++ Programming with Examples
cout << "Enter the unit price of the item: ";
cin >> unitPrice;
cout << "Enter the quantity bought: ";
cin >> quantity;
// Calculations
if (quantity > 10) {
freeItems = 1;
}
totalCost = (quantity - freeItems) * unitPrice;
if (totalCost > DISCOUNT_THRESHOLD) {
discount = totalCost * DISCOUNT_RATE;
totalCost -= discount;
}
// Output
cout << fixed << setprecision(2);
cout << "\n=== Bill ===" << endl;
cout << "Unit Price: $" << unitPrice << endl;
cout << "Quantity: " << quantity << endl;
23| C++ Programming with Examples
cout << "Total Cost: $" << totalCost << endl;
cout << "Discount: $" << (totalCost + discount) - (quantity * unitPrice)
<< endl;
cout << "Amount Tendered: $";
cin >> amountTendered;
change = amountTendered - totalCost;
cout << "Change: $" << change << endl;
return 0;
}
24| C++ Programming with Examples
2
For, while, do-while Loops
Example 10: Find the factorial
Write a C++ program to find the factorial of a given number
#include <iostream>
using namespace std;
// Function to calculate factorial
int factorial(int n) {
if (n == 0 || n == 1)
return 1;
25| C++ Programming with Examples
else
return n * factorial(n - 1);
}
int main() {
int number;
// Input
cout << "Enter a number to find its factorial: ";
cin >> number;
// Calculate factorial
int fact = factorial(number);
// Output
cout << "Factorial of " << number << " is: " << fact << endl;
return 0;
}
Example 11: Accept numbers until the user enters
Write a C++ program to accept numbers until the user enters a 999 and
output the sum of the given numbers
26| C++ Programming with Examples
#include <iostream>
using namespace std;
int main() {
int number, sum = 0;
// Input numbers until 999 is entered
cout << "Enter numbers (enter 999 to stop):\n";
do {
cin >> number;
if (number != 999) {
sum += number;
}
} while (number != 999);
// Output the sum
cout << "Sum of the numbers: " << sum << endl;
return 0;
}
27| C++ Programming with Examples
Example 12: Check given number is Palindrome
Create a C++ program to identify the given number is Palindrome
number or not. Read number as an integer Find the number is Palindrome
or not Print the results
#include <iostream>
using namespace std;
int main() {
int number, originalNumber, reversedNumber = 0, remainder;
// Input
cout << "Enter a number: ";
cin >> number;
originalNumber = number;
// Reverse the number
while (number != 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number /= 10;
}
28| C++ Programming with Examples
// Check if the original number is equal to the reversed number
if (originalNumber == reversedNumber) {
cout << "The number " << originalNumber << " is a palindrome."
<< endl;
} else {
cout << "The number " << originalNumber << " is not a
palindrome." << endl;
}
return 0;
}
Example 13: Read N number of integers
Write a C++ program to read N number of integers and find the total and
average.
N is an input 1, 2, 3….. N
Use for, while and do-while loops
#include <iostream>
using namespace std;
int main() {
int N, number, total = 0;
29| C++ Programming with Examples
double average;
// Input the value of N
cout << "Enter the number of integers (N): ";
cin >> N;
// Using for loop
cout << "\nUsing for loop:" << endl;
total = 0; // Reset total
for (int i = 1; i <= N; ++i) {
cout << "Enter number " << i << ": ";
cin >> number;
total += number;
}
average = static_cast<double>(total) / N;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
// Using while loop
cout << "\nUsing while loop:" << endl;
total = 0; // Reset total
int count = 1;
while (count <= N) {
30| C++ Programming with Examples
cout << "Enter number " << count << ": ";
cin >> number;
total += number;
count++;
}
average = static_cast<double>(total) / N;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
// Using do-while loop
cout << "\nUsing do-while loop:" << endl;
total = 0; // Reset total
count = 1;
do {
cout << "Enter number " << count << ": ";
cin >> number;
total += number;
count++;
} while (count <= N);
average = static_cast<double>(total) / N;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
31| C++ Programming with Examples
return 0;
}
Example 14: Find the total and average
Write a C++ program to read N number of integers and find the total and
average.
N is an input 1, 2, 3….. N
Use for, while and do-while loops
#include <iostream>
using namespace std;
int main() {
int N, number, total = 0;
double average;
// Input the value of N
cout << "Enter the number of integers (N): ";
cin >> N;
32| C++ Programming with Examples
// Using for loop
cout << "\nUsing for loop:" << endl;
total = 0; // Reset total
for (int i = 1; i <= N; ++i) {
cout << "Enter number " << i << ": ";
cin >> number;
total += number;
}
average = static_cast<double>(total) / N;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
// Using while loop
cout << "\nUsing while loop:" << endl;
total = 0; // Reset total
int count = 1;
while (count <= N) {
cout << "Enter number " << count << ": ";
cin >> number;
total += number;
count++;
}
33| C++ Programming with Examples
average = static_cast<double>(total) / N;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
// Using do-while loop
cout << "\nUsing do-while loop:" << endl;
total = 0; // Reset total
count = 1;
do {
cout << "Enter number " << count << ": ";
cin >> number;
total += number;
count++;
} while (count <= N);
average = static_cast<double>(total) / N;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
return 0;
}
34| C++ Programming with Examples
Example 15: Compute the gross pay
Write a C++ program to compute the gross pay for an employee. An
employee is paid at hourly rate for the first 40 hours worked in a week.
Any hours worked in excess of 40 hours are paid at the overtime rate of
one and half times that. Your program should print the pay sheets of all
the employees.
#include <iostream>
using namespace std;
const double OVERTIME_RATE = 1.5;
// Function to calculate gross pay
double calculateGrossPay(double hoursWorked, double hourlyRate) {
double grossPay;
if (hoursWorked <= 40) {
grossPay = hoursWorked * hourlyRate;
} else {
double regularPay = 40 * hourlyRate;
double overtimeHours = hoursWorked - 40;
double overtimePay = overtimeHours * hourlyRate *
OVERTIME_RATE;
grossPay = regularPay + overtimePay;
}
return grossPay;
35| C++ Programming with Examples
}
int main() {
int employeeCount;
double hourlyRate, hoursWorked;
cout << "Enter the number of employees: ";
cin >> employeeCount;
for (int i = 1; i <= employeeCount; ++i) {
cout << "\nEnter details for employee " << i << ":" << endl;
cout << "Enter hourly rate: $";
cin >> hourlyRate;
cout << "Enter hours worked: ";
cin >> hoursWorked;
// Calculate gross pay
double grossPay = calculateGrossPay(hoursWorked, hourlyRate);
// Output pay sheet
cout << "\nPay Sheet for Employee " << i << ":" << endl;
cout << "Hourly Rate: $" << hourlyRate << endl;
cout << "Hours Worked: " << hoursWorked << endl;
36| C++ Programming with Examples
cout << "Gross Pay: $" << grossPay << endl;
}
return 0;
}
END
37| C++ Programming with Examples