0% found this document useful (0 votes)
18 views39 pages

C++ Practical Programs for Beginners

The document outlines a series of practical programming problems for C++ students at Mehran University, covering various topics such as arithmetic operations, time conversion, shape printing, and basic billing systems. Each problem includes a description and a sample code implementation to guide students in developing their programming skills. The problems are structured in labs, with each lab focusing on different programming concepts and applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views39 pages

C++ Practical Programs for Beginners

The document outlines a series of practical programming problems for C++ students at Mehran University, covering various topics such as arithmetic operations, time conversion, shape printing, and basic billing systems. Each problem includes a description and a sample code implementation to guide students in developing their programming skills. The problems are structured in labs, with each lab focusing on different programming concepts and applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Mehran University – 25 CS 108 – C++

Practical Programs

Lab 1
Problem 01: sum, product, difference, and quotient of the two numbers.

[Link] a program that asks the user to enter two numbers, obtains the two numbers from
the user and prints the sum, product, difference, and quotient of the two numbers.

Problem 02: Circle Diameter, Circumference, and Area

2. Write a program that reads in the radius of a circle as an integer and


prints the circle’s diameter, circumference and area. Use the constant value
3.14159 for π. Do all calculations in output statements.

#include <iostream>
using namespace std;

int main() {
int radius;
const double pi = 3.14159;
cout << "Enter radius (integer): ";
cin >> radius;
cout << "Diameter = " << 2 * radius << endl;
cout << "Circumference = " << 2 * pi * radius << endl;
cout << "Area = " << pi * radius * radius << endl;
return 0;
}

Problem 03: Print shapes (box, oval, arrow, diamond) using stars without loops

3. Write a program that prints a box, an oval, an arrow and a diamond as follows:

#include <iostream>
using namespace std;

int main() {
cout << "********* *** * *\n";
cout << "* * * * *** * *\n";
cout << "* * * * ***** * *\n";
cout << "* * * * * * *\n";
cout << "* * * * * * *\n";
cout << "* * * * * * *\n";
cout << "* * * * * * *\n";
cout << "* * * * * * *\n";
cout << "********* *** * *\n";
return 0;
}

Lab 2
Problem 01: Time Conversion (hour, minute, second to minutes)

1. Write a time conversion program that asks a user to enter


time in hour, minute and seconds and convert it into minutes
and displayed to user.

#include <iostream>
using namespace std;
int main() {
int hr, min, sec;
cout << "Enter time in hours, minutes, and seconds: ";
cin >> hr >> min >> sec;

int totalMinutes = hr * 60 + min + sec / 60;


cout << "Total time in minutes: " << totalMinutes << endl;
return 0;
}

Problem 02: Celsius to Fahrenheit

1. Write a program that converts a user entered temperature


in Celsius to Fahrenheit according to formula:

#include <iostream>
using namespace std;

int main() {
cout << "Enter temperature in Celsius: ";
cin >> tempC;
double tempF = 1.8 * tempC + 32;
cout << "Temperature in Fahrenheit = " << tempF << endl;
return 0;
}
Problem 03: Daily Driving Cost Calculator

1. Create an application that calculates your daily driving


cost, so that you can estimate how much money could be
saved by car pooling, which also has other advantages such
as reducing carbon emissions and reducing traffic
congestion. The application should input the following
information and display the user’s cost per day of driving
to work:
a) Total miles driven per day.
b) Cost per gallon of gasoline.
c) Average miles per gallon.
d) Parking fees per day.
e) Tolls per day

#include <iostream>
using namespace std;

int main() {
double miles, costPerGallon, milesPerGallon, parking, tolls;
cout << "Total miles driven per day: ";
cin >> miles;
cout << "Cost per gallon of gasoline: ";
cin >> costPerGallon;
cout << "Average miles per gallon: ";
cin >> milesPerGallon;
cout << "Parking fees per day: ";
cin >> parking;
cout << "Tolls per day: ";
cin >> tolls;

double fuelNeeded = miles / milesPerGallon;


double fuelCost = fuelNeeded * costPerGallon;
double totalCost = fuelCost + parking + tolls;

cout << "Total cost per day of driving: Rs. " << totalCost << endl;
return 0;
}

Problem 04: Assignment and Arithmetic Assignment (a, b -> c, c += 5, display


c> ? )

1. Write a program that:


 Takes two integers a and b as input.
 Assigns their sum to a new variable c using the assignment
operator.
 Update c by adding 5 to it using the arithmetic assignment
operator (+=).
 Display whether c is greater than using a relational operator
(output 1 or 0).
#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers a and b: ";
cin >> a >> b;
int c = a + b; // assignment
c += 5; // add 5
cout << (c > a) << endl; // outputs 1 if true else 0
return 0;
}

Problem 05: Logical operations without if-else (print 1/0)


2. Write a program that:
 Takes two integers x and y as input.
 Check and display the result of:
 x is greater than y AND x is even.
 y is less than x OR y is positive.
 NOT (x is equal to y).
Output should be 1 or 0, printed directly without using if–else.
#include <iostream>
using namespace std;

int main() {
int x, y;
cout << "Enter x and y: ";
cin >> x >> y;
cout << ( (x > y) && (x % 2 == 0) ) << endl;
cout << ( (y < x) || (y > 0) ) << endl;
cout << ( !(x == y) ) << endl;
return 0;
}

Problem 09: Prefix and Postfix Increment/Decrement demonstration


[Link] a program that:
 Takes one integer num as input.
 Display the result of prefix increment (++num) and postfix
increment (num++).
 Display the result of prefix decrement (--num) and postfix
decrement (num--).
 Show the outputs directly in cout to highlight the difference
between prefix and postfix.

#include <iostream>
using namespace std;

int main()
{
int num;
cout << "Enter an integer: ";
cin >> num;
cout << "Prefix ++num: " << ++num << endl; // increment then print
cout << "Postfix num++: " << num++ << endl; // print then increment
cout << "Now num = " << num << endl;
cout << "Prefix --num: " << --num << endl; // decrement then print
cout << "Postfix num--: " << num-- << endl; // print then decrement
cout << "Now num = " << num << endl;
return 0;
}

Lab 3
Question 1:
A person enters the bank and stands in the queue to get his salary. When his turn
comes, he requests the cashier that I need my salary with minimum notes and coins.
Write a program in C++ for the cashier that first asks the cashier to enter the salary
amount and then displays the number of notes and coins of (Rs. 5000, Rs. 1000, Rs.
100, Rs. 50, Rs. 20, Rs. 10, Rs. 5, Rs. 2 and Re. 1).

#include <iostream>
using namespace std;
int main() {
int amount;
cout << "Enter the salary amount: ";
cin >> amount;

int notes5000 = amount / 5000; amount %= 5000;


int notes1000 = amount / 1000; amount %= 1000;
int notes100 = amount / 100; amount %= 100;
int notes50 = amount / 50; amount %= 50;
int notes20 = amount / 20; amount %= 20;
int notes10 = amount / 10; amount %= 10;
int notes5 = amount / 5; amount %= 5;
int notes2 = amount / 2; amount %= 2;
int notes1 = amount;

cout << "Rs. 5000: " << notes5000 << endl;


cout << "Rs. 1000: " << notes1000 << endl;
cout << "Rs. 100: " << notes100 << endl;
cout << "Rs. 50: " << notes50 << endl;
cout << "Rs. 20: " << notes20 << endl;
cout << "Rs. 10: " << notes10 << endl;
cout << "Rs. 5: " << notes5 << endl;
cout << "Rs. 2: " << notes2 << endl;
cout << "Re. 1: " << notes1 << endl;
return 0;
}

Question 2:
Write a program in C++ that prompts the capacity in gallons, of an automobile fuel
tank and the miles per gallons the automobile can be driven. The program outputs
the number of miles the automobile can be driven without refueling.

#include <iostream>
using namespace std;
int main() {
double capacity, miles_per_gallon;
cout << "Enter fuel tank capacity (in gallons): ";
cin >> capacity;
cout << "Enter miles per gallon: ";
cin >> miles_per_gallon;

double total_miles = capacity * miles_per_gallon;


cout << "The automobile can be driven " << total_miles << " miles
without refueling." << endl;
return 0;
}

Question 3:
A milk carton can hold 3.78 liters of milk. Each morning, a dairy farm ships cartons of
milk to a local grocery store. The cost of producing one liter of milk is PKR 80.15, and
the profit of each carton of milk is PKR 8.9. Write a program in C++ that does the
following:
a) Prompts the user to enter the total amount of milk produced in the morning.
b) Outputs the number of milk cartons needed to hold milk. (Round your answer to
the nearest integer.)
c) Outputs the cost of producing milk.
d) Outputs the profit for producing milk.

#include <iostream>
#include <cmath>
using namespace std;
int main() {
double milk_produced;
const double carton_capacity = 3.78;
const double cost_per_liter = 80.15;
const double profit_per_carton = 8.9;
cout << "Enter total milk produced (in liters): ";
cin >> milk_produced;

int cartons = round(milk_produced / carton_capacity);


double cost = milk_produced * cost_per_liter;
double profit = cartons * profit_per_carton;

cout << "Cartons needed: " << cartons << endl;


cout << "Cost of production: PKR " << cost << endl;
cout << "Profit: PKR " << profit << endl;
return 0;
}

Question 4:
Newton’s law states that the force, F, between two bodies of masses M1 and M2 is
given by:
F = k * (M1 * M2) / (d * d)
in which k is the gravitational constant and d is the distance between the bodies. The
value of k is approximately 6.67 × 10^-11. Write a program in C++ that prompts the
user to input the masses of the bodies and the distance between the bodies. The
program then outputs the force between the bodies.

#include <iostream>
using namespace std;
int main() {
double M1, M2, d;
const double k = 6.67e-11;
cout << "Enter mass of first body (kg): ";
cin >> M1;
cout << "Enter mass of second body (kg): ";
cin >> M2;
cout << "Enter distance between bodies (m): ";
cin >> d;

double F = k * (M1 * M2) / (d * d);


cout << "The force between the bodies is: " << F << " N" << endl;
return 0;
}

Question 5:
One metric ton is approximately 2205 pounds. Write a program in C++ that prompts
the user to input the amount of rice, in pounds, in a bag. The program outputs the
number of bags needed to store one metric ton of rice.

#include <iostream>
using namespace std;
int main() {
double pounds_in_bag;
const double metric_ton = 2205;
cout << "Enter amount of rice in a bag (in pounds): ";
cin >> pounds_in_bag;

double bags_needed = metric_ton / pounds_in_bag;


cout << "Number of bags needed to store one metric ton of rice: "
<< bags_needed << endl;
return 0;
}
Lab 4
Problem Statement 01: INDUS CAFE billing (start and end time)

The “INDUS CAFE” is the Internet cafe located at Jamshoro. It provides Internet
services to clients 24 hours a week. They charge the Internet services as given in the
table below. Write down a computer program in C++ for the accountant which asks
him to enter the starting and ending time of the Internet services used by the client
and displays the amount that is to be charged on the client for the service.

Service hour Amount to charge


First Hour Rs. 20
Second Hour Rs. 15
Rest of the hours Rs. 10 per hour

Note: Enter the time in 24 Hour format. If the client uses even 1 second of the next hour it
will considered as complete hour.

Say if client has used 1 hour 0 minutes and 2 seconds than he will be charged for 2 hours.

#include <iostream>
using namespace std;

int main() {
int sh, sm, ss, eh, em, es;
cout << "Start Time (HH MM SS): ";
cin >> sh >> sm >> ss;
cout << "End Time (HH MM SS): ";
cin >> eh >> em >> es;

int start = sh * 3600 + sm * 60 + ss


int end = eh * 3600 + em * 60 + es;
int total = end - start;

int hours = total / 3600;


if (total % 3600 != 0) hours++;
int charge = 0;
if (hours >= 3)
charge = 20 + 15 + (hours - 2) * 10;
else if (hours == 2)
charge = 20 + 15;
else
charge = 20;
cout << "Hours Used: " << hours << endl;
cout << "Charge: Rs. " << charge << endl;
return 0;
}
Problem Statement 02: DINERS shop billing with discounts

DINERS” is a well-known garments shop located at Gul Center Hyderabad. They stock
different varieties of Shirts, T-Shirts, Dress Pants, Jeans, Belts and Ties. The rates of
each product are shown in table below along with the discount offers due to Eid.

Discount per item for Discount per item for


Item Actual Rate
Registered Customer Normal Customer
Shirt Rs. 1750 50% 30%
T-Shirt Rs. 1550 50% 30%
Dress Pant Rs. 2100 40% 20%
Jeans Rs. 4500 30% 10%
Lather Belt Rs. 2150 40% 20%
Tie Rs. 1100 40% 20%

Write a C++ program that asks the type of customer, number of products purchase of
each item specified in the table and calculates the actual amount and amount after
discount in rupees.

#include <iostream>
using namespace std;

int main() {
string type;
int s, t, p, j, b, i;

cout << "Customer Type (registered/normal): ";


cin >> type;
cout << "Shirts: ";
cin >> s;
cout << "T-Shirts: ";
cin >> t;
cout << "Dress Pants: ";
cin >> p;
cout << "Jeans: ";
cin >> j;
cout << "Belts: ";
cin >> b;

cout << "Ties: ";


cin >> i;

int total = s * 1750 + t * 1550 + p * 2100 + j * 4500 + b * 2150 + i * 1100;

float d = (type == "registered")


? s * 875 + t * 775 + p * 840 + j * 1350 + b * 860 + i * 440
: s * 525 + t * 465 + p * 420 + j * 450 + b * 430 + i * 220;

cout << "\n--- BILL SUMMARY ---\n";


cout << "Total: Rs. " << total << endl;
cout << "Discount: Rs. " << d << endl;
cout << "Final Amount: Rs. " << total - d << endl;

return 0;
}

Problem Statement 03: Leap Year check

Write a program in C++ that asks the user to enter the year and displays
whether it is a leap year or not.

#include <iostream>
using namespace std;

int main() {
int year;
cout << "Enter year: ";
cin >> year;
bool isLeap = (year%4==0 && year%100!=0) || (year%400==0);
cout << (isLeap ? "Leap Year" : "Not a Leap Year") << endl;
return 0;
}

statement 04: Three numbers in ascending order

Write a program in C++ that prompts the user to input three numbers. The program should
then output the numbers in ascending order.

#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;
// simple sorting using swaps
if (a > b) swap(a,b);
if (a > c) swap(a,c);
if (b > c) swap(b,c);
cout << "Ascending order: " << a << " " << b << " " << c << endl;
return 0;
}
Problem Statement 05: Check if triangle is right-angled

In a right triangle, the square of the length of one side is equal to the sum of the squares of
the lengths of the other two sides. Write a program that prompts the user to enter the lengths
of three sides of a triangle and then outputs a message indicating whether the triangle is a
right triangle.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
double x, y, z;
cout << "Enter three side lengths: ";
cin >> x >> y >> z;
// sort so largest is z
if (x > y) swap(x,y);
if (y > z) swap(y,z);
if (x > y) swap(x,y);
// check Pythagoras
if (abs(z*z - (x*x + y*y)) < 1e-6)
cout << "Right Triangle" << endl;
else
cout << "Not a Right Triangle" << endl;
return 0;
}
Problem Statement 06: Cookies -> boxes and containers

A box of cookies can hold 24 cookies, and a container can hold 75 boxes of cookies. Write a
program that prompts the user to enter the total number of cookies, the number of cookies in
a box, and the number of cookie boxes in a container. The program then outputs the number
of boxes and the number of containers to ship the cookies. Note that each box must contain
the specified number of cookies, and each container must contain the specified number of
boxes. If the last box of cookies contains less than the number of specified cookies, you can
discard it and output the number of leftover cookies. Similarly, if the last container contains
less than the number of specified boxes, you can discard it and output the number of leftover
boxes.

#include <iostream>
using namespace std;

int main() {
int totalCookies, cookiesPerBox, boxesPerContainer;
cout << "Enter total cookies, cookies per box, boxes per container:
";
cin >> totalCookies >> cookiesPerBox >> boxesPerContainer;

int boxes = totalCookies / cookiesPerBox; // discard incomplete


last box
int leftoverCookies = totalCookies - boxes * cookiesPerBox;
int containers = boxes / boxesPerContainer; // discard incomplete
last container
int leftoverBoxes = boxes - containers * boxesPerContainer;
cout << "Full boxes = " << boxes << endl;
cout << "Leftover cookies (discarded) = " << leftoverCookies <<
endl;
cout << "Full containers = " << containers << endl;
cout << "Leftover boxes (discarded) = " << leftoverBoxes << endl;
return 0;
}

Lab 5
Problem Statement 1: Generate first N three-digit odd numbers

Write a program in C++ that generates and displays the first N three digit odd numbers.
Whereas the number N is provided by the user.
#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter N: ";
cin >> N;
int val = 101; // first three-digit odd
for (int i = 0; i < N; i++) {
cout << val;
if (i != N-1) cout << " ";
val += 2;
}
cout << endl;
return 0;
}
Problem Statement 2: Sum of last 5 four-digit multiples of 5

Write a program in C++ that displays the sum of last 5 four digit multiples of 5.

#include <iostream>
using namespace std;

int main() {
int count = 5;
int start = 9999 - (9999 % 5); // largest multiple of 5 <= 9999
int sum = 0;
for (int i = 0; i < count; i++) {
sum += (start - i*5);
}
cout << "Sum = " << sum << endl;
return 0;
}
Problem Statement 3: Multiplication table up to 10

Write a program in C++ that prints the multiplication table of a number entered by the
user.

.The program should ask the user to input a number.

.Then, display its multiplication table up to 10 (e.g., 7 × 1 = 7 … 7 × 10 = 70).

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter number: ";
cin >> n;
for (int i = 1; i <= 10; i++) {
cout << n << " x " << i << " = " << n * i << endl;
}
return 0;
}
Problem Statement 4: FOR to sum a sequence (first integer is count)

Write a program in C++ that uses FOR statement to sum a sequence of integers. Assume that
the first integer read specifies the number of values remaining to be entered. Your program
should read only one value per input statement. A typical input sequence might be

5 100 200 300 400 500

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter count followed by values: ";
cin >> n;
int sum = 0, val;
for (int i = 0; i < n; i++) {
cin >> val;
sum += val;
}
cout << "Sum = " << sum << endl;
return 0;
}
Problem Statement 5: FOR to find smallest of several integers

Write a program in C++ that uses FOR statement to find the smallest of several integers.
Assume that the first value read specifies the number of values remaining.

#include <iostream>
#include <limits>
using namespace std;

int main() {
int n;
cout << "Enter number of values: ";
cin >> n;
int val;
int smallest = std::numeric_limits<int>::max();
for (int i = 0; i < n; i++) {
cin >> val;
if (val < smallest) smallest = val;
}
cout << "Smallest = " << smallest << endl;
return 0;
}
Problem Statement 6: Sum of digits of a positive integer

Write a program in C++ that calculates and displays the sum of digits of any positive integer
entered by the user.

For example, if the user enters 5432, the program should display Sum of digits = 14.

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter positive integer: ";
cin >> n;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
cout << "Sum of digits = " << sum << endl;
return 0;
}
Problem Statement 7: Prime number check using for loop

Write a program in C++ that checks whether a number entered by the user is a prime
number or not.

Use a for loop to check divisibility.

Display an appropriate message like “Prime Number” or “Not a Prime Number.”

#include <iostream>
#include <cmath>
using namespace std;

int main() {
int n;
cout << "Enter integer: ";
cin >> n;
if (n <= 1) {
cout << "Not a Prime Number" << endl;
return 0;
}
bool prime = true;
for (int i = 2; i <= sqrt(n); i++) {
if (n % i == 0) { prime = false; break; }
}
if (prime) cout << "Prime Number" << endl;
else cout << "Not a Prime Number" << endl;
return 0;
}
Problem Statement 8: Fibonacci series up to N terms

Write a program in C++ that displays the Fibonacci series up to N terms, where N is entered by
the user.

Example: If the user enters 7, the output should be:


0112358

#include <iostream>
using namespace std;

int main() {
int N;
cout << "Enter N: ";
cin >> N;
int a = 0, b = 1;
if (N >= 1) cout << a;
if (N >= 2) cout << " " << b;
for (int i = 3; i <= N; i++) {
int c = a + b;
cout << " " << c;
a = b;
b = c;
}
cout << endl;
return 0;
}
Problem Statement 9: Factorials 1 to 5 using WHILE

Write a program in C++ that uses WHILE statement to evaluate and display the factorials of
the integers from 1 to 5.

#include <iostream>
using namespace std;

int main() {
int i = 1;
while (i <= 5) {
int fact = 1;
int j = 1;
while (j <= i) {
fact *= j;
j++;
}
cout << i << "! = " << fact << endl;
i++;
}
return 0;
}
Problem Statement 10: Print number of rows of stars (simple loop)

Write a program in C++ using any type of loop that prompts a user to enter number of rows to

print stars, if user enter 10, then program prints 10 rows of stars in following manner.

#include <iostream>
using namespace std;

int main() {
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for (int i = 1; i <= rows; i++) {
for (int j = 0; j < i; j++) cout << "*";
cout << endl;
}
return 0;
}
Problem Statement 11: Print triangle of stars (rows >=5)

#include <iostream>
using namespace std;

int main() {
int rows;
cout << "Enter number of rows (>=5): ";
cin >> rows;
if (rows < 5) rows = 5;
for (int i = 1; i <= rows; i++) {
for (int k = 0; k < rows - i; k++) cout << " ";
for (int j = 0; j < 2*i - 1; j++) cout << "*";
cout << endl;
}
return 0;
}
Problem Statement 12: Diamond shape of stars
Write a program in C++ using any type of loop that prints diamond shape of stars.

For Example

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter half-diamond height (>=1): ";
cin >> n;
// upper half
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) cout << " ";
for (int j = 0; j < 2*i - 1; j++) cout << "*";
cout << endl;
}
// lower half
for (int i = n-1; i >= 1; i--) {
for (int s = 0; s < n - i; s++) cout << " ";
for (int j = 0; j < 2*i - 1; j++) cout << "*";
cout << endl;
}
return 0;
}

Lab 6
EXERCISE 1- do with loops: Problem 01 inverted half pyramid numbers

Write a program using nested loop to print inverted half pyramid as using numbers

55555

4444

333

22

1
#include <iostream>
using namespace std;
int main() {
for (int i = 5; i >= 1; i--) // Outer loop for rows
{
for (int j = 1; j <= i; j++) // Inner loop for numbers
{
cout << i << " ";
}
cout << endl;
}
return 0;
}

EXERCISE 2- nested loops: Problem 02 pyramid of digits pattern

Write a program using nested loop to print inverted half pyramid as using numbers
#include <iostream>
using namespace std;

int main() {
int rows = 5;
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int s = i; s < rows; s++) {
cout << " ";
}
// Print numbers
for (int j = 1; j <= (2 * i - 1); j++) {
cout << j << " ";
}
cout << endl;
}
return 0;
}

EXERCISE 3- nested loops: Problem 03 Floyd's Triangle

Write a program using nested loop to print the pyramid of digits in pattern

#include <iostream>
using namespace std;

int main() {
int n = 5;
int num = 1;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << num++ << " ";
}
cout << endl;
}
return 0;
}
EXERCISE 4- nested loops: Problem 04 Hollow square pattern using stars

Write a program in C++ using nested loops to print a hollow square pattern
using stars (*).
For example, if the user enters 5, the output should be:

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter size of square: ";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i==1 || i==n || j==1 || j==n) cout << "*";
else cout << " ";
}
cout << endl;
}
return 0;
}
EXERCISE 5 - nested loops: Problem 05 Right-aligned half pyramid using
numbers

Write a program in C++ using nested loops to print a right-aligned half


pyramid using numbers.
For example, if the user enters 5, the output should be:

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter rows: ";
cin >> n;
for (int i = 1; i <= n; i++) {
for (int s = 0; s < n - i; s++) cout << " ";
for (int j = 1; j <= i; j++) cout << j;
cout << endl;
}
return 0;
}
EXERCISE 6 - nested loops: Problem 06 Pascal's Triangle up to n rows

Write a program in C++ using nested loops to print a Pascal’s Triangle


pattern up to n rows.
Example (for n = 5):

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter number of rows for Pascal's Triangle: ";
cin >> n;

for (int i = 0; i < n; i++) {


for (int space = 0; space < n - i - 1; space++) {
cout << " ";
}

int num = 1; // First number in every row is 1


for (int j = 0; j <= i; j++) {
cout << num << " ";
num = num * (i - j) / (j + 1);
}
cout << endl;
}

Return 0;
}

You might also like