0% found this document useful (0 votes)
9 views34 pages

Pf Lab

The document is a lab manual for the Programming Fundamentals course (CSC-111) at the Hyderabad Institute for Technology and Management Sciences. It outlines various lab sessions focused on C++ programming, including exercises on basic operations, conditional statements, loops, and user input systems. Each lab includes objectives, problem statements, and expected outcomes to guide students in developing their programming skills.

Uploaded by

abdulhaleem47222
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)
9 views34 pages

Pf Lab

The document is a lab manual for the Programming Fundamentals course (CSC-111) at the Hyderabad Institute for Technology and Management Sciences. It outlines various lab sessions focused on C++ programming, including exercises on basic operations, conditional statements, loops, and user input systems. Each lab includes objectives, problem statements, and expected outcomes to guide students in developing their programming skills.

Uploaded by

abdulhaleem47222
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
You are on page 1/ 34

Hyderabad Institute for Technology and Management

Sciences

Department of Computer Sciences and Related


Studies

LAB MANUAL

For the course


Programming Fundamentals (CSC-111)

Instructor name:
Student Name
Student Roll No.
Program BS Software Engineering & BS Computer Science
Semester First
Year First
Hyderabad Institute for Technology and Management
Sciences

Department of Computer Sciences and Related


Studies

VISION

MISSION
LAB MANUAL

For

CSC-111 Programming Fundamentals

Approved By HOD

Date: ____________________

Sign: ____________________
CONTENTS

Lab No. Title of Experiment Page No


Lab Rubrics
1 Practice with working environment for C++ (DeV C++)
2 Practice with Marksheet Using C++
3 Practice with Basic Arithmetic Operations in C++
4 Practice with Conditional Statements in C++
5 Practice with for Loops for Repetitive Tasks in C++
6 Practice with Loop-Based User Input Systems in C++
7 Practice with do-while Loops for User-Driven Repetition in C++
8 Practice with Nested Loops to Create Visual Patterns in C++
9 Practice with while Loops for Repetitive Task Handling
10 Practice with Library Book Management System
11 Practice with Employee Attendance and Seat Arrangement Systems
12 Practice with String Operations in C++
13 Practice with Scientific Calculator Implementation in C++
14 Practice with Identifying and Fixing Logical Errors in C++ Program
15 Practice with Output Prediction for C++ Programs
16 Open Ended Lab
LAB RUBRIC
Needs Improvement
Criteria Excellent (4) Good (3) Satisfactory (2)
(1)
1. Problem
Understanding
2. Code Logic /
Algorithm
3. Syntax and
Compilation
4. Use of C++
Concepts
5. Submission &
Timeliness
Total (out of 20)

Lab Session 1
Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20

Topic: Practice with working environment for C++ (DevC++)

Aim: To get familiar with DeV C++ IDE working environment. Include header files,
write a simple program,save, compile and run the program.

Objective:
In this lab session, we shall cover the following objectives

 To get familiar with DeV C++ IDE working environment.

 Include header files,

 Write a simple program, save, compile and run the program.

Introduction

Dev-C++ provides an integrated environment for writing programs. "Integrated environment" means Dev-
C++ is a combination program, consisting of a text editor and a C++ compiler. A text editor is a limited word
processing program that allows you to type in your program, make corrections and changes, and save
and retrieve your program from disk storage. The editor is integrated with the Dev-C++ compiler so that
you can easily switch between editing your program and compiling and running it. Note that the Dev-C++
compiler allows you to write, compile and run programs in either C++ or C.
SECTION 1: THE BASICS

In Section 1, we'll summarize the major steps in using the Dev-C++ integrated environment. Then, in
Section 2, we will explain each of these one by one.

1. To enter Dev-C++, find and click on the icon shown at right. It may be in a folder
labeled Programming Languages. If there is such a folder, open it by double-
clicking on it, and then click the icon shown at right. If you can't find the icon, use
the search box and search for Dev-C++.

2. Select File | New | Source File. In the right hand lower window, type in and edit your
program using the Dev-C++ editor.

3. Save and name your program by selecting File | Save or by clicking on this icon: When you name your
program, you must specify three things:

a. The drive name (nothing, if saving on the hard drive; d: or e: or something else if you have a
flash drive)

b. The name of the program itself, which should be something like prog1 or code1.

c. The extension, which must be .cpp for a C++ program.

For example, you might name your first assignment (saved on a flash drive) as follows:

d:prog1.cpp

4. Compile your program by selecting Execute | Compile or by clicking on this icon above
the ed it window. If your compilation is successful, a Done message will appear;click OK to
return to the editor. If your compilation is unsuccessful, an error message will appear;
click OK to view a list of errors that you must correct. Use the editor to correct the errors, and repeat
step 4 until you are successful.

5. Execute your program by selecting Execute | Run or by clicking on this icon:

6. Print your program by selecting File | Print or by clicking this icon. In the window that
pops up, remove any check mark in the box that says “Line numbers.”

(With line numbers, your printed lines may run off the page.) Click OK.

7. To print your output, place the cursor in the bar at the top of the output window and right- click.From
the menu that pops up, place the cursor over Edit, and another menu will appear to the right. Move the
cursor to the new menu, and click on Select All. The window contents will change color. Again
place the cursor in the bar at the top of the output window and right-click. From the menu that pops
up, select Edit and then Copy. Then go back to the Dev-C++environment. Open a new editor
window by selecting File | New | Source file. Place the cursor in the new window that opens, select Edit
| Paste, and the output will be copied into the new window. Save it, if you wish, using a name like
prog1.out. Then print it as you printed the program file in step 6.

8. Exit from Dev-C++ by selecting File | Exit, or by clicking on the Close icon at the top
right corner of the Dev-C++ window
SECTION 2: THE DETAILS

Step 1: Entering Dev-C++

A typical way to find it is to select Start | All Programs | Dev- C++. You can also search for the
program using the Search box, typing in Dev-C++.

After you start the program, the Dev-C++ environment, shown in Figure 1, will appear on your
screen. (These screens are from an earlier version of Dev-C++ but are identical except for the version number, which is now
5.3.0.3.) The Dev-C++ main menu selections appear across the top of the screen. Placing the cursor over an icon will cause its
use to be displayed at the bottom left of the Dev-C++ window.

Figure 1 Dev-C++ Environment

Step 2: Creating a New File

To create a new file, select File from the main menu, then select New from the drop- down menu, and then select
Source file from the next drop-down menu (we'll abbreviate this kind of task this way: File | New | Source file).
Figure 2 File Menu with Sub-menu

Figure A new file window

Step 3: Saving a File

Once you have created a file and typed in a program, you should immediately save it to a disk so that you can use it
again. To save a file, click on the Save icon, shown above, or select File | Save.

If the file is a new one, the editor will ask you to provide a permanent name for the file before saving it. The
"Save File" window shown in Figure 4 will pop up, with the File Name box highlighted. The current
filename ("noname00.cpp") will appear in the box. When you start typing,the old name will disappear.
Figure The "Save File As" pop-up window

A file name has three parts: the drive name, the file name, and the file extension. For example,you could use
"d:first.cpp" as the name of the file, where "d:" is the drive name assigned to your flash drive, "prog1" is the file
name, and ".cpp" is the file extension.

 In the first box below the file list, type in a name for your file. The name should reflect what the file is or
does. There is no particular limit to the length of the name, but it should consist only of letters, numbers
and the underbar symbol; many keyboard symbols are illegal characters in file names.

 In the bottom box, select the type of file you are saving. The selection shown above is the default,and saves
your file with the extension .cpp. The extension for a C++ file MUST be .cpp; do not try to change it, or
you won't be able to use the program file.

Warning: If you do not specify otherwise, the system will automatically add the file extension".cpp" to the
name of your file. Look at the second item in the file list above; the user tried to name it first.out, but the system
automatically added .cpp at the end. If you want to save any type of file other than a program file (such as an output
file or a data file), select "All files (*.*)" from the bottom box's drop-down menu. Then you can specify your own
preferred extension, like .dat for a data file or .out for an output file.

To leave the "Save File" window and save your file, press <Enter> or click Save with the mouse. You can leave the
window without performing any action by selecting Cancel.

Once you have named a file, subsequent Save operations will not bring up the File Save window. Changes will be
noted only by two small changes in the appearance of the Dev-C++ window. The Save icon will become gray to
indicate that the save action cannot be performed at this time. In addition, the word "Modified" will disappear
from the status line at the bottom of the window.
Figure A window showing compilation errors

The bottom window contains a list of all your errors. You can scroll through the Message window to see all of the
errors. Clicking on an error message highlights the relevant line in the top window.

Once you have located the error, fix it. Then return to the Message window to view the next error. Continue the
process until you have corrected all the errors. Then again save and compile your program. Repeat this process
until your program is free of errors.

If you cannot identify the error from the message given by the compiler, or if you do not know how to correct the
error, take a printed copy of your program and the error message to your instructor.(Error messages are not always
perfectly clear, because they are based on trying to translate something that doesn't make sense.)

If you have corrected all the compilation errors in your program, it will compile successfully, and the
window shown in Figure 5 will appear on the screen.

Sample Program

Here is a complete sample C++ program. You should enter, compile and run it. This program

sends one line of output to the screen.


/* sample C++ program */
#include <iostream>
using namespace std;
int main()
{
cout << "my first C++ program" << endl;
return 0;
}
Lab Session 2
]
Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20

Lab Title: Practice with marksheet using C++

Problem Statement:

Design a C++ program that stores and displays a student's name and generates a marksheet using
variables and output statements. The program should demonstrate the use of string and cout.

Objectives:

 To understand the use of iostream and string header files.


 To declare and initialize string variables.
 To display student information using output statements.
 To develop the concept of formatted output for a simple marksheet.

Expected Outcome: Students will be able to:

 Create and initialize variables to store student details.


 Use cout for output formatting.
 Generate a basic output layout resembling a marksheet.
Lab Session 3
Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20

Lab Title: Practice with Basic Arithmetic Operations in C++

Problem Statement:
This lab focuses on applying basic arithmetic operations and formulas using C++. Students will write
three small programs that:

1. Calculate the area of a square


2. Implement the algebraic identity: (a² + 2ab + b²)
3. Compute the average of three numbers

Objectives:

 To understand input/output handling in C++.


 To use arithmetic operations and algebraic expressions.
 To apply mathematical formulas through code.
 To practice using different data types such as int and double.

Tasks :

1. Write a C++ program to calculate the area of a square using the formula area = side * side.
2. Write a C++ program that accepts two values (a and b) and evaluates the expression (a * a)
3. Develop a C++ program that takes three numbers as input and computes their average.
Lab Session 4

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Conditional Statements in C++

Problem Statement:
This lab focuses on using conditional statements (if, else if, and else) to control the flow of a program
based on various conditions. Students will develop four C++ programs to demonstrate the use of conditional
logic in real-world scenarios.

Objectives:

 To understand the use of conditional statements (if, else if, else) in C++.
 To apply decision-making logic in real-time situations.
 To work with both integer and float data types.
 To enhance logical thinking through condition-based programming.

Tasks:

1 Write a C++ program that takes temperature as input and classifies it as Cold (below 24), Moderate
(24–37), or Hot (above 37).
2 Write a C++ program that takes a percentage as input and displays the corresponding grade based
on predefined ranges.
3 Write a program that checks whether a person is eligible to vote. The user will enter their age, and
the program will determine eligibility (18 or older).
4 Write a C++ program that reads an integer and determines whether it is even or odd using the
modulus operator.
Lab Session 05

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20

Lab Title: Practice with for Loops for Repetitive Tasks in C++

Problem Statement:
This lab demonstrates how to use for loops to handle repetitive tasks efficiently. Students will implement two
classic programming problems:

1. A number guessing game with limited attempts


2. The FizzBuzz challenge up to 50 numbers

Objectives:

 To understand the structure and syntax of for loops.


 To apply iteration in real-world scenarios like guessing games and pattern-based printing.
 To practice logical condition handling inside loops.
 To strengthen control flow understanding using compound conditions.

Tasks :

1. Create a C++ program that gives the user 5 attempts to guess a secret number. After each guess, the
program should inform whether the guess was correct or not.
2. Write a C++ program that prints numbers from 1 to 50. For multiples of 3, print "Fizz", for multiples of
5, print "Buzz", and for numbers which are multiples of both 3 and 5, print "FizzBuzz".
Lab Session 06

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Loop-Based User Input Systems in C++

Problem Statement:
This lab explores how to use while loops to build interactive programs that accept user input continuously until
a stopping condition is met. Students will build three practical systems: a temperature alert monitor, a loan
repayment tracker, and a daily expense calculator.

Objectives:

 To understand and apply while loops in user-controlled programs.


 To implement real-world use cases using input validation.
 To handle string and numeric data types for calculations.
 To manage program flow using custom exit conditions.

Tasks:

1. Write a C++ program for a greenhouse monitoring system that continuously checks temperature values
entered by the user. If the temperature exceeds 35°C, it should raise a warning. The program exits when
the user types “stop”.
2. Create a program that tracks a user’s monthly loan payments. The program should reduce the total loan
amount until it reaches zero. Input validation must ensure only positive values are accepted.
3. Build a program that takes daily expenses as input from the user and adds them to a total. The user can
type “done” to finish entering values. All values should be validated as numeric before being processed.
Lab Session 07

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with do-while Loops for User-Driven Repetition in C++

Problem Statement:
This lab demonstrates the use of do-while loops for situations where the loop body should always execute at
least once before checking a condition. Students will implement three interactive programs to practice the
concept.

Objectives:

 To understand the structure and functionality of do-while loops.


 To apply input validation and repetition control.
 To implement condition-based exits from interactive loops.
 To build user-driven input systems with required retry logic.

Tasks:

1. Create a program that repeatedly prompts the user for a PIN until the correct one is entered (1234). The
loop must execute at least once to ask for the PIN.
2. Description:
Write a dice rolling simulation that continues to roll the dice until a 6 is rolled. The dice rolling should
simulate randomness using a simple linear congruential generator.
3. Develop a quiz program that keeps asking the user “What is the capital of Pakistan?” until the correct
answer "Islamabad" is entered.
Lab Session 08

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Nested Loops to Create Visual Patterns in C++

Problem Statement:
This lab aims to teach the use of nested loops for generating various patterns using numbers and symbols. These
include geometrical, symmetrical, and matrix-based structures for enhancing logic-building and visualization
skills.

Objectives:

 To understand nested for loops.


 To generate pyramid and diamond patterns using * and numbers.
 To generate matrix-style logic like prime numbers, pair combinations, and board games.
 To improve problem-solving and pattern recognition abilities.

Tasks :

1. Takes a number of rows as input and prints a left-aligned triangle pattern using stars ( *).
2. Creates a number-based pyramid where each row shows numbers increasing and then decreasing in a
symmetric format.
3. Generates a symmetric diamond using * characters with increasing and then decreasing number of stars.
4. Displays a 3x5 matrix of prime numbers. The program keeps checking for prime numbers and places
them in matrix form.
5. Prints all combinations (i, j) where i and j range from 1 to 3. Great for understanding Cartesian
products.
6. Simulates a 3x3 Tic Tac Toe board using alternating X and O values, showing a visual layout of the
game board with line separators.
Lab Session 09

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with while Loops for Repetitive Task Handling

Problem Statement:
This lab focuses on applying while loops to simulate real-world processes such as calendar tracking, resource
monitoring, and attendance logging. These tasks involve nested and conditional loops, encouraging deeper
understanding of repetition control structures in C++.

Objectives:

 To understand the working of while loops.


 To apply nested loops for simulating daily and monthly records.
 To use user input for conditional decisions inside loops.
 To simulate real-world scenarios like attendance, water usage, and calendar tracking.

Task:

1. Simulates the passage of 12 months, printing 30 days for each month. Demonstrates basic nested while
loop behavior.
2. Tracks daily water usage for 5 households over a week. Uses nested loops to repeat daily data entry for
each household.
3. Accepts attendance status for 10 students over 5 school days. Validates user input for "Present" and
"Absent" entries. Demonstrates error handling and loop control using conditions.
Lab Session 10

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Library Book Management System

Problem Statement:

This lab focuses on simulating a real-world library book management system. Using arrays, loops, and
conditional statements, we manage the addition of books, search for books, and display the available book list.
The user will interact with the system to perform different operations related to managing a simple library.

Objectives:

 To practice using arrays for storing and managing collections of data (e.g., book titles, availability
status).
 To implement user-driven choices using loops and conditional logic.
 To simulate real-world systems like library management.
 To enhance understanding of basic programming concepts like arrays, loops, string handling, and
conditions.
Lab Session 11

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Employee Attendance and Seat Arrangement Systems
Problem Statement:

This lab focuses on simulating a real-world attendance and seat arrangement system. Using arrays, loops, and
conditional statements, we manage employee attendance and track seat occupancy in a classroom or office
setting. The user will interact with the system by adding employees/students, marking attendance, and managing
seat assignments.

Objectives:

 To practice using arrays for storing and managing collections of data (e.g., employee names, attendance,
and seating arrangements).
 To implement user-driven choices using loops and conditional logic.
 To simulate real-world systems like attendance tracking and seat management.
 To enhance understanding of basic programming concepts like arrays, loops, and conditions in real-
world applications.

Tasks:

1. Employee Attendance System:


o This system allows the user to add employees, mark their attendance, and view the status of all
employees (present or absent).
o It simulates a basic attendance management system for the workplace.
2. Seat Arrangement System:
o This system manages seating arrangements for a classroom or office.
o The user can add students/employees and view the current seat status (occupied or available).
o It demonstrates how to manage seat allocation for a fixed number of individuals.

Pre-Lab Preparation:

 Understand arrays and their usage: Arrays are used to store lists of data, such as employee names or
seat statuses.
 Understand loops and conditions: Loops will be used for iterating over the data, while conditions will
be used to check and update attendance or seat statuses.
Lab Session 12

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with String Operations in C++
Problem Statement:

This lab demonstrates various fundamental operations on strings in C++ using built-in functions and techniques
such as string length, accessing characters, string comparison, concatenation, searching for substrings,
extracting substrings, and modifying strings.

Objectives:

 To understand and practice various string operations in C++.


 To manipulate and analyze strings using different string functions.
 To implement common string operations such as comparison, concatenation, and modification.

Tasks:
1. String Length: Write a program that calculates and displays the length of a string.
2. Accessing Character by Index : Write a program that accesses and displays a character at a
specific index of a string.
3. String Comparison : Write a program that compares two strings and checks if they are equal.
4. Concatenating Strings : Write a program that concatenates two strings to form a full name.
5. Searching for a Substring : Write a program that finds and displays the position of a substring
within a string.
6. Extracting Substrings : Write a program that extracts a substring from a string and displays it.
7. Modifying Strings : Write a program that modifies a string by inserting a new substring into it.
Lab Session 13

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Scientific Calculator Implementation in C++
Problem Statement:

In this lab, students will create a simple scientific calculator that performs basic arithmetic operations such as
addition, subtraction, multiplication, division, and advanced operations like square root, power, and
trigonometric functions (sine, cosine, tangent). This program will make use of functions, loops, conditional
statements, and mathematical libraries in C++.

Objectives:

 To develop an understanding of implementing a scientific calculator in C++.


 To practice using functions, loops, and conditionals for building a user-friendly menu-driven program.
 To use mathematical functions like sqrt(), pow(), sin(), cos(), and tan() from the C++ cmath library.
 To handle user input, perform operations, and display results.
Lab Session 14

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Identifying and Fixing Logical Errors in C++ Programs
Problem Statement:

In this lab, students will work with a series of C++ programs that contain logical errors. They are required to
identify and correct the errors in order to make the programs work as expected. The goal is to develop
debugging skills and enhance the understanding of program logic, which is critical for writing accurate and
efficient code.

Objectives:

 To identify logical errors in C++ programs.


 To practice debugging techniques and fixing issues in code.
 To understand the impact of logical errors on program behavior and output.
 To learn how to ensure that the program performs as expected by applying correct logic and structure.

1. Program to find the minimum of two numbers

#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;

if(a < b)
cout << "Minimum is: " << a << endl;
else
cout << "Minimum is: " << a << endl;
return 0;
}

2. Program to check if a number is a perfect number

#include <iostream>
using namespace std;

int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;

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


if(n % i == 0) {
sum = sum + i;
}
}

if(sum == n)
cout << n << " is a perfect number" << endl;
else
cout << n << " is not a perfect number" << endl;

return 0;
}

3. Program to find the power of a number

#include <iostream>
using namespace std;

int main() {
int base, exponent, result = 1;
cout << "Enter base and exponent: ";
cin >> base >> exponent;

for(int i = 1; i <= exponent; i++) {


result *= base;
}

cout << base << " raised to the power " << exponent << " is: " << result << endl;
return 0;
}

4. Program to count the number of digits in a number

#include <iostream>
using namespace std;

int main() {
int n, count = 1;
cout << "Enter a number: ";
cin >> n;

while(n != 0) {
n = n / 10;
count++;
}

cout << "The number of digits is: " << count << endl;
return 0;
}

5. Program to print all the even numbers from 1 to N

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

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


if(i % 2 == 0)
cout << i << " ";
}

return 0;
}

6. Program to print a triangle pattern of stars

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the number of rows: ";
cin >> n;

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


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

return 0;
}

7. Program to find the sum of squares of first N numbers

#include <iostream>
using namespace std;

int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;

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


sum += i * i;
}

cout << "Sum of squares of first " << n << " numbers is: " << sum << endl;
return 0;
}

8. Program to calculate the sum of the first N natural numbers


#include <iostream>
using namespace std;

int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;

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


sum += i;
}

cout << "Sum of first " << n << " natural numbers is: " << sum << endl;
return 0;
}

9. Program to print Fibonacci series up to N terms


#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;

int first = 0, second = 1;


cout << first << " " << second << " ";

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


int next = first + second;
cout << next << " ";
first = second;
second = next;
}

return 0;
}

10. Program to check if a number is a perfect square


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

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

if(sqrt(n) * sqrt(n) == n)
cout << n << " is a perfect square" << endl;
else
cout << n << " is not a perfect square" << endl;

return 0;
}

11. Program to print all prime numbers less than N

#include <iostream>
using namespace std;

int main() {
int n;
cout << "Enter a number: ";
cin >> n;

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


for(int j = 2; j < i; j++) {
if(i % j == 0) {
break;
}
}
cout << i << " ";
}

return 0;
}

12. Program to find the sum of all divisors of a number

#include <iostream>
using namespace std;

int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;

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


if(n % i == 0) {
sum = sum + i;
}
}

cout << "Sum of divisors of " << n << " is: " << sum << endl;

return 0;
}

13. Program to find the largest of three numbers

#include <iostream>
using namespace std;

int main() {
int a, b, c;
cout << "Enter three numbers: ";
cin >> a >> b >> c;

if(a > b > c)


cout << "Largest number is: " << a << endl;
else if(b > c)
cout << "Largest number is: " << b << endl;
else
cout << "Largest number is: " << c << endl;

return 0;
}

14. Program to check if a number is prime

#include <iostream>
using namespace std;

int main() {
int n;
bool isPrime = true;
cout << "Enter a number: ";
cin >> n;

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


if(n % i == 0) {
isPrime = false;
break;
}
}

if(isPrime == true)
cout << n << " is prime" << endl;
else
cout << n << " is not prime" << endl;

return 0;
}

15. Program to print the sum of all odd numbers from 1 to N


#include <iostream>
using namespace std;

int main() {
int N, sum = 0;
cout << "Enter a number: ";
cin >> N;

for(int i = 1; i <= N; i++) {


if(i % 2 != 0)
sum = sum + i;
}

cout << "Sum of odd numbers is: " << sum << endl;
return 0;
}
Lab Session 15

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Lab Title: Practice with Output Prediction for C++ Programs
Problem Statement:

In this lab, students will analyze and predict the outputs of various C++ programs provided. The objective is to
develop the ability to predict the behavior of code and understand how different constructs, such as loops,
conditionals, and functions, affect program execution.

Objectives:

 To practice reading and analyzing C++ code.


 To develop the ability to predict the output of a program based on its structure and logic.
 To understand the role of variables, operators, control structures, and functions in producing the output.
 To identify and explain any possible issues in the code such as logical errors, syntax errors, or runtime
errors.

Program # 1
#include <iostream>
using namespace std;

int main() {
int a = 5;
int* p = &a;
int** q = &p;

**q = 10;
cout << a << " " << *p << " " << **q << endl;
return 0;
}

Program # 2
#include <iostream>
using namespace std;

int main() {
int arr[] = {5, 10, 15, 20};
int* p = arr;

cout << *p++ << " " << *p << " " << *(++p) << endl;
return 0;
}

Program # 3
#include <iostream>
using namespace std;

int main() {
int arr[] = {1, 2, 3, 4, 5};
int* p = arr;

cout << p[2] << " " << *(p + 2) << " " << *p + 2 << endl;
return 0;
}

Program # 4
#include <iostream>
using namespace std;

int main() {
int a = 10, b = 20;
int *p = &a, *q = &b;

*p = *q;
q = p;
*q = 30;

cout << a << " " << b << endl;


return 0;
}

Program # 5

#include <iostream>
using namespace std;

void modify(int* p) {
*p = 50;
}

int main() {
int x = 100;
modify(&x);
cout << x << endl;
return 0;
}

Program # 6

#include <iostream>
using namespace std;

int main() {
int a = 5;
int* p = &a;
int** q = &p;

*p = 10;
**q = 20;

cout << a << " " << *p << " " << **q << endl;
return 0;
}
Program # 7

#include <iostream>
using namespace std;

int main() {
int x = 10;
int* p = &x;
int** q = &p;

cout << &x << " " << p << " " << *q << endl;
return 0;
}

Program # 8

#include <iostream>
using namespace std;

int main() {
char arr[] = "Hello";
char* p = arr;

cout << *(p + 1) << " " << p[3] << " " << *p + 1 << endl;
return 0;
}

Program # 9

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 20, c = 30;
int* arr[] = {&a, &b, &c};
int** p = arr;

cout << **p << " " << *p[1] << " " << *(*(p + 2)) << endl;
return 0;
}
Program # 10

#include <iostream>
using namespace std;

void swap(int* a, int* b) {


int* temp = a;
a = b;
b = temp;
}

int main() {
int x = 5, y = 10;
swap(&x, &y);
cout << x << " " << y << endl;
return 0;
}
Lab Session 16

Criterion1 Criterion2 Criterion3 Criterion4 Criterion5 Total

/20
Open Ended Lab

You might also like