Final Lab Manual CPPS
Final Lab Manual CPPS
Expt.
Problem Definition/Statement
No.
(Implement any 10)
Write a Program to convert Fahrenheit to Celsius.
1
Write a program to calculate simple and compound interests.
2
Write a program to develop an arithmetic calculator. Add the modulus (%) operator and
3 provision of negative numbers.
Write a program to calculate the electricity bill for the given MODULEs.
4
Write a program to check whether a triangle is valid or not, when the three angles of the
triangle are entered through the keyboard. A triangle is valid if the sum of all the three angles
5
is equal to 180 degrees.
Write a program to read the user given year as an input and determine whether it is a “leap”
6 year or not.
Write a program to accept a character from user and check whether entered character is:
1. alphabet (lower case or upper case)
2. vowel
7
3. digit
4. special character
Write a program to accept a suitable input from the user and count blanks, tabs and
8 newlines.
Write a program in C to swap two numbers using a function. (use call by value and call by
16 reference)
PREFACE
INTRODUCTION
These laboratory exercises are designed with a dual purpose:
1. To provide the student with “hands-on” experience in the C Programming Language
through the implementation of several programs.
2. To provide an atmosphere where the student will be required to communicate, both in
written and oral form.
It is the responsibility of the student to perform required preparation for lab work.
These labs will require some preparation prior to arriving in the lab.
JOURNAL WRITING INSTRUCTIONS
1. Title
2. Date of Completion
3. Problem Statement
4. Objectives
5. Software & Hardware requirements
6. Theory- Concept
7. Pseudo code
8. Flowchart
9. Test Cases minimum 3
10. Conclusion
Processor (CPU):
o Any modern processor, such as Intel Core i3/i5/i7 or AMD Ryzen series, will suffice
for compiling and running C programs. Even older processors can handle C programs well due
to the language's efficiency.
2. Memory (RAM):
o A minimum of 2 GB of RAM is usually sufficient for compiling and running simple C
programs. However, having more RAM (4 GB or more) can improve overall performance,
especially when working with larger projects or multiple applications simultaneously.
3. Storage:
o C compilers and development environments require only a small amount of disk space
(typically less than 1 GB). However, ensure you have enough disk space for storing your source
code files, compiler executables, and any additional libraries or tools you might use.
Introduction to Programming
Software refers to a program or set of instructions that instructs a computer to perform some
task. Software can be divided into two major categories called system software and application
software. Systems software includes operating systems and various device drivers. Application
software are used to perform real-world tasks and solve specific problems.
Program Development
Programmers should clearly understand “what are the inputs to the program”, “what is
expected as output(s)” and “how to process inputs to generate necessary outputs”. Consider an
example where a computer program is to be written to calculate and display the circumference
and area of a circle when the radius.
The next step is to develop an algorithm that will produce the desired result(s). An algorithm
is a segment of precise steps that describes exactly the tasks to be performed, and the order in
which they are to be carried out to solve a problem. Pseudocode (a structured form of the
English language) can be used to express an algorithm. A suitable algorithm for our example
would be:
Start
Input r
Calculate circumference
c = 2 * PI* r
Calculate area
a = PI* r^2
Output c & a
End
Compile:
The next step is to compile the program. While compiling syntax errors can be identified. When
the written program does not adhere to the programming language rules those are called syntax
errors. These errors occur mostly due to miss typed characters, symbols, missing punctuations,
etc. If there are no syntax errors the program gets compiled and it produces an executable
program.
Running a Program:
After a program is developed using a programming language, it should be executed by the
computer. Programmers write programmes in human readable languages called high-level
languages. However, the computer understands only 1’s and 0’s (referred as the machine
language3 or machine code). Therefore, we need to convert the human readable programs into
a machine language before executing. This conversion is achieved by a special set of programs
called compilers (or interpreters). These programs convert the high-level language program
into machine language programs.
Interpretation of a program
Overview of C
“C’ seems a strange name for a programming language but it is one of the most widely used
languages in the world. C was introduced by Dennis Ritchie in 1972 at Bell Laboratories as a
successor of the language called B (Basic Combined Programming Language – BCPL). Since
C was developed along with the UNIX operating system it is strongly associated with UNIX.
UNIX was developed at Bell Laboratories and it was written almost entirely in C.
For many years, C was used mainly in academic environments. However with the release of C
compilers for commercial use and increasing popularity of UNIX, it began to gain wide- spread
interest among computer professionals. Various languages such as C++, Visual C++, Java and
C# have branched away from C by adding object-orientation and GUI features.
Today C compilers are available for a number of operating systems including all flavors of
UNIX, Linux, MS-DOS, Windows and Apple Mac. C is a robust language whose rich set of
built-in functions and operations can be used to write
any complex program. C is well suited to write both commercial applications and system
software since it incorporates features of high-level languages and Assembly language.
Programs written in C are efficient and fast. Most C programs are fairly portable; that is with
little or no modification and compiling, C programs can be executed on different operating
systems.
The syntax and coding style of C is simple and well structured. Due to this reason most of the
modern languages such as C++, Java and C# inherit C coding style. Therefore it is one of the
best languages to learn the art of programming. C is also suitable for many complex engineering
applications.
An Example C Program
#include <stdio.h>
int main()
{
printf(“Hello World!”);
return 0;
}
The C language is built from functions like printf that execute different tasks. The functions
must be used in a framework which starts with the word main( ) , followed by the block
containing the function(s) which is marked by braces ({ } ). The main() is a special function
that is required in every C program. The keyword int indicates that the main () function returns
an integer value. Because function main () returns an integer value, there must be a statement
that indicates what this value is. The statement “return 0;”
The first line starting with characters / * and ending with characters * / is a comment.
Comments are used by programmers to add remarks and explanations within the program. It is
always a good practice to comment on your code whenever possible. Comments are of two
types; single line comments and block comments. Single line comments start with two slashes
{/ /} and all the text until the end of the line is considered a comment. Block comments start
with characters / * and end with
$ vim HelloWorld.c
$ gcc HelloWorld.c
$ ./a.out
Hello World! $
However, you will see the prompt ($) appearing just after the message “Hello World!” you can
avoid this by adding the new line character (\ n) to the end of the message. Then your modified
program should look like the following:
Assignment No – 1
Objective :
By the end of this experiment, students will be able to:
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: Program Structure:
A C program typically includes:
● Header Files: Include necessary libraries (e.g., #include <stdio.h>).
● Main Function: The entry point of the program where execution
begins (int main()).
● Statements and Expressions: The code that performs operations
and controls program flow.
Input and Output:
● printf: Displays output to the user.
● scanf: Reads input from the user.
Variables:
● Definition: Variables are used to store data that can be used and
manipulated within a program. Each variable has a specific type that
determines the size and layout of the variable's memory.
● Types: Common types include int (integer), float (floating-point),
char (character), and double (double-precision floating-point).
● Declaration: Variables must be declared before they are used. The
declaration specifies the variable's type and name.
Data Types:
● Primitive Types: Basic data types provided by C, such as int, float,
char, and double.
○ int: Used for integer values.
○ float: Used for single-precision floating-point numbers.
○ char: Used for single characters.
○ double: Used for double-precision floating-point numbers.
● Derived Types: Include arrays, pointers, structures, and unions.
Operators:
● Arithmetic Operators: Used to perform basic mathematical
operations.
○ Addition (+): Adds two values.
○ Subtraction (-): Subtracts one value from another.
○ Multiplication (*): Multiplies two values.
○ Division (/): Divides one value by another.
Conclusion:
This experiment successfully demonstrates how to convert a temperature
from Fahrenheit to Celsius using a C program. The exercise reinforces the
application of arithmetic operations and user interaction within a program.
Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 32 0.00 0.00 Pass
2 112 44.4444 44.4444 Pass
3 98.6 37.00 37.00 Pass
4 0 -17.78 -17.78 Pass
Questions:
1. What is the formula for converting Celsius to Fahrenheit?
2. What data types should I use for the variables in a Celsius to Fahrenheit conversion
program?
3. How does the use of floating-point numbers in C affect the accuracy of temperature
conversions?
4. Which data types in C are best suited for handling temperature values, and why?
5. How can you handle user input in C to ensure valid temperature values are entered?
1. Create a program that converts temperatures from Fahrenheit to Celsius and also from
Celsius to Fahrenheit.
2. Implement a C program to display a conversion table from Fahrenheit to Celsius for
temperatures ranging from -50°F to 100°F, with increments of 10°F.
3. Design a C program that calculates the average of multiple temperature readings in
Fahrenheit and then converts the average to Celsius.
4. Write a program to determine the state of water (solid, liquid, or gas) based on a given
temperature in Fahrenheit after converting it to Celsius.
5. The distance between two cities (in km.) is input through the keyboard. Write a program
to convert and print this distance in meters, feet, inches and centimeters.
6. Write a program that converts speed from kilometers per hour (km/h) to miles per hour
(mph).
7. Create a program that converts an amount of money from one currency to another based
on the provided exchange rate.
8. Design a program that converts a distance from kilometers to miles.
9. Create a program that converts an amount in US Dollars (USD) to Euros (EUR) using
a predefined exchange rate.
10. Write a program that converts fuel efficiency from miles per gallon (mpg) to liters per
100 kilometers (L/100 km).
11. Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of
basic salary, and house rent allowance is 20% of basic salary. Write a program to calculate his
gross salary.
Assignment No – 2
Problem Write a program to develop an arithmetic calculator. Add the modulus (%)
Statement: operator and provision of negative numbers.
Objective :
By the end of this experiment, students will be able to:
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
● Key Components of the Program
3. if Statement
The if in C is the most simple decision-making statement. It consists of the
test condition and if block or body. If the given condition is true only then
the if block will be executed.
Syntax:
if(condition)
{
// if body
// Statements to execute if condition is true
}
if-else Statement:
Syntax:
if (condition) {
} else {
4. if else if ladder
if else if ladder in C programming is used to test a series of conditions
sequentially. Furthermore, if a condition is tested only when all previous if
conditions in the if-else ladder are false. If any of the conditional
expressions evaluate to be true, the appropriate code block will be
executed, and the entire if-else ladder will be terminated.
Syntax:
}
else if(condition) {
// this else if will be executed when condition in if is false and
// the condition of this else if is true
}
.... // once if-else ladder can have multiple else if
else { // at the end we put else
}
Nested if-else Statements:
Syntax:
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if condition1 and condition2 are true
} else {
// Code to execute if condition1 is true and condition2 is false
}
} else {
// Code to execute if condition1 is false
}
switch-case Statement:
Syntax:
switch (expression) {
case value1:
// Code to execute if expression equals value1
break;
case value2:
// Code to execute if expression equals value2
break;
// More cases...
default:
// Code to execute if expression does not match any case
}
for Loop:
The for loop is used for iterating over a block of code a specific number of
times. It is typically used when the number of iterations is known
beforehand.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute on each iteration
}
while Loop:
Syntax:
while (condition) {
// Code to execute while condition is true
// Update control variable to eventually break the loop
}
goto Statement:
Syntax:
goto label;
...
label:
// Code to execute
continue Statement:
The continue statement is used to skip the rest of the code in the current
loop iteration and proceed to the next iteration of the loop.
Syntax:
while (condition) {
if (condition) {
continue; // Skip to next iteration
}
// More code
}
FUNCTION main()
// Initialize variables
DECLARE choice AS INTEGER
DECLARE a, b, c AS DOUBLE
DECLARE continueCalc AS CHARACTER
END
Flowchart:
Menu:
Addition
Substractin
Input
Test Case:
Test Choice Enter two Expected Output Actual Output Test
Case numbers Status
no
1 6 - Invalid Choice Invalid choice Pass
2 4 a=7,b=3 2.33 2.33 Pass
3 5 a=7,b=3 1 1 Pass
Questions:
1. What is the modulus operator (%), and how does it differ from other arithmetic
operators?
2. How do you handle division by zero in an arithmetic calculator program?
3. How can a calculator program be designed to accept and correctly process negative
numbers?
4. What is an arithmetic calculator, and what basic operations should it support?
If x is input through the keyboard, write a program to calculate the sum of first seven terms of
this series.
Assignment No – 3
Problem Write a program to calculate the electricity bill for the given MODULEs.
Statement:
Objective :
By the end of this experiment, students will be able to:
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
Electricity billing is a standard problem involving the calculation of the
cost of electricity consumed by a user. The cost depends on the number of
units consumed and the applicable tariff rates. The calculation typically
involves the following steps:
Modular Programming in C:
Syntax:
return_type function_name(parameter_list);
2. Function Definition:
return_type function_name(parameter_list) {
3. Function Call:
function_name(arguments);
FUNCTION input()
DECLARE units AS INTEGER
PRINT "Enter units: "
INPUT units
RETURN units
END FUNCTION
FUNCTION calculate_bill(units)
DECLARE bill AS DOUBLE
IF units <= 150 THEN
bill = units * 2.75
ELSE
bill = 150 * 2.75 + ((units - 150) * 5.25)
END IF
RETURN bill
END FUNCTION
FUNCTION display_bill(bill)
PRINT "Bill is: ", bill
END FUNCTION
FUNCTION main()
DECLARE units AS INTEGER
DECLARE bill AS DOUBLE
RETURN 0
END FUNCTION
END
Flowchart:
if amount=unit*1.50
else if amount=(100*1.50)+((
else amount=(100*1.50)+(2
Conclusion
This experiment successfully demonstrates the use of modular
programming in C to develop a basic electricity bill calculator. The
program handles user input, calculates the bill based on different tariff
slabs, and displays the result effectively. This modular approach not only
makes the program easy to understand and maintain but also highlights the
importance of structured programming techniques in solving real-world
problems.
Test Case:
Test Units consumed Expected Bill Actual Output Test Status
Case no calculated
1 0 150 150 Pass
2 50 75 75 Pass
3 350 450 450 Pass
Questions:
1. Define mod.
2. What is mod arithmetic?
3. What is the difference between modulus and divide operator?
4. What are the typical components of an electricity bill?
5. How is energy consumption usually measured and billed?
6. What are usage slabs or MODULEs, and why are they used in electricity billing?
7. How can conditional statements be used in C to calculate electricity bills based on
different MODULEs?
10. Write a program to generate all combinations of 1, 2 and 3 using a for loop.
11. Write a program to produce the following output:
12. A machine is purchased which will produce an earning of Rs. 1000 per year while it
lasts. The machine costs Rs. 6000 and will have a salvage of Rs. 2000 when it is condemned.
If 12 percent per annum can be earned on alternative investments what would be the
minimum life of the machine to make it a more attractive investment compared to alternative
investment?
Assignment No – 4
Problem Write a program to check whether a triangle is valid or not, when the three
Statement: angles of the triangle are entered through the keyboard. A triangle is valid if
the sum of all the three angles is equal to 180 degrees.
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: A triangle is a polygon with three edges and three vertices. The most
important property of a triangle is that the sum of its internal angles is always
Flowchart:
Start
Read
ang1,ang2,and3
sum=ang1+ang2+ang3
If Triangle is not
sum==180 valid
Triangle is valid
Stop
Conclusion This experiment demonstrates how to use basic input, output, and conditional
logic in C to solve a real-world problem. By checking the sum of the three
angles, we can determine whether a given set of angles can form a valid
triangle. The experiment also reinforces the understanding of using relational
operators and conditional statements in programming.
Test Case:
Test Angle 1 Angle2 Angle3 Expected Actual Test
Case Output Output Status
no
1 60 60 60 Triangle is Triangle is Pass
valid valid
2 90 45 45 Triangle is Triangle is Pass
valid valid
3 12 30 25 Triangle is Triangle is Pass
not valid not valid
Questions:
1. What are the potential types of triangles based on their angles, and how can they be
identified?
2. What are some real-world applications where validating the angles of a triangle is
necessary?
8. Create a C program to calculate the area of a triangle given its three sides. The
program should use Heron's formula:
9. Write a program to print the multiplication table of the number entered by the user.
The table should get displayed in the following form.
Assignment No – 5
Problem Write a program to accept a suitable input from the user and count blanks,
Statement: tabs and newlines.
Objective : By the end of this experiment, students will be able to:
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: In text processing, characters such as blanks (spaces), tabs, and newlines are
used for formatting. These characters are part of the control characters in
ASCII:
Strings:
Strings are used for storing text/characters.
For example,
"Hello World" is a string of characters.
Unlike many other programming languages, C does not have a String type
to easily create string variables. Instead, you must use the char type and
create an array of characters to make a string in C
Note that you have to use double quotes ("").
To output the string, you can use the printf() function together with
the format specifier %s to tell C that we are now working with strings:
Example:
printf("%s", greetings);
Access Strings:
Since strings are actually arrays in C, you can access a string by referring
to its index number inside square brackets [].
Example:
printf("%c", greetings[0]);
Modify Strings:
To change the value of a specific character in a string, refer to the index
number, and use single quotes.
Example:
You can also loop through the characters of a string, using a for loop.
Example:
You should also note that you can create a string with a set of characters.
Example:
5. C String Functions:
C also has many useful string functions, which can be used to perform
certain operations on strings.
To use them, you must include the <string.h> header file
#include <string.h>
String Length
For example, to get the length of a string, you can use the strlen() function.
Example:
char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
printf("%d", strlen(alphabet));
In the Strings chapter, we used sizeof to get the size of a string/array. Note
that sizeof and strlen behaves differently, as sizeof also includes the \0
character when counting
Example:
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function
Example:
// Print str1
printf("%s", str1);
Copy Strings
To copy the value of one string to another, you can use the strcpy()
function
char str1[20] = "Hello World!";
char str2[20];
// Print str2
printf("%s", str2);
Compare Strings
In C, the getchar() function is used to read characters one by one from the
standard input (keyboard). This function reads input until the end-of-file
(EOF) is reached, which allows processing of all characters entered by the
user. By counting each occurrence of blanks, tabs, and newlines, the
program can provide useful statistics about the input text.
Pseudo Code: START
END
Flowchart:
Initialize
Read
printf(“blank=%d,tab%d,newline%d”,blan
Conclusion
This experiment demonstrates how to use basic input functions in C to read
and process character data. It reinforces understanding of character control
structures like loops and conditional statements. By counting pecific types
of characters (blanks, tabs, and newlines), students gain insight into text
processing and control flow in programming.
Test Case:
Questions:
1. What is the purpose of the program that counts blanks, tabs, and newlines?
2. Explain the difference between a blank, a tab, and a newline character.
3. How does the getchar() function work, and why is it used in this program?
4. What is ASCII, and why is it important in programming?
5. How are characters represented in C using ASCII values?
6. What functions or operators in C can be used to work with ASCII values?
Assignment No – 6
Requirements:
OS : Linux
Processor: 32/64 bit
Theory Concepts:
The for loop in C is the most general looping construct. The loop header
contains three parts: an initialization, a continuation condition, and an
action.
//block of code
The initialization is executed once before the body of the loop is entered.
The loop continues to run as long as the continuation condition remains true.
After every execution of the loop, the action is executed. Output
○ Expression 1 is optional.
○ Expression 2 can have more than one condition. However, the loop
will iterate until the last condition becomes false. Other conditions will be
treated as statements.
○ Expression 2 is optional.
To make a for loop infinite, we need not give any expression in the syntax.
Instead of that, we need to provide two semicolons to validate the syntax
of the for loop. This will work as an infinite for loop.
The nested for loop means any type of loop which is defined inside the
'for' loop.
2.Pattern Characteristics:
The number of rows in the pattern is twice the size minus one (i.e., 2*size
- 1).
3.Program Logic:
For i from 1 to n:
End For
// Print stars
For k from 1 to i:
Print "*"
End For
Print newline
End For
End For
// Print stars
For k from 1 to i:
Print "*"
End For
Print newline
End For
End Function
Flowchart
Start
Take Input
Initialize i=1
Initialize i=n-1
Conclusion This program effectively provides an excellent way to practice and solidify
your understanding of fundamental programming concepts such as loops,
conditional statements, and output formatting.
Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 Numbers of rows=1 * * Pass
** **
* *
3 Numbers of rows=6 * * Pass
** **
*** ***
**** ****
***** *****
****** ******
***** *****
**** ****
*** ***
** **
* *
Questions:
*
* * *
* * * * *
* * * * * * *
5. Write a program to print “Hollow Diamond Star Pattern”.
*
* *
* *
* *
*
Assignment No –07
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: 1. Basic Concepts
Array
An array is defined as the collection of similar types of data items stored at
contiguous memory locations. Arrays are the derived data type in C
programming language which can store the primitive type of data such as
int, char, double, float, etc
Each element of an array is of the same data type and carries the same size,
i.e., int = 4 bytes.
Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size
of the data element.
● Declaration of C Array
We can declare an array in the c language in the following way.
1. data_type array_name[array_size];
Now, let us see the example to declare the array.
1. int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the
array_size.
● Initialization of C Array
The simplest way to initialize an array is by using the index of each
element. We can initialize each element of the array by using the index.
Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
nt marks[5]={20,30,40,50,60};
int marks[]={20,30,40,50,60};
Bounds Checking
In C there is no check to see if the subscript used for an array exceeds the
size of the array. Data entered with a subscript exceeding the array size
will simply be placed in memory outside the array; probably on top of
other data, or on the program itself. This will lead to unpredictable results,
main( ) {
int num[40], i ;
num[i] = i ; }
Thus, to see to it that we do not reach beyond the array size is entirely the
programmer’s botheration and not the compiler’s.
arr = {1, 2, 8, 3, 2, 2, 2, 5, 1}
arrayfr[length]
visited = -1
count = 1
IF arr[i] == arr[j]
Increment count
fr[j] = visited
END IF
END FOR
IF fr[i] != visited
fr[i] = count
END IF
END FOR
PRINT "---------------------"
PRINT "---------------------"
IF fr[i] != visited
END IF
END FOR
PRINT "---------------------"
END
Flowchart:
start
Initialize
variables:
ye
i freq[i] i++
i=0
ye ctr=1 j fr
i
ye
i++ ye
Print freq[i]
arr
i f Print ye
ye i++
ye Cnt+
Conclusion By understanding the principles behind this program, you can adapt the
approach for more complex data structures , maintaining its effectiveness
across various scenarios.
Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 Input array elements: The array is The array is Pass
empty. empty.
int arr[] = {};
Frequency of 3 = Frequency of 3
1 =1
Frequency of 5 = Frequency of 5
1 =1
Frequency of 8 = Frequency of 8
1 =1
3 Input array elements: You might get a You might get a Pass
int arr[9]={1, 2, 8, 3, 2, random value, the random value,
2, 2, 5, 1,10,11} program might the program
crash with a might crash
segmentation with a
fault, or it might segmentation
behave fault, or it might
unpredictably in behave
other ways. unpredictably in
other ways.
Questions:
1. Define Array
2. What is meant by Frequency of elements
3. What are some efficient algorithms to count element frequencies in a large dataset?
4. How can I modify the program to count the frequency of elements in a
multidimensional array?
5. How can I implement a program to find the most frequent element in an array?
6. How can I handle and count the frequency of elements in an array with duplicate
values?
7. what will be the output of following code
main( ) {
int num[ ] = { 24, 34, 12, 44, 56, 17 } ;
int i ;
for ( i = 0 ; i <= 5 ; i++ ) {
Assignment No – 08
Problem Write a program to find the smallest and largest elements in an array
using pointers and then swap these elements and display the resultant
Statement:
array.
Objective : The objective of the program is to use pointers to find and swap the smallest
and largest elements in an array. It demonstrates pointer arithmetic and
dereferencing to efficiently manipulate array elements. Finally, it verifies
the operation by displaying the modified array.
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts: ● C Pointers
Consider the following example to define a pointer which stores the address
of an integer.
1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address
of the variable n of type integer.
● Declaring a pointer
Pointer Example
As you can see in the above figure, pointer variable stores the address of
number variable, i.e., fff4. The value of number variable is 50. But the
address of pointer variable p is aaa3.
● Pointer to array
1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the
address of an integer array arr.
● Pointer to a function
1. void show (int);
2. void(*p)(int) = &display; // Pointer p is pointing to the address of a
function
● Pointer to structure
1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;
The address of operator '&' returns the address of a variable. But, we need
to use %u to display the address of a variable.
● NULL Pointer
A pointer that is not assigned any value but NULL is known as the NULL
pointer. If you don't have any address to be specified in the pointer at the
time of declaration, you can assign a NULL value. It will provide a better
approach.
int *p=NULL;
There are several things which must be taken into consideration while
reading the complex pointers in C. Lets see the precedence and associativity
of the operators which are used regarding pointers.
○ Data type: Data type is the type of the variable to which the pointer
is intended to point. It also includes the modifier like signed int, long, etc).
2. calloc()
3. realloc()
4. free()
● malloc() function in C
ptr=(cast-type*)malloc(byte-size)
● calloc() function in C
The calloc() function allocates multiple blocks of requested memory.It
initially initializes all bytes to zero.It returns NULL if memory is not
sufficient.
ptr=(cast-type*)calloc(number, byte-size)
● realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the
memory by realloc() function. In short, it changes the memory size.
ptr=realloc(ptr, new-size)
● free() function in C
free(ptr)
END IF
END FOR
// Swap smallest and largest elements if they are different
IF smallest != largest THEN
temp = *smallest
*smallest = *largest
*largest = temp
END IF
// Display the resultant array
PRINT "Array after swapping smallest and largest elements:"
FOR i FROM 0 TO size - 1
PRINT array[i]
END FOR
End
Flowchart
Start
Initialize
Array
Traverse Array:
Compare each
element to ,
current smallest
Swap Smallest
and Largest, Display End
Conclusion This method leverages pointers for direct access and modification of array
elements, demonstrating a practical application of pointer arithmetic and
array manipulation techniques.
Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 Enter 2 integers: 2 ,5 , After interchange After interchange Pass
array elements array elements
are:5,2 are:5,2
Questions:
main( ) {
int *j ;
j = &i ;
#include<stdio.h>
void main () {
int **pp = p;
pp++;
*pp++;
++*pp;
++**pp;
#include<stdio.h>
void main () {
int a = 10;
int *p;
int **pp;
p = &a;
pp = &p;
printf("address of a: %x\n",p);
printf("address of p: %x\n",pp); /
printf("value stored at p: %d\n",*p);
printf("value stored at pp: %d\n",**pp); }
int main(){
int a=10,b=20,*p1=&a,*p2=&b;
*p1=*p1+*p2;
*p2=*p1-*p2;
*p1=*p1-*p2;
return 0;
2.Write a program in C to store n elements in an array and print the elements using a pointer.
3.Write a Program to Create a dynamic array of pointers, allocate memory for each pointer,
and initialize each pointer to point to an integer. Then, display the values.
4.Write a program in C to count the number of vowels and consonants in a string using a
pointer.
Assignment No – 09
2.Matrix Transposition:
3.Matrix Multiplication:
Pseudo Code:
● 1. Matrix Addition
function AddMatrices(Matrix1, Matrix2):
// Ensure both matrices have the same dimensions
If dimensions of Matrix1 != dimensions of Matrix2:
Raise error "Matrices must have the same dimensions for addition."
Initialize ResultMatrix with same dimensions as Matrix1
For each row index i from 0 to number of rows in Matrix1 - 1:
For each column index j from 0 to number of columns in Matrix1 - 1:
ResultMatrix[i][j] = Matrix1[i][j] + Matrix2[i][j]
Return ResultMatrix
2. Matrix Transposition
Function TransposeMatrix(Matrix):
// Get the dimensions of the original matrix
NumberOfRows = number of rows in Matrix
NumberOfColumns = number of columns in Matrix
Initialize TransposedMatrix with dimensions (NumberOfColumns,
NumberOfRows)
For each row index i from 0 to NumberOfRows - 1:
For each column index j from 0 to NumberOfColumns - 1:
TransposedMatrix[j][i] = Matrix[i][j]
Return TransposedMatrix
3. Matrix Multiplication
Flowchart
1. Flowchart for addition
start
Declare
A[r][c],B[r][c
], C[r][c]
Read
r,c,p A[]
i=0,j=0
C[i][j]=A[i][j]+
i j<
B[i][j]
Print c
i=i+1 j=j+1
start
Read m,n,p,q
False
If
Read Multiplicat
a[m,p],b[p,q] ion not
For
Declare
Read
matrix
initialise
Print
matrix i=i+1
Conclusion
Matrix addition allows for combining data from matrices of the same
dimensions, matrix transposition facilitates the rearrangement of data, and
matrix multiplication enables complex linear transformations and
computations.
Test Case:
Test Test case description Expected Output Actual Output Test
Case no Status1
1 Enter no of rows and Result of matrix Result of matrix Pass
column in matrix A: 1,1 Addition: 5 Addition: 5
Enter no of rows and Result of matrix Result of matrix
column in matrix B: 1,1 multiplication:6 multiplication:6
Enter elements of matrix Transpose of Transpose of
A: 2 Matrix A :2 Matrix A :2
Enter elements of matrix B: Transpose of Transpose of
3 Matrix B :3 Matrix B :3
18 18 18 27 6669
24 24 24 36 12 12 12 18
Transpose of 18 18 18 27
Matrix A 24 24 24 36
1234 Transpose of
1234 Matrix A
1234 1234
Transpose of 1234
Matrix B: 1234
222 Transpose of
222 Matrix B:
222 222
333 222
222
333
Questions:
1.What are the basic operations you need to implement for matrices?
2. What are the dimensional requirements for matrix addition and multiplication?
3.How do you handle matrices of different sizes in addition?
4.What is the transpose of a matrix?
5.How do you implement the transpose operation?
6.What are the rules for matrix multiplication?
7. What would be the output of the following programs:
main( )
{ int n[3][3] = { 2, 4, 3, 6, 8, 5, 3, 5, 1 } ;
printf ( "\n%d %d %d", *n, n[3][3], n[2][2] ) ; }
Assignment No – 10
Problem The instructor has a class of 20 students. Each student is identified by roll
no from 1 to 20. and name. The two test scores of each student are to be
Statement:
stored. The instructor would like to enter student roll no, name and test
score. Write a program to process this information, grade each student and
display the result in pleasing format.
Objective :
The objective of the program is to manage and process student information
by:
1. Collecting: Inputting each student's roll number, name, and test scores.
2.What is Structure
Structure in c is a user-defined data type that enables us to store the
collection of different data types. Each element of a structure is called a
member.The ,struct keyword is used to define the structure.
Syntax
structure in c.
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
1..p1->id
FUNCTION display_results(students)
PRINT header row: "Roll No | Name | Test 1 | Test 2 | Average | Grade"
PRINT separator line
FOR EACH student IN students
CALCULATE average_score = (score1 + score2) / 2
GET grade = calculate_grade(average_score)
PRINT student details: roll_no, name, score1, score2, average_score, grade
END FOR
END FUNCTION
// Main program flow
students = get_student_data()
display_results(students)
END
Flowchart
Declare
Pe Dis
Dis P Dis
Conclusion The program not only supports essential academic record-keeping and
grading functions but also exemplifies fundamental programming concepts
such as data structures, loops, conditionals, and formatted output. This
structured approach ensures that the program can be adapted to various
educational contexts or extended with additional features as needed.
Test Case:
Enter student name: Ian Enter Tes2 Average Score Tes2 Average Score Grade
test score 1: 100 Grade 0 0.00 no grade
Enter test score 2: 100 0 0.00 no 100 100.00 A
Enter roll number : 21 grade Invalid roll number. Please enter
Enter student name: Kyle 100 100.00 A a number between 1 and 20.
Enter test score 1: 75 Invalid roll number. Please ----------
Enter test score 2: 85 enter a number between 1
---------- and 20.
----------
Questions:
1. What inputs does the program require?
2. How many students should the program handle?
3. How is the average score calculated?
4. How does the program handle invalid roll numbers?
5. What happens if non-numeric input is provided for test scores?
6. How does the program perform with the maximum number of students?
2. Write a menu driven program that depicts the working of a library. The menu options
should be:
1. Add book information
2. Display book information
3. List all books of given author
4. List the title of specified book
5. List the count of books in the library
6. List the books in the order of accession number
7. Exit
3. A record contains the name of a cricketer, his age, number of test matches that he has
played and the average runs that he has scored in each test match. Create an array of structure
to hold records of 20 such cricketer and then write a program to read these records and
arrange them in ascending order by average runs
4. Create a structure to specify data on students given below: Roll number, Name,
Department, Course, Year of joining Assume that there are not more than 450 students in the
college.
(a) Write a function to print names of all students who joined in a particular year.
5. Create a structure to specify data of customers in a bank. The data to be stored is:
Account number, Name, Balance in account. Assume a maximum of 200 customers in the
bank. Write a function to print the Account number and name of each customer with balance
below Rs. 100.
Assignment No – 11
Problem Write a program in C to swap two numbers using a function. (use call by
Statement: value and call by reference)
Syntax:
return_type function_name(parameter_list) {
// function body
Components of a Function:
1. Return Type:
○ The return type specifies the data type of the value the function
returns.
○ Common return types are:
■ int: Returns an integer value.
■ float: Returns a floating-point value.
■ void: If no value is returned by the function.
2. Example: int, float, void
3. Function Name:
○ The function name is an identifier used to uniquely name a
function.
○ It follows the same naming rules as variables.
4. Example: add, multiply
5. Parameter List:
○ The parameter list (also called arguments) contains variables (with
their types) that are passed to the function.
○ These parameters act as inputs to the function.
○ If no parameters are required, the function uses void in the
parameter list.
6. Example: (int a, int b) or (void)
7. Function Body:
○ The function body contains the code to perform the desired task.
Call by Value and Call by Reference. These two approaches differ in how
data is passed to a function and how the function interacts with the data.
1. Call by Value:
In Call by Value, the actual value of the argument is passed to the function.
This means that a copy of the variable is made, and any changes made to
this copy inside the function do not affect the original variable in the calling
function. The function works with the copied value, leaving the original
variables unchanged.
● How it works:
○ A copy of the variable is created and passed to the function.
○ The function operates on this copy, without modifying the original
values.
○ Once the function ends, the original variables remain the same.
int temp;
}
● 2. Call by Reference:
● How it works:
○ A pointer to the memory location of the variable is passed to the
function.
○ The function operates on the original data stored at this memory
address.
○ Once the function ends, the changes made to the variables persist.
int temp;
Main Function:
INPUT num1, num2
END
Flowchart:
Start
Read a
Read b
temp=a
End a=b
b=temp
print a
print b
Return
Conclusion In this experiment, the differences between Call by Value and Call by
Reference were demonstrated. Using Call by Reference, the values of the
variables were successfully swapped in the calling function. This
experiment shows how functions and pointers are used to manipulate data
directly in C programming.
Test Case:
Questions:
1. What is the difference between call by value and call by reference?
2. What happens when you pass variables using call by value?
3. How does swapping work using call by reference?
4. Why is the temporary variable necessary in the swapping process?
8. Write a function to compute the distance between two points and use it to develop
another function that will compute the area of the triangle whose vertices are A(x1, y1), B(x2,
y2), and C(x3, y3). Use these functions to develop a function which returns a value 1 if the
point (x, y) lines inside the triangle ABC, otherwise a value 0.
9. Write a function to compute the greatest common divisor given by Euclid’s algorithm,
exemplified for J = 1980, K = 1617
Assignment No – 12
Requirements: OS : Linux
Processor: 32/64 bit
Theory Concepts:
Matrix Representation:
Syntax:
int matrix[i][j];
Matrix Input:
Functions in C:
The row and column sums are calculated using two separate functions.
For each row i, sum all elements in that row (matrix[i][j] where j
varies from 0 to n-1).
After computing the sums, display the sum of each row and column using
loops.
Flowchart:
Read
Allocate
Read
Initialise Initialise
Compute Compute
Conclusion
This lab exercise helps in understanding matrix operations in C. It provides
practical experience in working with two-dimensional arrays, handling user
input, and implementing functions to compute sums. The exercise
reinforces key concepts such as iteration and memory management.
Test Case:
Questions:
1. What is a matrix in the context of computer programming?
2. What are the dimensions of a matrix?
Assignment No – 13
Statement:
Objective :
The objective of the recursive factorial function is to provide a clear
example of recursion, compute factorials, and demonstrate how problems
can be divided into simpler sub problems.
Requirements:
OS : Linux
Processor: 32/64 bit
Theory Concepts:
1. Recursive Concept:
2. Factorial Definition:
n×(n−1)! If n>1
5.Code Example:
int factorial(int n)
{
return (n <= 1) ? 1 : n * factorial(n - 1);
}
Flowchart
Start
Read n
i=1,fact=1
i< Ye Print
=n fact
Stop
i=i+1 fact=fact*i
Test Case:
Test Test case description Expected Output Actual Output Test Status
Case no
1 Enter number n=0 1 1 Pass
2 Enter number n=5 120 120 Pass
Questions: