IP LAB MANUAL 2023
IP LAB MANUAL 2023
INTRODUCTION TO PROGRAMMING
(JNTUK)
(R23)
V S M COLLEGE OF ENGINEERING
RAMCHANDRAPURAM
1
INDEX
EXP NO. NAME OF THE EXPERIMENT PAGE NO.
1 i) Basic Linux environment and its editors like Vi, Vim &Emacs
etc. 4-8
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()
2 i) Sum and average of 3 numbers
ii) Conversion of Fahrenheit to Celsius and vice versa 9-12
iii) Simple interest calculation
3 i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae 13-17
iv) Distance travelled by an object
4 i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A 18-22
d. J= (i++) + (++i)
ii) Find the maximum of three numbers using conditional
operator
iii) Take marks of 5 subjects in integers, and find the total,
average in float
5 i) Write a C program to find the max and min of four numbers
using if-else.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation. 23-33
iv) Write a C program to simulate a calculator using switch case.
v) Write a C program to find the given year is a leap year or not.
6 i) Find the factorial of given number using any loop.
ii) Find the given number is a prime or not.
iii) Compute sine and cos series
iv) Checking a number palindrome
v) Construct a pyramid of numbers. 34-41
7 i) Find the min and max of a 1-D integer array.
ii) Perform linear search on1D array.
iii) The reverse of a 1D integer array 42-48
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array.
8 i) Addition of two matrices
ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions 49-57
v) Reverse a string using built-in and without built-in string
functions
9 i) Write a C program to find the sum of a 1D array using malloc()
2
ii) Write a C program to find the total, average of n students using
structures
iii) Enter n students data using calloc() and display failed students
list 58-65
iv) Read student name and marks from the command line and
display the student details along with the total.
3
UNIT I
WEEK 1
Objective: Getting familiar with the programming environment on the computer and
writingthe first program.
Suggested Experiments/Activities:
Tutorial 1: Problem-solving using Computers.
Lab1: Familiarization with programming environment
1. Basic Linux environment and its editors like Vi, Vim &Emacs etc.
2. Exposure to Turbo C, gcc
3. Writing simple programs using printf(), scanf()
i)Basic Linux environment and its editors like Vi, Vim &Emacs etc.
What is Linux?
Just like Windows, iOS, and Mac OS, Linux is an operating system. In fact, one of the
most popular platforms on the planet, Android, is powered by the Linux operating system. An
operating system is software that manages all of the hardware resources associated with your
desktop or laptop. To put it simply, the operating system manages the communication
between your software and your hardware. Without the operating system (OS), the software
wouldn’t function.
You can install Linux on as many computers as you like without paying any thing for
software or server licensing. Linux is also distributed under an open source license. Open
source follows these key tenets:
The freedom to run the program, for any purpose.
The freedom to study how the program works, and change it to make it do what you
wish.
Linux commands are used to perform a variety of tasks, including displaying information
about files and directories.
1. Is – Displays information about files in the current directory.
2. pwd – Displays the current working directory.
3. mkdir – Creates a directory.
4. cd – To navigate between different folders.
5. cd .. – To navigate back to the previous folders.
6. rmdir – Removes empty directories from the directory lists.
7. cp – Moves files from one directory to another.
8. mv – Rename and Replace the files
9. rm – Delete files
10. locate– Find a file in the database.
11. cat – Display file contents on terminal
12. clear – Clear terminal
4
Vi: The default editor that comes with the UNIX operating system is called vi (visual
editor). Using vi editor, we can edit an existing file or create a new file from scratch. we can
also use this editor to just read a text file. The advanced version of the vi editor is the
vimeditor.
Vim is an advanced and highly configurable text editor built to enable efficient text editing.
Vim text editor is developed by Bram Moolenaar. It supports most file types and vim editor
is also known as a programmer’s editor.It's based on shortcuts, called the Vim language,
which can make coding and writing faster and more efficient. With Vim, you can jump to
any specific text position and rapidly make precise edits.
EmacsEmacs originally was an acronym for Editor MACroS,is a text editor designed for
POSIX operating systems and available on Linux, BSD, macOS, Windows, and more. Users
love Emacs because it features efficient commands for common but complex actions and for
the plugins and configuration hacks that have developed around it for nearly 40 years.
EMAC is a national interstate mutual aid agreement that enables states to share resources
during times of disaster.
Example: ctrl-x ctrl-f : Find file or Open a file. This command prompts for a file name and
opens it in buffer for editing.
Turbo C
The Turbo C compiler is one of the most popular compilers used to convert a program
written in a high level language into machine code that can be executed by a computer.
Turbo C was an integrated development environment (IDE) for programming in the C
language. It was developed by Borland and first introduced in 1987. At the time, Turbo C
was known for its compact size, comprehensive manual, fast compile speed and low price.
Turbo C was a software development tool for writing programs in the C language. As an
IDE, it included a source code editor, a fast compiler, a linker and an offline help file for
reference.
Is Turbo C and C++ same?
C is structured programming language. Turbo C refers to a specific compiler made by
Borland that can be used for C programming. C++ is a superset of C, meaning everything
that you can do in C, you can do in C++.
How to Compile a Program in Turbo C?
Step 1: Open turbo C IDE(Integrated Development Environment), click on File, and then
click on New
Step 2: Write a program that we need to be executed.
Step 3: Click on Compile menu and then on Compile option, or press the keys and press
Alt + F9 to compile the code.
Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled
to generate the object code and then that object code is Run.
Step 5: Output is displayed in terminal window.
5
Compiling with Turbo C requires you to use terminal commands to enter your code into the
IDE environment. Once you are finished entering your code, you can then run it through the
compiler using specific compiler options depending on what type of output file you want to
generate. These options include creating an executable (.exe) file or creating static libraries
(.lib)
The Turbo C compiler is one of the most popular compilers used to convert a program
written in a high level language into machine code that can be executed by a computer. The
compiler is responsible for translating the source code, detecting any potential errors at
compile time which includes syntax errors, type mismatches and incorrect argument types,
and then it produces an object file with all of the compiled instructions ready to run on the
computer.
Run time errors are different from compile time errors as they only appear after running a
program. These occur when an action is performed on something unexpected due to user
input or other causes and can often be difficult to detect without proper debugging tools.
Error detection consists of inspecting data structures and variables in order to identify any
issues with their values or sizes that could result in an incorrect operation or cause a fault.
After an error is detected, corrective measures can be taken to fix it before any damage is
done. Error correction involves making changes in order to correct any logic flaws or data
inconsistency issues so that the system runs smoothly again.
What is GCC?
The GNU Compiler Collection, commonly known as GCC, is a set of compilers and
development tools available for Linux, Windows, various BSDs, and a wide assortment of
other operating systems. It includes support primarily for C and C++ and includes Objective-
C, Ada, Go, Fortran, and D. The Free Software Foundation (FSF) wrote GCC and released it
as completely free software.
GCC is a toolchain that compiles code, links it with any library dependencies, converts that
code to assembly, and then prepares executable files. It follows the standard UNIX design
philosophy of using simple tools that perform individual tasks well.
How to download GCC?
Nearly all Linux distributions either come pre-installed with GCC or have it in their primary
repositories, making it easy to install.
If you do not wish to set up an IDE and prefer the old-school way, then download
the C compiler which is called gcc from the GCC website
https://gcc.gnu.org/install/
Once you have downloaded and installed the gcc compiler, all you have to do is,
open any text editor, copy and paste the C program code for C Hello World
Program, and save it with the name the helloworld.c like any other file you save
with a name.
Now, Open the Command prompt or Terminal(if you use Ubuntu or Mac OS),
and go to the directory where you have saved the helloworld.c program file.
6
Type the command gcchello.c to compile the code. This will compile the code,
and if there are no errors then it will produce an output file with name
a.out(default name)
Now, to run the program, type in ./a.out and you will see Hello, World displayed
on your screen.
printf()
Algorithm:
1. Include the standard input-output library (stdio.h)
2. Define the main function, which is the entry point of the program
3. Use the printf function to print the "Hello, World!" message
4. Return 0 to indicate successful execution of the program
Pseudo Code
#include <stdio.h>
int main()
{
printf("Hello World");
return 0;
}
Output:
Hello World
Flowchart
7
scanf()
Algorithm:
1. Start
2. Declare variables a,b.
3. Prompt the user to enter the number using printf statement
4. Read and store the number in the number variable.
5. Repeat the steps 3,4 again.
6. Using printf statement Display the contants of a,b.
7. End.
Pseudo Code:
#include <stdio.h>
int main()
{
int a, b;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("A : %d \t B : %d" ,a , b);
return 0;
}
Output:
Enter first number : 5
Enter second number :6
A: 5 B: 6
FlowChart
8
WEEK 2
Objective: Getting familiar with how to formally describe a solution to a problem in a series
of finite steps both using textual notation and graphic notation.
Suggested Experiments /Activities:
Tutorial 2: Problem-solving using Algorithms and Flow charts.
Lab 1: Converting algorithms/flow charts into C Source code.Developing the
algorithms/flowcharts for the following sample programs:
1. Sum and average of 3 numbers
2. Conversion of Fahrenheit to Celsius and vice versa
3. Simple interest calculation
Algorithm
1. Start
2. Declare variables num1, num2, num3, sum, and average.
3. Prompt the user to input three numbers.
4. Read and store the three numbers in num1, num2, and num3.
5. Calculate the sum: sum = num1 + num2 + num3.
6. Calculate the average: average = sum / 3.0.
7. Display the sum and average.
8. End.
Pseudo code
#include <stdio.h>
int main()
{
float num1, num2, num3;
float sum, average;
printf("Enter three numbers: ");
scanf("%f%f%f", &num1, &num2, &num3);
sum = num1 + num2 + num3;
average = sum / 3.0;
printf("Sum: %f\n", sum);
printf("Average: %f\n", average);
return 0;
}
Output
9
Flowchart:
Algorithm:
1. Start
2. Declare variables Fahrenheit and Celsius.
3. Prompt the user to input the temperature in Fahrenheit.
4. Read and store the temperature in Fahrenheit.
5. Calculate the equivalent temperature in Celsius using the formula: celsius = (fahrenheit -
32) * 5/9.
6. Display the temperature in Celsius.
7. End.
Pseudo code
#include <stdio.h>
int main() {
double fahrenheit, celsius;
printf("Enter temperature in Fahrenheit: ");
scanf("%lf", &fahrenheit);
celsius = (fahrenheit - 32.0) * 5.0 / 9.0;
printf("Temperature in Celsius: %.2lf\n", celsius);
return 0;
}
10
Output
Flowchart
Algorithm:
1. Start
2. Declare variables principal, rate, time, and interest.
3. Prompt the user to enter the principal amount.
4. Read and store the principal amount in the principal variable.
5. Prompt the user to enter the annual interest rate (as a decimal).
6. Read and store the interest rate in the rate variable.
7. Prompt the user to enter the time period in years.
8. Read and store the time period in the time variable.
9. Calculate simple interest using the formula: interest = principal * rate * time.
10. Display the calculated simple interest.
11. End.
Pseudo code
#include <stdio.h>
11
int main() {
double principal, rate, time, interest;
printf("Enter principal amount: ");
scanf("%lf", &principal);
printf("Enter annual interest rate (as a decimal): ");
scanf("%lf", &rate);
printf("Enter time period (in years): ");
scanf("%lf", &time);
interest = principal * rate * time;
printf("Simple Interest: %.2lf\n", interest);
return 0;
}
Output:
Flowchart
12
WEEK 3
Objective: Learn how to define variables with the desired data-type, initialize them with
appropriate values and how arithmetic operators can be used with variables and constants.
Suggested Experiments/Activities:
Tutorial 3: Variable types and type conversions:
Lab 3: Simple computational problems using arithmetic expressions.
1. Finding the square root of a given number
2. Finding compound interest
3. Area of a triangle using heron’s formulae
4. Distance travelled by an object
Pseudo code
#include <stdio.h>
#include <math.h>
int main() {
double number, result;
printf("Enter a number: ");
scanf("%lf", &number);
result = sqrt(number);
printf("Square root: %.4lf\n", result);
return 0;
}
Output:
Flowchart
13
ii) Finding compound interest
Algorithm:
1. Start
2. Declare variables principal, rate, time, n, compoundInterest.
3. Prompt the user to enter the principal amount.
4. Read and store the principal amount in the principal variable.
5. Prompt the user to enter the annual interest rate (as a decimal).
6. Read and store the interest rate in the rate variable.
7. Prompt the user to enter the time period in years.
8. Read and store the time period in the time variable.
9. Prompt the user to enter the number of times interest is compounded per year (n).
10. Read and store the compounding frequency in the n variable.
11. Calculate the compound interest using the formula:compoundInterest = principal *
pow(1 + rate / n, n * time) - principal
12. Display the calculated compound interest.
13. End.
Pseudo code
#include <stdio.h>
#include <math.h>
int main() {
double principal, rate, time, n, ci;
printf("Enter principal amount: ");
scanf("%lf", &principal);
printf("Enter annual interest rate (as a decimal): ");
scanf("%lf", &rate);
printf("Enter time period (in years): ");
scanf("%lf", &time);
printf("Enter compounding frequency (n): ");
scanf("%lf", &n);
ci= principal * (pow(1 + rate / n, n * time) - 1);
printf("Compound Interest: %.2lf\n", ci);
return 0;
}
Output:
14
Flowchart
Algorithm:
1. Start
2. Declare variables side1, side2, side3, s, and area.
3. Prompt the user to enter the length of the first side of the triangle (side1).
4. Prompt the user to enter the length of the second side of the triangle (side2).
5. Prompt the user to enter the length of the third side of the triangle (side3).
6. Calculate the semi-perimeter s using the formula: s = (side1 + side2 + side3) / 2.
7. Calculate the area area using Heron's formula: area = sqrt(s * (s - side1) * (s - side2) * (s -
side3)).
8. Display the calculated area.
9. End.
Pseudo code
#include <stdio.h>
#include <math.h>
int main() {
double side1, side2, side3, s, area;
printf("Enter the length of the first side: ");
scanf("%lf", &side1);
printf("Enter the length of the second side: ");
scanf("%lf", &side2);
printf("Enter the length of the third side: ");
scanf("%lf", &side3);
s = (side1 + side2 + side3) / 2;
15
area = sqrt(s * (s - side1) * (s - side2) * (s - side3));
printf("Area of the triangle: %.2lf\n", area);
return 0;
}
Output:
Flowchart
Algorithm
1. Start
2. Declare variables:
a. initialVelocity (initial velocity of the object)
b. acceleration (acceleration of the object)
c. time (time taken)
d. distance (to store the result)
16
3. Prompt the user to enter initialVelocity, acceleration, and time.
4. Read initialVelocity, acceleration, and time from the user.
5. Calculate the distance using the formula:
Distance = initialVelocity * time + 0.5 * acceleration * time * time
Pseudo code:
#include <stdio.h>
int main() {
double initialVelocity, acceleration, time;
printf("Enter initial velocity (m/s): ");
scanf("%lf", &initialVelocity);
printf("Enter acceleration (m/s^2): ");
scanf("%lf", &acceleration);
printf("Enter time (s): ");
scanf("%lf", &time);
double distance = initialVelocity * time + 0.5 *acceleration * time * time;
printf("Distance traveled: %.2lf meters\n", distance);
return 0;
}
Output:
Flowchart :
17
WEEK 4
Objective: Explore the full scope of expressions, type-compatibility of variables & constants
and operators used in the expression and how operator precedence works.
Suggested Experiments/Activities:
Tutorial4: Operators and the precedence and as associativity:
Lab4: Simple computational problems using the operator’ precedence and associativity
i) Evaluate the following expressions.
a. A+B*C+(D*E) + F*G
b. A/B*C-B+A*D/3
c. A+++B---A
d. J= (i++) + (++i)
a. A+B*C+(D*E) + F*G
Algorithm
Step 1:Start
Step 2: READ a , b , c , d , e , f , g
Step 3: SET res := a + b * c + ( d * e ) + f * g
Step 4: PRINT res
Stop 5: Stop
PSEUDO CODE:
#include <stdio.h>
int main()
{
int a, b, c, d,e,f,g,res;
printf("Enter a,b,c,d,e,f,g values:");
scanf("%d %d %d%d%d %d%d ", &a, &b, &c, &d, &e, &f, &g);
res=a+b*c+(d*e)+f*g;
printf("result = %d", res);
return 0;
Output:
result = 69
b. A/B*C-B+A*D/3
Algorithm
Step 1:Start
Step 2: READ a , b , c , d
Step 3: SET res := a/b*c-b+a*d/3
Step 4: PRINT res
Stop 5: Stop
PSEUDO CODE:
#include <stdio.h>
18
int main()
{
int a, b, c, d ,res;
printf("Enter a,b,c,d values:");
scanf("%d %d %d%d ", &a, &b, &c, &d);
res= a/b*c-b+a*d/3;
printf("result = %d", res);
return 0;
Output:
c. A+++B---A
Algorithm
Step 1:Start
Step 2: READ a , b
Step 3: SET res := a+++b---a
Step 4: PRINT res
Stop 5: Stop
Pseudo Code:
#include <stdio.h>
int main()
{
int a, b ,res;
printf("Enter a, b values:");
scanf("%d %d ", &a, &b);
res= a+++b---a;
printf("result = %d", res);
return 0;
Output:
d. J= (i++) + (++i)
19
Algorithm
Step 1:Start
Step 4: PRINT j
Stop 5: Stop
Pseudo Code:
#include <stdio.h>
int main()
{
int i, j ,res;
printf("Enter i, j values:");
scanf("%d %d ", &i, &j);
j= (i++) + (++i);
return 0;
Output:
Algorithm :
Step 1:Start
Step 2: READ a , b , c
Step 3: SET max := ( a > b ) ? ( ( a > c ) ? a : c ) : ( ( b > c ) ? b : c )
Step 4: PRINT max
Stop 5: Stop
Pseudo Code:
#include <stdio.h>
int main()
{
int a, b, c, max;
printf("Enter Three Integers\n");
20
scanf("%d %d %d", &a, &b, &c);
max = (a > b)?((a > c)?a:c):((b > c)?b:c);
printf("Maximum Number is = %d\n", max);
return 0;
}
Output:
Enter three numbers: 20
10
50
The maximum of the three numbers is: 50
iii) Take marks of 5 subjects in integers, and find the total, average in float
Algorithm:
Begin procedure main():-
Step 1: SET total := 0
Step 2: PRINT Enter marks for 5 subjects : \ n "
End procedure
Step 3: Repeat step 1 to 2 while i < 5 ;
Step 1: PRINT i + 1 )
Step 2: SET i := i + 1
End of for block
Step 3: READ marks [ i ]
Step 4: SET total := total + marks [ i ]
Step 5: SET average := ( float ) total / 5.0
Step 6: PRINT total
Step 7: PRINT average
Step 8: RETURN 0
Psuedo Code:
#include <stdio.h>
int main()
{
int marks[5];
int total = 0;
float average;
printf("Enter marks for 5 subjects:\n");
for (int i = 0; i < 5; i++)
{
printf("Enter mark for subject %d: ", i + 1);
scanf("%d", &marks[i]);
total += marks[i];
}
average = (float)total / 5.0;
printf("Total marks: %d\n", total);
printf("Average marks: %.2f\n", average);
return 0;
}
21
OUTPUT:
Total marks: 64
22
WEEK 5
Objective: Explore the full scope of different variants of “if construct” namely if-else,
nullelse,
if-else if*-else, switch and nested-if including in what scenario each one of them can be
used and how to use them. Explore all relational and logical operators while writing
conditionals for “if construct”.
Suggested Experiments/Activities:
Tutorial 5: Branching and logical expressions:
Lab 5: Problems involving if-then-else structures.
i) Write a C program to find the max and min of four numbers using if-else.
Algorithm:
End of if block
Step 5: else :
End of if block
End of if block
Step 7: else :
End of if block
23
Step 8: if num4 > max then :
End of if block
Step 9: else :
End of if block
End procedure
Pseudo Code:
#include <stdio.h>
int main()
max = num2;
min = num2;
max = num3;
24
else if (num3 < min)
min = num3;
max = num4;
min = num4;
return 0;
Output
10
15
Maximum number: 15
Minimum number: 5
Algorithm:
End of if block
Step 4: else :
25
Step 1: if units < = 100 then :
End of if block
Step 5: else :
End of if block
Step 6: else :
Step 9: RETURN 0
End procedure
Pseudo Code:00
#include <stdio.h>
int main()
{
int units;
float amt, unitcharg, total;
printf(" Enter no of units consumed : ");
scanf("%d", &units);
26
if (units < 50)
{
amt = units * 3.50;
unitcharg = 25;
}
else if (units <= 100)
{
amt = 130 + ((units - 50 ) * 4.25);
unitcharg = 35;
}
else if (units <= 200)
{
amt = 130 + 162.50 + ((units - 100 ) * 5.26);
unitcharg = 45;
}
else
{
amt = 130 + 162.50 + 526 + ((units - 200 ) * 7.75);
unitcharg = 55;
}
total= amt+ unitcharg;
printf("electricity bill = %.2f", total);
return 0;
}
Output
Enter no of units consumed : 280
Algorithm:
27
Step 1: PRINT b , c ) of the quadratic equation ( ax ^ 2 + bx + c ) : "
Step 2: READ a , b , c
End of if block
Step 5: else :
End of if block
Step 6: else :
Step 7: RETURN 0
End procedure
28
Pseudo Code:
#include <stdio.h>
#include <math.h>
int main()
float a, b, c;
discriminant = b * b - 4 * a * c;
if (discriminant > 0)
sqrt_discriminant = sqrt(discriminant);
else if (discriminant == 0)
root1 = -b / (2 * a);
} else
sqrt_discriminant = sqrt(fabs(discriminant));
29
printf("Roots are complex and different:\n");
return 0;
Output:
Enter coefficients (a, b, c) of the quadratic equation (ax^2 + bx + c): 3
Root 1 = -0.67
Root 2 = -1.00
Algorithm:
Step 3: do
Begin
Step 4: Read ch
Step 5: switch(ch)
Begin
Step 6:
case 1:
Begin
Calculate c = a+b
Print “result”
30
break;
End
case 2:
Begin
Calculate c = a-b
Print “result”
break;
End
case 3:
Begin
Calculate c = a*b
Print “result”
break;
End
case 4:
Begin
Calculate c = a/b
Print “result”
break;
End
#include <stdio.h>
int main()
{
char ch;
int a, b, result;
printf("Enter an Operator (+, *, *, /): ");
scanf("%c", &ch);
printf("Enter two operands: \n");
scanf("%d %d ", &a, &b);
switch(ch)
{
case '+':
result = a + b;
31
break;
case '-':
result = a - b;
break;
case '*':
result = a * b;
break;
case '/':
result = a / b;
break;
}
printf("result = %d",result);
return 0;
}
Output
Result: 7
Result: 3
Result: 10
Result: 2.5
Algorithm:
Step 1: Start
Step 2: Read year
Step 3: If the year is divisible by 4 then go to Step 4 else go to Step 7
Step 4: If the year is divisible by 100 then go to Step 5 else go to Step 6
Step 5: If the year is divisible by 400 then go to Step 6 else go to Step 7
Step 6: Print "Leap year"
32
Step 7: Print "Not a leap year"
Step 8: Stop
Pseudo Code:
#include <stdio.h>
int main()
int year;
scanf("%d", &year);
else
return 0;
Output
Enter a year: 2024
33
WEEK 6
Objective: Explore the full scope of iterative constructs namely while loop, do-while loop
and for loop in addition to structured jump constructs like break and continue including when
eachof these statements is more appropriate to use.
Suggested Experiments/Activities:
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
Pseudo Code:
#include <stdio.h>
int main()
int loop;
int factorial=1;
int number = 5;
return 0;
34
OUTPUT:
Factorial of 5 = 120
Algorithm:
Step 1: Start
Step 7: Loop
else
Step 9: Stop
Pseudo Code:
#include <stdio.h>
int main()
scanf("%d", &num);
35
if (num % i == 0)
temp++;
break;
else
return 0;
OUTPUT:
5 is a Prime number
36
#include <stdio.h>
#include <math.h>
double result = x;
double numerator = x;
double denominator = 1;
numerator *= x * x;
denominator *= (2 * i) * (2 * i + 1);
sign *= -1;
return result;
double result = 1;
double numerator = 1;
double denominator = 1;
numerator *= x * x;
denominator *= (2 * i) * (2 * i - 1);
37
result += sign * (numerator / denominator);
sign *= -1;
return result;
int main()
double angle_radians;
int terms;
scanf("%lf", &angle_radians);
scanf("%d", &terms);
return 0;
OUTPUT:
Sine(5.000000) = 5.000000
Cosine(5.000000) = 1.000000
Algorithm:
Step 1: Start
38
Step 2: Read the input number from the user
Step 3: Declare and initialize the variable reverse and assign input to a temp variable
tempNum=num
Step 4: Start the while loop until num !=0 becomes false
rem = num % 10
reverse*= 10 + rem
num = num / 10
Step 8: Stop
Pseudo Code:
#include <stdio.h>
int main()
{
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
while (n != 0)
{
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0;
}
OUTPUT:
Enter an integer: 15
39
15 is not a palindrome.
1001 is a palindrome.
Algorithm:
Step 3: PRINT \ n
Step 1: PRINT j
Step 2: SET := + 1
Step 1: PRINT \ n
Step 2: SET := + 1
Step 4: RETURN 0
End procedure
Pseudo Code:
#include <stdio.h>
int main()
int i, j, rows;
scanf("%d", &rows);
40
printf("\n");
printf ("\n");
return 0;
OUTPUT:
12
123
1234
12345
123456
41
WEEK 7
Objective: Explore the full scope of Arrays construct namely defining and initializing 1-D
and 2-D and more generically n-D arrays and referencing individual array elements from the
defined array. Using integer 1-D arrays, explore search solution linear search.
Suggested Experiments/Activities:
Tutorial 7: 1 D Arrays: searching.
Lab 7:1D Array manipulation, linear search
i) Find the min and max of a 1-D integer array.
ii) Perform linear search on1D array.
iii) The reverse of a 1D integer array
iv) Find 2’s complement of the given binary number.
v) Eliminate duplicate elements in an array
1)Read the entered array size and store that value into the variable n.
2) Read the entered elements using scanf and store the entered array elements into the
arrayusing for loop for(i=0;i<n;i++).
3) Initialise min, max values with the 1st element of the array.
4) Compare min, max values with a[i],
If min value is greater than a[i] then initialise min=a[i] and if max value is less than a[i]
then initialise max=a[i]. Repeat this step for each element of the string using for loop
which is having the structure for(i=1;i<n;i++).
Print the minimum of the array and maximum of the array values
Pseudo code:
#include
<stdio.h> int
main()
{
int a[1000],i,n,min,max;
printf("Enter size of the array :
");scanf("%d",&n);
printf("Enter elements in array :
");for(i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
min=max=a[0];
42
for(i=1; i<n; i++)
{
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("minimum of array is : %d",min);
3) If x does not match with any of the elements then return -1.
Pseudo code:
#include<stdio.h>
int main()
{
int a[20],i,x,n;
printf("How many
elements?");scanf("%d",&n);
43
printf("Enter array
elements:n");for(i=0;i<n;++i)
scanf("%d",&a[i]);
printf("nEnter element to
search:");scanf("%d",&x);
for(i=0;i<n;+
+i) if(a[i]==x)
break;
if(i<n)
printf("Element found at index
%d",i);else
printf("Element not found");
return 0;
}
Output:-
How many
elements?10 Enter
array elements:n1 2
6
8
Enter element to
search:6Element found
at index 3
#include
<stdio.h> int
main()
44
{
int n, arr[n], i;
printf("Enter the size of the array:
");scanf("%d", &n);
printf("Enter the elements:
");for(i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
int rev[n], j = 0;
for(i = n-1; i >= 0; i--)
{
rev[j] =
arr[i];j++;
}
printf("The Reversed array:
");for(i = 0; i < n; i++)
{
printf("%d ", rev[i]);
}
}
Output:
45
Pseudo code:
#include
<stdio.h>#define
SIZE 8
int main()
{
char binary[SIZE + 1], onesComp[SIZE + 1], twosComp[SIZE +
1];int i, carry=1;
/*
* Add 1 to the ones complement
*/
for(i=SIZE-1; i>=0; i--)
{
if(onesComp[i] == '1' && carry == 1)
{
twosComp[i] = '0';
}
else if(onesComp[i] == '0' && carry == 1)
{
twosComp[i] = '1';
carry = 0;
}
else
46
{
twosComp[i] = onesComp[i];
}
}
twosComp[SIZE] = '\0';
return 0;
}
Output:-
Enter 8 bit binary value: 10011000
Original binary = 10011000
Ones complement =
01100111Twos complement
= 01101000
#include <stdio.h>
// Function to eliminate duplicate elements in an
arrayint removeDuplicates(int arr[], int n) {
if (n <=
1)
return
n;
int uniqueIndex = 0;
47
for (int i = 0; i < n - 1;
i++) { int isDuplicate =
0;
if (!isDuplicate) {
arr[uniqueIndex] =
arr[i];uniqueIndex++;
}
}
arr[uniqueIndex] = arr[n -
1];uniqueIndex++;
return uniqueIndex;
}
int main() {
int arr[] = {1, 2, 2, 3, 4, 4, 5, 6, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:
"); for (int i = 0; i < n;
i++) {printf("%d ",
arr[i]);
}
n = removeDuplicates(arr, n);
48
WEEK-8
Objective: Explore the difference between other arrays and character arrays that can be
usedas Strings by using null character and get comfortable with string by doing
experiments that will reverse a string and concatenate two strings. Explore sorting solution
bubble sort using integer arrays.
Suggested Experiments/Activities:
Tutorial 8: 2 D arrays, sorting and Strings.
i) Addition of two
matricesAlgorithm:
1) Start with two matrices, matrix1 and matrix2, with the same dimensions (number of rows
and columns).
2) Create a result matrix, resultMatrix, with the same dimensions as the input matrices to
storethe sum.
3) Iterate through each element of the matrices using nested loops, i.e., two loops for rows
andcolumns.
4) For each element at position [i][j] in the result matrix, add the corresponding elements
frommatrix1 and matrix2 at the same position.
5) Store the result in the corresponding position in the result matrix.
After iterating through all elements, the resultMatrix will contain the sum of the two
input matrices
Pseudo code:
#include<stdio.h
>
int main()
{
int rows, cols;
printf("Enter the number of rows:
");scanf("%d", &rows);
printf("Enter the number of columns:
");scanf("%d", &cols);
int matrix1[rows][cols], matrix2[rows][cols], resultMatrix[rows][cols];
49
printf("Enter elements of the first
matrix:\n");for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix1[i][j]);
}
}
// Input the second matrix
printf("Enter elements of the second
matrix:\n");for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++) {
scanf("%d",
&matrix2[i][j]);
}
}
return 0;
}
Output:
Enter the number of rows: 2
Enter the number of columns: 2
Enter elements of the first
matrix:2 3
46
Enter elements of the second
matrix:5 7
89
50
Resultant matrix after
addition:7 10
12 15
matricesAlgorithm:
1) Start with two matrices, matrix1 and matrix2, with compatible dimensions for
multiplication (the 2)number of columns in matrix1 must be equal to the number of rows
in matrix2).
3) Create a result matrix, resultMatrix, with dimensions [rows1][cols2], where rows1 is
thenumber of rows in matrix1, and cols2 is the number of columns in matrix2.
4) Initialize elements of the resultMatrix to 0.
Perform matrix multiplication using nested
loops:
For each element at position [i][j] in the result matrix:
5) Initialize a temporary variable sum to 0.
Iterate through a common index k (from 0 to the number of columns in matrix1 or
thenumber of rows in matrix2):
Add the product of matrix1[i][k] and matrix2[k][j] to sum.
Set resultMatrix[i][j] to sum.
After completing the multiplication, the resultMatrix will contain the product of the two
input matrices.
Pseudo code:
#include<stdio.h
>
int main()
{
int rows1, cols1, rows2, cols2;
printf("Enter the number of rows for matrix 1:
");scanf("%d", &rows1);
printf("Enter the number of columns for matrix 1:
");scanf("%d", &cols1);
printf("Enter the number of rows for matrix 2:
");scanf("%d", &rows2);
printf("Enter the number of columns for matrix 2:
");scanf("%d", &cols2);
if (cols1 != rows2) {
printf("Matrix multiplication is not possible. The number of columns in matrix 1 must be
equal to the number of rows in matrix 2.\n");
return 1; // Exit with an error code
}
51
int matrix1[rows1][cols1], matrix2[rows2][cols2], resultMatrix[rows1][cols2];
52
Enter the number of columns for matrix 1:
2Enter the number of rows for matrix 2: 2
Enter the number of columns for matrix 2:
2Enter elements of the first matrix:
23
45
Enter elements of the second
matrix:5 6
78
Resultant matrix after
multiplication: 31 36
55 64
i) Sort array elements using bubble sort
Algorithm:
Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted,
compares adjacent elements, and swaps them if they are in the wrong order. The pass through
the list is repeated until the list is sorted.
1) Start from the first element (index 0) and compare it with the next element (index 1).
2) If the elements are out of order (the current element is greater than the next element in
thecase of ascending order), swap them.
3) Move to the next pair of elements (index 1 and index 2) and repeat the comparison
andswap if necessary.
4) Continue this process for each pair of adjacent elements until you reach the end of
thearray.
5) After one pass through the array, the largest element will have "bubbled up" to the end
ofthe array.
6) Repeat steps 1-5 for a total of (n-1) passes (where n is the number of elements in the
array) to completely sort the array.
Pseudo code:
#include <stdio.h>
void bubbleSort(int arr[], int
n) { int temp;
int swapped;
53
arr[j] = arr[j +
1];arr[j + 1] =
temp;
swapped = 1; // Mark as swapped
}
}
return 0;
}
Output:
Enter the number of elements in the array: 12 45 8 6 13 56 11 9
Enter 12 elements:
12
15
15
19
21
Sorted array using Bubble Sort:
6 8 9 11 12 13 15 15 19 21 45 56
54
ii) Concatenate two strings without built-in functions
Algorithm:
To concatenate two strings without using built-in functions, you can create a new character
array (string) and copy the characters from the first string into it, followed by the characters
from the second stringCreate a character array (result) to store the concatenated string.
1. Initialize variables to keep track of the positions in both input strings (str1 and str2)
and in the result string (resultPos).
2. Iterate through the characters of the first string (str1) and copy them to the result
string one by one.
3. Update the resultPos and str1 positions accordingly.
4. Iterate through the characters of the second string (str2) and copy them to the result
string one by one, starting from the resultPos position.
Pseudo code:
#include <stdio.h>
void concatStrings(char result[], const char str1[], const char str2[]) {
int resultPos = 0;
int str1Pos = 0;
int str2Pos = 0;
// Copy characters from str1 to result
while (str1[str1Pos] != '\0') {
result[resultPos] = str1[str1Pos];
resultPos++;
str1Pos++;
}
int main() {
const char str1[] = "Hello, ";
const char str2[] = "world!";
char result[100]; // Assuming a maximum length for the result
return 0;
}
Output:
Concatenated string: Hello, world!
iii) Reverse a string using built-in and without built-in string functions
Algorithm:
1. Initialize two pointers, start and end, to the beginning and end of the string,
respectively.
2. Swap the characters at the start and end positions.
3. Increment the start pointer and decrement the end pointer.
4. Repeat steps 2 and 3 until start is less than end. This means you're swapping
characters from both ends towards the middle of the string.
5. When start becomes greater than or equal to end, the entire string is reversed.
Pseudo code:
#include <stdio.h>
reverseString(str);
56
return 0;
}
Output:
Enter a string: hello
Reversed string: olleh
57
WEEK 9
Objective: Explore pointers to manage a dynamic array of integers, including memory
allocation & value initialization, resizing changing and reordering the contents of an
array
and memory de-allocation using malloc (), calloc (), realloc () and free () functions. Gain
experience processing command-line arguments received by C
Suggested Experiments/Activities:
Tutorial 9: Pointers, structures and dynamic memory allocation
Lab 9: Pointers and structures, memory dereference.
i) Write a C program to find the sum of a 1D array using malloc()
ii) Write a C program to find the total, average of n students using structures
iii) Enter n students data using calloc() and display failed students list
iv) Read student name and marks from the command line and display the student details
along
with the total.
v) Write a C program to implement realloc()
1. Ask the user for the number of elements in the array (array size).
2. Dynamically allocate memory for the array using malloc() based on the input size.
3. Initialize a variable sum to zero to store the sum of elements.
4. Iterate through the elements of the array using a loop.
5. For each element, prompt the user for its value and store it in the corresponding
position in the dynamically allocated array.
6. Add each element's value to the sum variable as you iterate through the array.
7. After processing all elements, the sum variable will contain the sum of all elements in
the array.
8. Finally, free the dynamically allocated memory using free() to prevent memory leaks
Pseudo code:
#include <stdio.h>
#include <stdlib.h> // for malloc and free functions
int main() {
int n;
58
// Check if memory allocation was successful
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit with an error code
}
// Input array elements and calculate the sum
int sum = 0;
for (int i = 0; i < n; i++) {
printf("Enter element %d: ", i + 1);
scanf("%d", &arr[i]);
sum += arr[i];
}
// Print the sum of array elements
printf("Sum of elements in the array: %d\n", sum);
// Free the dynamically allocated memory
free(arr);
return 0;
}
Output:
Enter the number of elements in the array: 5
Enter element 1: 5
Enter element 2: 6
Enter element 3: 7
Enter element 4: 8
Enter element 5: 9
Sum of elements in the array: 35
Algorithm:
1. Define a structure to represent student information. The structure can contain fields
like student name, roll number, and an array to store scores.
2. Ask the user for the number of students (n).
3. Dynamically allocate memory for an array of n student structures.
4. Iterate through each student and input their details, including name, roll number, and
scores.
5. Calculate the total score for each student and the average score for all students.
6. Print the total and average scores.
Pseudo code:
#include <stdio.h>
#include <stdlib.h> // for malloc and free functions
// Define a structure to represent a student
59
struct Student {
char name[50];
int rollNumber;
int scores[5]; // Assuming 5 scores per student
};
int main() {
int n;
60
// Print total and average scores
printf("Total scores of all students: %d\n", totalScores);
printf("Average score of all students: %.2lf\n", averageScore);
return 0;
}
Output:
Enter the number of students: 2
Enter student 1 name: h
Enter student 1 roll number: 5
Enter 5 scores for student 1: 23 25 26 29 30
Enter student 2 name: k
Enter student 2 roll number: 6
Enter 5 scores for student 2: 29 24 26 30 28
Total scores of all students: 270
Average score of all students: 27.00
29
iii)Enter n students data using calloc() and display failed students list
Algorithm:
1. Define a structure to represent student information, including fields such as name, roll
number, and marks.
2. Ask the user for the number of students (n).
3. Allocate memory for an array of n student structures using calloc(). This ensures that
the memory is initialized to zero.
4. Input student details, including name, roll number, and marks for each student.
5. Calculate the average marks for each student.
6. Determine a passing threshold (e.g., passing marks could be 40).
7. Iterate through the student array and identify students whose average marks are below
the passing threshold.
8. Display the list of failed students.
Pseudo code:
#include <stdio.h>
#include <stdlib.h> // for calloc and free functions
61
double averageMarks;
};
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", &n);
62
// Free the dynamically allocated memory
free(students);
return 0;
}
Output:
Enter the number of students: 2
Enter student 1 name: j
Enter student 1 roll number: 5
Enter 5 subject marks for student 1: 21 35 36
32 65
Enter student 2 name: k
Enter student 2 roll number: 6
Enter 5 subject marks for student 2: 25 33 36 41 54 21
List of Failed Students:
Name: j, Roll Number: 5, Average Marks: 37.80
Name: k, Roll Number: 6, Average Marks: 37.80
iv) Read student name and marks from the command line and display the student
details along with the total.
Algorithm:
1. Accept command line arguments for the student name and marks.
2. Initialize variables to store the student name, total marks, and individual subject
marks.
3. Iterate through the command line arguments, starting from the second argument (the
first argument is the program name).
4. Convert each argument to an integer (marks) using atoi() and add it to the total marks.
5. Print the student name and individual subject marks.
6. Print the total marks at the end.
Pseudo code:
#include <stdio.h>
#include <stdlib.h> // for atoi function
// Start from argv[2] to skip the program name and student name
for (int i = 2; i < argc; i++) {
int marks = atoi(argv[i]); // Convert argument to integer
totalMarks += marks;
printf("Subject %d: %d\n", i - 1, marks);
}
return 0;
}
Output:
Pseudo code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr = NULL; // Declare a pointer to int
int initialSize = 5; // Initial size of the array
int newSize = 10; // New size to which we want to resize
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit the program with an error code
}
64
}
printf("\n");
if (arr == NULL) {
printf("Memory reallocation failed.\n");
return 1; // Exit the program with an error code
}
65
WEEK 10:
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab10 : Bitfields, linked lists
Read and print a date using dd/mm/yyyy format using bit-fields and differentiate the same
without using bit- fields
i) Create and display a singly linked list using self-referential structure.
ii) Demonstrate the differences between structures and unions using a C program.
iii) Write a C program to shift/rotate using bitfields.
iv) Write a C program to copy one structure variable to another structure of the same type
Pseudo code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num; //Data of the node
struct node *nextptr; //Address of the next node
}*stnode;
int main()
{
int n;
printf("\n\n Linked List : To create and display Singly Linked List :\n");
printf(" \n");
66
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL) //check whether the fnnode is NULL and if so no memory allocation
{
printf(" Memory can not be allocated.");
}
else
{
// reads data for the node through keyboard
67
}
void displayList()
{
struct node *tmp;
if(stnode == NULL)
{
printf(" List is empty.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->num); // prints the data of current node
tmp = tmp->nextptr; // advances the position of current node
}
}
}
Output:
Input the number of nodes : 3
Input data for node 1 : 1
Input data for node 2 : 2
Input data for node 3 : 3
Data entered in the list :
Data = 1
Data = 2
Data = 3
ii)Demonstrate the differences between structures and unions using a C program.
Pseudo code:
#include <stdio.h>
#include <string.h>
// Define a structure
struct Student {
int roll_number;
char name[20];
};
// Define a union
union Money {
float dollars;
int euros;
};
int main() {
// Structure Example
struct Student student1;
student1.roll_number = 101;
68
strcpy(student1.name, "John");
// Union Example
union Money money1;
money1.dollars = 100.50;
money1.euros = 80;
// When using a union, only one member can have a value at a time
printf("Union - Money: Dollars = %.2f, Euros = %d\n", money1.dollars, money1.euros);
printf("Size of Union Money: %lu bytes\n", sizeof(money1));
return 0;
}
Output:
Structure - Student: Roll Number = 101, Name = John
Size of Structure Student: 24 bytes
Union - Money: Dollars = 0.00, Euros = 80
Size of Union Money: 4 bytes
Pseudo code:
#include <stdio.h>
#define INT_BITS 32
/*Function to left rotate n by d bits*/
int leftRotate(int n, unsigned int d)
{
/* In n<<d, last d bits are 0. To put first 3 bits of n
at last, do bitwise or of n<<d with n >>(INT_BITS -
d) */
return (n << d) | (n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)
{
/* In n>>d, first d bits are 0. To put last 3 bits of at
first, do bitwise or of n>>d with n <<(INT_BITS
- d) */
return (n >> d) | (n << (INT_BITS - d));
}
/* Driver program to test above functions */
void main()
{
int n = 16;
69
int d = 2;
Output:
Left Rotation of 16 by 2 is 64 Right Rotation of 16 by 2 is 4
iv)Write a C program to copy one structure variable to another structure of the sametype.
Pseudo code:
#include <stdio.h>
// Define a structure
struct Student
{
int roll_number;
char name[50];
float marks;
};
int main()
{
// Declare two structure variables
struct Student student1, student2;
return 0;
}
Output:
Copied Structure - Student 2:
Roll Number: 101
70
Name: John
Marks: 85.50
71
WEEK 11:
Objective: Explore the Functions, sub-routines, scope and extent of variables, doing some
experiments by parameter passing using call by value. Basic methods of numerical integration
Suggested Experiments/Activities:
Tutorial 11: Functions, call by value, scope and extent,
Lab 11: Simple functions using call by value, solving differential equations using Eulers
theorem.
i) Write a C function to calculate NCR value.
ii) Write a C function to find the length of a string.
iii) Write a C function to transpose of a matrix.
iv) Write a C function to demonstrate numerical integration of differential equations using Eulers
method
nCr(n r)
STEP 1: START
STEP 2: RETURN fact(n) / (fact(r)*fact (n-r))
STEP 3: END
fact(n)
STEP 1: START
STEP 2: SET res= 1
STEP 3: REPEAT STEP 3 and STEP 4 UNTIL i<=n
STEP 4: res = res*i
STEP 5: RETURN res
STEP 6: END
Flowchart:
72
Output:
73
Program :
#include <stdio.h>
int main()
{
char s[1000];
int c = 0;
printf("Input a string\n");
gets(s);
while (s[c] != '\0')
c++;
printf("Length of the string: %d\n", c);
return 0;
}
Output:
Input a string
vsm college
Length of the string: 11
74
3. Write a C function to transpose of a matrix
75
Program:
// Driver code
int main()
{
int A[N][N] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
int B[N][N], i, j;
transpose(A, B);
return 0;
}
Output:
Result matrix is
1234
1234
1234
1234
76
4 . Write a C function to demonstrate numerical integration of differential equations using Euler’s
method
Algorithm:
1. Start
2. Define function
3. Get the values of x0, y0, h and xn
*Here x0 and y0 are the initial conditions
h is the interval
xn is the required value
4. n = (xn – x0)/h + 1
5. Start loop from i=1 to n
6. y = y0 + h*f(x0,y0)
x=x+h
7. Print values of y0 and x0
8. Check if x < xn
If yes, assign x0 = x and y0 = y
If no, goto 9.
9. End loop i
10. Stop
Flowchart:
Program:
#include<stdio.h>
77
float fun(float x,float y)
{
float f;
f=x+y;
return f;
}
main()
{
float a,b,x,y,h,t,k;
printf("\nEnter x0,y0,h,xn: ");
scanf("%f%f%f%f",&a,&b,&h,&t);
x=a;
y=b;
printf("\n x\t y\n");
while(x<=t)
{
k=h*fun(x,y);
y=y+k;
x=x+h;
printf("%0.3f\t%0.3f\n",x,y);
}
}
Output:
78
WEEK 12:
Objective: Explore how recursive solutions can be programmed by writing recursive
functions
that can be invoked from the main by programming at-least five distinct problems that
have
naturally recursive solutions.
Suggested Experiments/Activities:
Tutorial 12: Recursion, the structure of recursive calls
Lab 12: Recursive functions
i) Write a recursive function to generate Fibonacci series.
ii) Write a recursive function to find the lcm of two numbers.
iii) Write a recursive function to find the factorial of a number.
iv) Write a C Program to implement Ackermann function using recursion.
v) Write a recursive function to find the sum of series.
Algorithm:
1. START
2. Input the non-negative integer ‘n’
3. If (n==o || n==1)
return n;
else
return fib(n-1)+fib(n-2);
4. Print, nth Fibonacci number
5. END
FLOWCHART:
Program:
#include<stdio.h>
79
#include<conio.h>
void main()
{
int n, i;
int fibo(int);
printf("Enter n:");
scanf("%d",&n);
printf("Fibonacci numbers up to %d terms:\n",n);
for(i=1;i<=n;i++)
printf("%d\n",fibo(i));
getch();
}
int fibo(int k)
{
if(k == 0 || k == 1)
return k;
else
return fibo(k-1)+fibo(k-2);
}
Output:
Enter n:10
Fibonacci numbers up to 10 terms:
1
1
2
3
5
8
13
21
34
55
Flow Chart:
80
Program :
#include <stdio.h>
81
// If both the numbers are equal
if (Num1 == Num2)
return Num1;
// Otherwise
else
return LCMUtil(Num1, Num2, K + 1);
}
// If K exceeds minimum
else
return Num1 * Num2;
}
// Print LCM
printf("%d", lcm);
}
// Driver Code
int main()
{
// Given N & M
int N = 2, M = 4;
// Function Call
LCM(N, M);
return 0;
82
}
Output:
Flowchart:
Program:
#include<stdio.h>
long factorial(int n)
{
83
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);
fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}
Output:
Enter a number: 6
Factorial of 5 is: 720
Algorithm:
Ackermann(m, n)
{next and goal are arrays indexed from 0 to m, initialized so that next[O] through next[m] are 0, goal[O]
through goal[m - l] are 1, and goal[m] is -1}
repeat
value ← next[O] + 1
transferring ← true
current ← O
next[current] ← next[current]+l
current ← current + 1
84
end while
until next[m] = n + 1
end Ackermann
flowchart:
Program:
#include <stdio.h>
if (m == 0){
return n+1;
int main(){
int A;
85
A = ack(1, 2);
printf("%d", A);
return 0;
Output: 4
Algorithm:
First printf statement will ask the user to enter any integer value and the scanf statement will assign the
user entered value to Number variable.
Next, we used For Loop to iterate between 1 and user entered value.
Flowchart:
86
Program:
#include<stdio.h>
int series(int n);
int main( )
{
int n;
printf("Enter number of terms : ");
scanf("%d", &n);
printf("\b\b Using Recursion :: \n");
printf("\b\b = %d\n", series(n)); /* \b to erase last +sign */
printf("\n\b\b Using Recursion :: \n");
printf("\b\b = %d\n\n\n", rseries(n));
return 0;
}/*End of main()*/
/*Iterative function*/
int series(int n)
{
int i, sum=0;
for(i=1; i<=n; i++)
{
printf("%d + ", i);
sum+=i;
}
return sum;
}/*End of series()*/
/*Recursive function*/
87
int rseries(int n)
{
int sum;
if(n == 0)
return 0;
sum = (n + rseries(n-1));
printf("%d + ",n);
return sum;
}/*End of rseries()*/
Output:
Using Recursion ::
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120
Using Recursion ::
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120
88
WEEK 13:
Objective: Explore the basic difference between normal and pointer variables, Arithmetic
operations using pointers and passing variables to functions using pointers
Suggested Experiments/Activities:
Tutorial 13: Call by reference, dangling pointers
Lab 13: Simple functions using Call by reference, Dangling pointers.
i) Write a C program to swap two numbers using call by reference.
ii) Demonstrate Dangling pointer problem using a C program.
iii) Write a C program to copy one string into another using pointer.
iv) Write a C program to find no of lowercase, uppercase, digits and other
characters using pointers.
Flow Chart:
89
Program:
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in
main
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual paramet
ers do change in call by reference, a = 10, b = 20
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a =
20, b = 10
}
Output:
Algorithm:
90
Program:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
if (ptr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
*ptr = 42;
printf("Value pointed to by 'ptr': %d\n", *ptr);
printf("Value pointed to by 'ptr' after deallocation: %d\n", *ptr); // Dangling pointer access
return 0;
}
Output:
Value pointed to by 'ptr': 42
Value pointed to by 'ptr' after deallocation: 0
1. Here we've created a function named copystr() that has two pointer arguments.
2. The first argument is responsible for the target string, and the second one is for the source string.
3. After calling the function copystr(), the target string and source string get passed as arguments.
4. And we know that the source string holds the value that the user enters at runtime. But the target
string has some garbage values by default.
5. Now we've created a while loop inside the function that runs before the source string comes to its
null-terminated character, that is, '\0' (or runs until the last character of the string).
6. Inside the loop, we have copied each character (one by one) of the source string into the target
string.
7. After copying or initializing, we have incremented both the pointer variables for target and
source strings.
8. After completing the while loop, all the characters of the source string get copied to the target
variable.
9. As we have used a pointer here, we only have to output the value of both strings.
10. Never forget to end the targetString pointer variable with a null terminating character ('\0').
91
Program:
#include<stdio.h>
main()
{
char source[100], target[100];
printf("Enter source string\n");
gets(source);
copy_string(target, source);
printf("Target string is \"%s\"\n", target);
return 0;
}
4 Write a C program to find no of lowercase, uppercase, digits and other characters using
pointers.
Algorithm:
Declare and initialize an integer variable with the following values: int i, upper=0, lower=0, special=0.
The user was requested to type a string with upper and lower case letters and special characters.
92
It starts with i=0, checks whether str[i]!= '\0' in the test expression, and then executes the loop until the
supplied condition is met.
If if(str[i]>='A' && str[i]='Z') is true, use an if condition to test it. Upper is changed to upper+1 (or
upper=upper+1).
If it is false, control passes to the else-if portion, which evaluates the test expression of else-if. If true,
control passes to the else-if part, which examines the test expression of else-if. Lower becomes lower+1
(or lower=lower+1).
If it is false, control passes to the other part, which performs the other part's instructions. The special
becomes special+1.
Finally, the program displays the total amount of upper, lower, and special characters in the given string.
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[100];
int i;
int upper=0,lower=0,special=0;;
printf("Please enter the string \n");
gets(str);
// For Uppercase
for(i=0; str[i] != '\0'; i++){
if(str[i]>='A' && str[i]<='Z') {
upper++;
}
// For Lowercase
else if(str[i]>='a' && str[i]<='z') {
lower++;
}
// For special
else{
special++;
}
}
printf("\nUpper case letters: %d",upper);
printf("\nLower case letters: %d",lower);
printf("\nSpecial characters: %d",special);
getch();
93
return 0;
}
Output:
94
WEEK14:
Objective: To understand data files and file handling with various file I/O functions. Explore the
differences between text and binary files.
Tutorial 14: File handling
Lab 14: File operations
i) Write a C program to write and read text into a file.
ii) Write a C program to write and read text into a binary file using fread() and
fwrite()
iii) Copy the contents of one file to another file.
iv) Write a C program to merge two files into the third file using command-line
arguments.
v) Find no. of lines, words and characters in a file
vi) Write a C program to print last n characters of a given file.
Algorithm:
Flowchart:
95
Program:
#include< stdio.h >
int main()
{
FILE *fp; /* file pointer*/
char fName[20];
printf("\nEnter file name to create :");
scanf("%s",fName);
/*creating (open) a file*/
fp=fopen(fName,"w");
/*check file created or not*/
if(fp==NULL)
{
printf("File does not created!!!");
exit(0); /*exit from program*/
}
fclose(fp);
return 0;
}
Output:
Enter file name to create :vsm
File created successfully.
Data written successfully.Contents of file is :ABC
96
2 Write a C program to write and read text into a binary file using fread() and fwrite()
Algorithm:
open in write mode a file with name “out.bin”, in order to store in the file the vector of
structures
written the file in a binary way by using the function fwrite
close the file
reopen the file for reading it
read the file by using the function fread and fill the vector of structures with the read data
print all the data contained in the vector of structures
close the file
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 50
#define N_STUD 2
char name[LEN+1];
float average;
}stud_t;
int main() {
FILE *fp;
stud_t student[N_STUD];
int i;
char row[LEN+1];
strcpy(student[0].name, "Steven");
student[0].id = 120000;
student[0].average = 25.5;
strcpy(student[1].name, "Julia");
97
student[1].id = 120001;
student[1].average = 28.5;
if (fp == NULL){
exit(1);
*/
n_stud*sizeof(stud_t)
*/
if (fp == NULL){
exit(1);
98
/* Read the file */
n_stud = 0;
n_stud++;
return 0;
Output:
99
Flowchart:
Program:
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
100
printf("Cannot open file %s \n", filename);
exit(0);
}
fclose(fptr1);
fclose(fptr2);
return 0;
}
Output:
Enter the filename to open for readinga.txt
Enter the filename to open for writingb.txt
Contents copied to b.txt
4 Write a C program to merge two files into the third file using command-line arguments.
101
Flowchart:
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("file1.txt", "r");
FILE *fp2 = fopen("file2.txt", "r");
102
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
Output:
Algorithm:
103
Flowchart:
Program:
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * file;
char path[100];
char ch;
int characters, words, lines;
104
/* Check if file opened successfully */
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
/*
* Logic to count characters, words and lines.
*/
characters = words = lines = 0;
while ((ch = fgetc(file)) != EOF)
{
characters++;
/* Check words */
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
words++;
}
return 0;
}
Output:
I love programming.
Working with files in C programming is fun.
I am learning C programming at Codeforwin.
105
6 Write a C program to print last n characters of a given file.
Algorithm:
Move pointer in the file to the N-th position from the last
Program:
#include<stdio.h>
int main() {
FILE *fp;
char ch;
int num;
long length;
fp = fopen("test.txt", "r");
if (fp == NULL) {
puts("cannot open this file");
exit(1);
}
fseek(fp, 0, SEEK_END);
length = ftell(fp);
fseek(fp, (length - num), SEEK_SET);
do {
ch = fgetc(fp);
putchar(ch);
} while (ch != EOF);
fclose(fp);
return(0);
}
Output:
106