Download as pdf or txt
Download as pdf or txt
You are on page 1of 125

1

PROGRAMMING FUNDAMENTALS

LAB SESSION 1
1 INTRODUCTION
1 TITLE:
Installation of Visual Studio Code and minGW compiler for C++.

1 OBJECTIVES:
Students must be able to install visual studio code and minGW and basic
files necessary for them to run.

2 LAB TASK
To install Visual Studio Code and minGW compiler for C++.

3 REQUIRED MATERIAL
• Internet connection
• Google Chrome

4 CONSTRAINTS
Internet connection must be strong.
There should be enough space in your PC.
Use official websites to get correct version of your software’s.

5 PROCEDURE
5 STEP 1:
First of all, open your PC and go for the google chrome and search for visual studio code
in the search section. Then there comes a website https://code.visualstudio.com/ go for
It and go for download option.
2

5 STEP 2:
Then comes an interface in front of you that provides you three options to install for
Windows, macOS and deb or rev. you should choose for windows according to the
Operating system installed in your PC. After that visual studio will start downloading
3

5 STEP 3:
After downloading setup from the chrome let this setup be installed to run the
Software in application form.

5 STEP 4:
After installing the application of visual studio code open the application and then go for
Extension search on top left side options and search for following extensions.
• C/C++ Themes
• C/C++ Extension Pack
• Code Runner
Note that these extensions must be installed completely.

5 STEP 5:
After performing all the above activities our next step is to install the basic minGW compiler
required for visual studio code. For that purpose again go to the google chrome and search for
minGW interface opens in front of you and go to website https://sourceforge.net/projects/mingw/
4

5 STEP 6:
5

After visiting this website a page opens in front of you as below and provide you the
option to download the minGW click on that and let it be downloaded.

5 STEP 7:
This will download a setup for the minGW in your PC install that setup and converts it into
application and open it and allow it to make changes to your PC. Let it be completely
installed in your device.

5 STEP 8:
After the software is completely installed open an interface as below provides you various
type of compilers for different languages. Choose compiler according to the language you
are using. We are using C++ so we should go to mingw32-gcc-g++ and mark it for
installation.
6

Below interface shows that our mingw32-gcc-g++ is installing.

5 STEP 9:
After installing mingw32-gcc-g++ your system will start extracting the internal files of
Our compiler as below page shows.
7

5 STEP 10:
Now our final step is to
change the
environmental
variable. Search for edit
environmental variable
in your control panel
and open it. As you
open it an interface as
below will open and
you will show three
options on the screen
and go for
environmental
variable.

5 STEP 11:
Lastly locate the minGW as C:\MinGW\bin copy it and select path in system variable
8

And start to edit. After completing the editing simply pasting in the path the copy data
Apply changes and doing everything ok your system with visual studio code and
MinGW is ready to run in your PC.

6 CONCLUSIONS
After performing students must be able to install and run visual studio code and minGW
Everywhere there they want and, in every pc, they are required to run because they have
Got familiar with the installation process and problems to deal with. Their basic concept
About the whole process is cleared and everything is understood for them.
1

PROGRAMMING FUNDAMENTALS

LAB SESSION 2
1 INTRODUCTION
1 TITLE FOR LAB:
Introduction to C++ and operating basic input, output functions and operations.

1 OBJECTIVES:
Main objective of this lab is to get the familiarity with C++ and its basics.
The purpose is to perform basic tasks using C++.

1 CONCEPT COVERED:
By performing this lab students must be cleared to get the use of the basic input, output
Commands, and to know the use of libraries and header files in the code.

2 BACKGROUNDS
In this lab I have used these operations and functions: -
• #include<iostream> • floor(x)
• #include<math.h> • ceil(x)
• #include<conio.h> • round(x)
• using name space std • sin(x)
• int main () • log(x)
• cout<< • log10(x)
• cin>> • exp(x)
• return 0 • fmod(x,y)
• sqrt(x) • min(x,y)
• pow(x,y) • max(x,y)
• abs(x) • getch()
3 LAB TASKS
1. Problem: Write a C++ program that prompts the user to enter two integers, calculates
their sum, and displays the result using cout.
2. Problem: Write a C++ program that prompts the user to enter the length and width of a
rectangle, calculates its area using the formula area = length * width, and displays the
result using cout.
2

3. Problem: Write a C++ program that prompts the user to enter a radius, calculates the
area and circumference of a circle using the formulas area = pi * radius * radius and
circumference = 2
* pi * radius, and displays the results using cout. Display unit with the answer.
4. Problem: Write a C++ program that prompts the user to enter three numbers,
calculates their average, and displays the result using cout.
5. Problem: Write a C++ program that prompts the user to enter a temperature in
Fahrenheit, converts it to Celsius using the formula Celsius = (Fahrenheit - 32) * 5 / 9,
and displays the result using cout.
6. Problem: Write a C++ program that prompts the user to enter two decimal numbers,
calculates their product and division, and displays the results using cout.
7. Problem: Write a C++ program that prompts the user to enter a number and calculates
its square using the arithmetic operator * and displays the result using cout.
8. Problem: Write a C++ program that prompts the user to enter a number and calculates
its square root using the sqrt() function from the <math.h> library and displays the
result using cout. Verify other functions available in <math.h>

sqrt(x): Calculates the square root of a log(x): Calculates the natural logarithm of x.
number x. log10(x): Calculates the base-10 logarithm
pow (x, y): Raises x to the power of y. of x.
abs(x): Returns the absolute value of x. exp(x): Computes the exponential value of
floor(x): Rounds x downward to the nearest x.
integer. fmod(x, y): Calculates the remainder when x
ceil(x): Rounds x upward to the nearest is divided by y.
integer. min (x, y): Returns the smaller of the two
round(x): Rounds x to the nearest integer. values x and y.
sin(x): Computes the sine of x (where x is in max (x, y): Returns the larger of the two
radians). values x and y.

9. Problem: Write a C++ program that prompts the user to enter two integers, calculates
their sum, difference, product, and division using arithmetic operators, and displays the
results using cout.

4 REQUIRED MATERIALS
Following is the material required to perform this specific lab :-
• C++ compiler
• DEV C++
• Visual Studio Code
Libraries that are included are: -
iostream
• math.h
• conio.h
3

5 CONSTRAINTS
Students must be well aware of the data type they are giving in the code.
Students must be able to do in the specific time assigned by the instructor.
6 CODE TEMPLATES
6 TASK 1:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main()
{
int a,b,c;
cout<<"enter first No# \n";
cin>>a;
cout<<"enter second No# \n";
cin>>b;
c=a+b;
getch();
cout<<"result \n";
cout<<c;
return 0;
}
In this program:

• We include the necessary headers for input and output (iostream) and for the getch() function
(conio.h, which is specific to Windows).
• We declare two integer variables, “a” and “b”, to store the user's input.
• We prompt the user to enter the first integer and store it in “a” using cin.
• We prompt the user to enter the second integer and store it in “b” using cin.
• We calculate the sum of “a” and “b” and store it in the “c” variable.
• We use cout to display the result along with a message.
• We use getch() (specific to Windows) to wait for a key press before exiting the program. This is
optional and can be omitted if you don't need this functionality

6 TASK 2:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main()
{
int a,b;
cout<<"enter the length \n";
4

cin>>a;
cout<<"enter the width \n";
cin>>b;
cout<<"enter to get the area of rectangle \n";
getch();
cout<<"area of rectangle is = "<<a*b<<"meters";
return 0;
}
Here's a breakdown of the program's logic:

• We include the necessary header file, <iostream>, to enable input and output operations.
• We use using namespace std; to simplify the code by allowing us to use cout and cin without
explicitly specifying std:: each time.
• We declare three variables: “a”,”b” and area to store the user input and calculated area.
• We use cout to prompt the user to enter the length of the rectangle and then use cin to read the
user's input into the “a” variable.
• Similarly, we prompt the user to enter the width of the rectangle and read the input into
the “b” variable.
• We calculate the area of the rectangle using the formula area = length * width.
• Finally, we use cout to display the calculated area.

6 TASK 3:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main ()
{
float a;
# define pi 3.14
cout<<"enter the radius \n";
cin>>a;
cout<<"enter to get area of circle \n";
getch();
cout<<"area of circle is= "<<pi*a*a<<"meters \n";
getch();
cout<<"enter to get circumference of circle ="<<2*pi*a<<"meters \n";
return 0;
}
In this program:

• We include the necessary header files for input and output (iostream) and for the mathematical
constant pi (math.h).
• We declare a float variable radius to store the user's input and a constant pi with the value of π
from the math.h library.
• We prompt the user to enter the radius and read it into the “a” variable using cin.
• We calculate the area and circumference using the provided formulas.
5

• Finally, we display the results with units using cout.

6 TASK 4:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main ()
{
float a,b,c,d;
cout<<"enter the numbers to get average \n";
cout<<"enter 1st number \n";
cin>>a;
cout<<"enter 2nd number \n";
cin>>b;
cout<<"enter 3rd number \n";
cin>>c;
d=(a+b+c)/3;
cout<<"your average is = "<<d;
return 0;
}
Pseudocode:

• Initialize variables: a, b, c, and d.


• Prompt the user to enter the first number (a).
• Read and store a.
• Prompt the user to enter the second number (b).
• Read and store b.
• Prompt the user to enter the third number (c).
• Read and store c.
• Calculate the average as (a + b + c) / 3.
• Display the average using cout.

6 TASK 5:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main ()
{
float a,b;
cout<<"provide temprature in fahrenheit \n";
cout<<"enter temperature \n";
cin>>a;
b=(a-32) *5/9;
cout<<"temperature is = "<<b<<"degree celcius \n";
6

return 0;
}
Pseudocode:

• Declare a variable 'a' to store the temperature in Fahrenheit.


• Declare a variable 'b' to store the temperature in Celsius.
• Prompt the user to enter a temperature in Fahrenheit.
• Read the input temperature from the user and store it in 'fahrenheit'.
• Use the formula 'b = (a - 32) * 5 / 9' to convert Fahrenheit to Celsius.
• Display the result using cout with an appropriate message.
• End the program.

6 TASK 6:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main ()
{
float a,b;
cout<<"enter 1st decimal number \n";
cin>>a;
cout<<"enter 2nd decimal number \n";
cin>>b;
cout<<"enter to get multiplication result \n";
getch();
cout<<a<<"*"<<b<<"="<<a*b<<"\n";
cout<<"enter to get fraction result \n";
getch();
cout<<a<<"/"<<b<<"="<<a/b<<"\n";
return 0;
}
In this program:

• We include the necessary libraries using #include.


• We declare variables to store the two decimal numbers, as well as the variables for the product
and division.
• We prompt the user to enter the two decimal numbers and read them using cin.
• We calculate the product and division and store them in the respective variables.
• We use cout to display the results.
• Finally, we use getch to wait for a key press before closing the console window.

6 TASK 7:
#include<iostream>
#include<math.h>
#include<conio.h>
7

using namespace std;


int main ()
{
float a,b;
cout<<"enter the No# you want to square \n";
cout<<"enter the No# \n";
cin>>a;
b=a*a;
cout<<"enter to get the result \n";
getch();
cout<<" The answer is = "<<b;
return 0; }
In this program:

• We declare variables number and square to store the user input and the square of the number,
respectively.
• We use cout to prompt the user to enter a number and then read the input using cin.
• The square is calculated by multiplying the number by itself.
• We use cout again to display the result to the user.
• To simulate getch, we use key presses before exiting the program.

6 TASK 8:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main ()
{
float a,b,c,d,e,f,g,h,i,j,k,l,m,n,o;
cout<<"enter the no# \n";
cin>>a;
b=sqrt(a);
getch ();
cout<<"square root is = "<<b<<"\n";
c=abs(a);
getch ();
cout<<"absolute value is = "<<c<<"\n";
d=log(a);
getch ();
cout<<"natural logaritham value is = "<<d<<"\n";
e=log10(a);
getch ();
cout<<"logaritham to base 10 value is = "<<e<<"\n";
f=exp(a);
getch ();
8

cout<<"exponential value is = "<<f<<"\n";


g=ceil(a);
getch ();
cout<<"ceil value is = "<<g<<"\n";
h=floor(a);
getch ();
cout<<"floor value is = "<<h<<"\n";
i=sin(a);
getch ();
cout<<"sin value is = "<<i<<"\n";
j=round(a);
getch ();
cout<<"round off value is = "<<j<<"\n";
cout<<"enter 2nd number \n";
cin>>k;
l=pow(a,k);
getch ();
cout<<"power raise to 2nd number is = "<<l<<"\n";
m=min(a,k);
getch ();
cout<<"min value is = "<<m<<"\n";
n=max(a,k);
getch ();
cout<<"max value is = "<<n<<"\n";
o=fmod(a,k);
getch ();
cout<<"remainder is = "<<o<<"\n";
return 0;
}
In this program:

• We prompt the user to enter a number and calculate its square root using the sqrt() function.
• We also demonstrate the usage of other math functions provided by <math.h>.
• Finally, we use getch() to pause the program before exiting so that the user can see the results.

6 TASK 9:
#include<iostream>
#include<math.h>
#include<conio.h>
using namespace std;
int main ()
{
float a,b;
cout<<"enter 1st no# \n";
9

cin>>a;
cout<<"enterr 2nd no# \n";
cin>>b;
cout<<"sum is = "<<a+b<<"\n";
cout<<"product is = "<<a*b<<"\n";
cout<<"difference is = "<<a-b<<"\n";
cout<<"division is = "<<a/b<<"\n";
return 0;
}
Pseudo-code explanation:

• Import the necessary libraries, including <iostream> for input and output operations.
• Define the main function as the entry point of the program.
• Declare variables for storing user input and results.
• Prompt the user to enter two float and store them in a and b.
• Calculate the sum, difference, and product of a and b.
• Display the results using cout.

7 OUTPUTS
7 TASK 1:
10

7 TASK 2:

7 TASK 3:
11

7 TASK 4:

7 TASK 5:
12

7 TASK 6:

7 TASK 7:
13

7 TASK 8:

7 TASK 9:
14

8 CONCLUSIONS
After performing this lab, I have got the concept how to run the code.
I am aware now about the data type e.g., int, float and string etc.

I came to know about the body of the code and what changings are required in the body to run
the code according to the given task.
I understood the information of the libraries requires in the code and the use of main function
and most importantly using namespace std.
I learned if some error occurs how to make it correct.
1

PROGRAMMING FUNDAMENTALS

LAB SESSION 3
1 INTRODUCTION
1 TITLE FOR LAB:
String, String Stream, If/Else, Nested If.
1 OBJECTIVES:
These concepts are fundamental in many programming languages and are used
extensively for controlling the flow of your code, processing strings, and performing various
tasks based on conditions.

2 BACKGROUNDS
In this lab I have used these operations and functions: -

• #include<iostream> • String
• #include<math.h> • String Stream
• #include<conio.h> • If/Else
• using name space std • Nested If
• int main ()
• cout<<
• cin>>
• return 0

3 LAB TASKS
1. Write a program to get string input from user and display on the screen.
2. Write a program to get name of the user and display a greeting message displaying
user's name in start as well as in middle of the message.
3. Write program to determine size of each type of variable and display the result on
screen.
4. Develop a program that input two numbers in string format and add both and display
answer.
2

5. Write a program that convert int to float, char to int, int to char, int to float data types.
6. Develop a code that takes character input and displays the ASCII code of that character.
(Output format: ASCII of A is 65)
7. Create a program that determines if a number is even or odd.
8. Write a program to check if a given number is positive, negative, or zero.
9. Develop a program that calculates the maximum of three numbers using nested
ifstatements.
10. Create a program that checks if a given character is a vowel or not.
11. Develop a program to calculate the grade of a student based on their percentage
12. Implement a program that checks if a number is divisible by both 2 and 3.
13. Create a program that determines if a triangle is equilateral, isosceles, or scalene based
on its side lengths.
14. Write a program to check if a character is an uppercase letter, lowercase letter, or a digit
or special character.
15. Write a program that calculates the sum of digits of a given number.
16. Write a program that takes three-digit number as input and break the number in units,
17. tens and hundreds. Display each digit separately in the following format, 786 →
Hundreds 7 Tens-8 Units-6. If user enters any number having more than three digits or 0,
then error message is displayed.
18. Implement a program that checks if a given string is a palindrome or not. (Remains same
if revered)
19. Write a program to get scores of four subjects from user, calculate CGPA and display
whether student has passed the semester or not. For passing a semester, student must
attain at least 1.7 GPA in all the courses.

4 REQUIRED MATERIALS
Following is the material required to perform this specific lab :-
• C++ compiler
• DEV C++
• Visual Studio Code
Libraries that are included are: -
iostream
• math.h
• conio.h

5 CONSTRAINTS
Students must be well aware of the data type they are giving in the code.
Students must be able to do in the specific time assigned by the instructor.
3

6 CODE TEMPLATES
6 TASK 1:
#include <iostream>
using namespace std;

int main ()
{
string a;
cout << "Enter a string: ";
cin >> a;
cout << "You entered: \n" <<a;
return 0;
}
Pseudocode:

1. Declare a string variable ‘a’.


2. Display "enter a string: " to the user.
3. Read ‘a’ from the user.
4. Display "You entered: " followed by ‘a’.
5. End the program.

6 TASK 2:
#include <iostream>
using namespace std;
int main ()
{
string a;
cout << "Enter your name: ";
cin >> a;
cout << "Hello, " << a << "! Welcome to the program." << endl;
return 0;
}
Pseudocode:

1. Start
2. Declare a string variable "name"
3. Display "Enter your name: " to the user
4. Read the user's input into the "name" variable
5. Display "Hello, " + name + "!" to the user
6. End

6 TASK 3:
#include <iostream>
using namespace std;
int main ()
4

{
cout << "Size of int: " << sizeof(int) << " bytes\n";
cout << "Size of char: " << sizeof(char) << " bytes\n";
cout << "Size of float: " << sizeof(float) << " bytes\n";
cout << "Size of double: " << sizeof(double) << " bytes\n";
cout << "Size of bool: " << sizeof(bool) << " bytes\n";
cout << "Size of short: " << sizeof(short) << " bytes\n";
cout << "Size of long: " << sizeof(long) << " bytes\n";
cout << "Size of long long: " << sizeof(long long) << " bytes\n";

return 0;
}
In this program:

• We include the necessary header file #include <iostream> to enable input and output
operations.
• We use the using namespace std; directive to simplify our code and allow us to use objects and
functions from the std namespace without prefixing them with std::.
• Inside the main function, we use the sizeof operator to determine the size in bytes of different
types of variables (char, int, float, double, long, and long long).
• We then use cout to display the results on the screen, along with labels to indicate the type of
variable and the size in bytes.

6 TASK 4:
#include <iostream>
#include <sstream>
using namespace std;
int main ()
{
string num1_str, num2_str;
cout << "Enter the first number: ";
cin >> num1_str;
cout << "Enter the second number: ";
cin >> num2_str;
int num1;
int num2;
stringstream(num1_str) >> num1;
stringstream(num1_str) >> num2;
int sum = num1 + num2;
cout << "The sum is: " << sum << endl;
return 0;
}
In this program:

• We use the string class to store the input numbers as strings.


5

• We prompt the user to enter the first and second numbers as strings using cin.
• We use the stoi function to convert the input strings to integers.
• We perform the addition operation on the integer values.
• Finally, we display the result using cout

6 TASK 5:
#include <iostream>
using namespace std;
int main() {
int integerNumber = 42;
float floatNumber;
char charValue = 'A';
floatNumber = static_cast<float>(integerNumber);
int intValue = static_cast<int>(charValue);
char charResult = static_cast<char>(integerNumber);
cout << "Converted int to float: \n" << floatNumber;
cout << "Converted char to int: \n" << intValue;
cout << "Converted int to char:\n " << charResult;

return 0;
}
In this program:

• We convert an integer to a float using static_cast<float>(integerNumber).


• We convert a character to an integer using static_cast<int>(charCharacter).
• We convert an integer to a character using static_cast<char>(intToChar).
• We convert an integer to a float using static_cast<float>(integerToFloat).

6 TASK 6:
#include <iostream>
using namespace std;

int main ()
{
char ch;
cout << "Enter a character: ";
cin >> ch;
int cd;
cd=(int)ch;
cout << "ASCII of " << ch << " is " <<cd ;

return 0;
}
In this code:
6

• We include the necessary header files.


• We declare a variable character of type char to store the input character.
• We use cout to prompt the user to enter a character.
• We use cin to read the character input and store it in the character variable.
• We convert the character to its ASCII code by casting it to
an int using static_cast<int>(character).
• We use cout to display the ASCII code along with the original character.

6 TASK 7:
#include <iostream>
using namespace std;
int main ()
{
int number;
cout << "Enter an integer: ";
cin >> number;
if (number % 2 == 0) {
cout << number << " is even.\n";
} else {
cout << number << " is odd.\n";
}

return 0;
}
In this pseudocode:

• We declare an integer variable called number to store the input number.


• We prompt the user to enter a number.
• We use the modulo operator % to check if the remainder of number when divided by 2 is equal to
0. If it is, the number is even, and we print that. Otherwise, it's odd, and we print that.

6 TASK 8:
#include <iostream>
using namespace std;
int main()
{
double number;

cout << "Enter a number: ";


cin >> number;
7

if (number > 0){

cout << "The number is positive.\n";


}
else if (number < 0)
{
cout << "The number is negative.\n";
} else
{
cout << "The number is zero.\n";
}

return 0;
}
Pseudocode:

• Declare a variable number to store the input number.


• Prompt the user to enter a number.
• Read the number from the user.
• Check if the number is greater than 0.
• If true, print "The number is positive."
• If the number is not greater than 0, check if it is less than 0.
• If true, print "The number is negative."
• If neither condition in steps 4 nor 5 is met, it means the number is zero.
• In this case, print "The number is zero."
• End the program.

6 TASK 9:
#include <iostream>
using namespace std;

int main()
{
int num1, num2, num3;
cout << "Enter three numbers: \n";
cin >> num1 >> num2 >> num3;
if (num1 >= num2)
{
if (num1 >= num3) {
cout << "The maximum number is: \n" << num1;
} else {
cout << "The maximum number is: \n" << num3;
}
8

} else {
if (num2 >= num3) {
cout << "The maximum number is: \n" << num2;
} else {
cout << "The maximum number is: \n" << num3;
}
}

return 0;
}
Pseudocode:

• Declare three integer variables num1, num2, and num3.


• Prompt the user to enter three numbers.
• Read and store the input numbers in the variables num1, num2, and num3.
• Use nested if statements to determine the maximum number: a. If num1 is greater than or equal
to num2, then: i. If num1 is also greater than or equal to num3, then num1 is the maximum. ii.
Otherwise, num3 is the maximum. b. If num1 is not greater than or equal to num2, then: i. If num2 is
greater than or equal to num3, then num2 is the maximum. ii. Otherwise, num3 is the maximum.
• Display the maximum number to the user.

6 TASK 10:
#include <iostream>
using namespace std;
int main ()
{
char character;
cout << "Enter a character: ";
cin >> character;
if (character == 'a' || character == 'e' || character == 'i' || character == 'o' || character
== 'u' ||
character == 'A' || character == 'E' || character == 'I' || character == 'O' || character
== 'U')
{
cout << character << " is a vowel.\n";
} else
{
cout << character << " is not a vowel.\n";
}

return 0;
}
Pseudocode:
9

1. Prompt the user to enter a character.


2. Read the character from the user.
3. Check if the character is 'a' or 'e' or 'i' or 'o' or 'u' or 'A' or 'E' or 'I' or 'O' or 'U
'.
4. If the character matches any of these conditions, display "Character is a vowel."
5. If the character does not match any of these conditions, display "Character is not a vowel.
"
6. End the program.

6 TASK 11:
#include <iostream>
using namespace std;
int main()
{
float percentage;
cout << "Enter the student's percentage: ";
cin >> percentage;
if (percentage >= 0 && percentage <= 100)
{
char grade;
if (percentage >= 90)
{
grade = 'A';
}
else if (percentage >= 80)
{
grade = 'B';
}
else if (percentage >= 70)
{
grade = 'C';
}
else if (percentage >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
cout << "The student's grade is:\n " << grade;
}
else
{
cout << "Invalid percentage! Please enter a percentage
between 0 and 100.\n" ;
}
10

return 0;
}
Pseudocode for the program:

• Prompt the user to enter the student's percentage.


• Read the percentage from the user.
• Check if the entered percentage is within the valid range (0-100).
• If the percentage is valid, determine the grade based on the following criteria:
• If the percentage is greater than or equal to 90, assign the grade 'A'.
• If the percentage is greater than or equal to 80, assign the grade 'B'.
• If the percentage is greater than or equal to 70, assign the grade 'C'.
• If the percentage is greater than or equal to 60, assign the grade 'D'.
• Otherwise, assign the grade 'F'.
• Output the calculated grade.
• If the entered percentage is not within the valid range, display an error message.

6 TASK 12:
#include <iostream>
using namespace std;
int main ()
{
int number;
cout << "Enter a number: ";
cin >> number;
if (number % 2 == 0 && number % 3 == 0)
{
cout << number << " is divisible by both 2 and 3.\n";
}
else
{
cout << number << " is not divisible by both 2 and 3.\n";
}

return 0;
}
pseudocode for the same program:

1. Start
2. Declare an integer variable named "number".
3. Output "Enter a number: ".
4. Input a value into the "number" variable.
5. Check if the number is divisible by both 2 and 3:
a. If (number % 2 == 0) AND (number % 3 == 0) then
i. Output "number is divisible by both 2 and 3."
b. Else
i. Output "number is not divisible by both 2 and 3."
11

6. End

6 TASK 13:
#include <iostream>
using namespace std;

int main()
{
double a, b, c;
cout << "Enter the lengths of three sides of the triangle: ";
cin >> a >> b >> c;

if (a <= 0 || b <= 0 || c <= 0 || (a + b <= c) || (a + c <= b) || (b + c <= a))


{
cout << "Not a valid triangle.\n" ;
}
else
{
if (a == b && b == c)
{
cout << "It's an equilateral triangle.\n";
} else if (a == b || a == c || b == c)
{
cout << "It's an isosceles triangle.\n";
}
else
{
cout << "It's a scalene triangle.\n";
}
}

return 0;
}
Pseudocode:

• Input the lengths of three sides of the triangle (a, b, and c).
• Check if the input values form a valid triangle: a. Make sure that each side length is greater than
0. b. Ensure that the sum of any two sides is greater than the third side.
• Determine the type of triangle: a. If all sides are equal (a == b == c), it's an equilateral triangle. b.
If exactly two sides are equal (a == b, b != c or a == c, b != c or b == c, a != b), it's an isosceles
triangle. c. If none of the above conditions are met, it's a scalene triangle.
• Print the type of the triangle.

6 TASK 14:
#include <iostream>
using namespace std;
12

int main() {
char ch;
cout << "Enter a character: ";
cin >> ch;
if (ch >= 'A' && ch <= 'Z') {
cout << "The character is an uppercase letter.\n";
}
else if (ch >= 'a' && ch <= 'z')
{
cout << "The character is a lowercase letter.\n";
}
else if (ch >= '0' && ch <= '9')
{
cout << "The character is a digit." << endl;
}
else
{
cout << "The character is a special character.\n";
}

return 0;
}
Pseudocode:

• Ask the user to enter a character.


• Read the character input from the user.
• Check if the character is in the range 'A' to 'Z' (uppercase letter).
• If true, print "The character is an uppercase letter."
• Check if the character is in the range 'a' to 'z' (lowercase letter).
• If true, print "The character is a lowercase letter."
• Check if the character is in the range '0' to '9' (digit).
• If true, print "The character is a digit."
• If none of the above conditions are met, print "The character is a special character."

6 TASK 15:
#include<iostream>
using namespace std;
int main ()
{
int x,a,t,h,u;
cout<<"enter number\n";
cin>>x;
u=x%10;
a=x/10;
t=a%10;
13

h=a/10;
cout<<(u+t+h);
return 0;
}
Pseudocode for the program:

• Input a number.
• If the number is negative, make it positive.
• Initialize a variable sum to store the sum of digits and set it to 0.
• If the number is 0, set sum to 0.
• If the number is less than 10, set sum to the number itself.
• If the number is greater than or equal to 10, repeat the following steps until the number
becomes 0: a. Extract the last digit of the number using modulo operation (%). b. Add the
extracted digit to the sum. c. Remove the last digit from the number by integer division (/).
• Output the sum of digits.

6 TASK 16:
#include<iostream>
using namespace std;
int main()
{
int x,a,t,h,u;
cout<<"enter three digit number\n";
cin>>x;
u=x%10;
a=x/10;
t=a%10;
h=a/10;
cout<<"unit"<<"=\n"<<u;
cout<<"ten"<<"=\n"<<t;
cout<<"hundred"<<"=\n"<<h;
return 0;
}
Pseudocode:

1. Input a number from the user.


2. Check if the number is less than 100 or greater than 999.
a. If true, display an error message and exit.
3. Extract the hundreds digit by dividing the number by 100.
4. Extract the tens digit by dividing the number by 10 and taking the remainder when divided b
y 10.
5. Extract the units digit by taking the remainder when divided by 10.
6. Display the original number and the extracted digits in the specified format.
7. Exit.
14

6 TASK 17:
#include<iostream>
using namespace std;
int main()
{
int x,a,t,h,u;
cout<<"enter three digit number\n";
cin>>x;
u=x%10;
a=x/10;
t=a%10;
h=a/10;
if(u==h)
{
cout<<"number is palindrome";
}
else
{
cout<<"number is not palindrome";
}
return 0;
}
Pseudocode:

• Define a function isPalindrome that takes a string as input.


• Initialize two pointers, left and right, where left starts at the beginning of the string,
and right starts at the end of the string.
• Use a while loop to iterate until left is less than right.
• Inside the loop, check if the characters at the left and right pointers are not the same. If they
are not the same, return false, indicating it's not a palindrome.
• If the characters at left and right match, increment left and decrement right to move closer to
the center of the string.
• If the loop completes without finding any non-matching characters, return true, indicating it's a
palindrome.
• In the main function, get input from the user, call the isPalindrome function, and print the result.

6 TASK 18:
#include <iostream>
using namespace std;
int main()
{
float a,b,c,x;
cout<<"GPA subject 1 \n";
cin>>a;
15

cout<<"GPA Subject 2 \n";


cin>>b;
cout<<"GPA Subject 3 \n";
cin>>c;
x =(a*2+ b*3 +c*3)/8;
cout<<"total cgpa "<<"="<<x;
if (x=1.7)
{
cout<<"pass";
}
else
{
cout<<"fail";
}
return 0;
}
Pseudocode:

1. Declare variables: subject1, subject2, subject3, subject4, totalCredits, totalPoints, cgpa


2. Prompt the user to enter scores for four subjects (subject1, subject2, subject3, subject4)
3. Calculate totalPoints as the sum of subject scores
4. Set totalCredits to the total number of subjects (4 in this case)
5. Calculate cgpa as totalPoints divided by totalCredits
6. Check if all subject scores are greater than or equal to 1.7 to determine if the student pa
ssed
7. Display the calculated cgpa
8. Display pass/fail status based on the passing criteria

7 OUTPUTS
7 TASK 1:
16

7 TASK 2:

7 TASK 3:
17

7 TASK 4:

7 TASK 5:
18

7 TASK 6:

7 TASK 7:
19

7 TASK 8:

7 TASK 9:
20

7 TASK 10:

7 TASK 11:
21

7 TASK 12:

7 TASK 13:
22

7 TASK 14:

7 TASK 15:
23

7 TASK 16:

7 TASK 17:
24

7 TASK 18:

8 CONCLUSIONS
The learning outcomes of this lab were that now we were no longer limited to simple functions
in c++. We were able to execute complex conditional (true/false) statements. We learned how
to implement string inputs and gather required results in c ++. It was a great experience which
depend our understanding of this programming language.
1

PROGRAMMING FUNDAMENTALS

LAB SESSION 4
1 INTRODUCTION
1 TITLE FOR LAB:
Switch case and for loop.
1 OBJECTIVES:
Students be able to implement and run switch case and for loop commands properly.

2 BACKGROUNDS
In this lab I have used these operations and functions: -
• #include<iostream> • break;
• #include<math.h> • goto
• #include<conio.h> • continue;
• #include<string.h> • for loop
• #include<sstream> • switch case
• using name space std; • modulo a%b
• int main () • !=
• cout<< • cin>>
• return 0;

3 LAB TASKS
1. Problem: Write a program that takes a number as input and print whether it Is even
or odd using a switch case.
2. Problem: Create a program that asks the user to enter a day number (1-7) and prints
the corresponding day of the week using switch case.
3. Problem: Write a program that takes a character as a input and determines whether it
is a vowel or consonant using switch case.
4. Problem: Develop a calculator program that perform basic arithmetic operation (+.-
,*,/) based on the user choice using switch case.
5. Problem: Create a program that asks the user to enter a number month (1-12) and
print the corresponding month name using switch case.
6. Problem: Write a program that takes a grade as a input (A, B, C, D, E and F) and print
the corresponding message using switch case.
7. Problem: Implement a program that converts a given temperature in Celsius to
Fahrenheit or vice versa based on the user choice using switch case.
8. Problem: Write a program to display the numbers from 1 to 10 using a goto
statement.
9. Problem: Write a program to calculate the sum of user defined numbers using for
loop.
10. Problem: Write a program to print the even numbers between 1 and 50 using for
loop.
11. Problem: Write a program to find the factorial of the given number using for loop.
12. Problem: Write a program to check whether a number is prime or not using for loop.
13. Problem: Write a program to find the largest number among the 10 numbers entered
by the user using a for loop.
14. Problem: Write a program to wait for 0 from the user using a for loop and break else
it keeps on asking the numbers.
15. Problem: Write a program to print the numbers from 1 to 10 skipping the number 5
using a for loop.
16. Problem: Write a program to find the factorial of the given number but if the number
is negative break the loop and display an error message.
17. Problem: Write a program to find the sum of all the even numbers between two given
numbers using a for loop and continue statement.

4 REQUIRED MATERIALS
Following is the material required to perform this specific lab :-
• C++ compiler
• DEV C++
• Visual Studio Code
Libraries that are included are
:- iostream
• math.h
• conio.h
• string.h
• sstream

5 CONSTRAINTS
Students must check the condition properly and then implement them.
3

Students should check the libraries for the commands they are putting in.

6 CODE TEMPLATES
6 TASK 1:
#include<iostream>
#include<math.h>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int a;
cout<<"enter a number : ";
cin>>a;
a=a%2;
switch(a)
{
case 0:
cout<<"enter number is even \n";
break;
case 1:
cout<<"enter number is odd \n";
break;
}
return 0;
}
Pseudocode:

1. Declare a variable 'number' to store the user's input.


2. Display a message to prompt the user to enter a number.
3. Read the user's input and store it in the 'number' variable.
4. Use a switch-case statement to check whether 'number' is even or odd:
a. Compute 'number % 2' to get the remainder when dividing by 2.
b. Case 0: If the remainder is 0, print that 'number' is even.
c. Case 1: If the remainder is 1, print that 'number' is odd.
d. Default: Handle any unexpected input with an error message.
5. End the program.

6 TASK 2:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int days;
cout<<"enter a number to display the days of week : \n";
cin>>days;
switch(days)
{
case 1:
cout<<"sunday \n";
break;
case 2:
cout<<"monday \n";
break;
case 3:
cout<<"tuesday \n";
break;
case 4:
cout<<"wednesday \n";
case 5:
cout<<"thursday \n";
break;
case 6:
cout<<"friday \n";
break;
case 7:
cout<<"saturday \n";
break;
}
return 0;
}
Here's a pseudocode version of the same program:

1. Initialize dayNumber as an integer


2. Display "Enter a day number (1-7): "
3. Input dayNumber from the user
4. Use a switch statement on dayNumber:
a. Case 1: Display "Monday"
b. Case 2: Display "Tuesday"
c. Case 3: Display "Wednesday"
d. Case 4: Display "Thursday"
e. Case 5: Display "Friday"
f. Case 6: Display "Saturday"
g. Case 7: Display "Sunday"
h. Default: Display "Invalid input. Please enter a number between 1 and 7."
5. End of switch statement
6. End of program

6 TASK 3:
#include<iostream>
5

#include<conio.h>
#include<sstream>
#include<string.h>
using namespace std;
int main()
{
char chr;
cout<<"enter character to know whether it is a vowel or not \n";
cin>>chr; switch(chr)
{
case 'a':
cout<<"character is a vowel \n";
break;
case 'A':
cout<<"character is a vowel \n";
break;
case 'e':
cout<<"character is a vowel \n";
break;
case 'E':
cout<<"character is a vowel \n";
break;
case 'i':
cout<<"character is a vowel \n";
break;
case 'I':
cout<<"character is a vowel \n";
case 'o':
cout<<"character is a vowel \n";
break;
case 'O':
cout<<"character is a vowel \n";
break;
case 'u':
cout<<"character is a vowel \n";
break;
case 'U':
cout<<"character is a vowel \n";
break;
default:
cout<<"character is a consonant \n";
break;
}
return 0;
}
Pseudocode:

1. Start
2. Declare a character variable 'character'
3. Output "Enter a character: "
4. Input the character from the user and store it in 'character'
5. Convert 'character' to lowercase to handle both uppercase and lowercase vowels
6. Using a switch-case statement, do the following:
a. Case 'a':
b. Case 'e':
c. Case 'i':
d. Case 'o':
e. Case 'u':
- Output "'character' is a vowel."
- Break
f. Default:
- Output "'character' is a consonant."
7. End

6 TASK 4:
#include<iostream>
#include<math.h>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int a,b;
char chr;
cout<<"enter first number \n";
cin>>a;
cout<<"enter second number \n";
cin>>b;
cout<<"enter operation sign to perform that operation \n";
cin>>chr;
switch(chr)
{
case '+':
cout<<"sum = "<<a<<"+"<<b<<"="<<a+b<<"\n";
break;
case '-':
cout<<"differnece = "<<a<<"-"<<b<<"="<<a-b<<"\n";
case '*':
cout<<"product = "<<a<<"*"<<b<<"="<<a*b<<"\n";
break;
7

case '/':
cout<<"division = "<<a<<"/"<<b<<"="<<a/b<<"\n";
break;
}
return 0;
}
Pseudocode explanation:

• Declare variables for the operation character, two numbers, and the result.
• Display a menu and prompt the user to choose an operation.
• Get the user's choice of operation (e.g., +, -, *, /).
• Prompt the user to enter two numbers.
• Use a switch-case statement to perform the selected operation:
• For addition (+), subtract the numbers and display the result.
• For subtraction (-), subtract the numbers and display the result.
• For multiplication (*), multiply the numbers and display the result.
• For division (/), check if the divisor is not zero, perform the division, and display the
result. If the divisor is zero, display an error message.
• For an invalid operation, display an error message.
• Return 0 to indicate successful program execution.

6 TASK 5:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int month;
cout<<"enter number to see what month it is (1-12) \n";
cin>>month;
switch(month)
{
case 1:
cout<<"january\n";
break;
case 2:
cout<<"february\n";
break;
case 3:
cout<<"march\n";
break;
case 4:
cout<<"april\n";
break;
case 5:
cout<<"may\n";
break;
case 6:
cout<<"june\n";
break;
case 7:
cout<<"july\n";
case 8:
cout<<"august\n"; break; case 9:
cout<<"september\n";
break; case 10:
cout<<"october\n";
break; case 11:
cout<<"november\n";
break; case 12:
cout<<"december\n";
break;
}
return 0;
}
Pseudocode for the program:

1. Start
2. Declare integer variable monthNumber
3. Display "Enter a number representing a month (1-12): "
4. Read monthNumber from the user
5. Use a switch statement on monthNumber:
a. Case 1: Display "January"
b. Case 2: Display "February"
c. Case 3: Display "March"
d. Case 4: Display "April"
e. Case 5: Display "May"
f. Case 6: Display "June"
g. Case 7: Display "July"
h. Case 8: Display "August"
i. Case 9: Display "September"
j. Case 10: Display "October"
k. Case 11: Display "November"
l. Case 12: Display "December"
m. Default: Display "Invalid month number. Please enter a number between 1 and 12."
6. End

6 TASK 6:
#include<iostream>
#include<conio.h>
9

#include<string.h>
#include<sstream>
using namespace std;
int main()
{
char chr;
cout<<"enter your grade (A-F) and get a comment \n";
cin>>chr;
switch(chr)
{
case 'A':
cout<<"excellent\n";
break;
case 'B':
cout<<"very good\n";
break;
case 'C':
cout<<"satisfactory\n";
break;
case 'D':

cout<<"average \n";
case 'E':
cout<<"below average \n";
break;
case 'F':
cout<<"very poor \n";
break;
}
return 0;
}
Pseudocode:

1. Prompt the user to enter a grade (A, B, C, D, E, or F).


2. Read the grade input from the user.
3. Use a switch-case statement to check the value of the grade.
4. For each case ('A', 'B', 'C', 'D', 'E', 'F'), print a corresponding message.
- Case 'A' or 'a': Print "Excellent! Keep up the good work."
- Case 'B' or 'b': Print "Good job. You're doing well."
- Case 'C' or 'c': Print "You are passing, but there's room for improvement."
- Case 'D' or 'd': Print "You need to work harder to improve."
- Case 'E' or 'e': Print "You're not doing well. Seek help and work harder."
- Case 'F' or 'f': Print "You failed. You should review and seek assistance."
- Default: Print "Invalid input. Please enter a valid grade."
5. End the switch-case
6 TASK 7:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int a;
float f,c,t;
cout<<"1:fahrenheit to centigrade \n2:centigrade to fahrenheit \n";
cin>>a;
switch(a)
{
case 1:
cout<<"enter temp in fahrenheit \n";
cin>>f;
t=(f-32)*5/9;
cout<<"temperature in centigrade = "<<t<<"\n";
break;
case 2:
cout<<"enter temp in centigrade \n";
cin>>c;
t=(9*c/5)+32;
cout<<"temperature in fahrenheit = "<<t<<"\n";
break;
}
return 0;
}
Pseudocode:

1. Display "Temperature Conversion Menu:"


2. Display "1. Celsius to Fahrenheit"
3. Display "2. Fahrenheit to Celsius"
4. Prompt the user to enter their choice and store it in 'choice'
5. Use a switch statement on 'choice':
- Case 1:
1. Prompt the user to enter a temperature in Celsius and store it in 'temperature'
2. Calculate 'result' = (temperature * 9/5) + 32
3. Display "Temperature in Fahrenheit: result °F"
- Case 2:
1. Prompt the user to enter a temperature in Fahrenheit and store it in 'temperature'
2. Calculate 'result' = (temperature - 32) * 5/9
3. Display "Temperature in Celsius: result °C"
- Default:
1. Display "Invalid choice. Please choose 1 or 2."
6. End of switch statement
7. End of program
11

6 TASK 8:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int m=1;
repeat:
cout<<m<<"\n";
m++;
if(m<=10)
{
goto repeat;
}
return 0;
}
Here's a pseudocode representation of the same logic:

Initialize num to 1

loop_start:
If num is greater than 10, go to loop_end
Display num
Increment num by 1
Go to loop_start

loop_end:
End of program

6 TASK 9:
#include<iostream>
#include<math.h>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int num;
int sum=0;
for(int i=1;i<=10;i++)
{
cout<<"enter num : "<<i;
cin>>num;
sum=sum+num;
}
cout<<"sum = "<<sum<<"\n";
return 0;
}
Pseudocode:

1. Initialize variables:
- numCount to store the number of values to sum
- sum to store the sum of the numbers

2. Prompt the user to enter the number of values to sum and store it in numCount

3. Initialize a for loop with the loop variable i from 1 to numCount (inclusive)

4. Inside the loop:


a. Prompt the user to enter a number and store it in the variable num
b. Add num to the sum

5. After the loop, display the sum

6 TASK 10:
#include<iostream>
#include<conio.h>
#include<sstream>
#include<string.h>
using namespace std;
int main()
{
int num;
for(int i=2;i<=50;i=i+2)
{
cout<<"even number (0-50)"<<i<<"\n";
}
return 0;
}
Pseudocode:

FOR each number i from 1 to 50


IF i is even
PRINT i
END IF

6 TASK 11:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<sstream>
13

using namespace std;


int main()
{
int num;
int fact=1;
cout<<"enter number for factorial \n";
cin>>num;
for(int i=1;i<=num;i++)
{
fact=fact*i;
}
cout<<"factorial = "<<fact<<"\n";
return 0;
}
Pseudocode:

1. Declare variables: number, factorial


2. Read a positive integer from the user and store it in 'number'
3. Check if 'number' is negative:
a. If it's negative, display an error message
b. If it's not negative, continue to the next step
4. Initialize 'factorial' to 1
5. Use a for loop to calculate the factorial:
a. Start the loop with 'i' from 1 to 'number'
b. Inside the loop, multiply 'factorial' by 'i' in each iteration
6. Display the result: "Factorial of [number] is [factorial]"

6 TASK 12:
#include<iostream>
#include<sstream>
#include<string.h>
#include<math.h>
#include<conio.h>
using namespace std;
int main()
{
int a,b; cout<<"enter number \n";
cin>>a;
for(int i=2;i<=a;i++)
{ b=a%i;
if(b!=0)
{
cout<<"prime\n";
break;
}
else
{
cout<<"not prime \n";
break;
}
}
return 0;
}
And here's the pseudocode version:

1. Start
2. Initialize number, isPrime
3. Read a positive integer into number
4. if number <= 1 then
5. isPrime = false
6. else
7. for i from 2 to number / 2 do
8. if number % i == 0 then
9. isPrime = false
10. exit loop
11. end if
12. end for
13. end if
14. if isPrime is true then
15. Print number is a prime number
16. else
17. Print number is not a prime number
18. end if
19. End

6 TASK 13:
#include<iostream>
#include<math.h>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
int num;
int largest=0;
for(int i=1;i<=10;i++)
{
cout<<"enter number \n";
cin>>num;
if(num>largest)
{
largest=num;
}
}
15

cout<<"largest number = "<<largest<<"\n";


return 0;
}
Pseudocode:

Initialize largest to the smallest possible integer value


Repeat 10 times:
Input a number from the user
If the input number is greater than the current largest number:
Update largest to the input number
Output the largest number

6 TASK 14:
#include<iostream>
#include<conio.h>
#include<sstream>
#include<string.h>
using namespace std;
int main()
{
int num;
for(int i=1;1<=10;i++)
{
cout<<"enter numbers : ";
cin>>num;
if(num==0)
{
break;
}
}
return 0;
}
Pseudocode:

1. Initialize a variable `number` to store user input.


2. Start an infinite loop:
a. Prompt the user to enter a number.
b. Read the number from the user.
c. Check if the number is equal to 0:
- If yes, print a message and break out of the loop.
d. Repeat the loop until the user enters 0.
3. Exit the program.

6 TASK 15:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<sstream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
cout<<i<<"\n";
}
return 0;
}
Here's the pseudocode for the same program:

FOR i FROM 1 TO 10 DO
IF i EQUALS 5 THEN
CONTINUE // Skip number 5
END IF
PRINT i
END FOR

6 TASK 16:
#include<iostream>
#include<math.h>
#include<sstream>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
int num;
cout<<"enter number to get factorial \n";
cin>>num;
if(num<=0)
{
cout<<"errror ! due to number is negative \n";
}
else
{
int fact=1;
for(int i=1;i<=num;i=i+1)
{
fact=fact*i;
17

}
cout<<"factorial = "<<fact<<"\n";
}
return 0;
}
Here's the pseudocode for the program:

• Start
• Declare an integer variable num to store the user input.
• Display a message asking the user to enter a non-negative integer.
• Read the value of num from the user.
• Check if num is less than 0 (i.e., negative).
• If num is negative, display an error message stating that the factorial is undefined for negative
numbers.
• If num is non-negative, initialize an integer variable factorial to 1.
• Use a for loop to calculate the factorial of num: a. Initialize a loop variable i to 1. b. Repeat the
following steps while i is less than or equal to num: i. Multiply factorial by i and store the result
in factorial. ii. Increment i by 1. c. End of the loop.
• Display the calculated factorial.
• End.

6 TASK 17:
#include<iostream>
#include<conio.h>
#include<sstream>
#include<string.h>
using namespace std;
int main()
{
int a,b,c;
int sum=0;
cout<<"enter starting range \n";
cin>>a;
cout<<"enter ending range \n";
cin>>b;
for(int j=a;j<=b;j=j+1)
{ c=j%2;
if(c!=0)
{
continue;
}
sum=sum + j;
}
cout<<"sum of even numbers between given range is = "<<sum<<"\n";
return 0;
}
Pseudocode:

1. Input start and end numbers


2. Initialize a variable 'sum' to 0 to store the sum of even numbers
3. Iterate through the numbers from 'start' to 'end' using a for loop:
a. Check if the current number 'num' is even (num % 2 == 0)
b. If it's not even, use the 'continue' statement to skip to the next iteration
c. If it's even, add it to the 'sum'
4. After the loop, output the 'sum' as the sum of even numbers between the given range

7 OUTPUTS
7 TASK 1:
19

7 TASK 2:

7 TASK 3:
7 TASK 4:

7 TASK 5:
21

7 TASK 6:

7 TASK 7:
7 TASK 8:

7 TASK 9:
23

7 TASK 10:

7 TASK 11:
7 TASK 12:

7 TASK 13:
25

7 TASK 14:

7 TASK 15:
7 TASK 16:

7 TASK 17:

8 CONCLUSIONS
Performing this lab helps me to use switch case for different types of command. For loop can
be used for different type of programs to run. For loop is quite helpful as it is a converting,
conditional loop. Different type of error occurred using these commands in our program but
now I fully aware of them what type of error may occurs using them. Goto statement, a
unconditional loop also being used. Break and continue command are also used to break the
loop and skip numbers respectively. Break command breaks if/else, nested if and for loop
commands.
1

PROGRAMMING FUNDAMENTALS

LAB SESSION 5
1 INTRODUCTION
1 TITLE FOR LAB:
While Loop.
1 OBJECTIVES:
Students be able to implement and run While Loop commands properly.

2 BACKGROUNDS
In this lab I have used these operations and functions: -
• #include<iostream>
• #include<math.h>
• #include<conio.h>
• #include<string.h>
• #include<sstream>
• using name space std;
• int main ()
• cout<<
• return 0;
• while loop

3 LAB TASKS
1. Write a program to calculate sum of user defined numbers using while loop.
2. Write a program to print even numbers from 1 to 50 using while loop.
3. Write a program to find factorial of a given number using while loop.
4. Write a program to find the largest among 10 numbers using while loop.
5. Write a program waiting for zero from user and break loop using while.

4 REQUIRED MATERIALS
Following is the material required to perform this specific lab: -
• C++ compiler
• DEV C++
• Visual Studio Code
2

Libraries that are included are: -


iostream
• math.h
• conio.h

5 CONSTRAINTS
Students must be well aware of the data type they are giving in the code.
Students must be able to do in the specific time assigned by the instructor.

6 CODE TEMPLATES
6 TASK 1:
#include <iostream>
using namespace std;
int main()
{
int num,x,i;
int sum;
cout<<"total no of elements \n";
cin>>x;
while (i<=x)
{cout<<"enter no \n";
cin>>num;
sum=sum + num;
i++;
cout<<"sum of all no is = \n"<<sum;}
return 0;
}
Pseudocode:

Initialize sum to 0
Prompt the user to enter numbers (enter 0 to finish)
While true:
Read a number from the user and store it in the variable num
If num is equal to 0:
Break out of the loop
Add num to sum
End while
Display the sum of entered numbers

6 TASK 2:
#include <iostream>
using namespace std;
int main()
{
3

int i;
while (i<=50)
{
i = i + 2;
cout<<i<<"\n";
}
return 0;
}
Pseudocode:

Initialize a variable 'number' to 2

While 'number' is less than or equal to 50:


Print 'number'
Increment 'number' by 2

6 TASK 3:
#include <iostream>
using namespace std;
int main()
{
int fact = 1;
int num;
int i = 1;
cout<<"enter no \n";
cin>>num;
while (num>=i)
{
fact= fact* i;
i++;
}
cout<<"fact of no is = "<<fact;
return 0;
}
Pseudocode:

1. Start
2. Initialize num, factorial, and i as integers
3. Prompt the user to enter a number and store it in num
4. Initialize factorial to 1 and i to 1
5. While i is less than or equal to num, do steps 6-8
6. Multiply factorial by i and update factorial
7. Increment i by 1
8. End of while loop
9. Display "Factorial of num is factorial" where num is the input number and factorial is the
calculated factorial
10. End
4

6 TASK 4:
#include <iostream>
using namespace std;

int main() {
int count = 1;
double number, largest;
cout << "Enter number " << count << ": ";
cin >> largest;
while (count < 10) {
count++;
cout << "Enter number " << count << ": ";
cin >> number;

if (number > largest) {


largest = number;
}
}
cout << "The largest number is: " << largest <<"\n";

return 0;
}
Pseudocode:

Initialize largest to 0
Initialize count to 1

Display "Enter number 1: "


Read largest

While count is less than 10


Increment count by 1
Display "Enter number count: "
Read num

If num is greater than largest


Set largest to num

Display "The largest number is: largest"

6 TASK 5:
#include <iostream>
using namespace std;
int main()
{
int num;
int sum=0;
5

while (1)
{
cout<<"enter number \n";
cin>>num;
}
sum=sum+num;
if (num==0)

cout<<"sum=:"<<sum;
return 0;
}
Pseudocode:

Initialize userInput to 0

Repeat the following:


Display "Enter a number (0 to exit): "
Read userInput from the user

If userInput is equal to 0, then


Display "You entered zero. Exiting the loop."
Exit the loop
End If

// Perform any additional processing with userInput if needed

End Repeat

7 OUTPUTS
7 TASK 1:
6

7 TASK 2:

7 TASK 3:
7

7 TASK 4:

7 TASK 5:

8 CONCLUSIONS
The main key takeaways in this lab were learning various uses of while loop in certain
prescribed user conditions for specific targeted or desired results to be achieved. With the help
of while loop we were able to meet user code requirements and execute proper results.
1

PROGRAMMING FUNDAMENTALS

LAB SESSION 6
1 INTRODUCTION
1 TITLE FOR LAB:
Do While Loop, Nested Loops
1 OBJECTIVES:
For instance, you might use a "do-while" loop with a nested loop to read and
process data from a file until the end of the file is reached (outer loop ensures at least one
attempt to read), and the nested loop could be used to process each line or record within the
file.

2 BACKGROUNDS
• #include<iostream>
• #include<math.h>
• #include<conio.h>
• using name space std
• int main ()
• cout<<
• cin>>
• return 0
• do while loop
• nested loop

3 LAB TASKS
1. Write a program to find the sum of even numbers from 1 to N, where N is an integer
provided by the user, using a DO-WHILE LOOP.
2. Write a program to display reverse of a number entered by user, using WHILE LOOP.
3. Write a program to display squares of digits in reverse order of number entered by user,
using WHILE LOOP.
4. Write a program to draw right angle triangle with, of user defined height using a FOR
LOOP.
2

5. Write a program to draw right angle triangle with *, of user defined height using a
WHILE LOOP.
6. Write a program to draw diagonal line with *, of user defined *s using a FOR LOOP.
7. Write a program to draw diagonal line with *, of user defined *s using a WHILE LOOP.
8. Write a program to draw square with, of user defined side using a FOR LOOP.
9. Write a program to draw square with ", of user defined side using a WHILE LOOP.
10. Write a program to draw hollow square with. of user defined side using a FOR LOOP.
11. . Write a program to draw hollow square with ", of user defined side using a WHILE
LOOP.
12. Write a program to draw rectangle with ", of user defined length and breadth using a
FOR LOOP.
13. Write a program to draw rectangle with *, of user defined length and breadth using a
WHILE LOOP.
14. Write a program to draw hollow rectangle with, of user defined length and breadth
using a FOR LOOP.
15. Write a program to draw hollow rectangle with, of user defined length and breadth
using a WHILE LOOP.

4 REQUIRED MATERIALS
Following is the material required to perform this specific lab: -
• C++ compiler
• DEV C++
• Visual Studio Code
Libraries that are included are: -
iostream
• math.h
• conio.h

5 CONSTRAINTS
Students must be well aware of the data type they are giving in the code.
Students must be able to do in the specific time assigned by the instructor.

6 CODE TEMPLATES
6 TASK 1:
#include <iostream>
using namespace std;
int main ()
{
int N;
int sum = 0;
3

cout << "Enter a positive integer N: ";


cin >> N;
int i = 2;
do {
sum += i;
}
while (i <= N);{
cout << "The sum of even numbers from 1 to " << N << " is: " << sum <<"\n";}
return 0;
}
Pseudocode:

• Declare variables N, sum, and i.


• Initialize i to 2 because we want to start with the first even number.
• Prompt the user to enter a positive integer N.
• Check if N is less than or equal to 0. If so, display an error message and exit the program.
• Initialize sum to 0 to store the sum of even numbers.
• Use a do-while loop to calculate the sum of even numbers:
• Add the current value of i to sum.
• Increment i by 2 to get the next even number.
• Continue the loop until i is less than or equal to N.
• Display the result, which is the sum of even numbers from 1 to N.
• Exit the program with a success code.

6 TASK 2:
#include<iostream>
using namespace std;
int main()
{

int num,a;
a=0;
cout<<"enter any number\n";
cin>>num;
while(a<num)
{
cout<< num%10;
num=num/10;
}
return 0;
}
explanation of the program:

• Ask the user to enter a number.


• Initialize reverse to 0.
4

• Use a while loop to reverse the number, where we:


• Calculate the last digit of num using the modulo operator (%).
• Add the last digit to reverse after shifting reverse left by one decimal place.
• Remove the last digit from num by dividing num by 10.
• Repeat these steps until num becomes 0.
• Display the reversed number.

6 TASK 3:
#include<iostream>
#include<math.h>
using namespace std;
int main()
{

int num, a;
a=0;
cout<<"enter any number\n";
cin>>num;
while(a=num)
{ cout<< pow(num%10,2);
num=num/10;
}
return 0;
}
Pseudocode for the program:

1. Start
2. Declare variables: number, digit, reversedNumber
3. Input the number from the user
4. Initialize reversedNumber to 0
5. While (number > 0):
a. Extract the last digit of the number and store it in 'digit'
b. Calculate the square of 'digit' and display it
c. Remove the last digit from 'number'
6. End While
7. Exit
6 TASK 4:
#include<iostream>
using namespace std;
int main()
{

int a,n,b;
cout<<"enter any number\n";
cin>>a;
for (int c = 0 ; c<a; c++)
5

for (int b = 0 ; b<c; b++)


{

cout<<"*";}
cout<<"\n";
}
return 0;
}
Pseudocode:

1. Get the user input for the height of the right-angle triangle (let's call it 'height').
2. Start a loop to iterate through each row from 1 to 'height'.
1. Start an inner loop to print '*' characters in each row from 1 to the current row number
.
1. Print '*'.
2. End the inner loop.
3. Move to the next line to start a new row.
3. End the outer loop.
4. End the program.

6 TASK 5:
#include<iostream>
using namespace std;
int main()
{

int a,n,b;
cout<<"enter any number\n";
cin>>a;
n = 0;
while (n<a)
{
n++;
for (int b = 0 ; b<n; b++)
{

cout<<"*";
}
cout<<"\n";
}
return 0;
}
6

pseudo-code:

• Input the height of the right-angle triangle from the user.


• Initialize a variable i to 1 to represent the current row.
• Use a while loop to iterate while i is less than or equal to the height.
• Initialize an inner loop variable j to 1 to represent spaces before each row.
• Use a while loop to print spaces (equal to height - i spaces) before each row.
• Initialize an inner loop variable k to 1 to represent asterisks in each row.
• Use a while loop to print asterisks (equal to i asterisks) for each row.
• Move to the next line to start a new row.
• Increment the i variable to move to the next row.
• End the program.

6 TASK 6:
#include<iostream>
using namespace std;
int main()
{

int a,n,b;
cout<<"enter any number \n";
cin>>a;
for(int c=0; c<a; c++)
{

for (int b=0; b<c; b++)


{
cout<<" ";
}
cout<<"*\n";
}
return 0;
}
Pseudocode:

1. Prompt the user to enter a character (e.g., '*') and store it in 'character'.
2. Prompt the user to enter the length of the diagonal line and store it in 'length'.
3. Initialize a loop variable 'i' from 0 to 'length - 1'.
4. Inside the outer loop:
a. Initialize an inner loop variable 'j' from 0 to 'i - 1'.
b. Inside the inner loop, print a space " " to create the diagonal effect.
c. After the inner loop, print the 'character' followed by a newline.
5. Repeat steps 4 until 'i' reaches 'length - 1'.
6. End of the program.
6 TASK 7:
#include<iostream>
using namespace std;
7

int main()
{
int a,n,b;
cout<<"enter any number\n";
cin>>a;
n=0;
while(n<a)
{
n++;
for (int b=0; b<n; b++)
{
cout<<" ";
}
cout<<"*\n";
}
return 0;
}
Pseudocode:

1. Prompt the user for the length of the diagonal line.


2. Initialize a variable 'row' to 1.
3. While 'row' is less than or equal to the user-defined length:
4. Initialize a variable 'col' to 1.
5. While 'col' is less than 'row':
6. Print a space.
7. Increment 'col'.
8. Print an asterisk '*'.
9. Move to the next line.
10. Increment 'row'.
11. End of program.
6 TASK 8:
#include<iostream>
using namespace std;
int main()
{

int a,n,b;
cout<<"enter any number\n"; cin>>a;
for(int c=0; c<=a; c++)
{
for (int b=0; b<=a; b++)
{
cout<<"*";
}
cout<<"\n";
}
8

return 0;
}
Pseudocode:

1. Prompt the user to enter the side length of the square.


2. Read and store the side length in a variable (sideLength).
3. Check if the sideLength is less than or equal to 0.
- If true, display an error message and exit.
4. Use a for loop with variable i from 0 to sideLength-1 (inclusive).
1. Inside the outer loop, use a nested for loop with variable j from 0 to sideLength-1 (inc
lusive).
1. Inside the inner loop, print a '*' followed by a space.
2. After the inner loop completes a row, move to the next line (endl).
5. Repeat steps 4 until the outer loop completes sideLength rows.
6. Exit the program with a success code.

6 TASK 9:
#include<iostream>
using namespace std;
int main()
{
int a,n,b;
cout<<"enter any number\n";
cin>>a;
while(n<a)
{
n++;
for (int b=0; b<a; b++)
{

cout<<"*";
}
cout<<"\n";
}
return 0;
}
Pseudocode:

1. Prompt the user to enter the side length of the square.


2. Read the user's input and store it in a variable (sideLength).
3. Initialize a variable (row) to 1 to keep track of the current row.
4. Start a while loop that continues as long as row is less than or equal to sideLength.
1. Initialize a variable (col) to 1 to keep track of the current column.
2. Start a nested while loop that continues as long as col is less than or equal to sideLen
gth.
1. Check if the current position is on the first or last row or the first or last column
.
2. If it is, print a comma.
3. Otherwise, print a space.
4. Increment col by 1.
9

3. Move to the next line (end of the current row).


4. Increment row by 1.
5. End of the while loop.
6. End of the program.

6 TASK 10:
#include<iostream>
using namespace std;
int main()
{
int a,n,b;
cout<<"enter any number\n";
cin>>a;
for (int c = 0 ;c<=a; c++)
{

for (int b = 0 ;b<=a; b++)


{
if (b==0||b==a||c==0||c==a)
{

cout<<"*";
}
else
{cout<<" ";
}}
cout<<"\n";
}
return 0;
}
Pseudocode:

1. Get the user-defined side length as input.


2. Check if the input is valid (greater than 1). If not, display an error message and exit.
3. Use a loop to iterate through each row (from 1 to sideLength):
a. Use a nested loop to iterate through each column (from 1 to sideLength):
i. Check if it's the first row, last row, first column, or last column.
ii. If yes, print an asterisk (*).
iii. If no, print a space (" ").
b. Move to the next row by printing a newline character.
4. End of the program.

6 TASK 11:
#include<iostream>
using namespace std;
int main()
10

{
int a,n,b;
cout<<"enter any number\n";
cin>>a;
int c=1;
while(c<=a)
{
c++;
for (int b = 0 ;b<=a; b++)
{
if (b==0||b==a||c==0||c==a)
{
cout<<"*";
}
else
{cout<<" ";
}}
cout<<"\n";
}
return 0;
}
pseudocode:

1. Read the side length (an integer) from the user.


2. Initialize variables i and j to 1.
3. Use a while loop to iterate over rows (i) from 1 to the side length.
a. If i is 1 or i is equal to the side length, print a row of '*' characters.
b. Otherwise, for columns (j) from 1 to the side length:
i. If j is 1 or j is equal to the side length, print a '*' character.
ii. Otherwise, print a space character.
c. Print a newline character to move to the next row.
d. Increment i by 1.
4. End the loop.
5. Exit the program.

6 TASK 12:
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"rows\n";
cin>>a;
cout<<"colum\n";
cin>>b;
for (int i = 1 ;i<=a; i++)
11

{
for (int j = 1 ;j<=b; j++)
{

cout<<"*";
}
cout<<"\n";
}
return 0;
}
Here's the pseudocode for the program:

1. Start
2. Declare variables: length, breadth
3. Input the length and breadth of the rectangle from the user
4. Loop over each row from 0 to (breadth - 1)
a. Loop over each column in the current row from 0 to (length - 1)
i. If (i == 0) or (i == breadth - 1) or (j == 0) or (j == length - 1), then
- Print "*"
ii. Else
- Print " "
b. Move to the next line
5. End

6 TASK 13:
#include<iostream>
using namespace std;
int main()
{
int a,b,i;
cout<<"rows\n";
cout<<"colum\n";
cin>>a;
cin>>b;
i=1;
while(i<=a)
{
i++;
for (int j = 1 ;j<=b; j++)
{
cout<<"*";
}
cout<<"\n";
}
return 0;
}
12

Pseudocode:

1. Input length and breadth from the user.


2. Initialize variables i and j to 0 (loop counters).
3. While i is less than breadth, do the following:
a. Set j to 0 (reset j for each row).
b. While j is less than length, do the following:
i. If i is 0, i is breadth - 1, j is 0, or j is length - 1, then:
- Print '*'
ii. Else:
- Print a space (' ')
iii. Increment j by 1 (move to the next column).
c. Print a newline to move to the next row.
d. Increment i by 1 (move to the next row).
4. End the program.

6 TASK 14:
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"rows\n";
cin>>a;
cout<<"colum\n";
cin>>b;
for (int i=1; i<=a; i++)
{
for (int j=1; j<=b; j++)
{
if(i=1||i==a||j==1||j==b)
{
cout<<"*";
}
else{
cout<<" ";
}}
cout<<"\n";
}
return 0;
}
Pseudocode:

1. Prompt the user to enter the length of the rectangle


2. Read and store the length in a variable 'length'
3. Prompt the user to enter the breadth of the rectangle
4. Read and store the breadth in a variable 'breadth'
5. Use a nested loop structure to iterate through each row and column of the rectangle:
a. For each row (i), iterate through each column (j):
13

i. If i is 1 or length, or if j is 1 or breadth:
- Print '*'
ii. Else:
- Print a space (' ')
b. Move to the next line after each row
6. End the program

7 OUTPUTS
7 TASK 1:

7 TASK 2:
14

7 TASK 3:

7 TASK 4:
15

7 TASK 5:

7 TASK 6:
16

7 TASK 7:

7 TASK 8:
17

7 TASK 9:

7 TASK 10:
18

7 TASK 11:

7 TASK 12:
19

7 TASK 13:

7 TASK 14:

8 CONCLUSIONS
The learning outcome of this lab was use of do while loop and for / while loop in
printing different types of patterns that require different conditions to be executed.
Additionally, we also learned reversing simple and reversed numbers.
1

PROGRAMMING FUNDAMENTALS

LAB SESSION 7
1 INTRODUCTION
1 TITLE FOR LAB:
Functions
1 OBJECTIVES:
Functions in C++ serve a wide range of objectives, from code organization and
modularity to data manipulation, error handling, and more. They are a fundamental building
block of C++ programs, enabling you to create structured and maintainable code.

2 BACKGROUNDS
• #include<iostream>
• #include<math.h>
• #include<conio.h>
• using name space std
• int main ()
• cout<<
• cin>>
• return 0
• Functions

3 LAB TASKS
1. Create a function to calculate the factorial of a given non-negative integer.
2. Write a function that checks whether a given number is prime or not.
3. Implement a function to find the greatest common divisor (GCD) of two integers.
4. Create a function that reverses a given string.
5. Write a program that displays a menu to calculate the area of a circle, rectangle and
square and display the result using functions.
6. Implement functions that converts temperature in Celsius, Fahrenheit and Kelvin.
7. Create functions to find the square root of a given positive number and negative
numbers.
8. Write a function that counts the number of vowels in a given string.
9. Implement a function that checks if a given number, is a palindrome.
10. Write a function that counts the numbers in sequence in a number.
2

11. Create a calculator using functions.


12. Write a function that converts a binary number to its decimal equivalent. Display error if
number is not binary.
13. Implement a function that checks if a given number, is a perfect square.
14. Write a function that calculates the perimeter of a triangle given its sides.
15. Create a function to calculate the volume of a sphere given its radius.

4 REQUIRED MATERIALS
Following is the material required to perform this specific lab: -
• C++ compiler
• DEV C++
• Visual Studio Code
Libraries that are included are: -
iostream
• math.h
• conio.h

5 CONSTRAINTS
Students must be well aware of the data type they are giving in the code.
Students must be able to do in the specific time assigned by the instructor.

6 CODE TEMPLATES
6 TASK 1:
#include<iostream>
using namespace std;
int fact(int a)
{
int fact=1;
for(int i=1;i<=a;i++)
{
fact=fact*i;
}
return fact;
}
int main()
{
int n,f;
cout<<"enter number for factorial \n";
cin>>n;
3

f=fact(n);
cout<<"factorial is "<<f;
}
Pseudocode for the factorial calculation:

function factorial(n):
if n < 0:
return 0 // Handle invalid input
else if n == 0 or n == 1:
return 1 // Base case: factorial of 0 or 1 is 1
else:
return n * factorial(n - 1) // Recursive case: n! = n * (n-1)!

6 TASK 2:
#include<iostream>
using namespace std;
int prime(int a)
{
int b;
for(int n=2;n<=a;n++)
{
b=a%n;
if(b==0)
{
cout<<"num is not prime \n";
break;
}
else
{
cout<<"num is prime \n";
break;
}
}
}
int main()
{
int m,c;
cout<<"enter num \n";
cin>>c;
m=prime(c);
}
Pseudocode for the isPrime function:
function isPrime(n)
if n <= 1
return false
end if
4

for i from 2 to sqrt(n)


if n % i == 0
return false
end if
end for

return true
end function

6 TASK 3:
#include<iostream>
using namespace std;
int gdc(int a, int b)
{
int gcd;
int x,y;
if(a>b)
{
for(int i=1;i<=b;i++)
{
x=b%i;
y=a%i;
if(x==0 && y==0)
{
gcd=i;
}
}
}
else
{
for(int i=1;i<=a;i++)
{
x=b%i;
y=a%i;
if(x==0 && y==0)
{
gcd=i;
}
}
}
return gcd;
}
int main()
{
5

int l,j;
cout<<"enter 1st num \n";
cin>>l;
cout<<"enter 2nd num \n";
cin>>j;
int k;
k=gdc(l, j);
cout<<"gdc is "<<k;
}
pseudocode representation of a function to find the greatest common divisor (GCD) of two integers in
C++:

FUNCTION gcd(a, b)
WHILE b is not equal to 0
temp = b
b = a % b
a = temp
END WHILE
RETURN a
END FUNCTION

6 TASK 4:
#include<iostream>
using namespace std;
int stringreverse(int n)
{
int m;
while(n>0)
{
m=n%10;
n=n/10;
cout<<m;
}
}
int main()
{
int s,g;
cout<<"entr num string \n";
cin>>g;
s=stringreverse(g);
}
Pseudocode:

function reverseString(input)
length = length of input
reversed = ""
6

for i from (length - 1) down to 0


append input[i] to reversed

return reversed

input = get user input


reversed = reverseString(input)
output reversed

6 TASK 5:
#include<iostream>
using namespace std;
int menu(int a, int b)
{
int areaC,areaS,areaR;
int c;
cout<<"enter your choice \n 1:cicle \n 2:square \n 3:rectangle \n";
cin>>c;
switch(c)
{
case 1:
{
cout<<"u want to take area of circle \n";
areaC=3.14*a*a;5
cout<<"area is circle "<<areaC<<"\n";
break;
}
case 2:
{
cout<<"u want to take area of sq \n";
areaS=a*a;
cout<<"area of sq is "<<areaA<<"\n";
break;
}
case 3:
{
cout<<"u want area of rectangle \n";
areaR=a*b;
cout<<"area of rect is "<<areaR<<"\n";
break;
}
}
}
int main()
{
7

int z,m,n,r;
cout<<"enter radius of circle \n";
cout<<"radius of circle is equal to one side of ract or sq \n";
cin>>r;
cout<<"enter 2nd length of sq or rect \n";
cin>>m;
z=menu(r,m);
}
Pseudocode:

function reverseString(input)
length = length of input
reversed = ""

for i from (length - 1) down to 0


append input[i] to reversed

return reversed

input = get user input


reversed = reverseString(input)
output reversed

6 TASK 6:
#include<iostream>
using namespace std;
int temp(float a)
{
int f,k,l;
cout<<"enter choice \n 1:to celcius \n 2: to faahehiet \n 3:to kelvin \n";
cin>>l;
switch(l)
{
case 1:
{
cout<<"temperature in C is "<<a<<"\n";
break;
}
case 2:
{
f=(a+32)*5/9;
cout<<"temperatue in F is "<<f<<"\n";
break;
}
case 3:
{
8

k=a+273;
cout<<"temperature in K is "<<k<<"\n";
break;
}
}
}
int main()
{
int z,d;
cout<<"entre temperature \n";
cin>>z;
d=temp(z);
}
In this program:

• We have four functions: celsiusToFahrenheit, fahrenheitToCelsius, celsiusToKelvin,


and kelvinToCelsius that perform the temperature conversions.
• The main function takes user input for the temperature and the scale (C, F, or K), and then it calls
the appropriate conversion function based on the selected scale.
• The converted temperature is displayed in degrees Celsius. You can add additional

6 TASK 7:
#include<iostream>
#include<math.h>
using namespace std;
int squareroot(int a)
{
int b;
b=sqrt(a);
return b;
}

int main()
{
int x,y,z,w;
cout<<"enter numr\n";
cin>>x;
cout<<"enter num\n";
cin>>y;
z=squareroot(x);
cout<<z<<"\n";
cout<<"square root is not defined for -ve number \n";
}
Pseudocode for the findSquareRoot function:
9

Function findSquareRoot(number)
If number < 0
Set absoluteValue = AbsoluteValue(number)
Set result = SquareRoot(absoluteValue)
Else
Set result = SquareRoot(number)
End If
Return result
End Function

6 TASK 9:
#include<iostream>
using namespace std;
int palindrome(int a)
{
int palin=0;
int n;
while(a>0)
{
n=a%10;
palin=palin*10+n;
a=a/10;
}
return palin;
}
int main()
{
int x,y;
cout<<"enter num \n";
cin>>x;
y=palindrome(x);
if(y==x)
{
cout<<"enter num is palindrome \n";
}
else
{
cout<<"enter num is not palindrome \n";
}
}
Palindrome program in C++
Get the number from user.
Hold the number in temporary variable.
Reverse the number.
Compare the temporary number with reversed number.
If both numbers are same, print palindrome number.
10

Else print not palindrome number.

6 TASK 10:
#include<iostream>
using namespace std;
int countdigit(int a)
{
int count=0;
while(a!=0)
{
a=a/10;
count++;
}
return count;
}
int main()
{
int b,c;
cout<<"enter num \n";
cin>>b;
c=countdigit(b);
cout<<"num of digits are "<<c;
}
In this code:

• We convert both the number and sequence to strings so that we can easily search for the
sequence within the number.

• We use a while loop to repeatedly search for the sequence in the number using
the find function of the std::string class.

• When we find a match, we increment the count and move the search position forward to
continue searching for the next occurrence.

• The countSequenceInNumber function returns the count of the sequence in the number,
which is then displayed in the main function.

6 TASK 11:
#include<iostream>
using namespace std;
int calculator(int a, int b)
{
int c,d;
cout<<"enter choice \n 1:+ \n 2:- \n 3:* \n 4:/ \n";
11

cin>>c;
switch(c)
{
case 1:
{
d=a+b;
break;
}
case 2:
{
d=a-b;
break;
}
case 3:
{
d=a*b;
break;
}
case 4:
{
d=a/b;
break;
}
}
return d;
}
int main()
{
int x,y,z;
cout<<"enter 1st number \n";
cin>>x;
cout<<"enter 2nd number \n";
cin>>y;
z=calcul(x,y);
cout<<z;
}
Pseudocode Explanation:

• We start by defining four functions add, subtract, multiply, and divide to perform the respective
arithmetic operations.
• In the main function, we declare variables for the operation (operation) and two numbers
(num1 and num2) that the user will input.
• We use a switch statement to determine which operation the user wants to perform.
• Based on the selected operation, we call the corresponding function to perform the calculation.
12

• If the user selects division and attempts to divide by zero, we handle this as an error.
• Finally, we display the result of the calculation.

6 TASK 12:
#include<iostream>
using namespace std;
int binary(int a)
{
int b=1;
int dec=0;
int n,i;
while(a>0)
{
n=a%10;
if(n==1 || n==0)
{
i=n*b;
a=a/10;
dec=dec+i;
b=b*2;
}
else
{
cout<<"ERROR ! num is not binary \n";
break;
}
}
return dec;
}
int main()
{
int x,y;
cout<<"enter binary num \n";
cin>>x;
y=binary(x);
cout<<y;
}
Here's the pseudocode for the above C++ program:

Function isBinary(binaryStr):
For each character c in binaryStr:
If c is not '0' and c is not '1':
Return false
Return true
13

Function binaryToDecimal(binaryStr):
Initialize decimal to 0
Initialize power to 0

For i from the length of binaryStr - 1 down to 0:


If binaryStr[i] is '1':
Add 2^power to decimal
Increment power

Return decimal

Main:
Read binaryStr from the user
If isBinary(binaryStr) is false:
Print "Error: Input is not a binary number."
Exit with an error code
Calculate decimal as binaryToDecimal(binaryStr)
Print "Decimal equivalent:", decimal
Exit with a success code

6 TASK 13:
#include<iostream>
#include<math.h>
using namespace std;
int perfectsquare(int a)
{
int n,m;
m=sqrt(a);
n=m*m;
if(n==a)
{
cout<<a<<" is perf sq \n";
}
else
{
cout<<a<<" is not perf sq \n";
}
return m;
}
int main()
{
int k,l,j;
cout<<"enter num \n";
cin>>k;
l=perfectsquare(k);
}
In this code:
14

• We include the necessary headers for input/output and math operations.


• The isPerfectSquare function takes an integer num as input.
• First, it checks if num is negative. If it's negative, it returns false because negative numbers can't
be perfect squares.
• It then calculates the square root of num using the sqrt function from the <cmath> library.
• Finally, it checks if the square of the square root is equal to the original number. If they are
equal, it returns true, indicating that num is a perfect square; otherwise, it returns false.

6 TASK 14:
#include<iostream>
using namespace std;
int perimeter(int a,int b,int c)
{
int d;
d=a+b+c;
return d;
}
int main()
{
int w,x,y,z;
cout<<"enter 1st side of triangle \n";
cin>>w;
cout<<"enter 2nd side of triangle \n";
cin>>x;
cout<<"enter 3rd side of triangle \n";
cin>>y;
z=perimeter(w,x,y);
cout<<"perimeter of triangle is "<<z;
}
Here's the pseudocode for the same function:

FUNCTION calculateTrianglePerimeter(side1, side2, side3)


// Calculate the perimeter by adding all three sides
perimeter = side1 + side2 + side3
RETURN perimeter

FUNCTION main()
// Input the lengths of the three sides
INPUT side1
INPUT side2
INPUT side3

// Calculate the perimeter


perimeter = calculateTrianglePerimeter(side1, side2, side3)

// Display the perimeter


OUTPUT "The perimeter of the triangle is: " + perimeter
15

6 TASK 15:
#include<iostream>
using namespace std;
int volume(int a)
{
int z;
z=3.14*a*a*a*4/3;
return z;
}
int main()
{
int k,l;
cout<<"enter r \n";
cin>>k;
l=volume(k);
cout<<l;
}
Pseudocode:

function calculateSphereVolume(radius):
// Define the value of pi
pi = 3.14159265358979323846

// Calculate the volume using the formula (4/3) * π * r^3


volume = (4/3) * pi * radius^3

// Return the calculated volume


return volume

function main():
// Declare a variable to store the radius
radius = 0.0

// Input the radius from the user


print "Enter the radius of the sphere: "
input radius

// Check if the radius is negative


if radius < 0:
print "Radius cannot be negative."
else:
// Calculate the volume of the sphere
volume = calculateSphereVolume(radius)

// Output the result


print "The volume of the sphere with radius", radius, "is", volume

// Call the main function to start the program


main()
16

7 OUTPUTS
7 TASK 1:

7 TASK 2:
17

7 TASK 3:

7 TASK 4:
18

7 TASK 5:

7 TASK 6:
19

7 TASK 7:

7 TASK 9:
20

7 TASK 10:

7 TASK 11:
21

7 TASK 12:

7 TASK 13:
22

7 TASK 14:

7 TASK 15:

8 CONCLUSIONS
The learning outcome of this lab was use of Function in printing different types of patterns that
require different conditions to be executed. Additionally, we also learned reversing simple and
reversed numbers.
1

PROGRAMMING FUNDAMENTALS

LAB SESSION 8
1 INTRODUCTION
1 TITLE FOR LAB:
Functions over loading, Recursive function.
1 OBJECTIVES:
Functions in C++ serve a wide range of objectives, from code organization and
modularity to data manipulation, error handling, and more. They are a fundamental building
block of C++ programs, enabling you to create structured and maintainable code.

2 BACKGROUNDS
• #include<iostream>
• #include<math.h>
• #include<conio.h>
• using name space std
• int main ()
• cout<<
• cin>>
• return 0
• Functions

3 LAB TASKS
1. Write a function overloading in C++ to add two numbers user input.
2. Write a recursive function in C++ to factorial a number user input.

4 REQUIRED MATERIALS
Following is the material required to perform this specific lab: -
• C++ compiler
• DEV C++
• Visual Studio Code
Libraries that are included are: -
iostream
• math.h
• conio.h
2

5 CONSTRAINTS
Students must be well aware of the data type they are giving in the code.
Students must be able to do in the specific time assigned by the instructor.

6 CODE TEMPLATES
6 TASK 1:
#include<iostream>
using namespace std;
int myabc(int a, int b)
{
int c;
c=a+b;
return c;
}
float mymno(float a, float b)
{
float c;
c=a+b;
return c;
}
int main()
{
int a,b,c;
float m,n,o;
cout<<"enter integer: \n";
cin>>a;
cout<<"enter integer: \n";
cin>>b;
cout<<"enter float: \n";
cin>>m;
cout<<"enter float: \n";
cin>>n;
c=myabc(a,b);
o=mymno(m,n);
cout<<"sum of integer: \n"<<c<<"\n";
cout<<"sum of float: \n"<<o;
}
In this pseudocode
, we have defined several overloaded add functions. There are functions for adding two integers,
two floats, and even three integers. Additionally, there's a template function that can add two
numbers of any data type. In the main function, we take user input for integers and floats and
then call the appropriate add function based on the data types of the input numbers. Finally, we
display the results.
3

6 TASK 2:
#include<iostream>
using namespace std;
int myfact(int a)
{
if(a>1)
{
return (a*myfact(a-1));
}
else
{
return 1;
}
}

int main()
{
int a,b;
cout<<"enter fact numnber:\n";
cin>>a;
b=myfact(a);
cout<<"factorial of number is: "<<b;
}
Pseudocode:

function factorial(n)
if n equals 0
return 1
else
return n times factorial(n - 1)

function main()
input num
if num is negative
display "Factorial is not defined for negative numbers."
else
result = factorial(num)
display "Factorial of", num, "is", result
4

7 OUTPUTS
7 TASK 1:

7 TASK 2:
5

8 CONCLUSIONS
The learning outcome of this lab was use of Function in printing different types of patterns that
require different conditions to be executed. Additionally, we also learned overloading of
functions and recursive functions.

Instructor: Engr. Danish Arif Siddiqi


Submitted by: Shabbir Hussain

You might also like