PF - Lab - Manual - Template 2024
PF - Lab - Manual - Template 2024
Prepared By:
1
Lab Manual Programming Fundmental with C++
List of Experiments
Week Topics
No.
1 Installation of Code Block, first program in C++,Compiling and Executing the
program.
2 Variable declaration and initialization, Assignment Operator
3 Arithmetic Operators, Input gathering, Operators Precedence
4 Decision making statements, if, if else and nested if else statements, Logical and
Conditional Operatrs
5 Using switch and break statements, enum
6 Loops, While Loop
6 Do-while loop, Difference between while and do while loop
7 For Loop (Basic Examples)
8 For Loop (Advanced Examples)
Mid Term Exams
9 Functions, Functions Declaration and Definition, Function Calling
9 Parameters of Functions, Argument Passing
10 Return Type, Return Value, Inline Functions, Local and GlobalVariables
11 Pointers, Pointers of Arrays, Pointer constants and pointer variables,
12 Passingpointers asarguments, Pointer and functions, Basic concept of Pass by
reference
13 Basic concepts of arrays, Traversing arrays
14 Arrays (Advanced Examples)
15 Strings and their oprations
16 File Handling in C++
2
Lab Manual Programming Fundmental with C++
Follow the below steps to install Code Blocks for C++ on windows:
Step 3: Click on the First Result shown on the Search Engine or click on this link.
3
Lab Manual Programming Fundmental with C++
Step 6: As per this Date, the Latest Version of Code Blocks is 20.03. Now here you’ll find several
download options
4
Lab Manual Programming Fundmental with C++
I’ll suggest you download the file with MinGW written on it (“codeblocks-20.03mingw-setup.exe”) as
MinGW is a Compiler that is needed to run the Program. If you download the normal setup file then you
have to download The compiler separately.
Step 7: Click on Sourceforge.net under the Download Section of your desired file.
Step 9: When the download is completed, Open Your Code Blocks Setup File.
5
Lab Manual Programming Fundmental with C++
Step 12: Click On Next ( you need to have at least 600 MB free storage on your drive for the
installation).
6
Lab Manual Programming Fundmental with C++
7
Lab Manual Programming Fundmental with C++
Step 14: Once Installation gets completed, click on Next and then Click on Finish
8
Lab Manual Programming Fundmental with C++
Step 1: Go to your Code Blocks MinGW installation folder location ( For me it is C:\Program
Files\CodeBlocks\MinGW\bin) and copy the address
9
Lab Manual Programming Fundmental with C++
Step 5: Click on New and Paste the Address into it and click on OK
10
Lab Manual Programming Fundmental with C++
11
Lab Manual Programming Fundmental with C++
12
Lab Manual Programming Fundmental with C++
13
Lab Manual Programming Fundmental with C++
Lab Objective:
Variable declaration and initialization, Assignment Operator
Lab Description:
Data Types:
A variable provides us with named storage that our programs can manipulate. Each variable in C++ has a specific
type, which determines the size and layout of the variable's memory, this type is known as data type of that variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin with either
a letter or an underscore. Upper and lowercase letters are distinct because C++ is case- sensitive
int a;
char b;
float c;
14
Lab Manual Programming Fundmental with C++
A variable can be initialized at the time of declaration or even after that. Basically initialization
means storing some actual meaningful data inside the variable.
int a=2;
char b=’x’;
float c=2.907
Constants
Constants refer to fixed values that the program may not alter during its execution. These
fixed values are also called literals.
Defining Constants
There are two simple ways in C++ to define constants:
Using #define preprocessor
#define LENGTH 10
Legal Identifiers:
Regardless of which style you adopt, be consistent and make your variable names as
sensible as possible. Here are some specific rules that must be followed with all
identifiers.
• The first character must be one of the letters a through z, A through Z, or
an underscore character (_).
• After the first character you may use the letters a through z or A through Z, the
digits 0 through 9, or underscores.
• Uppercase and lowercase characters are distinct. This means ItemsOrdered is
not the same as itemsordered.
Escape Sequence:
15
Lab Manual Programming Fundmental with C++
Assignment Operator:
C++ provides several assignment operators for abbreviating assignment expressions.
Any statement of the form
in which the same variable appears on both sides of the assignment operator and operator is one of the
binary operators +, -, *, /, or % , can be written in the form
variable operator= expression;
16
Lab Manual Programming Fundmental with C++
Above are examples of how the assignment operator is applied in code and works
17
Lab Manual Programming Fundmental with C++
Output is:
LAB Task
Task-1:
Type and save the following programs in Visual Studio. Run these programs and observe theiroutput.
Task2:
Take two integers as input from the user apply athematic operations on them(+,-,*,/) as printthem on screen.
Task3:
Task 4:
1. Calculate the Area of a Circle (area = PI * r2)
18
Lab Manual Programming Fundmental with C++
Home Tasks:
Task 1:
Exchange Write a program that reads in two variables and swaps the value of these variables. For example
if a variable ‘var1’ contains 10 and variable ‘var2’ contains 20, after the swap operation the variable ‘var1’
contains 20 (value of var2) and variable ‘var2’ contains 10 (value of var1).
Task 2:
Make Upper Write a program that prompts the user to enter an alphabet in small caps (a, b,c, … … … z)
and display the entered alphabet into its upper caps (A, B, C, … … … Z). (hint ASCII)
Task 3:
Write a C++ program to calculate the distance between the two points. Note: x1, y1, x2, y2 are all double
values.
Formula:
19
Lab Manual Programming Fundmental with C++
Task 4:
Total Purchase A customer in a store is purchasing five items. The prices of the five items are: Price of item
1 = $12.95
Price of item 2 = $24.95Price of item 3 = $6.95 Price of item 4 = $14.95Price of item 5 = $3.95
Write a program that holds the prices of the five items in five variables. Display each items price, the
subtotal of the sale, the amount of sales tax, and the total. Assume the sales tax is 6%.
Bonus Task:
Break Number:
Write a program that inputs a five-digit integer, separates the integer into its individual digits and prints the
digits separated from one another by three spaces each
20
Lab Manual Programming Fundmental with C++
Lab Description:
Operators’ precedence
Two operator characteristics determine how operands group with operators: precedence and
associativity. Precedence is the priority for grouping different types of operators with their
operands. Associativity is the left-to-right or right-to-left order for grouping operands to
operators that have the same precedence. An operator's precedence is meaningful only if other
operators with higher or lower precedence are present. Expressions with higher-precedence
operators are evaluated first. The grouping of operands can be forced by using parentheses.
Example:
Sample evaluation:
21
Lab Manual Programming Fundmental with C++
double x =
10.3; int y;
y = int (x); // functional
notation
22
Lab Manual Programming Fundmental with C++
Expressions:
Multiplication, mode and division have higher precedence than addition and subtraction.
Random Function:
rand() function is an inbuilt function in C++ STL, which is defined in header file
<cstdlib>. rand() is used to generate a series of random numbers. The random number
Output:
23
Lab Manual Programming Fundmental with C++
Output:
83 86 77 15 93
Formatting:
The following table represents various formatting operators used in C++ for output
manipulation
Example:
24
Lab Manual Programming Fundmental with C++
#include <iomanip>
#include <ios>
#include <iostream>
int main()
cout << "Before setting the width: \n" << num << endl;
// Using setw()
<< setw(5);
return 0;
Output
Before setting the width:
50
Setting the width using setw to 5:
50
25
Lab Manual Programming Fundmental with C++
In the above example, we have used setw() to add padding to the integer output. We can use setw() for
many such cases.
LAB:
Task 1:
Task 2:
Complete the following table by writing the value of each expression in the Value column
according C++ language rules.
Task 3:
26
Lab Manual Programming Fundmental with C++
Task 4:
Task 5:
Assume that qty and salesReps are both integers. Use a type cast expression to rewrite the
following statement so it will no longer perform integer division.
unitsEach = qty / salesReps;
Home Tasks:
Task 1:
Each of the following programs has some errors. Locate as many as you can.
Program-1
using namespace std; void main ()
{
Program-2
27
Lab Manual Programming Fundmental with C++
Task 2:
Average of Values to get the average of a series of values, you add the values up and then divide the sum by the
number of values. Write a program that stores the following values in five different variables: 28, 32, 37, 24, and
33. The program should first calculate the sum of these five variables and store the result in a separate variable
named sum. Then, the program should divide the sum variable by 5 to get the average. Display the average on the
screen.
28
Lab Manual Programming Fundmental with C++
1. C-Style Casting:
A cast is a special operator that forces one data type to be converted into another. As an
operator, a cast is unary and has the same precedence as any other unary operator.
The most general cast supported by most of the C++ compilers is as follows
Example: 1
#include <iostream>
using namespace std;
main() {
num_c = (int)num_a;
cout << "Line 1 - Value of (int) num_a is :" << num_c << endl; // 21
num_c = (int)num_b;
cout << "Line 2 - Value of (int) num_b is :" << num_c << endl; //
return 0;
return 0;
}
29
Lab Manual Programming Fundmental with C++
Example: 2
#include <iostream>
using namespace std;
main()
{
num_b = (float)num_a;
cout << num_b << endl;
num_b = (float)num_c;
return 0;
Example: 3
#include <iostream>
using namespace std;
main() {
double num_a;
float num_b= 22.1;;
int num_c = 10;
num_a = (double)num_b;
cout << num_a << endl;
num_a = (double)num_c;
cout << num_a << endl;
return 0;
}
30
Lab Manual Programming Fundmental with C++
Example: 4
#include <iostream>
using namespace std;
int main()
{ //ASCII NOs
char alp = 'C';
int num_c = 45;
num_c = (int)alp;
cout << num_c << endl;
alp = (char)num_c;
cout << alp << endl;
return 0;
TASK
• Take Birthday month, Day and Year as an Input from user and convert it into floating
point.
• Find the ASCII code of ‘A’, ‘e’, ‘i’, ‘O’, ‘U’
• Create Encryption Decrypion Model where Convert the word ‘H’, ‘e’, ‘L’, ‘p’ into
ASCII code and than convert back to Char.
31
Lab Manual Programming Fundmental with C++
2. Formatting
Formatting program output is an essential part of any serious application.
Example:1
#include<iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Hello world 1" << endl;
cout << "Hello world 2\n";
return 0;
}
OUTPUT:
Hello world 1
Hello world 2
Example: 2
Important Point
The setw() manipulator only affects the next value to be printed.
The setw() manipulator takes an integer argument which is the minimum field width for the value to be
printed.
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
int main()
{
// A test of setw()
cout << "*" << "Hi there!" << "*" << endl;
cout << "*" << setw(20) << "Hi there!" << "*" << endl;
cout << "*" << setw(3) << "Hi there!" << "*" << endl;
return 0;
}
OUTPUT
*-17*
* -17*
*Hi there!*
32
Lab Manual Programming Fundmental with C++
* Hi there!*
*Hi there!*
Example: 3
Important Point
Right: Right-align all values in their fields. This is the default alignment value.
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
using std::left;
using std::right;
int main()
{
cout << "*" << -17 << "*" << endl;
cout << "*" << setw(6) << -17 << "*" << endl;
cout << left;
cout << "*" << setw(6) << -17 << "*" << endl << endl;
cout << "*" << "Hi there!" << "*" << endl;
cout << "*" << setw(20) << "Hi there!" << "*" << endl;
cout << right;
cout << "*" << setw(20) << "Hi there!" << "*" << endl;
return 0;
}
Output:
*-17*
* -17*
*-17 *
*Hi there!*
*Hi there! *
* Hi there!*
Example:4
33
Lab Manual Programming Fundmental with C++
Internal: Internally aligns numeric values in their fields. Internal alignment separates the sign of a
number from its digits. The sign is left-aligned and the digits are right-aligned. This is a useful format in
accounting and business programs, but is rarely used in other applications.
Setfill: Sets the specified character as the stream's fill character. The fill character is the character used
by output insertion functions to fill spaces when padding results to the field width.
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::setw;
using std::internal;
int main()
{
cout << setw(9) << -3.25 << endl;
cout << setfill('0');
cout << internal << setw(9) << -3.25 << endl;
cout << setfill(' ');
cout << internal << setw(9) << -3.25 << endl;
return 0;
}
OUTPUT
-3.25
-00003.25
- 3.25
Example: 5
The manipulator fixed will set up the output stream for displaying floating-point values in fixed
format.
The scientific manipulator forces all floating point values to be displayed in scientific notation.
#include <iostream>
using std::cout;
using std::endl;
using std::scientific;
using std::fixed;
using std::ios;
int main()
{
float small = 3.1415926535897932384626;
float large = 6.0234567e17;
float whole = 2.000000000;
return 0;
}
Output
Task
• Take 3 numbers from the user one by one and Perform Setfill with Internal method.
• Take double type no# from the user and apply Scientific format and right method.
35
Lab Manual Programming Fundmental with C++
Examples:
// C program to illustrate If statement
#include <stdio.h>
int main()
{
int i = 10;
if (i > 15) {
cout<<("10 is greater than 15");
}
OutPut:
I am Not in if
Exmaple
#include <iostream>
using namespace std;
36
Lab Manual Programming Fundmental with C++
int main () {
// local variable declaration:
int a = 10;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Example
#include <iostream>
using namespace std;
37
Lab Manual Programming Fundmental with C++
int main () {
// local variable declaration:
int a = 100;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Example
int main()
{
int i = 20;
if (i == 10)
cout << ("i is 10");
else if (i == 15)
cout << ("i is 15");
else if (i == 20)
cout << ("i is 20");
else
cout << ("i is not present");
}
Output
i is 20
Eample
#include <iostream>
using namespace std;
int main() {
38
Lab Manual Programming Fundmental with C++
double cm=0.3937;
double m=1.0936;
double km=0.6214;
double num;
char menu_char;
//Menu
cout << "Press c for Centimeters to Inches\n";
cout << "Press m for Meters to Yards\n";
cout << "Press k for Kilometers to Miles\n";
//enter c, m, or k
cin >> menu_char;
if(menu_char == 'c') {
cout << " Centimeters equals " << num * cm << " Inches";
}
cout << " Meters equals " << num * m << " Yards";
}
cout << " Kilometers equals " << num * km << " Miles";
}
else
return 0;
}
Find Output:
39
Lab Manual Programming Fundmental with C++
Example: Nested
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
int a = 100;
int b = 200;
return 0;}
Example
// C++ program to find if an integer is positive, negative or zero
// using nested if statements
#include <iostream>
using namespace std;
int main() {
int num;
// outer if condition
if (num != 0) {
// inner if condition
if (num > 0) {
cout << "The number is positive." << endl;
}
// inner else condition
else {
cout << "The number is negative." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither positive nor negative." << endl;
}
return 0;
40
Lab Manual Programming Fundmental with C++
Output 1
Enter an integer: 35
The number is positive.
This line is always printed.
Output 2
Output 3
Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.
Example
if (i == 10) {
// First if statement
if (i < 15)
cout<<("i is smaller than 15\n");
// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
cout<< ("i is smaller than 12 too\n");
else
cout<< ("i is greater than 15");
}
return 0;
}
Output
i is smaller than 15
i is smaller than 12 too
Example
41
Lab Manual Programming Fundmental with C++
// driver code
int main()
{
int var;
int flag = 0;
return 0;
}
Output
Value of var when flag is 0: 25
Value of var when flag is NOT 0: -25
Example
Example
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (n % 2 == 0) {
cout << "Even" << endl;
}
else {
cout << "Odd" << endl;
}
return 0;
}
Output
Enter a number: Even
#include <iostream>
#include <string>
using namespace std;
int main() {
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
return 0;
}
Output
Good Evening
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = 0;
string result;
return 0;
}
Output
Number is Zero
&& AND
The AND ( && ) operator can be used in a multiple conditional “if” statement. Note the parenthesis
used to make each condition more clear to the programmer.
int var1=7;
int var2=11;
int var3=20;
if( (var1 < var2) && (var3 > var1) //if condition1 AND condition2 is true
|| OR
The OR ( || ) operator can be used in a multiple conditional “if” statement. Note the parenthesis used to
make each condition more clear to the programmer.
int var1=7;
int var2=11;
int var3=20;
if( (var1 < var2) || (var1 > var3) ) //if condition1 OR condition2 is true
! NOT
The NOT ( ! ) operator isn’t used as much, but can still make itself useful. Note the parenthesis used to
make each condition more clear to the programmer.
int var1=7;
int var2=11;
int var3=20;
bool status=false;
if( !status && (var3 > var2) ) //if status is NOT true AND condition is true
44
Lab Manual Programming Fundmental with C++
Example
#include <iostream>
using namespace std;
int main()
{
int a = 1, b = 3, c = 2;
if (a == b) {
if (c > b)
else
else
}
Output
a does not equal b
#include <iostream>
using namespace std;
int main()
{
int no = 8;
(no & 1 && cout << "odd" )|| cout << "even";
return 0;
}
Output
45
Lab Manual Programming Fundmental with C++
even
Task
• Take no from User and Check Whether Number is Even or Odd using if else
• Check Whether Number is Even or Odd without using If-else keyword
• Check Vowel or a Consonant Manually (Five alphabets a, e, i, o and u are known as vowels. All
other alphabets except these 5 alphabets are known as consonants.)
• Find Largest Number Using if...else Statement ( In this program, the user is asked to enter three
numbers this program finds out the largest number among three numbers entered by user and
displays it with a proper message.)
46
Lab Manual Programming Fundmental with C++
The switch statement allows us to execute a block of code among many alternatives.
You can do the same thing with the if...else statement. However, the syntax of the switch statement is
much easier to read and write.
switch (expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
Example
// Driver Code
int main()
{
// switch variable
char x = 'A';
// switch statements
switch (x) {
case 'A':
cout << "Choice is A";
break;
case 'B':
cout << "Choice is B";
break;
case 'C':
cout << "Choice is C";
break;
default:
cout << "Choice other than A, B and C";
break;
}
return 0;
}
47
Lab Manual Programming Fundmental with C++
Output
Choice is A
Example
#include <iostream>
using namespace std;
int main () {
// local variable declaration:
char grade = 'D';
switch(grade) {
case 'A' :
cout << "Excellent!" << endl;
break;
case 'B' :
case 'C' :
cout << "Well done" << endl;
break;
case 'D' :
cout << "You passed" << endl;
break;
case 'F' :
cout << "Better try again" << endl;
break;
default :
cout << "Invalid grade" << endl;
}
cout << "Your grade is " << grade << endl;
return 0;
}
You passed
Your grade is D
Example
int main()
{
int var = 2;
48
Lab Manual Programming Fundmental with C++
case 1:
printf("Case 1 is executed.\n");
case 2:
printf("Case 2 is executed.\n");
case 3:
printf("Case 3 is executed.\n");
case 4:
printf("Case 4 is executed.");
}
return 0;
}
Output
Case 2 is executed.
Case 3 is executed.
Case 4 is executed.
Example
int main()
{
int var1 = 1;
int var2 = 0;
// outer switch
switch (var1) {
case 0:
cout << "Outer Switch Case 0\n";
break;
case 1:
cout << "Outer Switch Case 1\n";
// inner switch
switch (var2) {
case 0:
cout << "Inner Switch Case 0\n";
break;
}
break;
default:
cout << "Default Case of Outer Loop";
break;
}
return 0;
}
Output
Outer Switch Case 1
Inner Switch Case 0
Example Enum
#include <iostream>
using namespace std;
49
Lab Manual Programming Fundmental with C++
int main()
{
enum color {RED, GREEN, BLUE};
switch (RED)
{
case RED:
cout << "red\n";
break;
case GREEN:
cout << "green\n";
break;
case BLUE:
cout << "blue\n";
break;
}
return 0;
Output
red
Example
#include <iostream>
int main()
{
cout << "Difficulty Levels\n\n";
cout << "1 - Easy\n";
cout << "2 - Normal\n";
cout << "3 - Hard\n\n";
switch (choice)
{
case easy:
cout << "You picked Easy." << endl;
break;
case normal:
cout << "You picked Normal." << endl;
break;
case hard:
cout << "You picked Hard." << endl;
break;
default:
cout << "You made an illegal choice." << endl;
}
50
Lab Manual Programming Fundmental with C++
system("pause");
return 0;
}
Find output
Task
#include <iostream>
using namespace std;
int main()
{
char marks;
switch (marks) {
break;
break;
break;
break;
default:
51
Lab Manual Programming Fundmental with C++
return 0;
Output 1
Output 2
Output 3
Output 4
In Previous labs we have seen the use of conditional statements, now getting one step forward, sometimes
there is a need to perform some operation more than once or (say) n number of times. Loops come into
use when we need to repeatedly execute a block of statements. For example: Suppose we want to print
“Hello World” 10 times. This can be done in two ways as shown below:
Manually we have to write cout for the C++ statement 10 times. Let’s say you have to write it 20 times
(it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it
would be really hectic to re-write the same statement again and again. So, here loops have their role. This
is represented by the code written as follows.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
cout << "Hello World\n";
return 0;
}
Using Loops:
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown
below. In computer programming, a loop is a sequence of instructions that is repeated until a certain
condition is reached. That was just a simple example; we can achieve much more efficiency and
sophistication in our programs by making effective use of loops.
#include <iostream>
using namespace std;
int main() {
for (int i = 0; i < 10; ++i) {
cout << "Hello World" << endl;
}
return 0;
}
53
Lab Manual Programming Fundmental with C++
1. for loop
2. while loop
3. do...while loop
In this Lab, we will learn the syntax of while loop in C++, its algorithm, flowchart, then some examples
illustrating the usage of it. Later we shall go through Infinite While Loop and Nested While Loop.
A while loop statement repeatedly executes the code block within as long as the condition is true. The
moment the condition becomes false, the program will exit the loop. While Loop in C++ is used in
situations where we do not know the exact number of iterations of the loop beforehand.
Note: The while loop might not ever run. If the condition is initially false, the code block will be skipped.
while (condition) {
// statement(s)
}
At the start of while loop execution, the condition is checked. If the condition is true, statement(s) inside
while block are executed. The condition is checked again. If it evaluates to true, the statement(s) inside
the while loop are executed. This cycle goes on. If at all, the condition evaluates to false, execution comes
out of while loop, meaning while loop is completed. And the program continues with the execution of
statements after while loop if any. This working is shown in the figure below:
54
Lab Manual Programming Fundmental with C++
You have to take care of the initialization and update of the variables present in condition. And make
sure that the condition would break after a definite number of iterations. If the condition is never going
to be false, then the while loop is going to execute indefinitely.
Infinite Loop
An infinite loop in C++ is a loop that continues to execute indefinitely. This often occurs when the loop's
termination condition is never met. Here's an example of an infinite loop in C++ using a while loop:
#include <iostream>
using namespace std;
int main() {
while (true) {
cout << "This is an infinite loop!" << endl;
}
// The code below the loop will never be reached
cout << "This code is unreachable." << endl;
return 0;
}
55
Lab Manual Programming Fundmental with C++
In this example, the while (true) statement creates an infinite loop because the condition is always true.
The loop will continue to print "This is an infinite loop!" to the console without ever terminating.
Output:
The code below the loop will never be executed because the loop is infinite.
It's important to avoid unintentional infinite loops in your code as they can lead to programs that don't
behave as expected and may become unresponsive. Always ensure that your loops have appropriate
termination conditions.
In this example, we shall write a while loop that prints numbers from 1 to 5 . The while loop contains
statement to print a number, and the condition checks if the number is within the limits.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int n = 5;
int i = 1;
while (i<=n) {
cout << i << "\n";
i++;
}
}
Output:
1
2
3
4
5
C++ Code:
56
Lab Manual Programming Fundmental with C++
#include <iostream>
using namespace std;
int main() {
int n = 5;
int factorial = 1;
int i = 1;
while (i<=n) {
factorial *= i;
i++;
}
cout << factorial;
}
Output:
120
Exercise 1.1
Write a C++ program to print all even numbers between 1 to 100 using while loop.
Sample output:
2
4
6
8
.
.
.
100
Solution:
#include <iostream>
using namespace std;
int main() {
int number = 1;
return 0;
}
57
Lab Manual Programming Fundmental with C++
Exercise 1.2
Write a C++ program that asks the user to type 10 integers. The program must compute how many even
and odd numbers were entered along with numbers that are divisible by 7.
Sample output:
Enter 10 integers :
1
2
3
4
5
6
7
8
9
10
Number of even numbers: 5
Number of odd numbers: 5
Numbers divisible by 7: 1
Solution:
#include <iostream>
using namespace std;
int main() {
int number;
int evenCount = 0, oddCount = 0, divisibleBy7Count = 0;
cout << "Number of even numbers: " << evenCount << endl;
cout << "Number of odd numbers: " << oddCount << endl;
cout << "Numbers divisible by 7: " << divisibleBy7Count << endl;
return 0;
58
Lab Manual Programming Fundmental with C++
Exercise 1.3
Write a C++ program to print the Fibonacci sequence up to a specified number of terms entered by the
user using a while loop.
Sample output:
Enter the number of Fibonacci terms: 10
Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Solution:
#include <iostream>
using namespace std;
int main() {
int numTerms;
return 0;
}
Exercise 1.4
Develop a number guessing game in C++ where the program generates a random number between 1 and
100. The user then tries to guess the number. The program should provide hints like "too high" or "too
low" until the user guesses the correct number. Use a while loop to repeatedly prompt the user for guesses.
59
Lab Manual Programming Fundmental with C++
Sample output:
Welcome to the Number Guessing Game!
Try to guess the secret number between 1 and 100.
Enter your guess: 76
Too low! Try again.
Enter your guess: 80
Too low! Try again.
Enter your guess: 90
Too low! Try again.
Enter your guess: 96
Too low! Try again.
Enter your guess: 97
Too low! Try again.
Enter your guess: 99
Too high! Try again.
Enter your guess: 98
Congratulations! You guessed the correct number in 7 attempts.
Solution:
#include <iostream>
#include <cstdlib> // For rand() and srand() functions
#include <ctime> // For time()
int main() {
// Seed the random number generator
srand(time(nullptr));
int guess;
int attempts = 0;
}
else if (guess < secretNumber)
{
cout << "Too low! Try again.\n";
}
else {
cout << "Too high! Try again.\n";
}
}
return 0;
}
Exercise 1.5
Write a C++ program that prompts the user to enter a positive integer. Use a while loop to print the
multiplication table for that number up to 10.
Sample output:
Enter a positive integer: -3
Please enter a positive integer: 3
Multiplication table for 3:
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Solution:
#include <iostream>
using namespace std;
int main() {
int number;
return 0;
}
Exercise 1.6
Write a program that prompts the user for a number and then determines if the number is prime using a
while loop. (Hint: A prime number has exactly two factors: 1 and itself).
Sample output 1:
Enter a number: 3
3 is a prime number.
Sample output 2:
Enter a number: 34
34 is not a prime number.
Solution:
#include <iostream>
using namespace std;
int main() {
int number;
bool isPrime = true;
int i = 2;
while (i * i <= number)
{
62
Lab Manual Programming Fundmental with C++
if (number % i == 0)
{
isPrime = false;
break;
}
i++;
}
}
return 0;
}
Exercise 1.6
Write a program that reads a list of integers from the user until they enter 0. Use a while loop to
calculate the average of the positive numbers entered.
Sample output:
Enter integers (enter 0 to stop):
3
2
4
5
6
0
Average of the positive numbers entered: 4
Solution:
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
int count = 0;
63
Lab Manual Programming Fundmental with C++
{
if (number > 0)
{
sum += number;
count++;
}
cin >> number; // Read the next number
}
return 0;
}
In Previous labs we have seen the use of while loops, now the next loop in line is do…while loop.
The do…while in C++ is a loop statement used to repeat some part of the code till the given condition is
fulfilled. It is a form of an exit-controlled or post-tested loop where the test condition is checked after
executing the body of the loop. Due to this, the statements in the do…while loop will always be executed
at least once no matter what the condition is.
do{
Statement(s)
}while(condition);
64
Lab Manual Programming Fundmental with C++
The body of the loop is executed first. Then the condition is evaluated. If the condition evaluates to true,
the body of the loop inside the do statement is executed again. The condition is evaluated once again. If
the condition evaluates to true, the body of the loop inside the do statement is executed again. This process
continues until the condition evaluates to false. Then the loop stops.
65
Lab Manual Programming Fundmental with C++
In C++ and many other programming languages, while and do...while loops are used for iteration, but
they have some differences in their behavior:
• Condition Evaluation:
In a while loop, the condition is evaluated before the loop body is executed. If the condition is false
initially, the loop body may never execute. In a do...while loop, the condition is evaluated after the loop
body is executed. This guarantees that the loop body will execute at least once, regardless of the
condition's initial value.
• Entry Control vs. Exit Control:
while loops are called entry-controlled loops because the condition is evaluated before entering the loop
body. If the condition is false initially, the loop body won't execute at all. do...while loops are exit-
controlled loops because the condition is evaluated after executing the loop body. This means that the
loop body will execute once before the condition is checked.
Syntax:
while loop syntax:
while (condition) {
// loop body
}
do...while loop syntax:
do {
// loop body
} while (condition);
• Use a while loop when you want to execute the loop body zero or more times, based on the condition.
66
Lab Manual Programming Fundmental with C++
• Use a do...while loop when you want to execute the loop body at least once, regardless of the condition,
and then continue execution as long as the condition is true.
Here's a basic example illustrating the difference:
#include <iostream>
using namespace std;
int main() {
int i = 5;
// while loop
while (i < 5) {
cout << "While loop: " << i << endl;
i++;
}
i = 5;
// do...while loop
do {
cout << "Do...While loop: " << i << endl;
i++;
} while (i < 5);
return 0;
}
In this example, the while loop doesn't execute because the condition (i < 5) is false initially. However,
the do...while loop executes once before checking the condition, so it prints "Do...While loop: 5" even
though the condition is false.
In this example, we shall write a while loop that prints numbers from 1 to 5 . The do…while loop contains
statement to print a number, and the condition checks if the number is within the limits.
C++ Code:
#include <iostream>
using namespace std;
int main() {
int n = 5;
int i = 1;
do {
cout << i << "\n";
i++;
67
Lab Manual Programming Fundmental with C++
} while (i<=n);
}
Output:
1
2
3
4
5
C++ Code:
#include <iostream>
using namespace std;
int main() {
int number;
int factorial = 1;
return 0;
}
Output:
68
Lab Manual Programming Fundmental with C++
Exercise 1.1
Write a program to print in the descending order first twenty natural numbers on the computer
screen by using “do-while” loop.
Sample output:
First twenty natural numbers in descending order:
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
Solution:
#include <iostream>
using namespace std;
int main() {
int number = 20; // Starting number
Exercise 1.2
Simulate a basic ATM with a do-while loop. The program starts with a specific balance (up to user).
The user can perform withdrawals (check for sufficient funds) or deposits. Use a do-while loop to keep
asking for transactions (withdrawal/deposit) until the user chooses to exit.
Sample output:
Welcome to the ATM!
Solution:
#include <iostream>
using namespace std;
int main() {
double balance = 1000.0; // Starting balance
char choice;
double amount;
switch (choice) {
case 'W' | ‘w’:
cout << "Enter the amount to withdraw: $";
cin >> amount;
if (amount > balance)
{
cout << "Insufficient funds!" << endl;
}
else
{
balance -= amount;
cout << "Withdrawal successful. New balance: $" <<
balance << endl;
}
break;
cout << "Exiting. Thank you for using the ATM!" << endl;
break;
default:
cout << "Invalid choice! Please try again." << endl;
}
} while (choice != 'E' && choice != 'e');
70
Lab Manual Programming Fundmental with C++
return 0;
}
Exercise 1.3
Write a program in C++ to find the perfect numbers between 1 and 500. (Hint: A perfect number is a
positive integer that is equal to the sum of its positive divisors, excluding the number itself1234. For
example, 6 is a perfect number because 1 + 2 + 3 = 6 )
Sample output:
Perfect numbers between 1 and 500:
6
28
496
Solution:
#include <iostream>
using namespace std;
int main() {
int number = 1;
if (sum == number) {
cout << number << endl;
}
number++;
} while (number <= 500);
return 0;
}
Exercise 1.4
Write a C++ program that prompts the user for a positive odd number. Use a do-while loop to find and
print the sum of all even numbers between 2 (inclusive) and the entered odd number (exclusive).
71
Lab Manual Programming Fundmental with C++
Sample output 1:
Enter a positive odd number: 45
Sum of all even numbers between 2 and 45 (exclusive): 506
Sample output 2:
Enter a positive odd number: 32
Invalid input! Please enter a positive odd number.
Enter a positive odd number: 11
Sum of all even numbers between 2 and 11 (exclusive): 30
Solution:
#include <iostream>
using namespace std;
int main() {
int oddNumber;
// Finding and printing the sum of all even numbers between 2 and the
entered odd number
int sum = 0;
int evenNumber = 2;
while (evenNumber < oddNumber) {
sum += evenNumber;
evenNumber += 2;
}
cout << "Sum of all even numbers between 2 and " << oddNumber << "
(exclusive): " << sum << endl;
return 0;
}
Exercise 1.5
72
Lab Manual Programming Fundmental with C++
Write a program in C++ to calculate the sum of the series (1*1) + (2*2) + (3*3) + (4*4) + (5*5) + ... +
(n*n).
Sample output:
Enter the value of n: 6
The sum of the series is: 91
Solution:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
int sum = 0;
int i = 1;
do {
sum += i * i;
i++;
} while (i <= n);
cout << "The sum of the series is: " << sum << endl;
return 0;
}
Exercise 1.6
Write a C++ program to make such a pattern like a pyramid with numbers increased by 1.
Sample output:
Display such a pattern like a pyramid with numbers increased by 1:
-----------------------------------------------------------------------
Input number of rows: 4
1
2 3
4 5 6
7 8 9 10
Solution:
#include <iostream>
#include <string>
73
Lab Manual Programming Fundmental with C++
cout << "\n\n Display such a pattern like a pyramid with numbers
increased by 1:\n";
cout << "---------------------------------------------------------------
--------\n";
cout << " Input number of rows: ";
cin >> rows;
spc = rows + 4 - 1;
i = 1;
do {
k = spc;
do {
cout << " ";
k--;
} while (k >= 1);
j = 1;
do {
cout << t++ << " ";
j++;
} while (j <= i);
return 0;
}
Exercise 1.7
*
***
*****
*******
*********
*******
*****
***
74
Lab Manual Programming Fundmental with C++
*
Solution:
#include <iostream>
using namespace std;
int main() {
int i, j, r;
i = 0;
do {
j = 1;
do {
cout << " ";
j++;
} while (j <= r - i);
j = 1;
do {
cout << "*";
j++;
} while (j <= 2 * i - 1);
i = r - 1;
do {
j = 1;
do {
cout << " ";
j++;
} while (j <= r - i);
j = 1;
do {
cout << "*";
j++;
} while (j <= 2 * i - 1);
return 0;
}
75
Lab Manual Programming Fundmental with C++
Exercise 1.1
Write a program in C++ to find the first 10 natural numbers
Note : Here, in this example you are required to print the first 10 natural numbers using a for loop.
Sample output:
76
Lab Manual Programming Fundmental with C++
Solution:
using namespace std; // Using the standard namespace to avoid writing std::
cout << "\n\n Find the first 10 natural numbers:\n"; // Display a message to
find the first 10 natural numbers
cout << "---------------------------------------\n"; // Display a separator
line
cout << " The natural numbers are: \n"; // Display a message indicating the
list of natural numbers
Write a program in C++ to find the sum of the first 10 natural numbers.
Sample output:
77
Lab Manual Programming Fundmental with C++
Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file
using namespace std; // Using the standard namespace to avoid writing std::
cout << "\n\n Find the first 10 natural numbers:\n"; // Display a message to
find the first 10 natural numbers
cout << "---------------------------------------\n"; // Display a separator
line
cout << " The natural numbers are: \n"; // Display a message indicating the
list of natural numbers
// Loop to print the first 10 natural numbers and calculate their sum
for (i = 1; i <= 10; i++)
{
cout << i << " "; // Output each natural number followed by a space
sum = sum + i; // Calculate the sum by adding the current number 'i' to
'sum'
}
cout << "\n The sum of first 10 natural numbers: " << sum << endl; // Display
the sum of the first 10 natural numbers
}
Exercise 1.3
Write a program in C++ to check whether a number is prime or not.
78
Lab Manual Programming Fundmental with C++
Sample output:
Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file
using namespace std; // Using the standard namespace to avoid writing std::
cout << "\n\n Check whether a number is prime or not:\n"; // Display a message
indicating the purpose
cout << "--------------------------------------------\n"; // Display a
separator line
cout << " Input a number to check prime or not: "; // Prompting the user to
input a number
cin >> num1; // Reading the input number entered by the user
for (int a = 1; a <= num1; a++) // Start of a 'for' loop from 1 to the input
number 'num1'
{
if (num1 % a == 0) // Check if 'num1' is divisible by 'a' without any
remainder
{
ctr++; // Increment 'ctr' when 'num1' is divisible by 'a'
}
79
Lab Manual Programming Fundmental with C++
Exercise 1.4
Write a program in C++ to find the factorial of a number.
Sample output:
Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file
using namespace std; // Using the standard namespace to avoid writing std::
cout << " The factorial of the given number is: " << factorial << endl; //
Displaying the factorial of the entered number
Exercise 1.5:
Write a program in C++ to find the sum of the digits of a given number.
Sample output:
81
Lab Manual Programming Fundmental with C++
Solution:
using namespace std; // Using the standard namespace to avoid writing std::
num2 = num1; // Store the original number in 'num2' for displaying later
82
Lab Manual Programming Fundmental with C++
Test Exercise
Q1: Write a program in C++ to find the natural numbers between 90 to 100 and print them in reverse
order.
Sample output:
The natural numbers are:
100 99 98 97 96 95 94 93 92 91 90
Q2: Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers.
Sample Output:
Input the first number: 25
Input the second number: 15
The Greatest Common Divisor is: 5
Q3: Write a program in C++ to find the perfect numbers between 1 and 500.
The perfect numbers between 1 to 500 are:
6
28
496
Q4: Write a program in C++ to display n terms of natural numbers and their sum.
Sample Output:
Input a number of terms: 7
The natural numbers upto 7th terms are:
1234567
The sum of the natural numbers is: 28
Q5: Write a program that will print the table of the user choice number. For example, if the user has given
the number 5, then the output will be:
5x1=5
5 x 2 = 10
83
Lab Manual Programming Fundmental with C++
5 x 3 = 15
5 x 4 = 20
…
5 x 10 = 50
84
Lab Manual Programming Fundmental with C++
Exercise 1.1
Write a program in C++ to print the half star pyramid using nested for loop
Sample output:
Solution:
#include <iostream>
using namespace std;
int main()
{
int i, j, n;
cout << "Enter number of rows: ";
cin >> n;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= i; j++)
{
cout << "* ";
}
//Ending line after each row
cout << "\n";
}
return 0;
}
Exercise 1.2
Write a program in C++ to print the following pattern using for loop
85
Lab Manual Programming Fundmental with C++
Solution:
#include <iostream>
using namespace std;
int main()
{
int rows, columns, number = 1, n = 5;
Exercise 1.3
Write a program in C++ to find the Greatest Common Divisor (GCD) of two numbers.
86
Lab Manual Programming Fundmental with C++
Sample output:
Solution:
#include <iostream> // Preprocessor directive to include the input/output stream
header file
using namespace std; // Using the standard namespace to avoid writing std::
// Display a message to find the Greatest Common Divisor (GCD) of two numbers
cout << "\n\n Find the Greatest Common Divisor of two numbers:\n";
cout << "-----------------------------------------------------\n";
// Loop to find the Greatest Common Divisor (GCD) of num1 and num2
for (int i = 1; i <= num1 && i <= num2; i++)
{
if (num1 % i == 0 && num2 % i == 0) // Check if 'i' divides both num1 and
num2 evenly
{
gcd = i; // Update the 'gcd' variable with the current common divisor
}
}
87
Lab Manual Programming Fundmental with C++
Exercise 1.4
Factorial of any number n is represented by n! and is equal to 1*2*3*....*(n-1)*n. E.g.-
4! = 1*2*3*4 = 24
3! = 3*2*1 = 6
2! = 2*1 = 2
Also,
1! = 1
0! = 0
Write a C++ program to calculate factorial of a number.
Solution:
#include <iostream>
int main()
{
using namespace std;
int j,number;
cout << "Enter number" << "\n";
cin >> number;
int fact = 1;
for (j=1;j<=number;j++){
fact = fact*j;
}
cout << fact << "\n";
return 0;
}
Exercise 1.5:
Write a program in C++ to calculate the series (1) + (1+2) + (1+2+3) + (1+2+3+4) + ... +
(1+2+3+4+...+n).
Sample output:
88
Lab Manual Programming Fundmental with C++
Solution:
using namespace std; // Using the standard namespace to avoid writing std::
// Display a message to find the sum of the series (1) + (1+2) + (1+2+3) +
(1+2+3+4) + ... + (1+2+3+4+...+n)
cout << "\n\n Find the sum of the series (1) + (1+2) + (1+2+3) + (1+2+3+4) +
... + (1+2+3+4+...+n):\n";
cout << "----------------------------------------------------------------------
--------------------\n";
// Prompt the user to input the value for the nth term of the series
cout << " Input the value for nth term: ";
cin >> n; // Read the value entered by the user
for (j = 1; j <= i; j++) // Inner loop to calculate the partial sums for
each term of the series
{
sum += j; // Add 'j' to 'sum'
tsum += j; // Add 'j' to 'tsum' for the current term
if (j < i) // Condition to print '+' for all values of 'j' except the
last one in each term
{
cout << "+"; // Display '+'
}
}
cout << " = " << tsum << endl; // Display the calculated partial sum for
the current term
89
Lab Manual Programming Fundmental with C++
Test Exercise
Q1: Write a program in C++ to print the inverted star pattern by taking the number of rows from the
user as shown below
Sample output:
Q3: Write a program in C++ to display the cube of the number up to an integer.
Sample Output:
Input the number of terms : 5
90
Lab Manual Programming Fundmental with C++
72 --> H
73 --> I
74 --> J
92
Lab Manual Programming Fundmental with C++
Functions:
A function is a group of statements that together perform a task. Every C++ program has at least one
function, which is main(), and all the most trivial programs can define additional functions. You can
divide up your code into separate functions. How you divide up your code among different functions is
up to you, but logically the division usually is so each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters. A function
definition provides the actual body of the function. The C++ standard library provides numerous built-in
functions that your program can call. For example, function strcat() to concatenate two strings, function
memcpy() to copy one memory location to another location and many more functions.
A function is knows as with various names like a method or a sub-routine or a procedure etc.
Defining a Function:
The general form of a C++ function definition is as follows:
A C++ function definition consists of a function header and a function body. Here are all the parts of a
function:
• Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
• Function Name: This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
• Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list refers
to the type, order, and number of the parameters of a function. Parameters are optional; that is, a
function may contain no parameters.
• Function Body: The function body contains a collection of statements that define what the
function does.
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a function,
you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function
performs defined task and when its return statement is executed or when its function-ending closing brace
is reached, it returns program control back to the main program.
93
Lab Manual Programming Fundmental with C++
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value.
Exercise 1.1
Write a C++ program that defines a function max to find and return the maximum value
between two integers.
Sample output:
Max value is : 200
Solution:
#include <iostream>
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
return 0;
}
94
Lab Manual Programming Fundmental with C++
Exercise 1.2
Write a C++ function calculatePolynomial that evaluates a polynomial expression of the form
ax^2 + bx + c given the values of a, b, c, and x. The function should take four parameters: the
coefficients a, b, and c, and the value of x. Demonstrate the usage of this function by calling it with
different sets of coefficients and x values.
Sample Output 1:
Enter the coefficient a: 3
Sample Output 2:
Enter the coefficient a: 3
Solution:
#include <iostream>
using namespace std;
return a * x * x + b * x + c;
int main() {
double a, b, c, x;
95
Lab Manual Programming Fundmental with C++
cin >> a;
cout << "Enter the coefficient b: ";
cin >> b;
cin >> c;
cout << "Enter the value of x: ";
cin >> x;
return 0;
Exercise 1.3
Write a C++ program that defines a function named isPrime which takes an integer as a parameter
and returns true if the number is prime and false otherwise.
Sample output 1:
Enter a number: 12
12 is not a prime number.
Sample output 2:
Enter a number: 11
11 is a prime number.
Solution:
#include <iostream>
using namespace std;
if (num <= 1) {
96
Lab Manual Programming Fundmental with C++
int main() {
int number;
return 0;
}
Test Exercise
1. Write a C++ program that defines a function named reverseString which takes a string as a parameter
and returns the reverse of the input string.
Sample output:
Enter a string: ProgrammingFundamentals
Reversed string: slatnemadnuFgnimmargorP
2. Develop a C++ program that defines a function named isPalindrome which takes a string as a
parameter and returns true if the string is a palindrome (reads the same backward as forward), otherwise
returns false.
Sample output 1:
Enter a string: Iqra
"Iqra" is not a palindrome.
Sample output 2:
Enter a string: karak
97
Lab Manual Programming Fundmental with C++
"karak" is a palindrome.
3. Write a program that defines a function named countOccurrences which takes a large number and a
single digit as parameters and returns the number of occurrences of that digit in the number.
Sample Output:
Enter a large number: 23729202
Enter a single digit: 2
Number of occurrences of digit 2 in 23729202: 4
98
Lab Manual Programming Fundmental with C++
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the arguments. These
variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type Description
Call by value This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument
Call by pointer This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
Call by reference This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
Exercise 1.1:
Write a C++ program that defines a function sum to calculate the sum of two integers. The function
takes two parameters, a and b, where b has a default value. Demonstrate the usage of this function by
calling it twice in the main function: once with both parameters provided, and once with only a provided,
relying on the default value of b. Display the total value after each function call.
Sample output:
Total value is : 300
Solution:
#include <iostream>
using namespace std;
99
Lab Manual Programming Fundmental with C++
int result;
result = a + b;
return (result);
int main ()
int a = 100;
int b = 200;
int result;
// calling a function to add the values.
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
Exercise 1.2
Write a C++ program that defines a function named swap which swaps the values of two integers.
After swapping, the program should print the values of a and b before and after the swap.
Sample output :
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Call by Value:
100
Lab Manual Programming Fundmental with C++
Solution:
#include <iostream>
using namespace std;
// function declaration
void swap(int x, int y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
return 0;
}
Call by Pointers:
#include <iostream>
using namespace std;
// function declaration
101
Lab Manual Programming Fundmental with C++
int main ()
int a = 100;
int b = 200;
*/
swap(&a, &b); //call by pointers
return 0;
}
Call by Reference:
#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
return 0;
}
Test Exercise
1. Raising a number to a power p is the same as multiplying n by itself p times. Write a function called
power that takes two arguments, a double value for n and an int value for p, and return the result as double
value. Use default argument of 2 for p, so that if this argument is omitted the number will be squared.
Write the main function that gets value from the user to test power function.
Sample Output:
Enter number : 5
Enter exponent : 4
Result is 625
Result without passing exponent is 25
2. Write a function called zero_small() that has two integer arguments being passed by reference and sets
the smaller of the two numbers to 0. Write the main program to access the function.
Sample Output 1:
Enter first number : 23
Enter second number : 6
First number is : 23
Second number is : 0
Sample Output 2:
3. Create a C++ program that defines a function modifyNumber which takes an integer parameter by
reference and modifies it by doubling its value. Demonstrate the usage of this function by modifying and
printing the value of 5 different numbers.
Sample Output:
Enter three Numbers:
103
Lab Manual Programming Fundmental with C++
3 6 9
Before modification, num1: 3
After modification, num1: 6
Before modification, num2: 6
After modification, num2: 12
Before modification, num3: 9
After modification, num3: 18
104
Lab Manual Programming Fundmental with C++
Return Type:
In programming, a return type refers to the data type of the value that a function is expected to return after
it completes its execution. Every function in C++ has a return type, which is specified in its function
declaration. The return type indicates the type of data that the function will produce as output when it is
called.
In C++, the return type of a function is declared before the function name in its prototype and definition.
It can be any valid data type in C++, including fundamental data types (int, float, double, char, etc.), user-
defined data types (structures, classes, enums), or even void if the function does not return any value.
Example:
int add(int a, int b); // Function prototype with return type 'int'
float calculateAverage(int arr[], int size); // Function prototype with return type 'float'
A return value is the actual data that a function sends back to the caller after its execution is complete. It
represents the output or result produced by the function based on its computation or processing. The
return value is determined by the expression specified in the return statement within the function body.
When a function is called, it executes its statements and may produce a result that needs to be sent back
to the calling code. This result is conveyed through the return statement, which contains the value to be
returned. The return value is then received and used by the calling code to perform further operations or
assignments.
In C++, the return statement is used to explicitly specify the return value of a function. The return
statement typically includes an expression whose value is the return value of the function. If the return
type of the function is void, the return statement is optional, and the function may terminate without
returning a value.
Example:
int add(int a, int b) {
return a + b; // Return statement with the sum of 'a' and 'b' as the return value
}
void greetUser() {
cout << "Hello, User!" << endl;
// No return statement needed in a void function
}
Exercise 1.1
Write a function which calculates & returns area of the circle. Take appropriate data types.
Sample output: Enter the radius of the circle: 5
The area of the circle with radius 5 is: 78.5397
Solution:
#include <iostream>
using namespace std;
int main() {
double radius;
cout << "Enter the radius of the circle: ";
cin >> radius;
// Call the calculateArea function with the radius as the argument and store
the return value
double circleArea = calculateArea(radius);
cout << "The area of the circle with radius " << radius << " is: " <<
circleArea << endl;
return 0;
}
Inline Function:
C++ provides inline functions to reduce the function call overhead. An inline function is a function that is
expanded in line when it is called. When the inline function is called whole code of the inline function gets
inserted or substituted at the point of the inline function call. This substitution is performed by the C++ compiler
at compile time. An inline function may increase efficiency if it is small.
Example
inline return-type function-name(parameters)
{
// function code
}
106
Lab Manual Programming Fundmental with C++
When the program executes the function call instruction the CPU stores the memory address of the
instruction following the function call, copies the arguments of the function on the stack, and finally
transfers control to the specified function. The CPU then executes the function code, stores the function
return value in a predefined memory location/register, and returns control to the calling function. This
can become overhead if the execution time of the function is less than the switching time from the caller
function to called function (callee).
For functions that are large and/or perform complex tasks, the overhead of the function call is usually
insignificant compared to the amount of time the function takes to run. However, for small, commonly-
used functions, the time needed to make the function call is often a lot more than the time needed to
actually execute the function’s code. This overhead occurs for small functions because the execution
time of a small function is less than the switching time.
Exercise 1.2
Write a C++ program to calculate sqare of circle using inline function.
Sample Output 1:
Square of 5 is: 25
Solution:
#include <iostream>
int main() {
int num = 5;
int squared = square(num); // The function call is replaced with the actual
code of the function
std::cout << "Square of " << num << " is: " << squared << std::endl;
return 0;
}
Local Variables
Variables defined within a function or block are said to be local to those functions.
107
Lab Manual Programming Fundmental with C++
Example:
Sample output: Age is: 18
// CPP program to illustrate
// usage of local variables
#include<iostream>
using namespace std;
void func()
{
// this variable is local to the
// function func() and cannot be
// accessed outside this function
int age=18;
cout<<age;
}
int main()
{
cout<<"Age is: ";
func();
return 0;
}
Global Variables
As the name suggests, Global Variables can be accessed from any part of the program.
Example:
Sample Output:
5
10
// global variable
108
Lab Manual Programming Fundmental with C++
int global = 5;
// main function
int main()
{
display();
Test Exercise
1. Write a funcDon that receives integer base and exponent as funcDon arguments and
calculates the result of the expression and return results to main funcDon and display on console.
result=Base^exponent
2. Develop a C++ program C++ program that demonstrates the usage of an inline function to calculate the area
of a rectangle.
3. Develop a C++ program in C++ to simulate tracking a pet's age. The program should utilize local and
global variables effectively.
109
Lab Manual Programming Fundmental with C++
Exercise 11.1
Write a C++ program that demonstrates the use of pointers by declaring an integer variable 'num',
a pointer 'ptr' that points to the address of 'num', and a pointer 'ptr1' that points to the address of 'ptr'. The
program should display the value of 'num', the value pointed to by 'ptr', and the value pointed to by 'ptr1'.
Additionally, it should show both the actual memory addresses and the memory addresses accessed
through references. Explain the significance of each output in terms of memory management.
Sample output 1:
Value of Num: 34
Value of Ptr: 34
Value of Ptr1: 34
Actual Memory Address of Num: 0x61ff0c
Actual Memory Address of Ptr: 0x61ff08
Actual Memory Address of Ptr1: 0x61ff04
Memory Address of Num: 0x61ff0c
Reference Memory Address of Ptr: 0x61ff0c
Reference Memory Address of Ptr1: 0x61ff0c
Solution:
#include <iostream>
int main() {
int num = 34;
int *ptr = #
int **ptr1 = &ptr;
cout << "Actual Memory Address of Num: " << &num << endl;
cout << "Actual Memory Address of Ptr: " << &ptr << endl;
cout << "Actual Memory Address of Ptr1: " << &ptr1 << endl;
cout << "Memory Address of Num: " << &num << endl;
cout << "Reference Memory Address of Ptr: " << &*ptr << endl;
cout << "Reference Memory Address of Ptr1: " << &**ptr1 << endl;
return 0;
}
110
Lab Manual Programming Fundmental with C++
Exercise 11.2
Write a C++ program to swap the values of two integers using pointers. Take input for the integers
from the user, perform the swap operation using pointers, and display the swapped values. Explain how
pointers are utilized in this program.
Sample output 1:
Enter the value of x: 45
Enter the value of y: 65
Before swapping: x = 45, y = 65
After swapping: x = 65, y = 45
Sample output 2:
Enter the value of x: 10
Enter the value of y: 20
Before swapping: x = 10, y = 20
After swapping: x = 20, y = 10
Solution:
#include <iostream>
using namespace std;
int main() {
int x, y;
cout << "Enter the value of x: ";
cin >> x;
cout << "Enter the value of y: ";
cin >> y;
cout << "Before swapping: x = " << x << ", y = " << y << endl;
cout << "After swapping: x = " << x << ", y = " << y << endl;
return 0;
}
Exercise 11.3
Write a C++ program that prompts the user to enter the number of subjects they have. For each
subject, the program should request the user to input the marks obtained. After receiving the marks
for all subjects, the program should calculate and display the sum and average of total marks.
Sample output 1:
Enter the number of Subjects: 3
Enter marks for 3 subjects:
Enter Marks of Subject 1: 66
Enter Marks of Subject 2: 78
Enter Marks of Subject 3: 75
Sum of marks: 219
Average of marks: 73
Sample output 2:
Enter the number of Subjects: 5
Enter marks for 5 subjects:
Enter Marks of Subject 1: 80
Enter Marks of Subject 2: 78
Enter Marks of Subject 3: 76
Enter Marks of Subject 4: 60
Enter Marks of Subject 5: 65
Sum of marks: 359
Average of marks: 71.8
Solution:
#include <iostream>
using namespace std;
int main() {
int subjects;
cout << "Enter the number of Subjects: ";
cin >> subjects;
if (subjects <= 0) {
cout << "Invalid number entered. Exiting program." << endl;
112
Lab Manual Programming Fundmental with C++
return 1;
}
cout << "Enter marks for " << subjects << " subjects:" << endl;
for (int i = 0; i < subjects; i++) {
cout << "Enter Marks of Subject " << i + 1 << ": ";
cin >> *(marks + i);
sum += *(marks + i);
}
delete[] marks;
return 0;
}
Exercise 11.4
Create a C++ program that sorts an array of double values using the bubble sort algorithm with
pointers. After sorting, the program prompts the user to continue or exit. If continuing, the process
repeats for a new array; otherwise, the program ends.
Sample output 1:
Enter the size of the array: 5
Enter 5 double values:
Enter value 1: 5.7
Enter value 2: 4.7
Enter value 3: 3.2
Enter value 4: 3.9
Enter value 5: 5.3
113
Lab Manual Programming Fundmental with C++
int main() {
char choice;
do {
int size;
cout << "Enter the size of the array: ";
cin >> size;
if (size <= 0) {
cout << "Invalid size entered. Exiting program." << endl;
return 1;
}
cout << "Enter " << size << " double values:" << endl;
for (int i = 0; i < size; ++i) {
cout << "Enter value " << i + 1 << ": ";
cin >> *(arr + i);
}
delete[] arr;
return 0;
}
Exercise 11.5:
Write a program that demonstrates the difference between pointer constants and pointer variables.
Sample output:
Pointer to constant - before modification: 10
Pointer to variable - before modification: 20
Pointer to variable - after modification: 30
Pointer to variable - after reassignment: 40
Solution:
#include <iostream>
using namespace std;
int main() {
const int* constPointer;
int constantValue = 10;
constPointer = &constantValue;
cout << "Pointer to constant - before modification: " << *constPointer << endl;
int* variablePointer;
int variableValue = 20;
variablePointer = &variableValue;
cout << "Pointer to variable - before modification: " << *variablePointer <<
endl;
*variablePointer = 30;
115
Lab Manual Programming Fundmental with C++
cout << "Pointer to variable - after modification: " << *variablePointer <<
endl;
return 0;
}
Exercise 11.6:
Write a C++ program demonstrating "passing pointers as arguments." The program dynamically
allocates memory for an array of integers based on user input. It then calculates the sum of the
entered values, displaying them before printing the sum. Ensure proper handling of invalid inputs.
Sample output 1:
Enter the size of the array: 4
Enter 4 integers:
Enter value 1: 4
Enter value 2: 5
Enter value 3: 6
Enter value 4: 4
Your entered values:
4 | 5 | 6 | 4 |
Sum of elements: 19
Solution:
#include <iostream>
using namespace std;
116
Lab Manual Programming Fundmental with C++
}
return sum;
}
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
if (size <= 0) {
cout << "Invalid size entered. Exiting program." << endl;
return 1;
}
Exercise 11.7:
Write a program showcasing the utilization of pointers within functions to identify the three largest
elements in an array. The program should acquire input from the user and emphasize the utilization
117
Lab Manual Programming Fundmental with C++
of pointers and functions. Ensure that the program enforces a requirement where the size of the
array the user provides cannot be less than 3.
Solution:
#include <iostream>
using namespace std;
cout << "Largest three elements in the array: " << largest1 << ", " << largest2
<< ", " << largest3 << endl;
}
int main() {
int size;
do {
cout << "Enter the size of the array (must be at least 3): ";
cin >> size;
} while (size < 3);
return 0;
}
Output:
118
Lab Manual Programming Fundmental with C++
Exercise 11.8:
Write a program demonstrating "Pointer and functions." It allows the user to input an array size
and elements. The program doubles each element using a function and displays both original and
doubled elements. Ensure proper handling of invalid input.
Solution:
#include <iostream>
*(arr + i) *= 2;
int main() {
int size;
if (size <= 0) {
cout << "Invalid size entered. Exiting program." << endl;
return 1;
119
Lab Manual Programming Fundmental with C++
}
cout<<"\nYour Entered Values: ";
}
doubleArray(arr, size);
}
cout << endl;
delete[] arr;
return 0;
Sample output:
Exercise 11.9:
Create a C++ program to manage student information. The program should prompt the user to
input the number of students and their details, including name, age, and CGPA. It should then
display the entered information for each student.
Sample output:
Enter the number of students: 1
Enter details for student 1:
Name: Zia
Age: 26
CGPA: 3.56
Student Information:
Student 1:
Name: Zia
120
Lab Manual Programming Fundmental with C++
Age: 26
CGPA: 3.56
Solution:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int numStudents;
cout << "Enter the number of students: ";
cin >> numStudents;
return 0;
}
121
Lab Manual Programming Fundmental with C++
Exercise 11.10:
Create a program for a student enrollment system using arrays and functions with pointers. The
program should allow administrators to register new students, update student information, and
display student details. Utilize functions with pointers to manage student data and ensure seamless
enrollment processes efficiently.
Sample output 1:
Menu:
1. Add Student
2. Update Student
3. Display Students
4. Exit
Enter your choice: 1
Enter student name: Zia
Enter student age: 34
Enter student CGPA: 3.2 …
Solution:
#include <iostream>
#include <cstring>
using namespace std;
numStudents++;
}
void updateStudent(char** names, int* ages, float* cgpas, int numStudents) {
if (numStudents == 0) {
cout << "No students to update." << endl;
return;
}
char searchName[50];
cout << "Enter the name of the student to update: ";
cin.ignore();
cin.getline(searchName, 50);
do {
cout << "\nMenu:\n1. Add Student\n2. Update Student\n3. Display
Students\n4. Exit\nEnter your choice: ";
cin >> choice;
switch (choice) {
case '1':
addStudent(names, ages, cgpas, numStudents);
break;
123
Lab Manual Programming Fundmental with C++
case '2':
updateStudent(names, ages, cgpas, numStudents);
break;
case '3':
displayStudents(names, ages, cgpas, numStudents);
break;
case '4':
cout << "Exiting program." << endl;
break;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (choice != '4');
deleteMemory(names, ages, cgpas, numStudents);
return 0;
}
Output:
124
Lab Manual Programming Fundmental with C++
Test Exercise
1. Write a program to manage a library system using arrays and functions with pointers. The program
should allow users to add books, display all books, and search for books by title or author. Utilize
functions with pointers to handle book data efficiently.
2. Write a program to simulate a student grading system using arrays and functions with pointers. The
program should enable instructors to input grades for multiple students, calculate their average scores,
and display the highest and lowest scores. Implement functions with pointers to manipulate student data.
3. Create a program for a retail store, employing arrays and functions with pointers. The program should
enable employees to add new products, update quantities, and display the current inventory. Utilize
functions with pointers to manage product data efficiently.
4. Develop a C++ application for a banking system that handles customer accounts using arrays and
functions with pointers. The program should allow bankers to add new accounts, deposit or withdraw
funds, and display account details. Employ functions with pointers to manage account data effectively.
5. Design a C++ program to track sales performance for a sales team using arrays and functions with
pointers. The program should enable managers to input sales figures for each team member, calculate
total sales, and display the highest and lowest-performing salesperson. Utilize functions with pointers to
handle sales data efficientl
125
Lab Manual Programming Fundmental with C++
1. Background:
So far we have talked about a variable as a single location in the computer’s memory. It is possible to
have a collection of memory locations, all of which have the same data type, grouped together under
one name. Such a collection is called an array. Like every variable, an array must be defined so that the
computer can “reserve” the appropriate amount of memory. This amount is based upon the type of data
to be stored and the number of locations, i.e., size of the array, each of which is given in the definition.
Each element of an array, consisting of a particular memory location within the group, is accessed by
giving the name of the array and a position with the array (subscript). In C++ the subscript, sometimes
referred to as index, is enclosed in square brackets. The numbering of the subscripts always begins at 0
and ends with one less than the total number of locations.
The best way to show you what an array is and how powerful it can be is to go through an example.
#include <iostream>
using namespace std;
int main(void)
{
int grade = 0; // Stores a grade
{
cout<<"Enter a grade: ";
cin>>grade; // Read a grade
sum += grade; // Add it to sum
return 0;
}
126
Lab Manual Programming Fundmental with C++
If you’re interested only in the average, then you don’t have to remember what the previous grades
were. You accumulate the sum of all the values, which you then divide by count, which has the value
10. This program uses a single variable, grade, to store each grade as it is entered within the loop. The
loop repeats for values of i from 0 to 9 so there are ten iterations.
Let’s assume you want to develop this into a more sophisticated program in which you need to store the
values entered. Perhaps you want to output each person’s grade, with the average grade next to it. In the
previous program, you had only one variable. Each time you add a grade, the old value is overwritten,
and you can’t get it back.
So how can you store all the grades? You could declare ten integer variables to store the grades, but
then you can’t use a loop to enter the values. You must include code that will read the values
individually.
This works, but it’s quite tiresome:
127
Lab Manual Programming Fundmental with C++
#include <iostream>
using namespace std;
int main(void)
{
int grade0 = 0, grade1 = 0, grade2 = 0, grade3 = 0, grade4 = 0;
cout << "\nAverage of the ten grades entered is: " << average <<
This is more or less okay for ten students, but what if your class has 30 students, or 100, or 1,000? How
endl;
can you do it then? This approach would become wholly impractical, and an alternative mechanism is
essential.return 0;
}
128
Lab Manual Programming Fundmental with C++
2. What is an Array?
• An array is a fixed number of data items that are all of the same type.
• The data items in an array are referred to as elements Look at the following statement:
long numbers[10];
The number between square brackets defines how many elements the array contains and is called the
array dimension.
Each of the data items stored in an array is accessed by the same name; in the previous statement the
array name is numbers. You select a particular element by using an index value between square brackets
following the array name.
Index values are sequential integers that start from zero, and 0 is the index value for the first array
element. The index values for the elements in the numbers array run from 0 to 9, so the index value 0
refers to the first element and the index value 9 refers to the last element. Therefore, you access the
elements in the numbers array as numbers[0], numbers[1], numbers[2], and so on, up to numbers[9].
You can see this in the following figure:
1. Initialization:
To initialize the elements of an array, you just specify the list of initial values between braces and
separate them by commas in the declaration. For example:
double values[5] = { 1.5, 2.5, 3.5, 4.5, 5.5 };
To initialize the whole array, there must be one value for each element. If there are fewer initializing
values than elements, the elements without initializing values will be set to 0. Thus, if you write:
double values[5] = { 1.5, 2.5, 3.5 };
The first three elements will be initialized with the values between braces, and the last two elements will
be initialized with 0.
Knowing that the compiler will supply zeroes for elements for which you don’t provide, an initial value
offers an easy way to initialize an entire array to zero. You just need to supply one element with the
value of 0:
double values[5] = {0.0};
129
Lab Manual Programming Fundmental with C++
2. Using an Array:
Let’s put what you’ve just learned about arrays into practice in calculating average grades.
You can use an array to store all the scores you want to average. This means that all the values will be
saved, and you’ll be able to reuse them. You can now rewrite the program to average ten scores:
#include <iostream>
using namespace std;
int main(void)
{
int grades[10]; // Array storing 10 values
int count = 10; // Number of values to be read
long sum = 0; // Sum of the numbers
cout<<i + 1<<">";
cin>>grades[i]; // Read a grade
cout << "\nAverage of the ten grades entered is: " << average << endl;
Output: return 0;
130
Lab Manual Programming Fundmental with C++
1> 450
2> 765
3> 562
4> 700
5> 598
6> 635
7> 501
8> 720
9> 689
10> 527
131
Lab Manual Programming Fundmental with C++
{
int grades[10]; // Array storing 10 values
int count = 10; // Number of values to be read
long sum = 0; // Sum of the numbers
{
cout << i + 1 << "> ";
}
average = (float)sum / count; // Calculate the average
cout << "\nGrade Number " << i + 1 << " is " << grades[i];
cout << "\nAverage of the ten grades entered is: " << average << endl;
return 0;
132
Lab Manual Programming Fundmental with C++
Output:
Enter the 10 grades: 1> 77
2> 87
3> 65
4> 98
5> 52
6> 74
7> 82
8> 88
9> 91
10> 71
Grade Number 1 is 77
Grade Number 2 is 87
Grade Number 3 is 65
Grade Number 4 is 98
Grade Number 5 is 52
Grade Number 6 is 74
Grade Number 7 is 82
Grade Number 8 is 88
Grade Number 9 is 91
Grade Number 10 is 71
Average of the ten grades entered is: 78.50
Arrays as Arguments:
Arrays can be passed as arguments (parameters) to functions. Although variables can be passed by value
or reference, arrays are always passed by pointer, which is similar to pass by reference, since it is not
efficient to make a “copy” of all elements of the array. Pass by pointer is discussed further in next Lab.
This means that arrays, like pass by reference parameters, can be altered by the calling function.
However, they NEVER have the & symbol between the data type and name, as pass by reference
parameters do. Sample Program given below illustrates how arrays are passed as arguments to
functions.
133
Lab Manual Programming Fundmental with C++
134
Lab Manual Programming Fundmental with C++
135
Lab Manual Programming Fundmental with C++
Notice that a set of empty brackets [ ] follows the parameter of an array which indicates that the data
type of this parameter is in fact an array. Notice also that no brackets appear in the call to the functions
that receive the array.
Since arrays in C++ are passed by pointer, which is similar to pass by reference, it allows the original
array to be altered, even though no & is used to designate this. The getData function is thus able to store
new values into the array. There may be times when we do not want the function to alter the values of
the array.
Inserting the word const before the data type on the formal parameter list prevents the function from
altering the array even though it is passed by pointer. This is why in the preceding sample program the
findAverage function and header had the word const in front of the data type of the array.
The variable numberOfGrades contains the number of elements in the array to be processed. In most
cases not every element of the array is used, which means the size of the array given in its definition and
the number of actual elements used are rarely the same. For that reason we often pass the actual number
of elements used in the array as a parameter to a procedure that uses the array. The variable
numberOfGrades is explicitly passed by reference (by using &) to the getData function where its
corresponding formal parameter is called sizeOfArray.
Prototypes can be written without named parameters. Function headers must include named parameters.
float findAverage (const int [], int); // prototype without named parameters
The use of brackets in function prototypes and headings can be avoided by declaring a programmer
defined data type. This is done in the global section with a typedef statement.
Example: typedef int GradeType[50];
This declares a data type, called GradeType, that is an array containing 50 integer memory locations.
Since GradeType is a data type, it can be used in defining variables. The following defines grades as an
integer array with 50 elements.
GradeType grades;
It has become a standard practice (although not a requirement) to use an uppercase letter to begin the
name of a data type. It is also helpful to include the word “type” in the name to indicate that it is a data
type and not a variable.
Sample Program given below shows the revised code (in bold) of Sample Program given above using
typedef.
136
Lab Manual Programming Fundmental with C++
137
Lab Manual Programming Fundmental with C++
138
Lab Manual Programming Fundmental with C++
Lab Tasks:
Exercise 1:
Write a program that will input temperatures for consecutive days.
The program will store these values into an array and call a function that will return the average of the
temperatures. It will also call a function that will return the highest temperature and a function that will
return the lowest temperature. The user will input the number of temperatures to be read. There will be
no more than 50 temperatures. Use typedef to declare the array type. The average should be displayed to
two decimal places.
Exercise 2:
Write a program that will input letter grades (A, B, C, D, F), the number of which is input by the user (a
maximum of 50 grades). The grades will be read into an array. A function will be called five times
(once for each letter grade) and will return the total number of grades in that category. The input to the
function will include the array, number of elements in the array and the letter category (A, B, C, D or
F). The program will print the number of grades that are A, B, etc.
139
Lab Manual Programming Fundamental with C++
140
Lab Manual Programming Fundamental with C++
Concept Map
Single-Dimensional Arrays
An array is basically a collection of data-items or values all based on same data-type. For example: A
student's marks in five courses in a semester: 78, 91, 83, 67, and 89; represent a collection of five int type
numbers where each value represents his/her marks in a certain course. An array is a structured data-type
(collection of values) of some fixed size (number of elements/values) where all values are of same type. To
define an array you have to mention its type, name and size (number of elements/values the array will
contain). For example:
int marks[5]
Above statements defines an int type array named marks, having size: 5 (capable of storing five
values).In the similar way, you can create array of any basic type, Examples:
Individual array elements can be accessed using same name (array name) along its index. An index (which
must be an integer value) indicates relative position of an element/value within an array. In C++, array are
0-index based, it means that index of the starting/first element of an array is 0. For example: int marks[5];
defines an int-type array having five elements, where first value or element will be at index 0, second on
index 1, thirds element at index 2, fourth at index 3, and the fifth element at index 4. Examples:
As you have learned that array elements can be accessed using index values. Therefore, it is common
and a very convenient way to access array elements using loops (mainly for-loop). For example, below
shown code gets input from the user for all five elements of array marks.
for(int i=0;i<5;
i++) cin>>marks[i];
C++ language does not provide any boundary-check; it means C++ does not prohibit access of array
elements beyond the array size. Therefore, it is the responsibility of the programmer to access only valid
array elements (within the limit of array size) otherwise runtime errors or system crash may occur.
Similar to simple variables, arrays can also be initialized. To initialize an array, you have to provide a
comma ( , ) separated list of values (enclosed in braces "{" and "}" ). All values to be used in initialization
should belong to the same data-type the array processes. In the following example, an array named marks
(int type) is being initialized:
int marks[4] = {87, 90, 73, 91};
char country[9] = {'P','A','K','I','S','T','A','N','\0'};
141
Lab Manual Programming Fundamental with C++
Above C++ code creates a two dimensional array having 3 rows (indexed from 0—2) and 5 columns
(indexed from 0—4). In a 2D array, accessing an array element requires two index values (one for row and
other for column). For examples:
4.2 Sorting
Sorting data means arranging values in some pre-defined order based on their numerical value etc.
Sorting an array means to arrange array elements in a certain order (ascending or descending). In
ascending-order, values are arranged in an array such that smaller values are followed by the larger ones,
e.g., 11, 36, 56, 98, 201. In descending-order, values of an array are arranged such that larger values are
placed first then the smaller values e.g., 201, 98, 56, 36, 11. There are many ways (algorithms) to sort an
array, in this course you will learn to sort an array using bubble-sort algorithm.
Bubble-sort algorithm performs N-1 steps, to sort an array. Here N refers to the size of an array (number of
elements in the array). In each step, the complete array is traversedand comparisonsare made for pair of
adjacent values. Based on the element's value and the order to sort (either ascending or descending)
those values may be swapped.For more details, kindly review lecture 15.
4.3 Summary
• Arrays are very useful data-structure that helps to process large amount of data of same-type.
Arrays simplify coding of the programs (processing large amount of similar data) using fewer code
lines as compared to the non-array based C++ program having same functionality.
• All array elements are accessed using same name, which helps to group related set of values
using same variable-name and results in improved code readability and maintainability.
• Sorting is the process of arranging data-items or values in a certain order. One of the main
advantages of using sorting is that it helps arranging data in a more meaningful way or desired
order (based on programmers need).
Task 1
Write a C++ program that reads marks of a class (having 5 students) from the user and places them in an
array of type float. After that, it should compute average marks obtained by the class. In the end, display
student number and their marks for all those students who got marks above average.
#include <iostream>
142
Lab Manual Programming Fundamental with C++
int main() {
float marks[numStudents];
cout << "Enter marks of " << numStudents << " students:" << endl;
do {
cout << "Enter marks for student " << i + 1 << ": ";
cout << "Marks cannot be greater than 100. Please enter again." << endl;
totalMarks += marks[i];
cout << "\nStudents who scored above average marks (" << averageMarks << "):" << endl;
143
Lab Manual Programming Fundamental with C++
cout << "Student " << i + 1 << ": " << marks[i] << endl;
return 0;
Q3 Write a program that creates and then reads a matrix of 4 rows and 4 columns of type int.
while reading; the program should not accept values greater than 100. For any entered value
greater than 100, the program should ask for input repeatedly. After reading all numbers, the
system should find the largest number in the matrix and its location or index of largest value.
The program should print the largest number and its location (row and column).
#include <iostream>
using namespace std;
int main() {
const int rows = 4;
const int cols = 4;
int matrix[rows][cols];
return 0;
}
Output:
145
Lab Manual Programming Fundamental with C++
Home Tasks:
Q1 Write a C++ program that creates a two 2D array having 4 rows and 4 columns of type int.
Calculate the sum of values of the arrays and store the result in third array.
Q2 Write c++ of program that creates char array of 5 elements of type char. The array contains 5
vowels a, e, i, o, u. Ask the user to enter characters of their choice until the user enters a vowel.
After user enters a vowel the program should stop taking inputs. And display all the entered
characters by user.
Q3 Write a program that creates and then reads a matrix of 4 rows and 4 columns of type int.
while reading; the program should not accept values greater than 100. For any entered value
greater than 100, the program should ask for input repeatedly. After reading all numbers, the
system should find the largest number in the matrix and its location or index of largest value.
The program should print the largest number and its location (row and column).
Q 4: Write a C++ program that creates two one dimensional arrays "A" and "B" of size 10 elements
each. The main program should get the input in the array "A" from the user and initialize array "B"
with values "0". Your program should calculates the square (number * number) of each element
of array "A" and should store in the square value in corresponding positions (index) in the array
"B". In the end, the main program (main function) prints the calculated values of array "B". Also
display the values in array B which are divisible by 3 (if any).
146
Lab Manual Programming Fundamental with C++
C++ Strings
#include <iostream>
#include <string>
using namespace std;
int main() {
string greeting = "Hello";
cout << greeting;
return 0;
}
Output
Hello
String Concatenation
The + operator can be used between strings to add them together to make a new string. This is
called concatenation:
#include <iostream>
#include <string>
using namespace std;
int main () {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;
return 0;
}
Output
John Doe
Append
A string in C++ is actually an object, which contain functions that can perform certain operations
on strings. For example, you can also concatenate strings with the append() function:
#include <iostream>
147
Lab Manual Programming Fundamental with C++
#include <string>
using namespace std;
int main () {
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName.append(lastName);
cout << fullName;
return 0;
}
Output :
John Doe
#include <iostream>
#include <string>
int main () {
string x = "10";
string y = "20";
string z = x + y;
cout << z;
return 0;
Output
1020
Example:
#include <iostream>
#include <string>
148
Lab Manual Programming Fundamental with C++
int main () {
int x = 10;
int y = 20;
int z = x + y;
cout << z;
return 0;
Output:
30
String Length
#include <iostream>
#include <string>
int main() {
cout << "The length of the txt string is: " << txt.length();
return 0;
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.length();
return 0;
149
Lab Manual Programming Fundamental with C++
Output
The length of the txt string is: 26
You might see some C++ programs that use the size() function to get the length of a string. This
is just an alias of length(). It is completely up to you if you want to use length() or size():
#include <iostream>
#include <string>
using namespace std;
int main() {
string txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "The length of the txt string is: " << txt.size();
return 0;
}
Output
The length of the txt string is: 26
Access Strings
You can access the characters in a string by referring to its index number inside square brackets
[].
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
cout << myString[0];
return 0;
}
Output
H
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
150
Lab Manual Programming Fundamental with C++
To change the value of a specific character in a string, refer to the index number, and use single
quotes:
#include <iostream>
#include <string>
using namespace std;
int main() {
string myString = "Hello";
myString[0] = 'J';
cout << myString;
return 0;
}
Output
Jello
Because strings must be written within quotes, C++ will misunderstand this string, and generate
an error:
string txt = "We are the so-called "Vikings" from the north.";
The solution to avoid this problem, is to use the backslash escape character.
The backslash (\) escape character turns special characters into string characters:
151
Lab Manual Programming Fundamental with C++
Example:
#include <iostream>
using namespace std;
int main() {
string txt = "We are the so-called \"Vikings\" from the north.";
cout << txt;
return 0;
}
Output
We are the so-called "Vikings" from the north.
Example:
#include <iostream>
using namespace std;
int main() {
string txt = "It\'s alright.";
cout << txt;
return 0;
}
Output
It's alright.
Example:
#include <iostream>
using namespace std;
int main() {
string txt = "The character \\ is called backslash.";
cout << txt;
return 0;
}
Output
The character \ is called backslash.
152
Lab Manual Programming Fundamental with C++
It is possible to use the extraction operator >> on cin to store a string entered by a user:
#include <iostream>
#include <string>
using namespace std;
int main() {
string fullName;
cout << "Type your full name: ";
getline (cin, fullName);
cout << "Your name is: " << fullName;
return 0;
}
Output
C Style Strings
These strings are stored as the plain old array of characters terminated by a null character ‘\0’.
They are the type of strings that C++ inherited from C language.
Syntax:
Example:
int main()
{
One more way we can make strings that have the same character repeating again and
again.
153
Lab Manual Programming Fundamental with C++
Syntax:
std::string str(number,character);
Example:
#include <iostream>
using namespace std;
int main()
{
string str(5, 'g');
cout << str;
return 0;
}
Output:
ggggg
int main()
{
string s = "dexter";
string str("dexter");
return 0;
}
Output
s = dexter
str = dexter
Example
int main()
{
154
Lab Manual Programming Fundamental with C++
return 0;
}
Output
s1 = gfg
s2 = gfg
s3 = gfg
s4 = gfg
Example
int main() {
string s;
cout<<"Enter String"<<endl;
cin>>s;
Output:
Enter String
Dexter
String is: Dexter
Example
int main()
{
string s;
cout << "Enter String" << endl;
getline(cin, s);
cout << "String is: " << s << endl;
155
Lab Manual Programming Fundamental with C++
return 0;
}
Output
Enter String
String is:
Output:
Enter String
Dexter
String is: Dexter
Example
int main()
{
Task
• Write a C++ program to reverse a given string.
• Write a C++ program to find the largest word in a given string.
• Write a C++ program to count all the vowels in a given string.
• Write a C++ program to count all the words in a given string.
• Write a C++ program to find the numbers in a given string and calculate the sum of all
numbers.
156
Lab Manual Programming Fundamental with C++
So far, we have been using the iostream standard library, which provides cin and cout methods for
reading from standard input and writing to standard output respectively. In this week wehave to
learn about how to read and write from a file.
This requires another standard C++ library called fstream, which defines three new data types:
Data Type Description
ofstream This data type represents the output file stream
and is used to create files and to write
information to files.
ifstream This data type represents the input file stream
and is used to read Information from files .
fstream This data type represents the file stream
generally, and has the capabilities of both
ofstream and ifstream which means it can
create files, write information to files, and read
information from files.
To perform file processing in C++, header files and must be included in your C++ source file.
Opening a File:
A file must be opened before you can read from it or write to it. Either the ofstream or fstream
object may be used to open a file for writing and ifstream object is used to open a file for reading
purpose only.
Following is the standard syntax for open function, which is a member of fstream, ifstream, and
ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second
argument of the open member function defines the mode in which the file should be opened.
Mode Flag Description
ios::app Append mode. All output to that file to be
appended to the end.
ios::ate Open a file for output and move the read/write
control to the end of the file
ios::in Open a file for reading.
ios::out Open a file for writing.
Closing a File
157
Lab Manual Programming Fundamental with C++
When a C++ program terminates it automatically closes flushes all the streams, release all the
allocated memory and close all the opened files.
But it is always a good practice that a programmer should close all the opened files before program
termination.
Following is the standard syntax for close function, which is a member of fstream, ifstream, and
ofstream objects.
void close();
Writing to a File:
While doing C++ programming, you write information to a file from your program using the
stream insertion operator << just as you use that operator to output information to the screen.
The only difference is that you use an ofstream or fstream object instead of the cout object.
Reading from a File:
You read information from a file into your program using the stream extraction operator >> just
as you use that operator to input information from the keyboard.
The only difference is that you use an ifstream or fstream object instead of the cin object.
Examples:
1. Writing to a File:
#include <iostream>
#include <fstream> // Required for file operations
using namespace std;
int main() {
ofstream outfile("example.txt"); // Create/open the file for writing
if (!outfile.is_open()) {
cout << "Error opening file for writing!" << endl;
return 1;
}
// Write to the file
outfile << "Hello, world!" << endl;
outfile.close(); // Close the file
return 0;
}
158
Lab Manual Programming Fundamental with C++
Output:
(No output to the console, but a file named "example.txt" will be created with the content "Hello,
world!")
2. Reading from a File:
#include <iostream>
#include <fstream> // Required for file operations
using namespace std;
int main() {
ifstream infile("example.txt"); // Open the file for reading
if (!infile.is_open()) {
cout << "Error opening file for reading!" << endl;
return 1;
}
// Read from the file
string line;
while (getline(infile, line)) {
cout << line << endl; // Print each line to the console
}
infile.close(); // Close the file
return 0;
}
Output:
Hello, world!
3. Appending to a File:
#include <iostream>
#include <fstream> // Required for file operations
using namespace std;
int main() {
ofstream outfile("example.txt", ios_base::app); // Open the file for appending
159
Lab Manual Programming Fundamental with C++
if (!outfile.is_open()) {
cout << "Error opening file for appending!" << endl;
return 1;
}
// Append to the file
outfile << "Appending text!" << endl;
outfile.close(); // Close the file
return 0;
}
Output:
(No output to the console, but the file "example.txt" will be appended with the text "Appending
text!")
160
Lab Manual Programming Fundamental with C++
5. Get three integer values from user and store them into a file Integer.txt and also
display the contents of file Interger.txt
#include<fstream.h>
void main()
{
ofstream ofile; // decide and declare stream object
ofile.open("Integer.txt",ios::out); // link file
int x,y,z;
// processing
cout<<"Enter any three integer\n";
cin>>x>>y>>z;
ofile<<x<<" "<<y<<" "<<z;
ofile.close();
// read and display
ifstream ifile;
ifile.open("Integer.txt",ios::in);
cout<<"the three integer are:\n";
ifile>>x>>y>>z;//read from file
cout<<"the values are\n";
cout<<x<<endl<<y<<endl<<z;
ifile.close();
}
#include<fstream.h>
int main()
{
ofstream fout;
fout.open("abc.txt");
fout<<"This is my first program in file handling";
fout.close();
return 0;
}
void main()
{
char s[80], ch;
ofstream file("myfile.txt"); //open myfile.txt in default output mode
do
{ cout<<"\n enter line of text";
gets(s); //standard input
file<<s; // write in a file myfile.txt
cout<<"\n more input y/n ";
cin>>ch;
}while(ch=='y'||ch=='Y');
file.close();
} //end of main
7. To create a text file using characters I/O
#include<fstream.h> //header file for file operations
#include<stdio.h>
void main()
{
char ch;
ofstream file("myfile2.txt"); //open myfile.txt in default output mode
ch=getchar();
file<<ch; // write a character in text file ‘myfile.txt ‘
file.close();
} //end of main
file.close();
} //end of main
163
Lab Manual Programming Fundamental with C++
When the above code is compiled and executed, it produces the following sample input and
output:
Note: Above examples, make use of additional functions from cin object, like getline function to
read the line from outside and ignore function to ignore the extra characters left by previous read
statement.
Exercise
Q: Write a function in a C++ to read the content of a text file “DELHI.TXT” and display
all those lines on screen, which are either starting with ‘D’ or starting with ‘M’.
void DispD_M()
{
ifstream File(“DELHI.TXT”) ; // by default in input mode
char str[80];
while(File.getline(str,80))
{
if(str[0] = =’D’ || str[0] = =’M’)
cout<<str<<endl;
}
File.close();
}
164
Lab Manual Programming Fundamental with C++
10. Write a function in a C++ to count the number of lowercase alphabets present in a text file
“BOOK.txt”
int countalpha()
{ ifstream Fin(“BOOK.txt”);
char ch;
int count=0;
while(!Fin.eof())
{Fin.get(ch);
if (islower(ch))
count++;
}
Fin.close();
return count;
}
165