Uploaded by suriyaa R

Labmanual-CProgramming2023-workbook (1)

advertisement
KARPAGAM ACADEMY OF HIGHER EDUCATION
(Deemed to be University Established Under Section 3 Of UGC Act 1956)
Accredited with A+ Grade by NAAC in the Second cycle
Pollachi Main Road, Eachanari Post, Coimbatore – 641 021, INDIA
Faculty of Engineering
Department of Computer Science and Engineering
23BECC143 - PROGRAMMING IN C LABORATORY
NAME
: ……………………………………………..
REG. NUMBER
: ……………………………………………..
SEM / YEAR
: ……………………………………………..
KARPAGAM ACADEMY OF HIGHER EDUCATION
(Deemed to be University Established Under Section 3 Of UGC Act 1956)
Accredited with A+ Grade by NAAC in the Second cycle
Pollachi Main Road, Eachanari Post, Coimbatore – 641 021, INDIA
DEPARTMENT: COMPUTER SCIENCE AND ENGINEERING
This is to Certify that this Programming for Problem Solving lab work done by
Mr./Ms.
…………………………………………………………..
……………………………………………………………. during
for
the
course
B.E
…….. SEM / …………
Year of Academic year 2023 – 2024 is bonafide.
Staff in-charge
Head of the Department
REGISTER No.
The record is submitted for ……… Semester B. E. University Practical Examination conducted
on …………………………………………...
Internal Examiner
External Examiner
INDEX
S.
No
1
Date
Name of
Page
Experiment
No.
Develop a C Program to find the roots of
quadratic equation for non-zero coefficient using if-else ladder construct.
2
Develop Programs using simple control
statements such as if else, while, do while.
Example Extracting the digits of an integer,
reversing
digits,
finding sum of digits
3
Develop a C Program to implement a simple
calculator
to
perform
addition,
subtraction, multiplication and division
operations using switch construct. Display
appropriate messages for invalid operator and
divide by zero error.
4
5
Develop C Program to generate Fibonacci
sequence, calculation of factorials, printing
various patterns
and generate the Prime
numbers between the ranges m & n using for
loop.
Develop a C program to read n elements into
an integer array, Insert and Delete element
from the array. Print the input array and the
resultant array with suitable messages.
6
Develop a C program to read two matrices A
(m x n) and B (p x q) and compute the
product of the two matrices. Print both the
input matrices and resultant matrix with
suitable headings and output should be in
matrix format only. Program must check
the compatibility of orders of the matrices for
multiplication.
Report
appropriate
message in case of incompatibility.
7
Develop a C function Program to sort the given
names in Ascending Order.
8
9
Develop a C program to count the vowels &
consonants in a given string.
Develop a C Program to find the GCD of two
integers using Euclid’s algorithm
Total
Marks (20)
Staff
Sign
10
11
12
13
Develop a recursive C function to find the
factorial of a number, n! , defined by
fact(n)=1, if n=0. Otherwise fact(n)=n*fact(n1). Using this function, develop a C
program to compute the Binomial coefficient
nCr. Perform input validation as well.
Develop a C program to find the smallest and
largest elements in an array using
pointers and then swap these elements and
display the resultant array.
Develop a C program to find the sum of all the
elements of an integer array using
pointers.
Insert, update, delete and append telephone
details of an individual or a company into a
23BECC143 - C PROGRAMMING LABORATORY
COURSE OBJECTIVES:
The goal of this course is for the students is to
 Interpret problem solving using C.
 Apply the concept of arrays and strings.
 Identify the functions of C Language.
 Apply the concept of pointers .
 Develop C Programs using user defined function and file handling.
LABORATORY OUTCOMES:
 Apply problem solving techniques for a given problem
 Solve problems using arrays and strings.
 Build modular applications in C using functions.
 Categorize dynamic memory management operators with pointers.
 Examine sequential and random access file processing.
LIST OF EXPERIMENTS:
1. Develop a C Program to find the roots of quadratic equation for non-zero coefficient using if-else ladder construct.
2. Develop Programs using simple control statements such as if else, while, do while. Example
Extracting
the
digits
of
an
integer,
reversing
digits,
finding sum of digits
3. Develop a C Program to implement a simple calculator to perform addition,
subtraction, multiplication and division operations using switch construct. Display
appropriate messages for invalid operator and divide by zero error.
4. Develop
C
Program
to
generate
Fibonacci
sequence,
calculation
of
factorials, printing various patterns and generate the Prime numbers between the ranges m & n
using for loop.
5. Develop a C program to read n elements into an integer array, Insert and Delete element from the
array.
Print
the
input
array
and
the
resultant
array
with
suitable messages.
6. Develop a C program to read two matrices A (m x n) and B (p x q) and compute the
product of the two matrices. Print both the input matrices and resultant matrix with
suitable headings and output should be in matrix format only. Program must check
the compatibility of orders of the matrices for multiplication. Report appropriate
message in case of incompatibility.
7. Develop a C function Program to sort the given names in Ascending Order.
8. Develop a C program to count the vowels & consonants in a given string.
9. Develop a C Program to find the GCD of two integers using Euclid’s
algorithm.
5
10. Develop a recursive C function to find the factorial of a number, n! , defined by
fact(n)=1, if n=0. Otherwise fact(n)=n*fact(n-1). Using this function, develop a C
program to compute the Binomial coefficient nCr. Perform input validation as well.
11. Develop a C program to find the smallest and largest elements in an array using
pointers and then swap these elements and display the resultant array.
12. Develop a C program to find the sum of all the elements of an integer array using
pointers.
13. Insert, update, delete and append telephone details of an individual or a company into a
telephone directory using structures and pointers
6
INSTRUCTIONS TO THE STUDENTS
The following instructions must be followed by the students in their laboratory classes.
1) Students are expected to be punctual to the lab classes. If they are late, they will be
considered absent for that particular session.
2) Students should strictly maintain the dress code.
3) Students must bring their Workbook, record note (completed with previous experiment) to
every lab class without fail.
4) Students are advised to come with full preparation for their lab sessions by
Reading the detailed procedure of the exercise from the laboratory manual.
Completion of Workbook (i.e.) Aim, Procedure, Algorithm, Program should be written
and Flowchart should be drawn in the observation note before entering into the
laboratory.
5) Students must use pen for writing and pencil to draw Flowchart in Work book.
6) Students must get attestations immediately for their output/execution.
7) Students are advised to enter their results evaluated in the Work book on the same day of
that exercise.
8) Assessment marks for each exercise is based only on their performance in the laboratory.
9) Record note has to be completed then and there and get corrected when the students are
coming for the next lab class.
10) Students must strictly maintain silence during lab classes.
11) If any of the students is absent for the lab class for genuine reasons, he/she will be permitted
to do the exercise during the repetition class only.
12) If any student is found causing damage to the lab equipments, he/she shall replace the same
with a new.
7
LIST OF EXPERIMENTS
1
2
3
4
5
6
Develop a C Program to find the roots of quadratic equation for non-zero coefficient using if-else ladder construct.
Develop Programs using simple control statements such as if else, while, do while.
a) Extracting the digits of an integer
b) Reversing digits,
c) Finding sum of digits
Develop a C Program to implement a simple calculator to perform addition,
subtraction, multiplication and division operations using switch construct. Display
appropriate messages for invalid operator and divide by zero error.
Develop C Program
a) To generate Fibonacci sequence,
b) Calculation of factorials,
c) Printing various patterns
d) Generate the Prime numbers between the ranges m & n using for loop.
Develop a C program to read n elements into an integer array, Insert and Delete element from
the array. Print the input array and the resultant array with
suitable messages
Develop a C program to read two matrices A (m x n) and B (p x q) and compute the
product of the two matrices. Print both the input matrices and resultant matrix with
suitable headings and output should be in matrix format only. Program must check
the compatibility of orders of the matrices for multiplication. Report appropriate
message in case of incompatibility.
7
Develop a C function Program to sort the given names in Ascending Order.
8
Develop a C program to count the vowels & consonants in a given string.
11
Develop a C Program to find the GCD of two integers using Euclid’s
algorithm
Develop a recursive C function to find the factorial of a number, n! , defined by
fact(n)=1, if n=0. Otherwise fact(n)=n*fact(n-1). Using this function, develop a C
program to compute the Binomial coefficient nCr. Perform input validation as well.
Develop a C program to find the smallest and largest elements in an array using
pointers and then swap these elements and display the resultant array.
12
Develop a C program to find the sum of all the elements of an integer array using
pointers.
13
Insert, update, delete and append telephone details of an individual or a company into a
telephone directory using structures and pointers
9
10
8
PROBLEM SOLVING TECHNIQUES
The process of solving a real life problem to get a solution through computer
programming. There are three approaches for problem solving:
1. Algorithm
2. Flowchart
3. Pseudo Code
1. Algorithm
 The algorithm is a step-by-step procedure to be followed in solving a problem.
 It provides a scheme to solve a particular problem in finite number of
unambiguous steps. It helps in implementing the solution of a problem
using any of the programming languages.
 In order to qualify as an algorithm, a sequence of instructions must possess the
followingcharacteristics:
 Definiteness: Instructions must be precise and unambiguous i.e.
each and every instruction should be clear and should have only one
meaning.
 Finiteness: Not even a single instruction must be repeated infinitely. i.e., each
instruction should be performed in finite time.
 Termination: After the algorithm gets executed, the user should get the desired result
Key features of an algorithm:
Any algorithm has a finite number of steps and some steps may involve
decision making, repetition. Broadly speaking, an algorithm exhibits three key
features that can be given as:
 Sequence (straight line): Sequence means that each step of the algorithm is executed
in the specified order.
 Selection (branching): Decision statements are used when the outcome of the
process depends on some condition.
 Repetition(looping) : Repetition which involves executing one or more steps for a
number of times can be implemented using constructs like the while, do-while and for
loops. These loops executed one or more steps until some condition is true.
Example: Algorithm to compute the Area of Rectangle
This algorithm takes length and breadth, the sides of the rectangle as input and
computes the areaof rectangle using the formula area=length * breadth. Finally it
prints the area of rectangle.
Steps:
Step 1 [Initialize]Start
Step 2: [Input the sides of Rectangle]Read length,
breadth
Step 3: [Compute the area of rectangle]
Area=length*breadth
Step 4: [Display the Area] Print Area
Step 5: [Finished] Stop
9
2. Flowcharts
A flowchart is a graphical or symbolic representation of an algorithm. They are basically used
to design and develop complex programs to help the users to visualize the logic of the program
for better understanding of the program and find flaws and other features within it. Basically, a
flowchart depicts the “flow” of a program.
The following table shows the symbols used in flowchart along with its descriptions.
Symbol
Name
Description
Oval
Represents Start or Stop of the
process.
Rectangle
Represents the process steps defined
in algorithm
Parallelogram
Indicate the reading operation used for
input/output or data or information
from/to any device.
Diamond
Indicates the decisions (questions) and
consequently the branch points or the
paths to be followed based on the
result of the question
Arrows
Shows the flowchart direction and
connects the various flow chart
symbols
Shows the continuation from one point
in the process flow to another.
Small circle
Hexagon
Represents Looping structures
Predefined
Process
Indicates Subroutines
Advantages of Flowcharts:

A flowchart is a diagrammatic representation that illustrates the sequence of steps that
must be performed to solve a problem. They are usually drawn in the early stages of
formulating computer solutions to facilitate communication between programmers and
business people.
10

Flowcharts help programmers to understand the logic of complicated and lengthy
problems. They help to analyse the problem in a more effective manner.
 Flowchart can be used to debug programs that have error(s).
Limitations of using Flowcharts:



Drawing flowcharts is a laborious and a time consuming activity.
Flowchart of a complex program becomes, complex and clumsy. At times, a little bit of
alteration in the solution may require complete re-drawing of the flowchart.
There are no well-defined standards that limit the details that must be incorporated in a
flowchart.
Example of Flowchart to compute the Area of Rectangle
3. Pseudocode:
It is a form of structured English that describes algorithms. It facilitates the designers to focus on
the logic of the algorithm without getting bogged down by the details of language syntax.
Pseudocode is a compact and informal high-level description of an algorithm that uses the
structural conventions of a programming language.
It is meant for human reading rather than machine reading, so it omits the details that are not
essential for humans. Such details include keywords, variable declarations, system-specific code
and subroutines. There are no standards defined for writing a pseudocode because it is not an
executable program. Flowcharts can be considered as a graphical alternative to pseudocode, but
are more spacious on paper.
Example of Pseudocode to compute the area of Rectangle
Begin
Input length, breadth
Area=length*breadth
Print Area
End
11
C LANGUAGE
Introduction
C is a programming language developed at AT&T‟s BELL Laboratory of USA in 1972. Dennis
Ritchie designed it. Because of its reliability, C is very popular. C is highly portable & it is well
suited for structured programming. C program consists of collection of functions.
Hardware Requirement
Software Requirement
System with TurboC
: Desktop Computer / laptop computer
: Linux Operating System with GCC or Windows Operating
GCC
gcc is a Linux-based C compiler usually operated via the command line, released by the Free
Software Foundation. It often comes distributed with a linux installation, so if you are running
Unix or a Linux variant you likely have it on your system. You can invoke gcc on a source code
file simply by typing :gcc filename
The default executable output of gcc is "a.out", which can be run by typing “ ./a.out”
It is also possible to specify a name for the executable file at the command line by using the
syntax
-o outputfile , as shown in the following example :gcc filename -o outputfile
Again, you can run your program with "./outputfile". (The ./ is there to ensure you run the
program for the current working directory.)
Note: If you need to use functions from the math library (generally functions from math.h such
as sin or sqrt), then you need to explicitly ask it to link with that library with the -l flag and the
library 'm':
gcc filename -o outputfile –lm
GENERAL PROCEDURE
PROGRAMS:
1. Create
: Type the command, “cd Desktop” to open the desktop directory. Open
editor with filename by “gedit filename.c” and save it.
2. Compile
3. Execute
: gcc filename.c
gcc filename.c -lm (if <math.h> library file is used in the program)
: ./a.out
12
Or Use online compiler for program execution. Turbo C/C++
Open Turbo C/C++ from your Desktop or Programs menu. Select “File” from
Menu bar and select option “New” and Save C program with filename „.C‟
extension.
To do compiling – Select -> Compile from menu and click-> compile.
If the compilation is successful – you will see a “success” message. Else you will
see the number of errors.
To RUN the program – you may select ->Run from menu and click -> Run
Now you will see the output screen.
Or any IDE like code blocks, and Dev c++
Or any online compiler
13
PRELIMINARY EXERCISES:
1. Write a program to greet a person using printf().
AIM:
To write a C program to greet a person.
DESCRIPTION:
To display text on the screen, and there are two ways: puts() and printf().
puts()
Puts probably stands for puts string, where a string is a bit of text you put to the screen.
puts("Greetings, human!");
The text to display is enclosed in the function‟s parentheses. Furthermore, it‟s enclosed in double
quotes, which is how you create text inside the C language, and how the compiler tells the
difference between text and programming statements. Finally, the statement ends in a semicolon.
The puts() function works inside the main() function. It‟s run first, displaying the text Hello
World ! on the screen. Then the return(0); statement is run next, which quits the program and
returns control to the operating system.
printf()
Another C language function that displays text on the screen is printf() which is used more often.
While the puts() function merely displays text on the screen, the printf() function
displays formatted text. This gives you more control over the output.
Putting two printf() statements on separate lines will not display two different lines of text.
But the puts() function automatically appends a newline character at the end of any text it
displays; the printf() function does not. Instead, you must manually insert the newline character
(\n) into your text.
The printf() has the message to be displayed on the screen within double quotations “” and ended
with a semicolon ;
14
#include<stdio.h>
void main()
{
printf(“Hi”);
puts(“Welcome !”);
}
ALGORITHM:
Step 1 : Start
Step 2 : Display message using puts()
Step 3 : Display message using printf()
Step 4 : Stop
CODING:
void main()
{
puts(“Hi”);
printf(“Welcome”);
}
OUTPUT:
15
2. Write a program to add two numbers
AIM:
To write a c program to produce the addition of given two Numbers.
DESCRIPTION:
Add Two numbers using the formula sum = a+b
where a and b are input numbers
FLOWCHART:
ALGORITHM:
Step 1: Declare the necessary variables a, b and c as integer.
Step 2: Read the input of the integer a and b.
Step 3: Add a & b and store the result in sum.
Step 3: Display the value of sum
CODING:
#include<stdio.h>
void main()
16
{
int a,b,sum;
printf("Enter Number 1\n");
scanf("%d",&a);
printf("Enter Number 2\n");
scanf("%d",&b);
sum=a*b;
printf("\nThe Multiplication Result is %d\n",sum);
}
OUTPUT:
17
3.Write a program to find area of circle
AIM:
To write a C program to compute the Area of a Circle.
DESCRIPTION:
The Area of a circle are computed by the following formula,
The Area of a circle = πr2
where r = radius of the circle and value of π is 3.14
float datatype displays 6 digit precision after decimal point. E.g) 3.142857 for pi value.
FLOWCHART:
18
ALGORITHM:
Step 1: Start
Step 2: Declare and read the variable r, radius of the Circle.
Step 3: Calculate the area of the circle
Area =3.14*r*r
Step 4: Display the Area Step 5: Stop
CODING:
#include<stdio.h>
int main()
{
float r, Area;
printf(“Enter the radius of circle”);
scanf(“%f”,&r);
Area = 3.14*r*r;
printf(“The area of the circle is %f\n”,Area);
return 0;
}
OUTPUT:
19
4.Write a program to convert Fahrenheit value to centigrade
AIM:
Write a program to convert Fahrenheit value to centigrade
DESCRIPTION:
The centigrade value is computed by the following formula,
a = (f-32)*9/5
where f= Fahrenheit value and c =centigrade value
FLOWCHART:
ALGORITHM:
Step1: Start
Step2: Read the input of temperature in Fahrenheit is F
Step3 : C=(F-32)*5/9
Step4 : Print temperature in Celsius (say C)
Step5 : Stop
CODING:
#include<stdio.h>
int main()
{
float fahrenheit, celsius;
printf("Enter Temperature Value (in Fahrenheit): ");
scanf("%f", &fahrenheit);
celsius = (fahrenheit-32)*5/9;
printf("\nEquivalent Temperature (in Celsius)
= %0.2f", celsius);
20
return 0;
}
OUTPUT:
21
5.Write a program to find the square root of a number.
AIM:
Write a program to find the square root of a number.
DESCRIPTION:
sqrt() - The sqrt() function takes a single argument (in double ) and returns its square root (also in double ).
The sqrt() function is defined in math. h header file
FLOWCHART:
Start
Read the value
of n
Calculate SR=sqrt(n)
Print SR
End
ALGORITHM:
Step1: Start
Step2: Read the input num
Step3 : Sroot=sqrt(num)
Step4 : Print Sroot
Step5 : Stop
CODING:
#include<stdio.h>
#include<math.h>
int main()
{
22
int num;
double sroot;
printf("Enter a Number: ");
scanf("%d",&num);
sroot = sqrt(num);
printf("Square Root of %d is %f",num,sroot);
return 0;
}
OUTPUT:
23
6.Write a program calculate simple and compound interest
AIM:
Write a program calculate simple and compound interest
DESCRIPTION:
Simple Interest is calculated using formula SI= (P*N*R)/100)
Compound interest is calculated using formula I= P*((1+R/100) N -1)
FLOWCHART:
ALGORITHM:
Step 1: Start.
Step 2: Read Principal Amount, Rate and Time.
Step 3: Calculate Interest using formula SI= (P*N*R)/100)
Step 4: Calculate Compound interest =CI= P*((1+R/100)N -1)
Step 4: Print SI and CI
Step 5: Stop
CODING:
#include<stdio.h>
#include<math.h>
int main()
{
float p, n, r, si, ci;
printf("Enter principal amount (p): ");
24
scanf("%f", &p);
printf("Enter time in year (t): ");
scanf("%f", &n);
printf("Enter rate in percent (r): ");
scanf("%f", &r);
/* Calculating simple interest */
si = (p * n * r)/100.0;
/* Calculating compound interest */
ci = p * (pow(1+r/100, n) - 1);
printf("Simple Interest = %0.3f\n", si);
printf("Compound Interest = %0.3f", ci);
return(0);
}
OUTPUT:
25
7.Write a program that determines whether a given integer is odd or even
AIM:
Write a program that determines whether a given integer is odd or even
DESCRIPTION:
Mod operator % - The modulo operator, denoted by %, is an arithmetic operator. The modulo
division operator produces the remainder of an integer division. produces the remainder when x is
divided by y.
FLOWCHART:
ALGORITHM:
Step 1: Declare a variable to get a Number
Step 2: Read the input
Step 3: Get the remainder of given number using modulo operator
Step 4: If remainder is 0 prints “Even Number”, else print “Odd Number”
26
CODING:
#include <stdio.h>
int main()
{
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if(num % 2 == 0)
printf (“Even Number”);
else
printf("Odd Number”);
return 0;
}
OUTPUT:
27
8. Write a program to find the greater of three integers.
AIM:
To write a C program to find the greatest among three numbers using if..else statement.
DESCRIPTION:
if..else structure:
The if..else structure in C programming language is used to test set of conditions in sequence. An if
condition is tested only when all previous if conditions in if-else ladder is false.
If any of the conditional expression evaluates to true, then it will execute the corresponding
code block and exits whole if-else ladder.
Syntax:
if(condition_expression_One)
{
Statement 1;
}
else if (condition_expression_Two)
{
Statement 2;
}
else if (condition_expression_Three)
{
Statement 3;
}
else
{
Statement 4;
}
 First of all condition_expression_One is tested and if it is true then statement1 will be
executed and control comes out of whole if else ladder.
 If condition_expression_One is false, then only condition_expression_Two is tested. Control
will keep on flowing downward.
 If none of the conditional expression is true, the last else is the default block of code
whichwill gets executed if none of the conditional expression is true.
 If the Boolean expression evaluates to true, then the if block will be executed, otherwise,
the else block will be executed.
 C programming language assumes any non-zero and non-null values as true, and if it
is either zero or null, then it is assumed as false value.
28
Flowchart for the if-else
FLOWCHART:
ALGORITHM:
Step1: Start
Step2: Declare and read the variables a,b,c
Step3: if(a>b) and (a>c) go to step 4 otherwise go to step 5
Step4: Display a is greater. go to 8
Step5: if (b>c) go to step 6. otherwise step 7
Step 6: Display b is greater, go to 8
Step 7: Display c is greater
Step 8: Stop
29
CODING:
#include<stdio.h>
void main()
{
int a,b,c;
printf("enter the values of a,b and c");
scanf("%d%d%d",&a,&b,&c);
if(a>b && a>c)
printf("%d is greatest of %d %d %d", a,a,b,c);
else if(b>c)
printf("%d is greatest of %d %d %d",b,a,b,c);
else
printf("%d is greatest of %d %d %d",c,a,b,c);
}
OUTPUT:
30
9.Write a program to find whether the given year is leap year or Not? (Hint: not
every centurion year is a leap.
AIM:
To Write a a program to find whether the given year is leap year or Not? (Hint: not every
centurion year is a leap.
DESCRIPTION:
Finding a year is leap or not is a bit tricky. We generally assume that if a year number is evenly
divisible by 4 is leap year. But it is not the only case. A year is a leap year if −


It is evenly divisible by 100
o If it is divisible by 100, then it should also be divisible by 400
Except this, all other years evenly divisible by 4 are leap years.
FLOWCHART:
ALGORITHM:
Step 1:Take integer variable year
Step 2: Assign value to the variable
Step 3: Check if year is divisible by 4 but not 100, DISPLAY "leap year"
Step 4: Check if year is divisible by 400, DISPLAY "leap year"
Step 5: Otherwise, DISPLAY "not leap year"
31
CODING:
#include<stdio.h>
void main()
{
int yr;
printf("Enter the year you want to check.\n");
scanf("%d",&yr);
if((yr%400==0)||((yr%4==0)&&(yr%100!=0)))
{
printf("The given year is leap-year.");
}
else
{
printf("The given year is not leap-year.");
}
}
OUTPUT:
32
10. Armstrong number
AIM:
To write a C program to check if a given number is Armstrong number.
DESCRIPTION:
An Armstrong number is a number which is equal to the sum of digits raise to the power „total
number of digits in the number‟. Some Armstrong numbers are: 153, 370, 407, 1634, 8208, etc.
First we calculate the number of digits in our program and then compute the sum of individual
digits raise to the power „number of digits‟. If this sum equals the input number, then the number
is an Armstrong number otherwise not.
In case of an Armstrong number of 3 digits, the sum of cubes of each digits is equal to the
number itself. For example:
153 = 1*1*1 + 5*5*5 + 3*3*3 // 153 is an Armstrong number.
This program is implemented using while loop.
while loop:
Syntax:
while (testExpression)
{
// statements
}
where, testExpression checks the condition is true or false before each loop.
 The while loop evaluates the test expression.
 If the test expression is true (nonzero), statements inside the body of while loop are exectued.
The test expression is evaluated again. The process goes on until the test expression is false.
 When the test expression is false, the while loop is terminated.
33
FLOWCHART:
ALGORITHM:
Step 1: Start
Step 2: Declare and Read the variable, number
Step 3: Assign temp=number and sum = 0
Step 4: while(temp!=0) do
Step 4a: rem= temp %10; // separating the one‟s digit, rem
Step 4b: sum =sum+( rem * rem * rem); // adding cube of one‟s digit with sum
Step 4c: temp = temp /10; // removing the one‟s digit
Step 4d: goto Step 4
Step 5: Else, check the condition if(sum = number)
Step 6: If the condition is true Print “Armstrong34
Number”
Step 7: Else Print “Not Armstrong Number”
Step 8: Stop
CODING:
void main()
{
int number, temp, rem, sum=0;
printf("\nPROGRAM TO CHECK WHETHER A GIVEN NO. IS ARMSTRONG NO. OR
NOT\n");
printf("\nEnter a Three digit positive integer: ");
scanf("%d", &number);
temp=number;
while(temp!=0)
{
rem=temp%10;
sum=sum+(rem*rem*rem);
temp=temp/10;
}
if(sum==number)
printf("\n%d is an Armstrong number",number);
else
printf("\n%d is not an Armstrong number",number);
}
OUTPUT:
35
11. From a given paragraph, find the total number of words. using
built-in functions
AIM:
To write a C program to , find the total number of words using built-in functions
ALGORITHM:
Step 1: Start
Step 2: Read the text until an empty line
Step 3: Compare each character with tab char ‘\t\’ or space char ‘ ‘ or newline ‘\n’ to count no of
words
Step 4: Increment the count for number of words and print.
Step 6: Stop.
CODING:
int main(void)
{
char p[50];
int i,c=0;
printf("Enter line");
fgets(p,sizeof(p),stdin);
for(i=0; i<= strlen(p);i++)
if (p[i]==' '||p[i]=='\t' || p[i]=='\n')
{
c++;
}
printf("%d",c);
return 0;
}
OUTPUT:
36
12.From a given paragraph, capitalize the first letter of each sentence.
AIM:
To write C programs to capitalize the first word of each sentence.
ALGORITHM:
Step 1: Start
Step 2: Read the text until an empty line
Step 3: Compare each character with tab char ‘\t\’ or space char ‘ ‘ to count no of words
Step 4: if not convert t uppercase and display.
Step 6: Stop.
CODING:
#include <stdio.h>
#include<string.h>
#include <ctype.h> //this is isalpha's library
int main(void)
{
char v[50];
int i=0;
printf("Enter line ");
fgets(v,sizeof(v),stdin);
while(v[i]!='\0')
{
if (v[i]==' '||v[i]=='\t'||i==0)
{
if(i!=0)
{
i++;
printf(" ");
}
printf("%c",toupper(v[i]));
}
else
printf("%c",v[i]);
i++;
}
return 0;
}
OUTPUT:
37
LIST OF EXPERIMENTS:
Ex.No: 1
Date :
Roots of quadratic equation
AIM:
To Write a C Program to find the Roots of a Quadratic equation.
DESCRIPTION:
The standard form of a quadratic equation is:
ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0.
2
The term (b -4ac) is known as the discriminant of a quadratic equation. The discriminant tells the
nature of the roots.



If discriminant is greater than 0, the roots are real and different.
If discriminant is equal to 0, the roots are real and equal.
If discriminant is less than 0, the roots are complex and different.
The two roots of Quadratic equation are,
𝑥=
−𝑏 ± √𝑏2 − 4𝑎𝑐
2𝑎
Sample Input:
Input
Enter a,b,c values:
1
-5
6
Output
Real and different roots
Root1 = 3.000000
Root2 = 2.000000
Enter a,b,c values:
1
1
1
Complex and different roots
Enter a,b,c values:
1
-8
16
Real and equal roots
Root1 = -0.500000+0.866025i
Root2 = -0.500000-0.866025i
Root1 = Root2 = 4.000000
38
FLOWCHART:
39
ALGORITHM:
Step 1: Start
Step 2: Read a,b,c values
Step 3: Initialize d ← b*b-4*a*c
Step 4: if d==0 do
Step 4a: then print “roots are real and
equal”Step 4b: r1← -b/2*a, r2 ← r1
Step 5: else if d>0 do
Step 5a: then print “roots are real and distinct”
Step 5b: r1← (-b+sqrt(d))/2*a, r2← (-bsqrt(d))/2*a
Step 6: else if d<0 do
Step 6a: then print “roots are complex”
Step 6b: rp ← -b/2a,
imp←sqrt(d)/2*a
Step 6c: print r1 and r2.
Step 7: Stop
CODING:
#include <stdio.h>
#include <math.h>
int main()
{
float a, b, c, discriminant, root1, root2, real, imaginary;
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f",&a, &b, c);
discriminant = b*b-4*a*c;
if (discriminant > 0)
// condition for real and different roots
{
// sqrt() function returns square root
root1 = (-b+sqrt(discriminant))/(2*a);
root2 = (-b-sqrt(discriminant))/(2*a);
printf("root1 = %f \n root2 = %f",root1 , root2);
}
else if (discriminant == 0)
//condition for real and equal roots
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %f",
root1);
}
40
else // if roots are not real
{
real = -b/(2*a);
imaginary = sqrt(-discriminant)/(2*a);
printf("root1 = %f+%fi \n root2 = %f-%fi", real, imaginary, real, imaginary);
}
return 0;
}
OUTPUT:
VIVA QUESTIONS:
1.What is Fibonacci series?
2. What is syntax error?
3. What are the various types of conditional statements?
41
4. What is identifier ?
5. Mention the different types of operators used in C ?
RESULT:
42
Ex.No: 2
Date:
Develop Programs using simple control statements such as if else, while, do
while. Example Extracting the
digits of
an
integer, reversing
digits,finding sum of digits
AIM:
To write a C program to develop programs using simple control statements such as if
else, while, do while.
DESCRIPTION:
This program uses simple control statements such as if else, while, do while for Extracting
the
digits of
an
integer, reversing digits, finding sum of digits.
For:

If-else Statement
In some situations, you may have to execute statements based on true or false under certain conditions,
therefore; you use if-else statements. If the condition is true, then if block will be executed otherwise the
else block is executed.
Syntax of the if-else statement is as given below:
Flow Chart
 While Loop

A while loop is also known as an entry loop because in a while loop the condition is tested first then the
statements underbody of the while loop will be executed.
If the while loop condition is false for the first time itself then the statements under the while loop will
not be executed even once.
43
The syntax of the while loop is as given below:
Flow Chart:
 do-while Loop
The do-while is also known as an exit loop because in the do-while loop, the statements will be
executed first and then the condition is checked.
If the condition of the while loop is true then the body of the loop will be executed again and again
until the condition is false. Once the condition is false, the control will transfer outside the do-while
loop and execute statements followed soon after the do-while loop.
The syntax of the do-while loop is as given below:
Flow Chart
44
2.1 EXTRACTING THE DIGITS
OF
AN
INTEGER
AIM:
To extract digits of an given integer using while loop.
ALGORITHM:
Step 1: Input : An Integer n
Step 2: Read number n
Step 3: If number not equal to 0 Go to Step 4 , else Go to Step 8
digit = number % 10
number = number / 10
Step4: print digit
Step5: Repeat Step 3
Step6: Stop
CODING:
#include<stdio.h>
int main()
{
int number;
printf("Enter a number: ");
scanf("%d",&number);
while(number != 0){
int digit = number % 10;
number = number /10;
printf("%d ", digit);
}
return 0;
}
OUTPUT :
45
2.2 REVERSING DIGITS AND FINDING SUM OF DIGITS
AIM:
To Reverse digits and sum the digits of a given number using while loop.
ALGORITHM:
Step 1:Start
Step 2: Read number num
Step 3: Set sum=0 and rev=0
Step 4: Repeat step 5 to 8 while num
Step 5: Set d=num mod 10
Step 6: Set num=num/10
Step 7: Set sum=sum+d
Step 8: Set rev=rev*10+d
Step 9: Print sum
Step 10: Print rev
Step 11: Stop
CODING:
/* Program to reversing digits and finding sum of digits */
#include<stdio.h>
void main( )
{
int num,sum=0,rev=0,d;
printf("Enter the number: ");
scanf("%d",&num);
while(num){
d=num%10;
num=num/10;
sum=sum+d;
rev=rev*10+d;
46
}
printf("Sumof digits = %d",sum);
printf("\nReverse of the number = %d",rev);
}
OUTPUT:
VIVA QUESTIONS:
1. What are the loop control statements in C?
2. What are the sections present in loop?
3. What is infinite loop?
47
4. Differentiate Entry controlled and Exit Controlled Loop in C.
5. Which loop statement is executed at least once even loop test condition if false?
RESULT:
48
Ex.No: 3
Date :
Develop a C Program to implement a simple calculator to perform
addition, subtraction, multiplication and division operations using switch
construct. Display appropriate messages for invalid operator and divide by
zero error
AIM:
To write a C program to compute Arithmetic operations with Type conversion using
switchstatement.
(Consider the operators +,-,*, /, % and use Switch Statement)
DESCRIPTION:
This program uses Switch Statement for selection of operation to be performed
Type Conversion:
A type conversion is basically a conversion from one type of data to another. E.g) If you
want tostore a 'long' value into a simple integer then you can type cast 'long' to 'int'.
Switch:
A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
Syntax:
The syntax for a switch statement in C programming language is as follows:
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case
statements */default : /* Optional */
statement(s);
}
The following rules apply to a switch statement:


The expression used in a switch statement must have an integral or enumerated
type, or be of a class type in which the class has a single conversion function to an
integral or enumerated type.
You can have any number of case statements within a switch. Each case is followed
49





by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in
the switch, and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements following
that casewill execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control
jumps tothe next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of
control will fallthrough to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end
of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.
To take the two integer operands and one operator from user to perform the some arithmetic
operations by using the following operators like 1,2,3,4,5 for +,-,*, /, % respectively.
FLOWCHART:
50
ALGORITHM:
Step 1: Start
Step 2: Declare and read the values of a,b and operator
Step 3: if the operator is “1” then
result=a+b Go to
step 8
Step 4: Else if the operator is “2”
thenresult =a-b
Go to step 8
Step 5: Else if the operator is “3”
thenresult =a*b
Go to step 8
Step 6: Else if the operator is “4”
thenresult =a/b
Go to step 8
Step 7: Else if the operator is “5”
thenresult =a%b
Go to step 8
Step 8: write result
Step 9:End
CODING:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char operator;
int a,b, result ;
printf("\nMenu \n1.Addition \n2.Subtraction \n3.Multiplication \n4.Division \n5.Modulo(remainder after
division)\n");
printf("\nEnter your choice of operator.\n");
scanf("%c",&operator);
printf("\nEnter two numbers.\n");
scanf("%d%df",&a,&b);
switch(operator)
{
case '+'.result=a+b;
break;
case '-'.result=a-b;
break;
case '*'.result=a*b;
break;
51
case '/'.
if(b==0)
{printf("Divide by zero");
exit(0);
}
else
result=a/b;
break;
case '%'.result=a%b;
break;
default.
printf("\nInvalid!! Enter correct operator…\n");
break;
}
printf("\nResult=%d\n", result );
return 0;
}
OUTPUT.
52
VIVA QUESTIONS.
1. What is the difference between the = symbol and == symbol?
2: What is the modulus operator?
3: What is logical error?
4: What does the && operator do in a program code?
5: What are reserved words?
RESULT:
53
Ex.No. 4
Develop C Program to generate Fibonacci sequence, calculation of
factorials, printing various patterns and generate the Prime numbers
between the ranges m & n using for loop.
Date .
AIM.
To write a C program to Develop C Program to generate Fibonacci sequence,
calculation of factorials, printing various patterns and generate the Prime numbers between
the ranges m & n using for loop.
DESCRIPTION.
This program uses for loop to generate Fibonacci sequence, calculation of factorials,
printing various patterns and generate the Prime numbers between the ranges m & n
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop.
Syntax.
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
The example below will print the numbers 0 to 4.
Example
int i;
for (i = 0; i < 5; i++)
{
printf("%d\n", i);
}
4.1 GENERATING FIBONACCI
SEQUENCE
AIM:
To write C Program to generate Fibonacci Sequence.
54
DESCRIPTION:
Fibonacci sequence
Fibonacci series is defined as a sequence of numbers in which the first two numbers are 1 and
1, or 0 and 1, depending on the selected beginning point of the sequence, and each subsequent
number is the sum of the previous two. So, in this series, the nth term is the sum of (n1)th term and (n-2)th term. In this tutorial, we’re going to discuss a
simple algorithm and flowchart for Fibonacci series along with a brief introduction to
Fibonacci Series and some of its important properties.
Mathematically, the nth term of the Fibonacci series can be represented as:
tn = tn-1 + tn-2
The Fibonacci numbers upto certain term can be represented as: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
89, 144….. or 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144….
This the major property used in algorithm and flowchart for Fibonacci series. The series starts
with either 0 or 1 and the sum of every subsequent term is the sum of previous two terms as
follows:
First Term = 0
Second term = 1
Third Term = First + Second = 0+1 =1
Fourth term = Second + Third =1+1 = 2
Fifth Term = Third + Fourth = 2+1 = 3
Sixth Term= Fourth + Fifth = 3+2 = 5
Seventh Term = Fifth + Sixth = 3+5 = 8
Eighth Term = Sixth + Seventh = 5+8 = 13 … and so on.
ALGORITHM:
Step 1:Start
Step 2:Declare variables term1,term2,sum
Step 3:Initialize the variables, term1=0, term2=1, and sum =0
Step 4:Enter the number of terms of Fibonacci series to be printed
Step 5:Print First two terms of series
55
Step 6:Use loop for the following steps
sum=term1+term2
term1=term2
term2=sum
increase value of i each time by 1
print the value of sum
Step 7:End
FLOWCHART:
CODING:
#include <stdio.h>
int main()
{
int i, n, term1 = 0, term2 = 1;
56
int nextTerm = term1 + term2;
printf("Enter the number of terms you want: ");
scanf("%d", &n);
printf("Fibonacci Series: %d, %d, ", term1, term2);
for (i = 2; i < n; ++i)
{
printf("%d, ", nextTerm);
term1 = term2;
term2 = nextTerm;
nextTerm = term1 + term2;
}
return 0;
}
OUTPUT.
57
4.2 FACORIAL OF A GIVEN NUMBER
AIM:
To write C program to find factorial of a given number.
DESCRIPTION:
Factorial is an important concept in mathematics, and it is used in various fields, such as probability
theory, combinatorics, and calculus. In programming, it is often used to solve problems related to
permutations and combinations. to calculate the factorial of 8. We can write it as 8! and it can be
calculated as follows.
8! = 8 x 6 x 5 x 4 x 3 x 2 x 1
= 40320
Therefore, the factorial of 8 is 40320.
ALGORITHM :
Step 1: Start
Step 2. Read a number n
Step 3: Initialize variables.
i = 1, fact = 1
Step 4: if i <= n go to step 4 otherwise go to step 7
Step 5: Calculate
fact = fact * i
Step 6: Increment the i by 1 (i=i+1) and go to step 3
Step 7: Print fact
Step 8: Stop
}
CODING:
int main()
{
int num, fact = 1,i, result;
//user input
printf("Enter the number to find factorial. ");
scanf("%d", &num);
for (i = 1; i <= num; i++)
fact = fact * i;
//display
printf("Factorial of %d is. %d\n", num, fact);
return 0;
}
58
OUTPUT:
4.3 PRINTING VARIOUS PATTERNS
AIM.
To write C program to genetare patterns.
DESCRIPTION.
Printing patterns using C programs has always been an interesting problem domain. Different
patterns like star patterns, pyramid patterns, Floyd’s triangle, Pascal’s triangle, etc. in C
language. These problems generally require the knowledge of loops and if-else statements.
59
4.3 a) PROGRAMS TO PRINT PATTERNS IN C
AIM.
To write C program to genetare Right Half Pyramid patterns.
DESCRIPTION.
Right Half Pyramid Pattern in C
The right-half pyramid is nothing but a right-angle triangle whose hypotenuse is in the right
direction. We can print the right half pyramid pattern using numbers, alphabets, or any other
character like a star (*).
CODING.
// C program to print right half pyramid pattern of star
#include <stdio.h>
int main()
{
int rows;
printf("Enter the number of rows.");
scanf("%d",&rows);
// first loop for printing rows
for (int i = 0; i < rows; i++) {
// second loop for printing character in each rows
for (int j = 0; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}
OUTPUT.
60
4.3 b). LEFT HALF PYRAMID PATTERN IN C
AIM.
To write C program to genetare left Half Pyramid patterns.
DESCRIPTION.
The Left Half Pyramid looks like a right-angled triangle with its hypotenuse facing the left.
We can also print this pattern using a character, alphabets, or numbers.
Coding
// c program to print left half pyramid pattern of star
#include <stdio.h>
int main()
{
int rows ;
printf("Enter the number of rows.");
scanf("%d",&rows);
// first loop is for printing the rows
for (int i = 0; i < rows; i++) {
// loop for printing leading whitespaces
for (int j = 0; j < 2 * (rows - i) - 1; j++) {
printf(" ");
}
// loop for printing * character
for (int k = 0; k <= i; k++) {
printf("* ");
}
printf("\n");
}
return 0;
}
OUTPUT:
61
34.3.c) FULL PYRAMID PATTERN IN C
AIM.
To write C program to genetare full Half Pyramid patterns.
DESCRIPTION.
The Full Pyramid pattern looks similar to the Equilateral triangle. We can see this as the
combination of the Left Half and Right Half pyramids patterns. The following example
demonstrates how to print this pattern using alphabets, numbers, or a star (*).
CODING
// C program to print the full pyramid pattern of stars
#include<stdio.h>
int main()
{
int rows;
printf("Enter the number of rows.");
scanf("%d",&rows);
// first loop to print all rows
for (int i = 0; i < rows; i++) {
// inner loop 1 to print white spaces
for (int j = 0; j < 2 * (rows - i) - 1; j++) {
printf(" ");
}
// inner loop 2 to print star * character
for (int k = 0; k < 2 * i + 1; k++) {
printf("* ");
}
printf("\n");
}
return 0;
}
OUTPUT:
62
4.3.d) PRIME NUMBERS BETWEEN THE RANGES M & N:
AIM:
To write C program to genetare full Half Pyramid patterns prime numbers between the
ranges m & n
DESCRIPTION:
A prime number is a whole number greater than 1 whose only factors are 1 and itself. A
factor is a whole number that can be divided evenly into another number. The first few
prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.
ALGORITHM:
Step 1: Read n value.
Step 2: Initialize count = 0
Step 3: for i = 2 to n
a. for j = 1 to i
b. if i % j = 0
c. then increment count
d. if count is equal to 2
e. then print i value
Step 4: stop
FLOWCHART:
.
63
CODING:
#include<stdio.h>
void main()
{
int i, num, n, count;
printf("Enter the range from 1 to ");
scanf("%d", &n);
printf("The prime numbers in between the range 1 to %d are : ",n);
for(num = 1;num<=n;num++)
{
count = 0;
for(i=2;i<=num/2;i++)
{
if(num%i==0)
{
count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d ",num);
}
}
OUTPUT:
64
VIVA VOCE QUESTIONS.
1. What is scope of a variable? How are variables scoped in C?
2. How will you print “Hello World” without semicolon?
3. Can we compile a program without main() function?
4. How a negative integer is stored.
5. What is difference between including the header file with-in angular braces < > and
double quotes “ “
RESULT:
65
Ex.No: 5
Date :
Develop a C program to read n elements into an integer array, Insert and
Delete element from the array. Print the input array and the resultant
array with suitable messages.
AIM:
To write a c program to insert and delete element from the array.
DESCRIPTION:
Insert operation in an array at any position can be performed by shifting elements to the right,
which are on the right side of the required position
In the delete operation, the element to be deleted is searched using the linear search, and then the delete
operation is performed followed by shifting the elements.
66
ALGORITHM:
Step 1: Get the element value which needs to be inserted.
Step 2: Get the position value.
Step 3: Check whether the position value is valid or not.
Step 4: If it is valid,
Shift all the elements from the last index to position index by 1 position to the right.
insert the new element in arr[position]
Step 5: Otherwise,
Invalid Position
Step 6: Get the element value which needs to be deleted
Step 7: Find the given element in the given array and note the index.
Step 8: If the element found,
Shift all the elements from index + 1 by 1 position to the left.
Reduce the array size by 1.
Step 9: Otherwise, print "Element Not Found"
CODING:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a[100];
int element,i,loc,size,n=0,j=0;
printf("Enter the size of an array\n");
scanf("%d",&size);
printf("Enter %d array elements\n",size);
for(i=0;i<size;i++)
{
scanf("%d",&a[i]);
}
printf("List before Insertion: ");
for(i=0;i<size;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter an element to insert\n");
scanf("%d",&element);
printf("Enter a position to insert an element %d\n",element);
scanf("%d",&loc);
loc--;
for(i=size-1;i>=loc;i--)
{
a[i+1]=a[i];
}
a[loc]=element;
printf("\nList after Insertion: ");
67
for(i=0;i<size+1;i++)
{
printf("%d ",a[i]);
}
printf("\nEnter an element to delete\n");
scanf("%d",&n);
i=0;
for(i=0;i<size;i++)
{
if(a[i]==n)
{
for(j=i;j<(size-1);j++)
{
a[j]=a[j+1];
}
break;
}
}
printf("List after deletion\n");
for(i=0;i<(size+1);i++)
{
printf("%d ",a[i]);
}
return 0;
}
OUTPUT:
68
VIVA VOCE QUESTIONS:
1: What is the difference between the Equality operator (==) and the Assignment operator
(=)?
2: What is Multidimensional Arrays.
3: Can you declare an array without assigning the size of an array?
4: What is the difference between 'break' and 'continue' statements?
5: Can I use “int” data type to store the value 32768? Why?
RESULT:
69
Ex.No: 6
Date :
Develop a C program to read two matrices A (m x n) and B (p x q) and compute
the product of the two matrices. Print both the input matrices and resultant matrix
with suitable headings and output should be in matrix format only. Program must
check the compatibility of orders of the matrices for multiplication. Report
appropriate message in case of incompatibility.
AIM:
To write a c program to compute the product of the two matrices.
DESCRIPTION:
A matrix is a rectangular array of numbers or symbols which are generally arranged in rows and
columns.The order of the matrix is defined as the number of rows and columns.The entries are the
numbers in the matrix and each number is known as an element.The plural of matrix is matrices.The size
of a matrix is referred to as ‘n by m’ matrix and is written as m×n, where n is the number of rows and m
is the number of columns.For example, we have a 3×2 matrix, that’s because the number of rows here is
equal to 3 and the number of columns is equal to 2.
Matrix Multiplication Formula
Let’s take two matrices A and B of order 3×3 such that A = [aij] and B = [bij]. Then the multiplication of
A and B is obtained in the image such that,
ALGORITHM:
Step 1: Start the program
Step 2: Enter the number of rows and columns of matrix A
Step 3: Enter the number of rows and columns of matrix B
Step 4: Enter the values of the A and B matrices
Step 5: Display the entered values of A and B in matrix format
Step 6: Set a loop up to row
Step 7 Set a inner loop up to column
Step 81: Set another inner loop up to column
Step 9: Multiply the A and B matrix and store the element in the C matrix
Step 10: Display the resultant matrix.
Step 11: Stop
70
CODING:
/* MULTPLICATION OF TWO MATRIX*/
#include<stdio.h>
void main()
{
int a[15][15],b[15][15],c[15][15],i,j,k,r,s;
int m,n;
printf("\nEnter the Rows and Columns of A matrix...");
scanf("%d %d",&m,&n);
printf("\nEnter the Rows and Columns of B matrix...");
scanf("%d %d",&r,&s);
if(m!=r)
printf("\nMatrix multiplication cannot be performed");
else
{
printf("\nEnter the elements of A matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("\t%d",&a[i][j]);
}
printf("\nEnter the elements of B matrix");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("\t%d",&b[i][j]);
}
printf("\nThe elements of A matrix");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",a[i][j]);
}
printf("\n The elements of B matrix");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",b[i][j]);
}
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
{
c[i][j]=0;
71
for(k=0;k<m;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("The multiplication of two matrixes");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("\t%d",c[i][j]);
}
}
OUTPUT:
72
VIVA VOCE QUESTIONS:
1: What is || operator and how does it function in a program?
2: What are logical errors and how does it differ from syntax errors?
3: What is flow chart?
4: When is a “switch” statement preferable over an “if” statement?
5: What are run-time errors?
RESULT:
73
Ex.No: 7
Develop a C function Program to sort the given names in Ascending Order.
Date :
AIM:
To write a c program to sort the given names in Ascending Order.
DESCRIPTION:
Sorting names in an Alphabetical order there are multiple ways to sort the array, using normal sorting
algorithms like the bubble sort
Example:
Input : Array[] = {"Sourabh", "Anoop, "Harsh", "Alok", "Tanuj"}
Output: Array[] = {"Alok", "Anoop", "Harsh", "Sourabh", "Tanuj"}
ALGORITHM:
Step 1: Start the program.
Step 2: Read input n.
Step 3: Get the names using for loop.
Step 4: CALL FUNCTION SORT()
Initialize i to 0, j=i+1.
Compare the names by using strcmp function.
Print the names in alphabetical order.
Step 7: Stop the execution.
CODING:
#include<stdio.h>
#include<string.h>
/* Function prototype */
void sort(char a[50][50], int n);
void main()
{
char a[50][50];
int i, n;
printf("Enter number of names:\n");
scanf("%d", &n);
/* Reading array */
for(i=0;i< n;i++)
{
printf("a[%d]=",i);
74
scanf("%s", a[i]);
}
/* Function Call */
sort(a,n);
/* Displaying sorted array */
printf("Array in ascending order is:\n");
for(i=0;i< n;i++)
{
printf("%s\t", a[i]);
}
}
/* Function definition for asc_sort */
void sort(char a[50][50], int n)
{
int i, j;
char temp[50][50];
for(i=0;i< n-1;i++)
{
for(j=i+1;j< n;j++)
{
if(strcmp(a[i],a[j])>0)
{
strcpy(temp[i], a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],temp[i]);
}
}
}
}
OUTPUT:
75
VIVA VOCE QUESTIONS:
1: What is structure of C program?
2: What is a C token and types of C tokens?
3: Can a C keyword used as a variable name?
4: What does an expression contains?
5: What is equality operator?
RESULT:
76
Ex.No: 8
Develop a C program to count the vowels & consonants in a given string.
Date :
AIM:
To write a c program to count the vowels & consonants in a given string.
DESCRIPTION:
The characters a, e, i, o, u or A, E, I, O, U are known as vowels in the English alphabet. Any character
other than that is known as the consonant.
ALGORITHM:
Step 1: Read the string s
Step 2:CALLL FUNCTION STRINGCOUNT()
do{ Check if(s[i] is between a and z)
Check if(s[i] is a,e,i,o,u)
vowels =vowels+1
else
consonants =consonants+1 }
Step 3: Print vowels, consonants.
CODING:
* C Program to Count Vowels and Consonants in a String */
#include <string.h>
#include <stdio.h>
void stringcount(char *s)
{
int i,vowels=0,consonants=0;
for(i=0;s[i];i++)
{
if((s[i]>=65 && s[i]<=90)|| (s[i]>=97 && s[i]<=122))
{
if(s[i]=='a'|| s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O' ||s[i]=='U')
vowels++;
else
consonants++;
}
}
77
printf("vowels = %d\n",vowels);
printf("consonants = %d\n",consonants);
}
int main()
{
char s[1000];
printf("Enter the string: ");
fgets(s,100,stdin);
stringcount(s);
}
OUTPUT:
VIVA QUESTIONS:
1: What are 2D arrays?
2: Does compiler perform bound checking on an arrays?
78
3: How are array elements stored?
4: What type of arithmetic can be done on pointer?
5: How is individual element in an array can be accessed?
RESULT:
79
Ex.No: 9
Date :
Develop a C Program to find the GCD of two integers using Euclid’s
algorithm
AIM:
To write a c program to find GCD of given two Numbers using Euclid’s algorithm.
DESCRIPTION:
The GCD of two integers, X and Y, is the largest number that divides both X and Y without leaving a
remainder.
For example,
Euclid(30, 50) = 10
Euclid(2740, 1760) = 20
A simple way to find GCD is to factorize both numbers and multiply common prime factors.
Euclid’s algorithm (or Euclidean algorithm) is a method for efficiently finding the greatest common
divisor (GCD) of two numbers. Euclidean algorithm was formulated as follows: subtract the smaller
number from the larger one until one of the numbers is zero.
ALGORITHM:
Step 1: Input Two numbers x and y.
Step 2: a, b be the two numbers which will have greater and smaller number.
Step 3: Find a mod b = R
Step 4: Let a = b and b = R
Step 5: Repeat Steps 2 and 3 until a mod b is greater than 0
Step 6: GCD = b
Step 7: Finish
CODING:
#include <stdio.h>
int gcd(int x, int y)
{
int r = 0, a, b;
a = (x > y) ?x : y; // a is greater number
b = (x < y) ?x : y; // b is smaller number
80
r = b;
while (a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
int main()
{
printf("Enter the two numbers: ");
int x, y;
scanf("%d", &x);
scanf("%d", &y);
printf("The GCD of two numbers is: %d", gcd(x, y));
return 0;
}
OUTPUT:
VIVA VOCE QUESTIONS:
1. What are sections present in for loop?
2. What is the difference between normal variable and array variable?
81
3. Which are called built-in functions?
4. What is the use of break statements?
5. What is a goto statement?
RESULT:
82
Ex.No: 11
Date :
Develop a recursive C function to find the factorial of a number, n! , defined by
fact(n)=1, if n=0. Otherwise fact(n)=n*fact(n-1). Using this function, develop a C
program to compute the Binomial coefficient nCr. Perform input validation as
well.
AIM:
To write a c program to find GCD of given two Numbers using Euclid’s algorithm.
DESCRIPTION:
1) A binomial coefficients C(n, k) can be defined as the coefficient of X k in the expansion of
(1 + X)n.
2) A binomial coefficients C(n, k) also gives the number of ways, disregarding order, that k
objects can be chosen from among n objects; more formally, the number of k-element subsets (or kcombinations) of an n-element set.
this coefficient can be computed by the multiplicative formula
which using factorial notation can be compactly expressed as
ALGORITHM:
Step 1: Start
Step 2: Read n, r
Step 3: Invoke function factorial()and binomialCoeff()
Step 4: Print binomialCoeffi
Step 5: Stop
Function factorial (n)
if(n<=0)
return 1;
else
return n*factorial(n- 1);
end if
Function binomialCoeff(n,r)
return factorial(n) / ( factorial(r) * factorial(n-r) );
83
CODING:
#include <stdio.h>
float fact(int n);
void main() {
int n,r;
float result;
clrscr();
printf(“\nEnter the value of n and r (0<=r<=n) \n”);
scanf(“%d%d”,&n,&r);
if(n<0||r<0||n<r)
printf(“\nInvalid input\n”);
else
{
result=fact(n)/(fact(r)*fact(n-r));
printf(“\nC(%d,%d)=%.2f”,n,r,result);
}
getch();
}
/* function definition factorial recursively*/
float fact(int n)
{
if(n==0)
return(1);
else
return(n*fact(n-1));
}
OUTPUT:
84
VIVA VOCE QUESTIONS:
1. Can you convert a recursive functional program into a loop?
2. How dynamic programming is different from recursion and memoization?
3. Return the nth value of the Fibonacci sequence recursively
4. What is the difference between recursion and backtracking?
5. Is it possible to write a non-recursive form for every recursive function?
RESULT:
85
Ex.No: 11
Date :
Develop a C program to find the smallest and largest elements in an array
using pointers and then swap these elements and display the resultant array
AIM:
To write a C program to find the smallest and largest elements in an array using pointers and
then swap these elements and display the resultant array
DESCRIPTION:
we have a pointer ptr that points to the 0th element of the array. Similarly, we can also declare a
pointer that can point to whole array instead of only one element of the array. This pointer is
useful when talking about multidimensional arrays.
Syntax:
data_type (*var_name) [size_of_array];
Example:
int (*ptr)[10];
Here ptr is pointer that can point to an array of 10 integers. Since subscript have higher
precedence than indirection, it is necessary to enclose the indirection operator and pointer name
inside parentheses. Here the type of ptr is ‘pointer to an array of 10 integers’.
Note : The pointer that points to the 0th element of array and the pointer that points to the whole
array are totally different.
p: is pointer to 0th element of the array arr, while ptr is a pointer that points to the whole
array arr.
The base type of p is int while base type of ptr is ‘an array of 5 integers’.
We know that the pointer arithmetic is performed relative to the base size, so if we write ptr++,
then the pointer ptr will be shifted forward by 20 bytes.
The following figure shows the pointer p and ptr. Darker arrow denotes pointer to an array.
On dereferencing a pointer expression we get a value pointed to by that pointer expression.
Pointer to an array points to an array, so on dereferencing it, we should get the array, and the
name of array denotes the base address. So whenever a pointer to an array is dereferenced, we
get the base address of the array to which it points.
86
ALGORITHM:
Step 1: Input the array elements.
Step 2: Initialize small = large = arr[0]
Step 3: Repeat from i = 2 to n
Step 4: if(arr[i] > large)
Step 5: large = arr[i]
Step 6: if(arr[i] < small)
Step 7: small = arr[i]
Step : Print small and large.
CODING:
#include<stdio.h>
void minmax(int arr[], int len, int *min, int *max)
{
*min=*max=arr[0];
int i;
for(i=1;i<len;i++)
{
if(arr[i]>*max)
*max=arr[i];
if(arr[i]<*min)
*min=arr[i];
}
}
int main()
{
int a[20];
int min,max,n,i;
printf("Enter the number of elements:");
scanf("%d",&n);
printf("Enter elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
minmax(a,n,&min,&max);
printf("Minimum value in the array is:%d and maximum value is: %d", min,max);
return 0;
}
OUTPUT:
87
VIVA VOCE QUESTIONS:
1. What is a Null Pointer?
2. How can you combine the following two statements into one?
char *pointer;
pointer = (char*)malloc(100);
3. What is the size of a generic pointer?
4. What is a dangling pointer in C?
5. Explain the term double-pointer.
RESULT:
88
Ex.No: 12
Date :
Develop a C program to find the sum of all the elements of an integer
array using pointers.
AIM:
To write a C program to find the sum of all the elements of an integer array using
pointers.
DESCRIPTION:
Array of Pointers
It is collection of addresses (or) collection of pointers.
Declaration
Following is the declaration for array of pointers −
datatype *pointername [size];
For example,
int *p[5];
It represents an array of pointers that can hold five integer element addresses.
Initialization
‘&’ is used for initialization
For example,
int a[3] = {10,20,30};
int *p[3], i;
for (i=0; i<3; i++) (or) for (i=0; i<3,i++)
p[i] = &a[i];
p[i] = a+i;
Accessing
Indirection operator (*) is used for accessing.
For example,
for (i=0, i<3; i++)
printf ("%d", *p[i]);
89
ALGORITHM:
Step 1: Create a pointer variable, which points to an integer data:
Step 2: Take a number i.e size of array as input.
Step 3: Create a block of space fo size (size-ofarray*sizeof(int)) using malloc() assigning the starting address of this
whole space to the pointer variable.
Step 4: Iterate via for loop for reading array elements as input.
Step 5: Iterate again via for loop to access the address stored in pointer variable,
adding the iterator value to it, so as to access every element of array, and
calculating the overall sum.
CODING:
#include <stdio.h>
#include <malloc.h>
int main()
{
int i, n, sum = 0;
int *ptr;
printf("Enter size of array : ");
scanf("%d", &n);
ptr = (int *) malloc(n * sizeof(int));
printf("Enter elements in the List ");
for (i = 0; i < n; i++){
scanf("%d", array elements using ptr + i );
}
//calculate sum of elements
90
for (i = 0; i < n; i++)
{
sum = sum + *(ptr + i)
;
}
printf("Sum of all elements in an array is = %d", sum);
return 0;
}
OUTPUT:
VIVA VOCE QUESTIONS:
1.
What is a wild pointer?
2.
What does it mean when a pointer is used inside an if statement?
3.
What is Dereference or Indirection Operator ( * )?
91
4.
How do you dereference a pointer?
5.
How many pointers can point to the same address?
RESULT:
92
Ex.No: 13
Date :
Insert, update, delete and append telephone details of an individual or a
company into a telephone directory using structures and pointers
AIM:
To Write a C Program to Insert, update, delete and append telephone details of an individual or a
company into a telephone directory using structures and pointers
DESCRIPTION:
The data to be displayed may be very large, and only a limited amount of data can be displayed on
the console, and since the memory is volatile, it is impossible to recover the programmatically
generated data again and again. However, if we need to do so, we may store it onto the local file
system which is volatile and can be accessed every time. Here, comes the need of file handling in
C.
File handling in C enables us to create, update, read, and delete the files stored on the local file
system through our C program. The following operations can be performed on a file.
 Creation of the new file
 Opening an existing file
 Reading from the file
 Writing to the file
 Deleting the file
Functions for file handling
There are many functions in the C library to open, read, write, search and close the file. A list of file
functions are given below:
Function
Description
fopen()
opens new or existing file
fprintf()
write data into the file
fscanf()
reads data from the file
fputc()
writes a character into the file
fgetc()
reads a character from file
fclose()
closes the file
fseek()
sets the file pointer to given position
fputw()
writes an integer to file
fgetw()
reads an93integer from file
ftell()
returns current position
rewind()
sets the file pointer to the beginning of
the file
ALGORITHM:
Step1: Start the program
Step2: Store the telephone details into a file
Step3: Read the data & Display it
Step4: Enter the telephone number to be modified & the new number
Ste5: Use fseek() function to randomly access the record
Step6: Copy the contents from source file to destination file
Step7: Store the updated record into the new file
Step8: Stop the program
CODING:
#include "stdio.h"
#include "string.h"
#include<stdlib.h>
#include<fcntl.h>
struct dir
{
char name[20];
char number[10];
};
void insert(FILE *);
void update(FILE *);
void del(FILE *);
void display(FILE *);
void search(FILE *);
int record = 0;
int main(void) {
int choice = 0;
FILE *fp = fopen( "telephone.dat", "rb+" );
if (fp == NULL ) perror ("Error opening file");
while (choice != 6)
{
printf("\n1 insert\t 2 update\n");
94
printf("3 delete\t 4 display\n");
printf("5 search\t 6 Exit\n Enter choice:");
scanf("%d", &choice);
switch(choice)
{
case 1: insert(fp); break;
case 2: update(fp); break;
case 3: del(fp); break;
case 4: display(fp); break;
case 5: search(fp); break;
default: ;
}
}
fclose(fp);
return 0;
}
void insert(FILE *fp)
{
struct dir contact, blank;
fseek( fp, -sizeof(struct dir), SEEK_END );
fread(&blank, sizeof(struct dir), 1, fp);
printf("Enter individual/company name: ");
scanf("%s", contact.name);
printf("Enter telephone number: ");
scanf("%s", contact.number);
fwrite(&contact, sizeof(struct dir), 1, fp);
}
void update(FILE *fp)
{
char name[20], number[10];
int result;
struct dir contact, blank;
printf("Enter name:");
scanf("%s", name);
rewind(fp);
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(name, contact.name) == 0)
{
printf("Enter number:");
scanf("%s", number);
strcpy(contact.number, number);
fseek(fp, -sizeof(struct dir), SEEK_CUR);
fwrite(&contact, sizeof(struct dir), 1, fp);
printf("Updated successfully\n");
return;
95
}
}
printf("Record not found\n");
}
void del(FILE *fp)
{
char name[20], number[10];
int result, record=0;
struct dir contact, blank = {"", ""};
printf("Enter name:");
scanf("%s", name);
rewind(fp);
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(name, contact.name) == 0)
{
fseek(fp, record*sizeof(struct dir), SEEK_SET);
fwrite(&blank, sizeof(struct dir), 1, fp);
printf("%d Deleted successfully\n", record-1);
return;
}
record++;
}
printf("not found in %d records\n", record);
}
void display(FILE *fp)
{
struct dir contact;
int result;
rewind(fp);
printf("\n\n Telephone directory\n");
printf("%20s %10s\n", "Name", "Number");
printf("*******************************\n");
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strlen(contact.name) > 0)
printf("%20s %10s\n",contact.name, contact.number);
}
printf("*******************************\n");
}
void search(FILE *fp)
{
struct dir contact;
int result; char name[20];
rewind(fp);
96
printf("\nEnter name:");
scanf("%s", name);
while(!feof(fp))
{
result = fread(&contact, sizeof(struct dir), 1, fp);
if(result != 0 && strcmp(contact.name, name) == 0)
{
printf("\n%20s %10s\n",contact.name, contact.number);
return;
}
}
printf("Record not found\n");
}
OUTPUT:
97
VIVA QUESTIONS:
1.
What is the use of printf() and scanf() functions? Also explain format specifiers?
2.
What's the value of the expression 5["abxdef"]?
3.
What is a Preprocessor?
4.
What is the difference between global int and static int declaration?
5.
What is the difference between struct and union in C?
RESULT:
98
Download