Cse1008l Lab Manual
Cse1008l Lab Manual
Cse1008l Lab Manual
G D Goenka University
Gurgaon, Haryana
1|P a g e
The document is for internal circulation only.
All materials on these pages are copyrighted by the G D Goenka University. All rights reserved.
Reproduction, modification, retransmission, in any form or by any means, electronic, mechanical
or otherwise, for reasons other than personal use, is strictly prohibited without prior written
permission.
First Edition
September 2024
Published by:
SCHOOL OF ENGINEERING & SCIENCES
Department of Computer Science and Engineering
G D Goenka University
Gurgaon, Haryana
2|P a g e
PREFACE
The School of Engineering & Sciences (SoES), GDGU has prepared this laboratory
manual. It is designed as an instruction book for purposes listed in order of
importance as follows:
1. To provide techniques, procedures and precautions related to the
experiments.
2. To provide the laboratory safety and general rules and instructions.
3. To provide a general reference book that will give information which will
assist in the understanding of details about the laboratory and the experiment
to be performed.
The manual is prepared with the idea that the revisions must be made periodically
to have the available text that represents the experiments. It has been tried to
maintain the format with diagrams, tables and illustrations.
It is believed that the information in the manual will enhance the practical skills of
the students along with developing the base of the subject.
Any suggestions and comments for further improvement of this manual will be
gratefully acknowledged.
Authors
G D Goenka University, Gurgaon
3|P a g e
VISION AND MISSION
Vision
4|P a g e
General Rules and Instructions:
Instruction for Students
To complete all the experiments within time, to understand them completely and
effectively, each student must obey the following points:
Discipline is always given the highest precedence for maintaining the quality
standard of your lab. Any misconduct will be seriously dealt with and immediately
responded without prior notification.
To ensure a pleasant, productive and comfortable experience for all of our users,
you are directed to adhere to the following guidelines:
1. Students will not be allowed after ten minutes from the scheduled time.
2. Students will not leave the lab till the period is over.
5. Students should not attend a different lab group/section other than the one
assigned at the beginning of the session.
7. Please respect the sensitivities of your peers and refrain from viewing any
inappropriate content.
Please abide by the rules and make appropriate use of all facilities. Users found to
be damaging computer configurations, accessing content or systems illegally or
attempting to compromise security may be deprived of the facility or will be fined.
5|P a g e
Preparations and Performance
1. Students should come to the lab thoroughly prepared on the experiments
they are assigned to perform on that day.
2. Faculty may check their preparation and understanding of the
experiments. If not found satisfactory, students may be debarred from
doing the experiments.
3. Students should save the results (Screenshots) of their programs performed
during lab session.
4. Students must bring the lab manual on each practical class with
Algorithm, Flowchart, Program and Results (Screenshots) of the last
experiments performed complete in all respect.
5. Students without lab manual will not be allowed to do the experiments and
hence lose their attendance.
Lab Report
6|P a g e
Safety Measures
2. In the event of fire, please follow the directions from the Labs Staff.
7|P a g e
CSE1008L: PROGRAMMING AND PROBLEM-SOLVING USING C LAB
2024-25 /Batch
LIST OF EXPERIMENTS
8|P a g e
5 Identify and correct the semantic errors in a given program (example given below) to
make it compile and run correctly.
6 Write a C program that takes an integer as input from the user and prints whether the
number is positive, negative, or zero. Additionally, if the number is positive, check if
it’s even or odd and print that information as well.
7 Write a C program to implement a simple guessing game. The program should generate
a random number between 1 and 100 (inclusive) and prompt the user to guess the
number. After each guess, the program should provide feedback to the user, indicating
whether the guess is too high, too low, or correct. The user should continue guessing
until they correctly identify the random number. Additionally, limit the number of
guesses to 10, and if the user exceeds this limit without guessing the correct number,
display a message indicating that they have lost the game
11 Write a C program that defines macros for mathematical operations (e.g., addition,
subtraction, multiplication, division) and
uses them to perform calculations. The program should use macros to define the
operations and then demonstrate their usage in various mathematical expressions.
12 The Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones, usually starting with 0 and 1:
9|P a g e
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Write a C program to generate the first 20 terms of the Fibonacci sequence and print
them.
13 Write a C program that calculates the factorial of a given number using a separate function for
the factorial calculation. The program should prompt the user to enter a non-negative integer,
calculate its factorial using the factorial function, and then print the result.
15 Write a C program to calculate the average of a set of numbers. The program should prompt
the user to enter the number of elements in the set, then prompt the user to enter each element.
Finally, the program should calculate and print the average of the entered numbers using
separate functions for input, calculation, and output. Additionally, use an external variable to
keep track of the sum of the numbers.
16 Write a C program that defines a function to count the number of vowels in a string
using character pointers. The program
should prompt the user to input a string, call the function to count the vowels, and then
print the count
17 Write a C program that defines a function to swap the values of two integers using
pointers. The program should prompt
the user to input two integers, call the swap function to swap their values, and then
print the swapped values.
18 Write a C program that simulates a simple banking system. The program should
include the following functionalities:
a. Deposit: Allow the user to deposit a certain amount into their account.
b. Withdraw: Allow the user to withdraw a certain amount from their account.
c. Check balance: Display the current balance in the account.
Use static variables to keep track of the total balance across all transactions. Ensure that
the total balance is shared
among all instances of the banking system.
19 Write a C program that takes an array of integers as input, calculates the sum and
average of the elements using pointers, and then prints the sum and average.
20 Write a C program that takes two nxn matrix as input from the user, calculates the
product of the matrices and prints it.
21 Write a C program that simulates a simple text editor. The program should allow the
user to perform the following
operations on a text string:
a. Append: Append a string to the end of the current text.
b. Insert: Insert a string at a specific position in the current text.
c. Delete: Delete a substring from the current text.
d. Replace: Replace a substring in the current text with another string.
e. Print: Print the current text.
27 Write a C program that defines a union called Data to represent a data structure that can
store either an integer or a
floating-point number. Additionally, define a structure called BitField to represent a
data structure that stores a set of bit-
fields including a flag, an integer value, and a floating-point value. Then, the program
should create variables of type Data
and BitField, initialize them with some values, and print their contents.
28 Write a C program that defines a typedef for a structure called Point to represent a
point in 2D space. The structure should
have two members: x and y, representing the coordinates of the point. Then, the
program should create a variable of type
Point and initialize it with some values. Finally, it should print the coordinates of the
point.
11 | P a g e
Experimental Setup Details
Hardware Requirements:
Operating system: Windows 10 (64 bit) or higher
Processor: A Core i5 (3.10 GHz) or higher processor
RAM: 8 GB of RAM
Storage: 32 GB of available storage space
Monitor resolution: 1366 x 768
12 | P a g e
Experiment 1:
Title Conversion of numbers from decimal to binary or hexadecimal number systems and vice versa.
(a)To familiarize the students about number systems
(b) To represent numbers in various numeration systems
Objectives
(c) To convert a numeral from one base to another base
Theory A number system is defined as a system of writing for expressing numbers. It is the
mathematical notation for representing numbers of a given set by using digits in a consistent
manner. It provides a unique representation of every number and represents the arithmetic and
algebraic structure of the figures. It also allows us to operate arithmetic operations like addition,
subtraction, and division.
There are various types of the number system in mathematics. The four most common number
system types are:
System Base Symbols
Decimal 10 0, 1, … 9
Binary 2 0, 1
Octal 8 0, 1, … 7
Hexa-decimal 16 0, 1, … 9,
A, B, … F
Practice Questions
1. What is the decimal equivalent of the number 3A16?
2. What is the 8 bit unsigned binary result of 5610 − 3110
3. What is the result of adding 710 and −410 using 8 bit signed binary notation?
4. Which of the following 4 bit Excess 3 numbers is equivalent to 510?
5. Consider the equation (123)5 = (x8)y with x and y as unknown. The number of possible
solutions is _____ .
6. The range of integers that can be represented by an n bit 2's complement number system
is:
7. Convert binary 111111110010 to hexadecimal.
8. The representation of octal number (532.2)8 in decimal is ________
9. The decimal equivalent of the octal number (645)8 is ______
10. The quantity of double word is ________
11. Octal to binary conversion: (24)8 =?
12. Convert binary to octal: (110110001010)2 =?
13. The octal number (651.124)8 is equivalent to (______)10.
14. Convert the hexadecimal number (1E2)16 to decimal:
13 | P a g e
Experiment 2
To familiarize the students with flowcharts, pseudocode and algorithms.
Title
(a) Design a flowchart for a program that takes two numbers as input from the user and then
performs the following operations:
(i) Add the two numbers.
(ii) Subtract the second number from the first number.
(iii) Multiply the two numbers.
(iv) Divide the first number by the second number (ensure to handle division by zero).
The flowchart should include decision points to handle division by zero and should
clearly illustrate the flow of the program from input to output.
(b) Design a flowchart for a program that calculates the total cost of a customer shopping cart
items, including tax and any applicable discounts. The program should have the
following features:
(i)Prompt the user to input the prices and quantities of each item they wish to purchase.
Objectives
(ii) Calculate the subtotal by multiplying the price of each item by its quantity and summing
up all the totals.
(iii). Apply any applicable discounts based on the total purchase amount. For example, if the
total purchase amount is above a certain threshold, apply a percentage discount.
(iv)Calculate the tax on the subtotal based on a predetermined tax rate.
(v)Add the tax to the subtotal to obtain the total cost.
(vi)Display the subtotal, any discounts applied, the tax amount, and the final total cost to the
user.
You can break down the program into separate modules or functions, each responsible for a
specific calculation (e.g., subtotal calculation, discount calculation, tax calculation), and then
integrate them into the main program flowchart.
Theory INTRODUCTION
The flowchart is a mean of visually presenting the flow of data through an
information processing systems, the operations performed within system and the
sequence in which they are performed.
A flowchart is a pictorial representation of an algorithm in which the steps are
drawn, in the form of different shapes of boxes and the logical flow indicated by
inter connecting arrows.
Meaning of a Flowchart
A flowchart is a diagrammatic representation that illustrates the sequence of
operations to be performed to get the solution of a problem. Once the flowchart is
drawn, it becomes easy to write the program in any high level language. Hence, it is
14 | P a g e
correct to say that a flowchart is a must for the better documentation of a complex
program.
ADVANTAGES:
Reasons for using flowcharts as a problem-solving tool are:
➢ Makes logic clear
➢ Communication: flowcharts are a good way of communicating the logic
of a system to all concerned.
➢ Using in coding, flowcharts act as a guide during the system’s analysis
and program development phase.
15 | P a g e
Experiment 3
Title To familiarize the students with different operators in C and how to use them to solve expressions.
Objectives (a)Identify and correct the syntactical errors in a given program (example given below) to make it
compile and run correctly.
(b) Identify and correct the semantic errors in a given program (example given below) to make
it compile and run correctly.
16 | P a g e
Theory An operator is a symbol that operates on a value or a variable. For example: + is an operator to
perform addition.
C has a wide range of operators to perform various operations.
C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction,
multiplication, division etc on numerical values (constants and variables).
Operator Meaning of Operator
+ Addition or unary plus
- subtraction or unary minus
* Multiplication
/ Division
% remainder after division (modulo division)
17 | P a g e
&& Logical AND. True only if all operands are true If c = 5 and d = 2 then, expression
((c==5) && (d>5)) equals to 0.
|| Logical OR. True only if either one operand is true If c = 5 and d = 2 then, expression
((c==5) || (d>5)) equals to 1.
! Logical NOT. True only if the operand is 0 If c = 5 then, expression! (c==5) equals to 0.
18 | P a g e
Experiment 4
To familiarize the students with if-else loop.
Title
(a) Write a C program that takes an integer as input from the user and prints whether the
number is positive, negative, or zero. Additionally, if the number is positive, check if it’s
even or odd and print that information as well.
(b) Write a C program to implement a simple guessing game. The program should generate
a random number between 1 and 100 (inclusive) and prompt the user to guess the number.
After each guess, the program should provide feedback to the user, indicating whether the
guess is too high, too low, or correct. The user should continue guessing until they
correctly identify the random number. Additionally, limit the number of guesses to 10,
and if the user exceeds this limit without guessing the correct number, display a message
indicating that they have lost the game
(c) Write a C program that calculates the value of a mathematical expression involving
trigonometric functions and logarithms. The program should prompt the user to input the
values of variables and evaluate the expression. Ensure to handle error cases such as
Objective division by zero or undefined values.Sample mathematical expression to evaluate:
sin(x)+cos(y)/log(z)
(d) Write a C program that calculates the factorial of a non-negative integer using recursion.
The factorial of a non-negative integer n, denoted as n!, is the product of all positive
integers less than or equal to n. The factorial of n is defined as:
n! = n*(n-1)*(n-2)*..*3*2*1
( e ) Write a C program that defines macros for mathematical operations (e.g.,
addition, subtraction, multiplication, division) and
uses them to perform calculations. The program should use macros to define the operations and
then demonstrate their usage in various mathematical expressions.
19 | P a g e
Theory
We have a number of situations where we may have to change the order of execution of
statements based on certain conditions or repeat a group of statements until certain specified
conditions are met. This involves a kind of decision making to see whether a particular condition
has occurred or not and then direct the computer to execute certain statements accordingly.
C language possesses such decision-making capabilities and supports the following statements
known as control or decision-making statements.
1. if statement
2. switch statement
3. conditional operator statement
4. goto statement
Decision making with ‘if’ statement
The if statement is a powerful decision-making statement and is used to control the flow of
execution of statements. It is basically a two-way decision statement and is used in conjunction
with an expression. It takes the following form:
𝑖𝑓(𝑡𝑒𝑠𝑡 𝑒𝑥𝑝𝑟𝑒𝑠𝑠𝑖𝑜𝑛)
It allows the computer to evaluate the expression first and then depending on whether the value
of expression (or condition) is true (1) or false (0), it transfers the control to a particular
statement. This point of program has two paths to follow, one for the true condition and the other
for the false condition.
Entry
test
expression? False
True
Two-way Branching
20 | P a g e
2. if(age is more than 60) person retires
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
1. Simple if statement
2. if…else statement
3. Nested if…else statement
4. else if ladder
Simple ‘if’ statement
The general form of a ‘simple if’ statement is
‘statement_block’ may be a single statement or a group of statements. If the test expression is
true the ‘statement_block’ will be executed, otherwise the ‘statement_block’ will be skipped and
the execution will jump to ‘statement_x’.
Flowchart for Simple If
PROGRAM (a)
: #include <stdio.h>
int main() {
int number;
return 0;
}
OUTPUT :
Enter an integer: 6
The number is positive.
The number is even.
PROGRAM (b):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int randomNumber, userGuess;
int attempts = 0;
const int maxAttempts = 10;
// Game loop
while (attempts < maxAttempts) {
printf("Enter your guess: ");
scanf("%d", &userGuess);
attempts++;
if (attempts == maxAttempts) {
printf("Sorry! You've used all your attempts. The correct number was: %d\n",
randomNumber);
}
return 0;
}
OUTPUT :
PROGRAM C:
#include <stdio.h>
#include <math.h>
int main() {
double x, y, z;
double result;
Program (d)
#include <stdio.h>
int main() {
int num;
OUTPUT :
Program (e)
#include <stdio.h>
int main() {
// Declare variables
double num1, num2;
return 0;
}
OUTPUT :
Enter two numbers: 12.5 3.5
Results:
25 | P a g e
Addition: 12.50 + 3.50 = 16.00
Subtraction: 12.50 - 3.50 = 9.00
Multiplication: 12.50 * 3.50 = 43.75
Division: 12.50 / 3.50 = 3.57
26 | P a g e
Experiment 5
Title To familiarize the students with switch-case statements.
Objectives Write a C Program with an algorithm and flowchart to make a simple calculator performing +,-,/,*
using switch-case. The program takes two integer operands and one operator from the user,
performs the operation and then prints the result.
Theory The switch statement allows us to execute one code block among many alternatives.You can do
the same thing with the if...else..if ladder. However, the syntax of the switch statement is much
easier to read and write.
Syntax of switch...case
switch (expression)
case constant1:
// statements
break;
case constant2:
// statements
break;
default:
// default statements
The expression is evaluated once and compared with the values of each case label.
27 | P a g e
• If there is a match, the corresponding statements after the matching label are executed. For
example, if the value of the expression is equal to constant2, statements after case constant2: are
executed until break is encountered.
• If we do not use break, all statements after the matching label are executed.
1) The expression provided in the switch should result in a constant value otherwise it would
not be valid.
switch(1+2+23)
switch(1*2+3%4)
switch(a*b+c*d)
switch(a+b+c)
3) The default statement is optional. Even if the switch case statement do not have a default
statement, it would run without any problem.
4) The break statement is used inside the switch to terminate a statement sequence. When a
break statement is reached, the switch terminates, and the flow of control jumps to the next line
28 | P a g e
following the switch statement.
5) The break statement is optional. If omitted, execution will continue on into the next case.
The flow of control will fall through to subsequent cases until a break is reached.
6) Nesting of switch statements are allowed, which means you can have switch statements
inside another switch. However nested switch statements should be avoided as it makes program
more complex and less readable.
PROGRAM :
#include <stdio.h>
int main() {
char operator;
int result;
// User input
scanf("%d", &num1);
scanf("%d", &num2);
scanf(" %c", &operator); // Notice the space before %c to consume any leftover whitespace
29 | P a g e
// Perform the operation based on the operator
switch (operator) {
case '+':
break;
case '-':
break;
case '*':
break;
case '/':
if (num2 != 0) {
} else {
30 | P a g e
}
break;
default:
return 0;
}
OUTPUT:
4 + 6 = 10
31 | P a g e
Experiment 6
To familiarize the students with for loop
Title
Objectives (a) Write a C program to print the first 10 natural numbers (1 to 10) in reverse order, one
number per line.
(b) The Fibonacci sequence is a series of numbers where each number is the sum of the
two preceding ones, usually starting with 0 and 1:
Write a C program to generate the first 20 terms of the Fibonacci sequence and print them.
• Then, the test expression is evaluated. If the test expression is evaluated to false, the for
loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body of for loop
are executed, and the update expression is updated.
• This process goes on until the test expression is false. When the test expression is false, the
loop terminates.
PROGRAM A)
#include <stdio.h>
int main() {
// Loop from 10 to 1
printf("%d\n", i);
return 0;
32 | P a g e
}
OUTPUT :
10
PROGRAM (B)
#include <stdio.h>
int main() {
if (i == 0) {
} else if (i == 1) {
} else {
33 | P a g e
next = a + b; // Calculate the next term
return 0;
OUTPUT :
13
21
34
55
89
144
233
377
610
34 | P a g e
987
1597
2584
4181
35 | P a g e
Experiment 7:
To familiarize the students with functions in C
Title
Objectives (a) Write a C program that calculates the factorial of a given number using a separate function for the
factorial calculation. The program should prompt the user to enter a non-negative integer, calculate
its factorial using the factorial function, and then print the result.
(b) Write a C program to calculate the average of a set of numbers. The program should prompt the
user to enter the number of elements in the set, then prompt the user to enter each element. Finally,
the program should calculate and print the average of the entered numbers using separate functions
for input, calculation, and output. Additionally, use an external variable to keep track of the sum of
the numbers.
(c) Write a C program that defines a function to count the number of vowels in a string using character
pointers. The program should prompt the user to input a string, call the function to count the
vowels, and then print the count
(d) Write a C program that defines a function to swap the values of two integers using pointers. The
program should prompt the user to input two integers, call the swap function to swap their values,
and then print the swapped values.
36 | P a g e
Theory A function is a set of statements that take inputs, do some specific computation and produces
output. The idea is to put some commonly or repeatedly done task together and make a function so
that instead of writing the same code again and again for different inputs, we can call the function.
Why do we need functions?
Functions help us in reducing code redundancy. If functionality is performed at multiple places in
software, then rather than writing the same code, again and again, we create a function and call it
everywhere. This also helps in maintenance as we have to change at one place if we make future
changes to the functionality.
Functions make code modular. Consider a big file having many lines of codes. It becomes really
simple to read and use the code if the code is divided into functions. Functions provide
abstraction. For example, we can use library functions without worrying about their internal
working.
PROGRAM A)
#include <stdio.h>
// Function prototype
long long factorial(int n);
int main() {
int number;
return 0;
}
PROGRAM b)
#include <stdio.h>
// Function prototypes
void inputNumbers(int *numbers, int count);
float calculateAverage(int *numbers, int count);
void outputAverage(float average);
int main() {
int count;
return 0;
}
38 | P a g e
}
}
int main() {
char inputString[100]; // Array to store the input string
39 | P a g e
// Call the function to count vowels
int vowelCount = countVowels(inputString);
Program d)
#include <stdio.h>
int main() {
int num1, num2;
40 | P a g e
}
OUTPUT :
Enter two integers: 5 10
Before swapping:
num1: 5
num2: 10
After swapping:
num1: 10
num2: 5
41 | P a g e
Experiment 8
To familiarize the students with pointers in C
Title
Objectives (a) Write a C program that simulates a simple banking system. The program should include the
following functionalities:
a. Deposit: Allow the user to deposit a certain amount into their account.
b. Withdraw: Allow the user to withdraw a certain amount from their account.
c. Check balance: Display the current balance in the account.
Use static variables to keep track of the total balance across all transactions. Ensure that the total
balance is shared
among all instances of the banking system.
42 | P a g e
Theory
Pointers in C language is a variable that stores/points the address of another variable. A Pointer in
C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging
to any of the data type such as int, float, char, double, short etc.
Pointer Syntax : data_type *var_name; Example : int *p; char *p;
Where, * is used to denote that “p” is pointer variable and not a normal variable.
KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
• Normal variable stores the value whereas pointer variable stores the address of the
variable.
• * symbol is used to get the value of the variable that the pointer is pointing to.
• Two pointers can be subtracted to know how many elements are available between these
two pointers.
PROGRAM (a)
#include <stdio.h>
float amount;
scanf("%f", &amount);
if (amount > 0) {
*balance += amount;
} else {
43 | P a g e
printf("Invalid deposit amount!\n");
float amount;
scanf("%f", &amount);
*balance -= amount;
printf("Insufficient balance!\n");
} else {
int main() {
int choice;
do {
44 | P a g e
printf("\nSimple Banking System\n");
printf("1. Deposit\n");
printf("2. Withdraw\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
deposit(&totalBalance);
break;
case 2:
withdraw(&totalBalance);
break;
case 3:
checkBalance(totalBalance);
break;
case 4:
break;
default:
return 0;
45 | P a g e
}
OUTPUT :
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
46 | P a g e
Simple Banking System
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
1. Deposit
2. Withdraw
3. Check Balance
4. Exit
47 | P a g e
Experiment 9
To familiarize the students with arrays in C
Title
Objective 1.Write a C program that takes an array of integers as input, calculates the sum and average of the
elements using pointers, and then prints the sum and average.
2. Write a C program that takes two nxn matrix as input from the user, calculates the product of
the matrices and prints it.
48 | P a g e
Theory
An array in C or C++ is a collection of items stored at contiguous memory locations and elements
can be accessed randomly using indices of an array. They are used to store similar type of
elements as in the data type must be the same for all elements. They can be used to store
collection of primitive data types such as int, float, double, char, etc of any particular type. To add
to it, an array in C or C++ can store derived data types such as the structures, pointers etc. Given
below is the picturesque representation of an array.
PROGRAM 1:
#include <stdio.h>
// Function prototypes
void calculateSumAndAverage(int *arr, int size, int *sum, float *average);
int main() {
int n;
int sum = 0;
float average = 0.0;
49 | P a g e
printf("Average: %.2f\n", average);
return 0;
}
PROGRAM 2:
#include <stdio.h>
int main() {
int n;
int first[MAX_SIZE][MAX_SIZE], second[MAX_SIZE][MAX_SIZE],
result[MAX_SIZE][MAX_SIZE];
50 | P a g e
inputMatrix(first, n);
return 0;
}
// Matrix multiplication
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
51 | P a g e
}
52 | P a g e
Experiment 10
To familiarize the students with strings in C
Title
Objectives (a) Write a C program that simulates a simple text editor. The program should allow the user to
perform the following
operations on a text string:
a. Append: Append a string to the end of the current text.
b. Insert: Insert a string at a specific position in the current text.
c. Delete: Delete a substring from the current text.
d. Replace: Replace a substring in the current text with another string.
e. Print: Print the current text.
(b) Write a C program that implements a recursive function to generate all possible combinations
of a given set of characters.
The program should take a string of characters as input and print all possible combinations of
those characters.
For example, given the input string “ABC”, the program should generate the following
combinations:
a. ABC
b. ACB
c. BAC
d. BCA
e. CAB
f. CBA
53 | P a g e
Theory
Strings are defined as an array of characters. The difference between a character array and a string
is the string is terminated with a special character ‘\0’.
In the above syntax str_name is any name given to the string variable and size is used define the
length of the string, i.e the number of characters strings will store. there is an extra terminating
character which is the Null character (‘\0’) used to indicate termination of string which differs
strings from normal character arrays.
Initializing a String: A string can be initialized in different ways. We will explain this with the
help of an example. Below is an example to declare a string with name as str and initialize it with
“CProgramming”.
PROGRAM b)
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
54 | P a g e
// Prompt user for input
printf("Enter a string of characters: ");
scanf("%s", str);
55 | P a g e
Experiment 11
To familiarize the students with structures in C
Title
Objectives 1Write a C program that defines a structure called Student to store the details of a student
including name, roll number, and marks in three subjects (Physics, Chemistry, and Mathematics).
The program should prompt the user to input the details of three students, store them in an array of
Student structures, and then print the details of all students.
2. Write a C program that defines a structure called Book to store the details of books including
title, author, and price. The program should then create an array of Book structures to store the
details of three books. After storing the details, the program should print the details of all books.
3. Write a C program that defines a structure called Employee to store the details of an employee
including name, ID, and
salary. The program should then create a pointer to an Employee structure and allocate memory
for it dynamically using
malloc(). After allocating memory, prompt the user to input the details of an employee using the
pointer, and then print the
details of the employee.
4. Write a C program that simulates a simple online shopping system. The program should include
the following
functionalities:
a. Add item to cart: Allow the user to add items to their shopping cart.
b. Remove item from cart: Allow the user to remove items from their shopping cart.
c. View cart: Display the items currently in the user’s shopping cart.
Ensure that each user has their own shopping cart, and use local variables to represent the items in
the cart.
5. Write a C program that defines a union called Data to represent a data structure that can store
either an integer or a
floating-point number. Additionally, define a structure called BitField to represent a data structure
that stores a set of bit-
fields including a flag, an integer value, and a floating-point value. Then, the program should
create variables of type Data
and BitField, initialize them with some values, and print their contents.
6: Write a C program that defines a typedef for a structure called Point to represent a point in 2D
space. The structure should
have two members: x and y, representing the coordinates of the point. Then, the program should
create a variable of type
Point and initialize it with some values. Finally, it should print the coordinates of the point.
56 | P a g e
Theory Structure is another user defined data type available in C that allows to combine data items of
different kinds. To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member. The format of the struct statement is as
follows −
member definition;
member definition;
...
member definition;
} [one or more structure variables];
The structure tag is optional and each member definition is a normal variable definition, such as
int i; or float f; or any other valid variable definition. At the end of the structure's definition,
before the final semicolon, you can specify one or more structure variables but it is optional.
PROGRAM 1:
#include <stdio.h>
// Function prototypes
void inputStudentDetails(struct Student *student);
void printStudentDetails(struct Student student);
int main() {
struct Student students[3]; // Array to hold details of three students
57 | P a g e
}
return 0;
}
OUTPUT :
Enter details for student 1:
Name: Amit
Roll Number: 12345
Marks in Physics: 70
Marks in Chemistry: 60
Marks in Mathematics: 50
Enter details for student 2:
Name: Ankur
Roll Number: 56789
Marks in Physics: 50
Marks in Chemistry: 80
Marks in Mathematics: 70
Enter details for student 3:
Name: Aakash
58 | P a g e
Roll Number: 56473
Marks in Physics: 90
Marks in Chemistry: 48
Marks in Mathematics: 57
Details of students:
Name: Amit
Roll Number: 12345
Marks in Physics: 70.00
Marks in Chemistry: 60.00
Marks in Mathematics: 50.00
-------------------------------
Name: Ankur
Roll Number: 56789
Marks in Physics: 50.00
Marks in Chemistry: 80.00
Marks in Mathematics: 70.00
-------------------------------
Name: Aakash
Roll Number: 56473
Marks in Physics: 90.00
Marks in Chemistry: 48.00
Marks in Mathematics: 57.00
PROGRAM 2:
#include <stdio.h>
int main() {
// Create an array of Book structures
struct Book books[3];
59 | P a g e
books[i].title[strcspn(books[i].title, "\n")] = '\0'; // Remove newline character
printf("Author: ");
fgets(books[i].author, sizeof(books[i].author), stdin);
books[i].author[strcspn(books[i].author, "\n")] = '\0'; // Remove newline character
printf("Price: ");
scanf("%f", &books[i].price);
}
return 0;
}
Enter details for book 1:
Title: The Catcher in the Rye
Author: J.D. Salinger
Price: 10.99
Enter details for book 2:
Title: To Kill a Mockingbird
Author: Harper Lee
Price: 12.49
Enter details for book 3:
Title: 1984
Author: George Orwell
Price: 14.99
60 | P a g e
Title: 1984
Author: George Orwell
Price: 14.99
Program 3:
#include <stdio.h>
#include <stdlib.h>
int main() {
// Create a pointer to Employee
struct Employee *emp;
printf("Name: ");
getchar(); // Clear the newline character from previous input
fgets(emp->name, sizeof(emp->name), stdin);
emp->name[strcspn(emp->name, "\n")] = '\0'; // Remove newline character
printf("ID: ");
scanf("%d", &emp->id);
printf("Salary: ");
scanf("%f", &emp->salary);
61 | P a g e
// Free the allocated memory
free(emp);
return 0;
}
OUTPUT :
Enter employee details:
Name: John Doe
ID: 12345
Salary: 55000.50
Employee Details:
Name: John Doe
ID: 12345
Salary: 55000.50\
Program 4:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function prototypes
void addItem(struct Item cart[], int *count);
void removeItem(struct Item cart[], int *count);
void viewCart(struct Item cart[], int count);
int main() {
struct Item cart[MAX_ITEMS];
int itemCount = 0;
int choice;
do {
printf("\nOnline Shopping Cart System\n");
printf("1. Add item to cart\n");
printf("2. Remove item from cart\n");
printf("3. View cart\n");
62 | P a g e
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Clear newline from input buffer
switch (choice) {
case 1:
addItem(cart, &itemCount);
break;
case 2:
removeItem(cart, &itemCount);
break;
case 3:
viewCart(cart, itemCount);
break;
case 4:
printf("Exiting the program.\n");
break;
default:
printf("Invalid choice! Please try again.\n");
}
} while (choice != 4);
return 0;
}
63 | P a g e
printf("Enter the name of the item to remove: ");
char itemName[ITEM_NAME_LENGTH];
fgets(itemName, ITEM_NAME_LENGTH, stdin);
itemName[strcspn(itemName, "\n")] = '\0'; // Remove newline character
64 | P a g e
OUTPUT :
Online Shopping Cart System
1. Add item to cart
2. Remove item from cart
3. View cart
4. Exit
Enter your choice: 1
Enter the name of the item to add: Apple
Item added to cart.
65 | P a g e
Items in your cart:
1. Banana
int main() {
// Initialize a variable of type Data
union Data data;
data.intValue = 42; // Assign an integer value
printf("Union Data (intValue): %d\n", data.intValue);
66 | P a g e
printf("Flag: %u\n", bitField.flag);
printf("Integer Value: %u\n", bitField.intValue);
printf("Floating-Point Value (simplified): %u\n", bitField.floatValue);
return 0;
}
OUTPUT :
Union Data (intValue): 42
Union Data (floatValue): 3.14
Structure BitField:
Flag: 1
Integer Value: 5
Floating-Point Value (simplified): 1
PROGRAM 6:
#include <stdio.h>
int main() {
// Create a variable of type Point and initialize it
Point p1;
p1.x = 5.0f; // Assign value to x
p1.y = 10.0f; // Assign value to y
return 0;
}
OUTPUT :
Point coordinates:
X: 5.00
Y: 10.00
67 | P a g e