SlideShare a Scribd company logo
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 1
LABORATORY RECORD
23ES1152
COMPUTER PROGRAMMING LAB
Department of Computer Science & Engineering
VELAGAPUDI RAMAKRISHNA
SIDDHARTHA ENGINEERING COLLEGE
KANURU, VIJAYAWADA-520007, A.P.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 2
COMPUTER PROGRAMMING LAB
23ES1152
STUDENT NAME:
REGISTERED
NUMBER:
ACADEMIC YEAR:
YEAR & SEMESTER:
SECTION:
No. of. Experiments Recorded: …………………….
Marks Awarded : ……………………..
Signature of the Faculty Signature of the HOD
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 3
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 4
INDEX
S.No Date Name of The Experiment Page No Marks Signature
1.i
1.ii
1.iii
Basic Linux environment and its
editors like Vi, Vim & Emacs.
Exposure to Turbo C, gcc
Writing simple programs using
printf(), scanf()
2.i
2.ii
2.iii
Sum and average of 3 numbers
Conversion of Fahrenheit to
Celsius and vice versa
Simple interest calculation
3.i
3.ii
3.iii
3.iv
Finding the square root of a given
number
Finding compound interest
Area of a triangle using heron’s
formulae
Distance travelled by an object
4.i
4.ii
4.iii
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)
Find the maximum of three
numbers using conditional
operator
Take marks of 5 subjects in
integers, and find the total,
average in float
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 5
S.No Date Name of The Experiment Page No Marks Signature
5.i
5.ii
5.iii
5.iv
5.5
To find the max and min of four
numbers using if-else.
To generate electricity bill.
Find the roots of the quadratic
equation.
To simulate a calculator using
switch case.
To find the given year is a leap
year or not.
6.i
6.ii
6.iii
6.iv
6.v
Find the factorial of given
number using any loop.
Find the given number is a prime
or not.
Compute sine and cos series
Checking a number palindrome
Construct a pyramid of numbers.
7.i
7.ii
7.iii
7.iv
7.v
Find the min and max of a 1-D
integer array.
Perform linear search on1D array.
The reverse of a 1D integer array.
Find 2’s complement of the given
binary number.
Eliminate duplicate elements in
an array.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 6
S.No Date Name of The Experiment Page No Marks
Signature
8.i
8.ii
8.iii
8.iv
Addition of two matrices.
Multiplication two matrices.
Sort array elements using bubble
sort.
Concatenate two strings without
built-in functions.
Reverse a string using built-in
and without built-in string
functions
9.i
9.ii
9.iii
9.iv
9.v
To find the sum of a 1D array
using malloc() .
To find the total, average of n
students using structures.
Enter n students data using
calloc() and display failed
students list.
Read student name and marks
from the command line and
display the student details along
with the total.
To implement realloc()
10.i
10.ii
10.iii
10.iv
Create and display a singly linked
list using self-referential structure.
Demonstrate the differences
between structures and unions
using a C program.
Write a C program to shift/rotate
using bit fields.
Write a C program to copy one
structure variable to another
structure of the same type
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 7
S.No Date Name of The Experiment Page No Marks Signature
11.i
11.ii
11.iii
11.iv
To calculate NCR value.
To find the length of a string.
To transpose of a matrix.
To demonstrate numerical
integration of differential
equations using Euler’s
Method.
12.i
12.ii
12.iii
12.iv
12.v
To generate Fibonacci series.
To find the lcm of two numbers.
To find the factorial of a number.
To implement Ackermann
function using recursion.
To find the sum of series.
13.i
13.ii
13.iii
13.iv
To swap two numbers using call
by reference.
To Demonstrate Dangling pointer
problem using a C program.
To copy one string into another
using pointer.
To find no of lowercase,
uppercase, digits and other
characters using pointers.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 8
S.NO Date Name of The Experiment Page No Marks Signature
14.i
14.ii
14.iii
14.iv
14.v
14.vi
To write and read text into a file.
To write and read text into a
binary file using fread() and
fwrite().
To Copy the contents of one file
to another file.
To merge two files into the third
file using command-line
arguments.
Find no. of lines, words and
characters in a file
To print last n characters of a
given file
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 9
COMPUTER PROGRAMMING LAB
(Common to All branches of Engineering)
__________________________________________________________________________________
Course Objectives:
The course aims to give students hands – on experience and train them on the concepts of the
C- programming language.
Course Outcomes:
CO1: Read, understand, and trace the execution of programs written in C language.
CO2: Select the right control structure for solving the problem.
CO3: Develop C programs which utilize memory efficiently using programming constructs
like pointers.
CO4: Develop, Debug and Execute programs to demonstrate the applications of arrays,
functions, basic concepts of pointers in C.
UNIT I
WEEK 1:
Objective: Getting familiar with the programming environment on the computer and writing
the first program.
Suggested Experiments/Activities:
Tutorial 1: Problem-solving using Computers.
Lab 1: Familiarization with programming environment
i) Basic Linux environment and its editors like Vi, Vim & Emacs etc.
ii) Exposure to Turbo C, gcc
iii) Writing simple programs using printf(), scanf()
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 2: Converting algorithms/flow charts into C Source code.
Developing the algorithms/flowcharts for the following sample programs
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 10
i) Sum and average of 3 numbers
ii) Conversion of Fahrenheit to Celsius and vice versa
iii) Simple interest calculation
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.
i) Finding the square root of a given number
ii) Finding compound interest
iii) Area of a triangle using heron’s formulae
iv) Distance travelled by an object
UNIT II
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:
Tutorial 4: Operators and the precedence and as associativity:
Lab 4: 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)
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
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 11
WEEK 5:
Objective: Explore the full scope of different variants of “if construct” namely if-
else, null- else, 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.
ii) Write a C program to generate electricity bill.
iii) Find the roots of the quadratic equation.
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.
WEEK 6:
Objective: Explore the full scope of iterative constructs namely while loop, do-
while loop and or loop in addition to structured jump constructs like break and
continue including when each of these statements is more appropriate to use.
Suggested Experiments/Activities:
Tutorial 6: Loops, while and for loops
Lab 6: Iterative problems e.g., the sum of series
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.
UNIT III
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.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 12
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.
WEEK 8:
Objective: Explore the difference between other arrays and character arrays that
can be used as 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.
Lab 8: Matrix problems, String operations, Bubble sort
i) Addition of two matrices
ii) Multiplication two matrices
iii) Sort array elements using bubble sort
iv) Concatenate two strings without built-in functions
v) Reverse a string using built-in and without built-in string functions
UNIT IV
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()
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 13
WEEK 10:
Objective: Experiment with C Structures, Unions, bit fields and self-referential
structures (Singly linked lists) and nested structures
Suggested Experiments/Activities:
Tutorial 10: Bitfields, Self-Referential Structures, Linked lists
Lab 10: 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.
UNIT V
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 Euler’s method
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
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 14
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.
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.
WEEK 14:
Objective: To understand data files and file handling with various file I/O
functions. Explore the differences between text and binary files.
Suggested Experiments/Activities:
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.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 15
Textbooks:
1. Ajay Mittal, Programming in C: A practical approach, Pearson.
2. Byron Gottfried, Schaum' s Outline of Programming with C, McGraw Hill
Reference Books:
1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language,
Prentice- Hall of India
2. C Programming, A Problem-Solving Approach, Forouzan, Gilberg, Prasad,
CENGAGE
-----------------------------------*****-------------------------------------
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 16
Lab Session - 1
Date:
Objective: Getting familiar with the programming environment on the computer and writing
the first program.
AIM: Familiarization with programming environment.
Pre-Lab|1:
1. Which of the following is the output of the program when the input values are 1 for 'a'
and 2 for 'b' in the given pseudocode?
A. 1
B. 2
C. Runtime error
D. Compile time error
2. What is the output of this program?
#include <stdio.h>
int main()
{
printf("variable! %d", x);
return 0;
}
A. "variable! x"
B. "variable! followed by a junk value"
C. Compile time error
D. "variable!"
3. Which of the following is not a data type?
A. _option
B. amount
C. sales_amount
D. salesAmount
E. $salesAmount
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 17
4. One of the most common errors for new programmers is forgetting to use the address
operator for variables in a scanf statement. What is that?
A. The address modifier (@)
B. The ampersand (&)
C. The caret (^)
D. The percent (%)
E. The pound sign (#)
5. i. Which of the following is not a character constant in C?
ii. Which of the following is not an integer constant in C?
I. II.
A. ‘C’ A.-320
B. ‘bb’ B.+45
C. “C” C.-31.80
D. ‘?’ D.1456
E. ‘ ‘ E.2,456
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 18
In–Lab|1:
1. i: Basic Linux environment and its editors like Vi, Vim & Emacs etc.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 19
1. ii: Exposure to Turbo C, gcc.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 20
1. iii: Writing simple programs using printf(), scanf().
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 21
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 22
Post–Lab|1:
1. Write a C program using printf statements to print the three first letters of your first name in
big blocks. This program does not read anything from the keyboard. Each letter is formed using
seven rows and five columns using the letter itself. For example, the letter B is formed using
17B’s as shown below as part of the initials BEF.
BBB EEEEE FFFFF
B B E F
B B E F
BBB EEE FFF
B B E F
B B E F
BBB EEEEE F
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 23
2. Write a program that reads nine integers and prints those three in a line separated by commas
as shown below.
Input: 10 31 2 73 24 65 6 87 18
Output:
10, 31, 2
73, 24, 65
6, 87,18
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 24
3. Write a program that reads a character, an integer, and a floating-point number. It then prints
the character, first using a character format specification (%c) and then using an integer
specification (%d). After printing the character, it prints the integer and floating-point numbers
on separate lines.
Program code:
Sample Input:
c
23
15. 234
Sample Output:
The character is c.
The integer number is 23.
The real number is 15.234.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 25
4. Write a program that prompts the user to enter three numbers and then prints them vertically
(each on one line), first forward and then reversed (the last one first), as shown in the following
design. Please enter three numbers: 15 35 72
Your numbers forward:
15
35
72
Program code:
Marks Secured:_____ Out of _____
Evaluator Signature
Your numbers reversed:
72
35
15
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 26
Lab Session – 2
Date:
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.
AIM: Converting algorithms/flow charts into C Source code
Pre–Lab|2:
1. What will be the outputs of the following program?
# include <stdio.h>
void main ()
{
int a = 1, b = 2; a += b -= a;
printf (“%d %d”, a, b);
}
o/p:
2. Which of the following is not a valid declaration in C.
1. short int x;
2. signed short x;
3. short x;
4. unsigned short x;
2. What will be the output of the following program?
#include <stdio.h>
int main (){
int x; char y;
x = -1;
y = -2;
printf(“x is %d and y is %d”, x, y);
}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 27
3. Predict the outputs of the following programs.
#include <stdio.h>
void main ()
{
char a = ‘012’;
printf (“%d, a);
}
#include <stdio.h>
void main ()
{
char c = 125;
c = c + 1 0;
printf (“%d”, c);
}
o/p: o/p:
4. If no data type is given to a variable, the compiler automatically converts it to the int
data type. What will be the outputs for 16-bit and 32-bit compilers?
#include <stdio.h>
void main() {
signed int a; // Explicitly specifying 'int' data type for clarity
signed int b; // Explicitly specifying 'int' data type for clarity
// The size of 'a' and 'b' is equal to the size of 'int'
printf("The size of a is %dn", sizeof(a));
printf("The size of b is %d", sizeof(b));
}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 28
In-Lab|2:
2. i: Declare three variables of integer data type. The user has to input three valid numbers. Display the
sum and average of the user-entered numbers. The approach is to take three numbers and find their sum
and average using the formula given below: Sum: a + b + c Average: (a + b + c) / 3 Where 'a,' 'b,' and
'c' are the three numbers.
Sample Input: Enter 3 Values: 10 20 30
Sample Output: Sum: 60 Average: 20"
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 29
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 30
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 31
2. ii: Take input for the temperature in Fahrenheit and output the Celsius equivalent, and vice versa.
Input two numbers. The first is for a Celsius value, and the second is for a Fahrenheit value.
For the Celsius value input, convert it to Fahrenheit using the formula F = C × 9/5 + 32 for
conversion. In case of decimals, display up to one decimal place.
For the Fahrenheit value input, convert it to Celsius using the formula C = (F - 32) × 5/9 for
conversion. In case of decimals, display up to one decimal place.
Sample Input: 0 100
Sample Output: 32 37.7"
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 32
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 33
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 34
2. iii: You can calculate simple interest by providing the principal amount, rate of interest, and time or
periods as provided by user input. Simple interest can be calculated using the formula below:
Simple Interest = (Principal * Rate * Time) / 100
Where: Principal: The principal is the initial amount borrowed (loaned) from the bank or
invested, denoted as 'P.' Rate: The rate is the interest rate at which the principal amount is given
to someone for a certain period. The interest rate can be 5%, 10%, or 13%, etc., and is denoted
as 'R.' Time: Time is the duration for which the principal amount is given to someone, denoted
as 'T.'
Constraints: 1 <= Principal <= 10000 1 <= Rate <= 10 1 <= Time <= 30
Sample Input: 100 3 10
Sample Output: 30
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 35
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 36
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 37
Post-Lab|2:
1. Take two numbers of type int and two numbers of type float as input and output their sum.
Declare four variables: two of type int and two of type float.
Read two lines of input from stdin (following the sequence provided in the 'Input Format'
section below) and initialize your variables. Use the + and - operators to perform the following
operations:
Print the sum and difference of the two int variables on a new line.
Print the sum and difference of the two float variables, rounded to one decimal place, on a new
line.
Input Format: The first line contains two integers. The second line contains two floating-point
numbers.
Constraints: 1 <= integer variables <= 10^4; 1 <= float variables <= 10^4
Output Format: Print the sum and difference of both integers separated by a space on the first
line and the sum and difference of both floats (rounded to 1 decimal place) separated by a space
on the second line. All outputs must be left-justified.
Sample Input: 10 4 4.0 2.0
Sample Output: 14 6 6.0 2.0
Test the output for the following input:
Sample Input:
 10 4 4.0 -2.0
Sample Output: The program should display an error message if a character is given instead
of numbers.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 38
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 39
2. Calculate a student’s average score for a course with 4 quizzes, 2 midterms, and a final. The quizzes
are weighted at 30%, the midterms at 40%, and the final at 30%.
Sample Input: Enter the score for the first quiz: 98 Enter the score for the second quiz: 89
Enter the score for the third quiz: 78 Enter the score for the fourth quiz: 79 Enter the score for
the first midterm: 90 Enter the score for the second midterm: 100 Enter the score for the final:
92
Sample Output: First Quiz: 98 Second Quiz: 89 Third Quiz: 78 Fourth Quiz: 79 Quiz Total:
344 First Midterm: 90 Second Midterm: 100 Total Midterms: 190 Final: 92 Quiz: 25.8%
Midterm: 38.0% Final: 27.6% Total: 91.4%
Explanation: Quiz percentage = 344 * 30/400 = 25.8%, Midterm = 190 * 40/200 = 38.0%, and
Final = 92 * 30/100 = 27.6%. Total = 25.8% + 38.0% + 27.6% = 91.4%
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 40
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 41
3. There are three types of fruits: T1, T2, and T3 in a shop. The number of fruits of type T1, T2, and T3
are Cnt1, Cnt2, and Cnt3, respectively, and each fruit costs Cost1, Cost2, and Cost3, respectively.
You want to obtain a total of S energy by buying some of the fruits while spending as little as
possible. Find the minimum amount you need to spend and print '-1' if the answer does not
exist.
Input Format: First line: S represents the total amount of energy. Second line: Three space-
separated integers Cnt1, Cnt2, and Cnt3. Third line: Three space-separated integers Cost1,
Cost2, and Cost3.
Output Format: Print the answer.
Sample Input Sample Output
Explanation: There are two ways to achieve a total energy of 10:
1. Buying two T1 and two T2, which costs 20.
2. Buying one T1, one T2, and one T3, which costs 30. So, the minimum cost is 20.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 42
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 43
Lab Session – 3
Date:
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.
AIM: Simple computational problems using arithmetic expressions.
Pre-lab|3:
1. What will be the output of the following program?
#include <stdio.h>
int main ()
{ int i = 0;
for (i = 0; i < 20; i++) {
switch (i) {
case 0 : i += 5;
case 1 : i += 2;
case 5 : i += 5;
default : i += 4; break; }
printf (“%d”, i);
}return 0;
}
a. 5 10 15 20
b. 7 12 17 22
c.16 21
d. Compilation Error
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 44
2. What will be the output of the following program?
#include <stdio.h>
void main ()
{
char c = ‘a’;
switch (c)
{ case ‘a’ :
case ‘e’ :
case ‘i’ :
case ‘o’ :
case ‘u’ :
printf (“Vowel character”);break;
default :printf (“Not a Vowel character”);break; }
}
o/p:
3. What will be the output of the following program?
#include <stdio.h>
int main () { int x = 3;
if (x ==2); x = 0; if (x == 3) x++; else x+= 2;
printf (“x = %d”, x); return 0;
}
a. x = 4
b. x = 2
c. Compiler Error
d. x = 0
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 45
4. What will be the output of the following program?
#include <stdio.h>
#define EVEN 0
#define ODD 1
int main () {
int i = 3; switch (i & 1) {
case EVEN : printf (“Even”);
break;
case ODD : printf (“Odd”);
break;
default : printf (“Default”);
}return 0;
}
o/p:
5. What will be the output of the following program?
#include <stdio.h>
int main () { int a = 100; if (a == 10)
printf (“Value of a is 10 n”); else if (a == 20) {
printf (“Value of a is 20 n”); else if (a == 30) {
printf (“Value of a is 30 n”); else
printf (“None of the values is matching n”);
printf (“Exact value of a is : %d n”, a);
return 0;}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 46
In-Lab|3:
3 .i: Watson likes to challenge Sherlock's math ability. He will provide a integer from a set of
integers Sherlock must determine the square root of that number
Constraints
1<=n<=109
Run Time Test cases:
Method 1: (Using sqrt() Function)
Test case 1: In this case, we enter the value “25” as input to find the square root.
Enter number: 25
Number is 25 and its square root is: 5
Test case 2: In this case, we enter the value “64” as input to find the square root.
Enter number: 64
Number is 64 and its square root is: 8
Method 2: (Using pow() Function)
Run Time Test cases
Test case 1: In this case, we enter the value “25” as input to find the square root.
Enter number: 25
Number is 25.00 and its square root is: 5.00
Test case 2: In this case, we enter the value “16” as input to find the square root.
Enter number: 16
Number is 16.00 and its square root is: 4.00
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 47
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 48
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 49
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 50
3 .ii: Compound interest is the addition of interest to the principal sum of a loan or deposit, or
in other words, interest on interest. It is the result of reinvesting interest, rather than paying it
out, so that interest in the next period is then earned on the principal sum plus previously-
accumulated interest. Compound interest is standard in finance and economics.
Compound interest may be contrasted with simple interest, where interest is not added to the
principal, so there is no compounding.
Compound Interest formula:
Formula to calculate compound interest annually is given by:
Amount= P(1 + R/100)t
Compound Interest = Amount – P
Where,
P is principal amount
R is the rate and
T is the time span
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 51
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 52
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 53
3 . iii: To calculate the area of a triangle using Heron's formula, we need the lengths of all three sides
of the triangle. First, take the lengths of the three sides of the triangle as input from the user using the
scanf() function and store them in three floating-point variables: 'a,' 'b,' and 'c.'
Calculate the semi-perimeter of the triangle as s = (a + b + c) / 2.
The area of the triangle is given by the formula: Area = √(s(s-a)(s-b)(s-c)).
Calculate the area of the triangle using Heron's formula as described above and store the result
in a floating-point variable named 'area.' Display the area of the triangle on the screen using
the printf function.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 54
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 55
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 56
3 .iv: When an object moves in a straight line at a constant speed, we can calculate its distance if we
know the object's speedand the time it takes. This equationillustrates the relationshipbetween speed,
distance traveled, and time taken:
Distance = speed * time
To find the distance traveled at regular intervals of time, given the values of 's' (speed) and 't'
(time), the program should offer users the flexibility to choose their own time and speed.
Constraints:
 Speed must be provided in kilometers per hour.
 Time must be provided in hours.
 Distance must be measured in kilometers.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 57
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 58
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 59
Post –Lab|3:
1. Write a program that determines a student’s grade. It reads three test scores m1, m2, and m3
(between 0 and 100) and calculates the student’s grade based on the following rules:
a. If the average score is 90% or higher, the grade is A.
b. If the average score is 70% or higher but less than 90%, it checks the third score. If the third
score is higher than 90%, the grade is A; otherwise, the grade is B.
c. If the average score is 50% or higher but less than 70%, it checks the average of the second
and third scores. If the average of the two is greater than 70%, the grade is C; otherwise, it is
D.
d. If the average score is less than 50%, then the grade is F.
Test case:
Input: Test score 1: 60 Test score 2: 70 Test score 3: 75
Output: The grade is C.
Explanation: Average score: (60 + 70 + 75) / 3 = 68.33 (Check condition c). Average of the
last two test scores = (70 + 75) / 2 = 72.5, which is greater than 70, so the grade is C.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 60
2. Write a program to compute the real roots of a quadratic equation (ax^2 + bx + c = 0). Your program
should prompt the user to enter the constants (a, b, c) and then display the roots based on the
following rules:
a. If both 'a' and 'b' are zero, there is no solution. b. If 'a' is zero, there is only one root (-c/b). c.
If the discriminant (b^2 - 4ac) is negative, there are no real roots. d. For all other combinations,
there are two roots.
Test your program with the data in the table:
A B C
3 8 5
-6 7 8
0 9 -10
Sample Input: a: 3 b: 8 c: 5
Sample Output: There are two roots. Roots are -1 and -1.66.
Program code:
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 61
Lab Session – 4
Date:
Objective: Explore the full scope of expressions, type-compatibility of variables & constants
and operators used in the expression and how operator precedence works.
AIM: Simple computational problems using the operator’ precedence and associativity.
Pre-Lab|4:
1. Think of operator associativity as a line of people passing items to each other. If the people
pass items from left to right, it's left-associative; if they pass from right to left, it's right-
associative. Which operator in many programming languages is right-associative?
a. Addition (+) b. Subtraction (-) c. Exponentiation (^) d. Multiplication (*)
Ans:
2. Think of operator precedence as the hierarchy in a corporate organization. Some employees
have higher ranks and make decisions that impact others. Which operator typically has the
highest rank in this hierarchy, similar to a CEO in a company?
a. Assignment operator (=)
b. Arithmetic operators (+, -, *, /)
c. Comparison operators (>, <, ==)
d. Logical operators (&&, ||)
Ans:
3. Consider a mathematical expression as a sentence. In this sentence, operators are like words,
and parentheses are like punctuation marks. What role do parentheses play in determining the
meaning of the sentence?
a. They change the operator precedence.
b. They change the operator associativity.
c. They act as operands.
d. They have no impact on the expression's meaning.
Ans:
4. Think of operators as workers in a factory. Each worker has a specific task, and they need to
know who to hand their work off to next. Which concept in programming is analogous to the
order in which workers pass their work along?
a. Operator Precedence
b. Operator Associativity
c. Operand Evaluation
d. Operator Overloading
Ans:
5. Imagine you have a calculator with only three buttons: "+", "-", and "=". When you enter a
sequence of numbers and operators, which concept determines the order in which the calculator
processes them?
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 62
a. Operator Precedence
b. Operator Associativity
c. Operand Evaluation
d. Operator Overloading
Ans:
In-Lab|4:
4 .i: Write a c program to calculate 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)
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 63
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 64
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 65
4 .ii: Input three values. Find the maximum of three numbers using conditional operator using
the following syntax
Max =Expr1? Expr2: Expr3;
Algorithm & Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 66
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 67
4 .iii: Take marks of 5 subjects as integers m1, m2, m3, m4, m5. Find the total, average in float.
Total = m1+m2+m3+m4+m5
Average = Total/5
Use relevant format specifier to display results.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 68
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 69
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 70
Post-Lab|4:
1. Consider a classroom scenario where students are graded based on their performance.
If they score above a certain threshold, they pass the course; otherwise, they fail.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 71
2. You're driving, and you approach a traffic signal. If the light is green, you continue
straight; otherwise, you stop. Write a C program that uses if and else to simulate this
scenario
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 72
3. Consider a weather forecast scenario. If the weather is sunny, you go for a picnic;
otherwise, you stay at home. Write a C program that checks the weather condition
(sunny or not) and uses an if-else statement to decide whether to plan a picnic or stay
at home.
Program Code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 73
4. Think of an if-else statement as a restaurant menu. If you're hungry, you order a main course;
otherwise, you order dessert. Write a C program that asks the user if they are hungry (yes/no).
If they are, prompt them to order a main course; otherwise, suggest a dessert. Use if-else for
this decision.
Program Code:
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 74
Lab Session – 5
Date:
Objective: Explore the full scope of different variants of “if construct” namely if-else, null
else, 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”.
AIM: Problems involving if-then-else structures.
Pre-Lab|5:
1: What would happen when we compile and run this program?
#include “stdio.h”
int main ()
{
int i;
goto LOOP;
for (i = 0; i < 10; i++)
{
printf (“Hi everyone”);
LOOP;
break;
}
return 0; }
o/p:
2: Trace the code and give the output.
#include <stdio.h>
int main () {
int a = 0, i = 0, b;
for (i = 0; i < 5; i++) {
a++;
continue; }
}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 75
3: What will be the outputs of the codes given below?
i. #include <stdio.h>
int main()
{
int i = 0, j = 0;
l1: while (i < 2)
{
i++;
while (j < 3)
{
printf (“Loop n”);
goto l1; } } }
o/p:
4. #include <stdio.h>
int main ()
{
int i = 0, k;
if (i == 0)
goto label;
for (k = 0; k < 3; k++)
{
printf (“hi n”);
label: k = printf (%03d”, I);
}
}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 76
In-Lab|5:
5 .i: Write a C program that accepts 4 numbers from the keyboard and prints out the maximum
and minimum values of these four numbers.
Note: Use integer or real numbers as input; declare the variables with required data
type.
Test data and expected output:
Input: 1.54 1.236 1.3625 1.002
Output:
Maximum Value is 1.54
Minimum Value is 1.002
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 77
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 78
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 79
5.ii: Write a C program to generate electricity bill with slabs by taking input as Consumer
Number, Name, Present Reading, Previous Reading.
Test data and expected output:
Input: 652114046358, Gupta, 35201, 35002
Calculate the number of units consumed and generate the bill amount for the consumed
units basing on the following slabs.
For first 50 units – Rs. 3.50/unit
For next 100 units – Rs. 4.00/unit
For next 100 units – Rs. 5.20/unit
For units above 250 – Rs. 6.50/unit
Output:
-------------------------------------------------------
Consumer Number : 652114046358
Consumer Name : Gupta
Billed Units : 199
Bill Amount : Rs. 829.80
Note: Declare variables with required data type. Use different number of billed units as
input to cover all the slabs.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 80
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 81
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 82
5 .iii: Find the roots of the quadratic equation.
Note: The standard form of a quadratic equation is ax2
+ bx + c where a, b and c are
real numbers and not equal to zero. The term b2 – 4ac is known as the discriminant (d)
of a quadratic equation. It tells the nature of the roots
If the d > 0 the roots are real and different
If the d = 0, the roots are real and equal.
If the d < 0 the roots are complex and different
Test Data:
1. x2
+ 5x + 6 = 0
D =b2
– 4ac
D = 52
– (4×1×6) = 25 – 24= 1
Since D>0, the equation will have two real and distinct roots. The roots are:
x = [(-b + √D)]/2a or [(-b – √D)]/2a
x = [(-5 + √1)]/2(1) or [(-5 – √1)]/2(1)
Output: The roots are -2 or -3
2: x2
+ x + 1 = 0 D =b2
– 4ac
D = 12
– (4×1×1) = 1 – 4= -3
Since D<0, the equation will have two distinct Complex roots. The roots are:
x = [(-b + √D)]/2a or [(-b – √D)]/2a
x = [(-1 + √-3)]/2(1) or [(-1 – √-3)]/2(1)
x = [(-1 + √3i)]/2 or [(-1 – √3i)]/2
3: 4x2
+ 12x + 9 =0
D =b2
– 4ac
D = 122
– (4×4×9) = 144 – 144= 0
Since D = 0, the equation will have two real and equal roots. The roots are:
x = -b/2a
x = -12/2(4)
x = -12/8
x = -3/2
Output: The roots are -3/2 and -3/2.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 83
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 84
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 85
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 86
5 .iv: Simulate a calculator using switch case.
Note: The program should takes an arithmetic operator +, -, *, /, % and two numeric operands
from the user. Then, it performs the calculation on the two operands depending upon the
operator entered by the user. For the modulus operator, you have to take only integer numbers,
for the rest of the operands you can declare real or integer data type. Test Cases Should test all
the operators.
Test Data and Output: +, 1.2, 2.3
Result = 3.5
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 87
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 88
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 89
5 .v: Write a C program to find the given year is a leap year or not.
Note: Should take year as an input and check whether it is divisible by 4 and not
divisible by 100 or can be divisible by 400.
Test Data and Output:
Enter the year: 2000 Output: 2000 is Leap Year
Enter the year: 1900 Output: 1900 is not a Leap Year
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 90
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 91
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 92
Post-Lab|5:
1: Develop a C program to find all possible permutations in which ‘n’ people can occupy‘t’
seats in a theater is discussed here. ‘N’friends are planning to go to a movie. Once among them
suggested few movies and all others started to discuss and finally they selected a movie. One
among them quickly booked their tickets online; to their surprise they are unable to select their
seats. All of them got confused. Then anyhow, decided to go to the movie.
They rushed to reach the theater on time. Again they are surprised that no one was there in the
theater. They are the only people about to watch the movie. There is ‘r’ number of seats in
which, ‘n’ number persons should sit. In how many ways they can sit inside the theater?
Input Format :
The number of people ‘n’ , and the number of seats ‘r’.
Output Format :
Total number ways ‘n’ people can be seated in ‘r’ seats.
Constraint :
Given the number of people ‘n’ and the number of seats ‘r’ as input as positive
integers. The task is to find the different number in which ‘n’ number of people can
be seated in those ‘r’ number of seats.
Sample Test Case :
Input :
Number of people : 5
Number of Rows : 3
Output :
The total number of ways in which ‘n’ people can be seated in ‘r’ seats = 60
Calculation : P(n,r) = P(5, 3) = 5!/(5-3)! = 120/2 = 60
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 93
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 94
2: Develop a C program to check whether a number can be expressed as a sum of two prime
numbers is discussed here. Given a positive integer N. The task is to check if the number N can
be represented as a sum of two prime numbers. Use break statement whenever it is possible.
Constraint :
The range of N should be less than 108
.Test Cases:
Input : N = 13
Output : Yes
Explanation : The number 13 can be written as 11 + 2, here 11 and 2 are both prime numbers.
Input : N = 11
Output : No
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 95
3: There are two banks; Bank A and Bank B. Their interest rates vary. You have received
offered from both the bank in terms of annual rate of interest. Tenure and variations of rate of
interest over the entire tenure. Here use unconditional control statements, where ever it is
required.
You have to choose the offer, which costs you least interest and reject the other.
Do the computation and make a wise choice.
The loan repayment happens at a monthly frequency and Equated Monthly
installment (EMI) is calculated using the formula given below:
EMI = loan amount * monthly interest rate / (1–1/(1+monthly interest rate)(no. of yrs * 12))
Constraints :
1 <= P <= 1000000
1 <= T <= 50
1 <= N1 <= 30
1 <= N2 <= 30
Input Format :
First Line : P – principal (Loan Amount)
Second Line : T – Total Tenure (in Years)
Third Line : N1 is number of slabs of interest rates for a given period by the bank A.
First slab starts from the first year and second slab starts from the end of the first
slab and so on.
Next N1 line will contain the interest rates and their period.
After N1 lines we will receive N2 viz. The number of slabs offered by the second
bank.
Next N2 lines are number of slabs of interest rates for a given period by the Bank
B. First slab starts from the first year and second slab starts from end of first slab
and so on.
Output : Your decision – either Bank A or Bank B.
Input :
10000
20
3
5 9 5
10 9 6
5 8 5
5 7 9
Output : Bank B
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 96
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 97
4: Develop a test-based game that asks the user to guess a number. The system then outputs
whether the guess was right or wrong. Let’s make the program give some help to the user; i.e.,
output whether the guess was higher or lower than the secret number.
Hint : srand(time(0)); /* see random number generator */
num = rand() % 100 + 1; /* random number between 1 and 100 */
Number Entered Message to Display
3 Too Low
5 You Win!
7 Too High
8 Too High
Test Case 1 :
Input : Enter the number you guess : 3
Output : The number is too low
Test Case 2 :
Input : Enter the number you guess : 5
Output : You Win!
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 98
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 99
Lab Session – 6
Date:
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 each
of these statements is more appropriate to use.
Aim: Solving Iterative Problems using Loops (for, While)
Pre-Lab|6:
1: What will be the output of this program.
#include <stdio.h>
int main() {
int i = 0;
printf (“Hello”);
char s[4] = {‘b’, ‘t’, ‘r’, ‘n’};
for (i = 0; i < 4; i++) {
printf (“%c”, s[i]);
return 0;
}
o/p:
2: What will be the output of this program.
#include <stdio.h>
int main() {
int i = 0;
char s[4] = {‘0’, ‘0’, ‘0’, ‘0’};
for (i = 0; i < 4; i++) {
printf (“%c”, s[i]);
return 0;
}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 100
3: Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ’, return
the length of last word in the string. If the last word does not exist return 0.
Hint : For the input value “Hello World” the output is 5.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 101
4: What will be the output of this program.
#include <stdio.h>
# define arr “abcd”
int main() {
printf (“%c”, arr[2]);
return 0;}
o/p:
In-Lab|6:
6 .i: Find the factorial of given number using any loop.
The factorial of a positive number n is given by: 1*2*3*4 ...
Note: This program should take a positive integer from the user as the factorial of a negative
number doesn't exist and, the factorial of 0 is 1. Compute the factorial using any loop. Since
the factorial of a number may be very large, the type of factorial variable is declared as unsigned
long long. If the user enters a negative number, the program should display a custom error
message.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 102
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 103
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 104
6 .ii: Input a number. Check the given number is a prime or not.
Note: A prime number should be a natural number greater than 1 that has no positive divisors
other than 1 and itself.
Test Data and Output:
Enter n: 5 Output: Prime
Enter n: 6 Output: Not Prime
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 105
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 106
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 107
6. iii: Compute sine and cos series
The formula for computing the sine and cosine series for a given degree, X is
Sine Series
Cosine Series
First, you have to change the value of x to radian (radian = degrees * π/180) and then using
the result compute the sine and cosine series.
Test Data and Output:
Sin(x)
Input : 90
Output: 1
Cos(x)
Input : 30
Output : 0.86602
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 108
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 109
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 110
6 .iv: Checking a number palindrome:
Note: Number should be a positive integer having more than one digit as all the single digits
are palindromes.
Test Data and output:
Input : 2002 Input : 1234
Output: true Output: false
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 111
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 112
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 113
6 .v: Construct a pyramid of numbers.
Note: A pyramid of numbers represents the number of individuals per unit area of various
trophic areas where producers are kept at the base and the tip is occupied by top carnivores.
1. The pyramid of numbers is mostly upright. The members of successive higher
trophic levels are higher than the previous one.
2. Ahigher trophic level has fewer individuals than that of the lower trophic levels.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 114
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 115
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 116
Post-Lab|6:
6. Print the following patterns.
i. ii.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 117
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 118
2. Given a string s, consisting of alphabets and digits, find the frequency of each digit in the
given string.
Input Format : The first line contains a string, num which is the given number.
Constraints : 1 <= len(num) <= 1000; All the elements of num are made of English
alphabets and digits.
Output Format : Print ten space-separated integers in a single line denoting the
frequency of each digit from 0 to 9.
Sample Input 0 : a11472o5t6
Sample Output 0 : 0210111100
Explanation 0 : In the given string ,
1 occurs two times
2, 4, 5, 6 and 7 occur one time each.
The remaining digits 0, 3, 8 and 9
don’t occur at all.
Sample Input 1 : 1w4n88j12n1
Sample Output 1 : 0210100020
Sample Input 2 : 1v88886l256338ar0ekk
Sample Output 2 : 1112012050
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 119
3. Given a number N denoted the elements in an array. He wants to arrange the elements of an
array such that the odd positions have sorted elements in the ascending order and even positions
have sorted elements in descending order. For example, if we have 1 2 3 4 5 then the result will
be 1 5 2 4 3.
Input Format : The first line of the input contains an integer T denoting the number of test
cases. The description of each test cases follow. First line of each test case contains N number
of elements in an array. Second line contains N space separated integers A1, A2, ….., AN.
Output Format : Print array in desired order.
Constraints : 1 <= T <= 10; 1 <= N <= 1000000; 1 <= Ai <= 100000000
Sample Input :
2
8
3 6 9 10 12 5 15 18
6
1 6 8 9 11 12
Sample Output :
3 18 5 15 6 12 9 10
1 12 6 11 8 9
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 120
4.Write a C program that creates an array of 100 random integers in the range 1 to 200 and
then, using the sequential search, searches the array 100 times using
randomly generated targets in the same range. At the end of the program, display
the following statistics:
a. The number of searched completed.
b. The number of successful searches.
c. The percentage of successful searches.
d. The average number of tests per search.
To determine the average tests per search, you will need to count the number of
tests for each search. Hint : Use the comma operator to count the compares.
Program code:
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 121
Lab Session – 7
Date:
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.
Aim: Programs on 1-D array manipulation, Searching
Pre-Lab|7:
1. Given an array arr = [3, 1, 4, 1, 5], what is the value at index 2?
a. 4
b. 1
c. 3
d. 5
Ans:
2. What does it mean when we say that arrays have a fixed size?
a. The size of an array cannot be changed after declaration.
b. Arrays can only store integers and no other data types.
c. Arrays can only have one dimension.
d. Arrays can only be used in certain programming languages.
Ans:
3. Which of the following statements best explains the concept of an array index?
a. It is the value stored in an array element.
b. It is a unique identifier for each element in an array.
c. It is the total number of elements in an array.
d. It is the maximum value an element in an array can have.
Ans:
#include <stdio.h>
int main() {
int arr[] = {5, 3, 7, 2, 8};
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Answer the following MCQ’s based on the above mentioned code snippet.
MCQ 1: What is the primary purpose of the C code provided above?
a. To find the sum of all elements in the array.
b. To sort the array in ascending order.
c. To print the elements of the array.
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 122
d. To reverse the order of elements in the array.
Ans:
MCQ 2: What will be the output when you run the C code?
a. 5 3 7 2 8
b. 8 2 7 3 5
c. 2 3 5 7 8
d. It will not compile due to a syntax error.
Ans:
MCQ 3: What does the variable n represent in the code?
a. The sum of all elements in the array.
b. The number of elements in the array.
c. The largest element in the array.
d. The smallest element in the array.
Ans:
In–Lab|7:
7 .i: Find the min and max of a 1-D integer array.
Given an array X[] of size n, write a program to find the maximum and minimum element in
the array. Our goal would be to solve this problem using minimum number of comparisons.
Test Data and Output:
Input: X[] = [4, 2, 0, 8, 20, 9, 2], Output: max = 20, min = 0
Input: X[] = [-8, -3, -10, -32, -1], Output: max = -1, min = -32
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 123
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 124
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 125
7 .ii : Perform linear search on 1D array.
Linear Search is defined as a sequential search algorithm that starts at one end and goes through
each element of a list until the desired element is found, otherwise the search continues till the
end of the data set.
o Every element is considered as a potential match for the key and checked for the same.
o If any element is found equal to the key, the search is successful and the index of that
element is returned.
o If no element is found equal to the key, the search yields “No match found
Test Data and Output:
Input: arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30
Output: Key found at 3rd
place
Input: arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 60
Output: Key not found in the array
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 126
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 127
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 128
7 .iii: The reverse of a 1D integer array
The first element becomes the last, and the last element becomes the first. Similarly, the second
element is transformed into the second last, and the second last element is transformed into the
second and so on.
Minimum array size should be 5, and elements can be any integer.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 129
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 130
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 131
7 .iv: Find 2’s complement of the given binary number.
To get 2’s complement of a binary number, simply invert the given number and add 1 to the
least significant bit (LSB) of given result.
Test Data and Output:
Find 2’s complement of binary number 10101110.
Simply invert each bit of given binary number, which will be 01010001. Then add 1 to the LSB
of this result, i.e., 01010001+1=01010010 which is answer.
Find 2’s complement of binary number 10001.001.
Simply invert each bit of given binary number, which will be 01110.110 Then add 1 to the
LSB of this result, i.e., 01110.110+1=01110.111 which is answer.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 132
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 133
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 134
7 .v: Eliminate duplicate elements in an array.
Note: Delete the same numbers present in an array. The resultant array consists of unique
elements. You have to enter some duplicate numbers in your array to check the correctness of
the program.
Test Data and Output:
Enter size of the array
10
Enter Elements of the array:
1 1 2 4 3 5 6 5 7 1
Entered element are:
1 1 2 4 3 5 6 5 7 1
After deleting the duplicate element, the Array is:
1 2 4 3 5 6 7
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 135
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 136
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 137
Post–Lab|7:
1.Given a text txt[0 … n-1] and a pattern pat[0 … m-1], write a function search (char pat[ ],
char txt[ ]) that prints all the occurrences of pat[ ] in txt[ ]. You may assume that n > m.
Input :
txt[ ] = “THIS IS A TEST TEXT”
pat[ ] = “TEST”
Output :
Pattern found at index 10
Input :
txt[ ] = “AABAACAADAABAABA”
pat[ ] = “AABA”
Output :
Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 138
2. Given two strings string 1, and string 2, the task is to find the smallest sub-string in the string
1 containing all characters of string 2 efficiently.
Input : string = “this is a test string”, pattern = “tist”.
Output : Minimum window is “t stri”.
Explanation : “t stri” contains all characters of pattern.
Input : string = “indiahelloindia”, pattern = “ile”.
Output : Minimum windows are “iahel” and “elloi”.
Explanation : “iahel” and “elloi” contain all characters of pattern.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 139
3. Given an input string, write a function that returns the Run Length Encoded string for the
input string.
Input : string is “wwwwaaadexxxxxx”
Output : string is “w4a3d1e1x6”
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 140
4.Given a string of length n, print all the permutation of the given string. Repetition of
characters is allowed. Print these permutations in lexicographically shorted order.
Input : AB
Output : All permutations of AB with repetition are :
AA
AB
BA
BB
Input : ABC
Output : All permutations of ABC with repetition are:
AAA
AAB
AAC
ABA
…
…
CCB
CCC
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 141
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 142
Lab Session - 8
Date:
Objective: Explore the difference between other arrays and character arrays that can be used
as 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.
Aim: Programs on 2-D arrays, Sorting and Strings
Pre–Lab|8:
1.Correct (Syntax/Logical) the following Code.
#include <stdio.h>
/* An example function that takes two parameters ‘x’ and ‘y’.as input and returns max of two
input numbers */
int max(int x, int y) {
if (x < y)
return x;
else
return y;
}
int main (void) {
int a =10, b = 20;
//Calling above function to find max of ‘a’ and ‘b’
int m = max(a, b); printf (“m is %d”, m); return 0;}
o/p:
2.What will be the output of the following program?
#include<stdio.h>
void fun (int x) {
x = 30;}
int main (void) {
int x = 20;
fun(x);
printf (“x = %d”, x);
return 0;
}
o/p:
3. What will be the output of the following program?
#include<stdio.h>
void increment (int x) {
printf (“%d %d %d”, x++, x++, x++);
}
int main (void) {
int i = 5;
fun(x);
increment (i);
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 143
return 0;
}
o/p:
4. What will be the output of the following program?
#include<stdio.h>
void dynamic (int s, ….) {
printf (“%d”, s);
}
int main (void) {
dynamic (2, 4, 6, 8);
dynamic (3, 6, 9);
return 0;}
o/p:
In–Lab|8:
8 .i: Amatrix can only be added to another matrix if the two matrices have the same dimensions.
To add two matrices, just add the corresponding entries, and place this sum in the
corresponding position in the matrix which results.
Input elements in 3x3 matrix1:
1 2 3
4 5 6
7 8 9
Input elements in 3x3 matrix2:
9 8 7
6 5 4
3 2 1
Sum of both matrix =
10 10 10
10 10 10
10 10 10
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 144
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 145
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 146
8. ii: Matrix multiplication is a binary operation that produces a matrix from two matrices. For
matrix multiplication, the number of columns in the first matrix must be equal to the number
of rows in the second matrix. The resulting matrix, known as the matrix product, has the
number of rows of the first and the number of columns of the second matrix. The product of
matrices A and B is denoted as AB.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 147
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 148
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 149
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 150
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 151
8.iii: Sort array elements using bubble sort .
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in the wrong order. This algorithm is not suitable for large data
sets as its average and worst-case time complexity is quite high.
 Traverse from left and compare adjacent elements and the higher one is placed
at right side.
 In this way, the largest element is moved to the rightmost end at first.
 This process is then continued to find the second largest and place it and so
on until the data is sorted.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 152
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 153
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 154
8 .iv: Concatenate two strings without using built-in functions
Note: User would be asked to enter two strings and then the program would concatenate them.
For concatenation we have not used the standard library function strcat(), instead we have
written a logic to append the second string at the end of first string.
Test Data and Output:
Str1: Good Str2: Morning Output: Good Morning
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 155
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 156
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 157
8 .v: Reverse a string using built-in and without built-in string functions
 Using built-in function: The function is used for reversing a string. The reversed
string will be stored in the same string.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 158
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 159
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 160
Post–Lab|8:
1.In this challenge, you will learn simple usage of functions in C. Functions are a bunch of
statements glued together. A function is provided with zero or more
arguments, and it executed the statements on it. Based on the return type, it either
returns nothing (void) or something.
A sample syntax for a function is
return_type function_name (arg_type_1 arg_1, arg_type_2 arg_2, …) {
…
…
…
[if return_type is non void]
return something of type ‘return_type’;
}
Task : You have to write a function int max_of_four (int a, int b, int c, int d), which
reads four arguments and returns the greatest of them.
Input Format:
Input will contain four integers a, b, c, d; one in each line.
Output Format:
Print the greatest of the four integers.
Note: I/O will be automatically handled.
Sample Input
3
4
6
5
Sample Output
6
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 161
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 162
2. Count of distinct power of prime factor of N. Given a positive integer N, the task is to find
the total number of distinct power of prime factor of the given number N.
Examples:
Input : N = 216
Output : 4
Explanation:
216 can be expressed as 2 * 22 * 3 * 32
The factors satisfying the conditions are 2, 22, 3 and 32 as all of them are written as distinct
positive powers of prime factors.
Input : N = 24
Output : 3
Explanation :
24 can be expressed as 2 * 22 * 3
Approach: The idea is to find all the prime factors of N and how many times each prime factor
divides N. Suppose the prime factor ‘p’ divides N ‘z’ times, then the required distinct factors
are p, p2, … pi
To find the number of distinct primes factor for prime number p, find the minimum value of ‘I’
such that (1 + 2 + … + I) <= z.
Program Code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 163
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 164
3. Given a big string and an array of small strings, all of which are smaller in length than the
big string. The task is to create an array of Boolean, where each Boolean represents whether
the small string at that index in the array of small strings is contained in the big string.
Note : That you can’t use language-built-in string-matching methods.
Input :
bigString = “this is a big string”,
smallStrings = [“this”, “yo”, “is”, “a”, “bigger”, “string”, “kappa”]
Output : [true, false, true, true, false, true, false]
Input : bigString = “Mary goes to the shopping center every week”, smallStrings =[“to”,
“mary”, “centers”, “shop”, “shopping”, “string”, “kappa”]
Output : [true, true, false, true, true, false, false]
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 165
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 166
4. There is a series S, where the next term is the sum of previous three terms. Given the first
three terms of the series a, b, and c respectively, you have to output the nth term of the series
using recursion. Recursive method for calculating nth term is given below.
Input Format:
The first line contains a single integer.
The next line contains 3 space-separated integers, , , and .
Constraints:
1 <= n <= 20
1 < a,b,c < 100
Output Format:
Print the nth term of the series, S(n).
Sample Input: 5 123
Sample Output : 11
Explanation:
Consider the following steps
S(1) = 1
S(2) = 2
S(3) = 3
S(4) = S(3) + S(2) + S(1)
S(5) = S(4) + S(3) + S(2)
From steps 1, 2, 3, and 4, we can say S(4) = 3+2+1 =6; then using the values from
step 2, 3, 4, and 5, we get S(5) = 2+3+6 = 11. Thus we print 11 as our answer.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 167
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 168
Lab Session – 9
Date:
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
AIM: Programs on Pointers and structures, memory dereference
Pre-Lab|9:
1. What will be the output of the following program ?
#include int main ()
{
char *ptr = “2braces.com”;
printf (“%c n”, *&*ptr);
return 0;
}
o/p:
2. What will be the output of the following program?
#include <stdio.h>
struct classroom {
int students[7];
};
int main () { struct classroom cr = {2, 3, 5, 7, 11, 13};
int *ptr;
ptr = (int*)&cr;printf (“%d”, *(ptr + 4));return 0;
}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 169
3. What is a memory leak? How to avoid it?
4. What will be the output of the following program?
#include <stdio.h>
void fun (int *a)
{
a = (int *) malloc (sizeof (int));
}
int main ()
{
int *p;
fun (p);
*p = 6;
printf (“%d n”, *p);
return 0;
}
o/p:
5. Mention different Dynamic memory allocation functions in c language.
Ans:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 170
In-Lab|9:
9 .i. Sum of one – dimensional array using malloc function
To create an integer array, of size , int *arr = (int*)malloc(n * sizeof(int)), where points to the
base address of the array. When you have finished with the array, use free(arr) to deallocate
the memory.
In this challenge, create an array of size dynamically, and read the values from stdin. Iterate
the array calculating the sum of all elements. Print the sum and free the memory where the
array is stored.
Input Format
The first line contains an integer, .
The next line contains space-separated integers.
Constraints
1>=n<=1000
1<=a[i]<=1000
Output Format
Print the sum of the integers in the array.
Sample Input 0
6
16 13 7 2 1 12
Sample Output 0
51
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 171
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 172
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 173
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 174
9 .ii: Structures are a way to group several related variables into one place.
There are n students in a class having name, class, section, etc. So if we want to store all of its
information, we can create different variables for every variable like a character array to store
the name, an integer variable to store the class, and a character variable to store the
section. Make a structure contains information of each student
Each Student Record should have:
Name
Roll Number
Marks of 3 subjects
Create a structure to store student information of n students and calculate the total, average of
n students
Constraints
1<= n<= 1000
Output Format
Sample Input 0
1
Input the Roll Number of the student :784
Input the Name of the Student : James
Input the marks of Physics, Chemistry and Computer Application : 70 80 90
Sample Output 0
Roll No : 784
Name of Student : James
Marks in Physics : 70
Marks in Chemistry : 80
Marks in Computer Application : 90
Total Marks = 240
Average = 80
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 175
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 176
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 177
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 178
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 179
9 .iii. Dynamic allocation using calloc (memory allocation) allows you to allocate memory
during the runtime of the program. Using calloc, you can allocate the specified number of
blocks of memory of the specified type.
Make a structure contains information of each student. Each Student Record should have:
Name
Roll Number
Marks of 3 subjects
Create a structure to store student information of n students using calloc and display failed
students list from ‘n’ students.
Constraints
1<= n<= 1000
1<= mi <= 10
Sample Input 0 2
Input the Roll Number of the student: 784
Input the Name of the Student: James
Input the marks of Physics, Chemistry and Computer Application: 70 80 90
Input the Roll Number of the student: 785
Input the Name of the Student: John
Input the marks of Physics, Chemistry and Computer Application : 25 52 46
Sample Output 0
Roll No : 784
Name of Student : James
Marks in Physics : 70
Marks in Chemistry : 80
Marks in Computer Application : 90
Total Marks = 240
Average = 80
Roll No: 785
Name of Student: John
Marks in Physics: 25
Marks in Chemistry: 52
Marks in Computer Application: 46
Total Marks = 123
Average = 41
NO.OF.STUDENTS FAILED=1
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 180
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 181
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 182
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 183
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 184
9 .iv: The main function in c can be created with two methods: first with no parameters (void) and
second with two parameters. The parameters are argc and argv,argc denotes the number of
arguments given argv[] is a pointer array pointing to each parameter passed to the program. int
main(int argc, char* argv[])
where argc is an integer and the argv is a list of command line arguments.
Write a Program to read student name and marks from the command line and display the student
details along with the total.
Sample Input
$ ./a.out John 34 56 78
Sample output
----Following Are The Command Line Arguments Passed----
Name= john
Physics= 34
Chemistry=56
Computer Applications=78
Total=168
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 185
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 186
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 187
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 188
Post–Lab|9:
1. Write a menu driven program in C to create a structure employee having fields - empid,
emp name, salary. Accept the details of 'n' Employees from user and perform the following
operations using function.
- Search by Emp-Id
- Display All
- Display Names of Employee having Salary > 10000.
Sample Input and output
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 189
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 190
2. Write a 'C' Program to calculate sum of non-diagonal elements of m X n matrix using
dynamic memory allocation.
Sample Input and output
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 191
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 192
3. Write a C program to create a student structure having fields stud_name and address. Accept
the details of 'n' students, rearrange the data in alphabetical order of student name and display
it.
Sample Input and Output
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 193
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 194
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 195
4. Write a function that receives two integers and passes back the greatest common divisor and
the least common multiplier. The calculation of the greatest common divisor can be done using
Euclid’s method of repetitively dividing one number by the other and using the remainder
(modulo). When the remainder is zero, the greatest common divisor has been found. For
example, the greatest common divisor of 247 and 39 is 13, as given in the table. Once you
know the greatest common divisor (gcd), the least common multiplier (lcm) is determined by
the equation as given below(Use pointers).
lcm = (num 1 * num 2) / gcd
Test case :
Input : num 1 : 60 num 2 : 45
Output : gcd : 15 lcm : (60 * 45) / 15 = 180
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 196
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 197
5. Create an user – defined datatype using enumeration.
enum tagname {value1, value2, value3,....};
(or)
enum tagname {identifier list..};
enum is a keyword. It is a user defined data type.
tag name is our own created variable.
value1, value2, value3,.... are create set of enum values.
Program Code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 198
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 199
Lab Session – 10
Date:
Objective: Experiment with C Structures, Unions, bit fields and self-referential structures
(Singly linked lists) and nested structures.
Aim: Programs on Bit-fields , linked lists
Pre–Lab|10:
1. What is the functionality of the following piece of code?
public int function(int data)
{
Node temp = head;
int var = 0;
while(temp != null)
{
if(temp.getData() == data)
{
return var;
}
var = var+1;
temp = temp.getNext();
}
return Integer.MIN_VALUE;
}
o/p:
2. What does the following function do for a given Linked List with first node as head?
void fun1(struct node* head){
if(head == NULL)
return;
fun1(head->next);
printf("%d ", head->data);}
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 200
3. What will be the output of the following program?
#include <stdio.h>
int main () {
struct node {
int a, b, c;
};
struct node num = {3, 5, 6};
struct node *ptr = &num;
printf (“%d n”, ((int*)ptr + 1 + (3-2)));
return 0;
}
o/p:
4. For what minimum value of x in a 32-bit Linux OS would make the size of s equal to 8
bytes?
struct temp
{
int a : 13;
int b : 8;
int c : x;
}s;
a) 4
b) 8
c) 12
d) 32
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 201
5. How do you insert an element at the beginning of the List?
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 202
In–Lab|10:
10 .i. Given a pointer to the head node of a linked list, print each node's data element, one per
line. If the head pointer is null (indicating the list is empty), there is nothing to print.
Input Format
The first line of input contains n , the number of elements in the linked list.
The next n lines contain one element each, the data values for each node.
Constraints
1<= n<= 1000
1<= list[i]<= 1000,where list[i] is the ith
element of linklist
Sample Input
2
16
13
Sample Output
16
13
Explanation
There are two elements in the linked list. They are represented as 16 -> 13 -> NULL. So, the
print Linked List function should print 16 and 13 each on a new line.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 203
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 204
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 205
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 206
10. ii: Structure uses a separate location to store the entities whereas union uses the same
location to save all the entities.
Create an employee structure with the following details
Name
Class
ID
Create a person union with the following details
Age
Name
Department
Salary
Declare the structure for employee and union for person. Display employee information and
person information along with size of employee record and size of person record.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 207
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 208
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 209
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 210
10. iii: Abit field is a data structure that allows the programmer to allocate memory to structures
and unions in bits in order to utilize computer memory in an efficient manner.
Create a bitfield
struct
{
data_type member_name : width_of_bit-field;
};
data_type: It is an integer type that determines the bit-field value which is to be interpreted.
The type may be int, signed int, or unsigned int.member_name: The member name is the name
of the bit field.width_of_bit-field: The number of bits in the bit-field. The width must be less
than or equal to the bit width of the specified type.Demonstrate shift operations (LEFT
SHIFT,RIGHT SHIFT) using bit fields
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 211
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 212
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 213
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 214
10 .iv: Write a definition of structure type Employee, Where a value of type Employee has
three fields:
(1) a constant null-terminated string called name
(2) a value of type double called salary
(3) a constant null-terminated string called office.
Write statements that create an Employee variables called John and another Employee
variable Abraham, and copy all of the information from variable john into variable Abraham.
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 215
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 216
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 217
Post-Lab|10:
1. Given a pointer to the head node of a linked list, the task is to reverse the linked list. We
need to reverse the list by changing the links between nodes.
Examples:
Input: Head of following linked list
1->2->3->4->NULL
Output: Linked list should be changed to,
4->3->2->1->NULL
Input: Head of following linked list
1->2->3->4->5->NULL
Output: Linked list should be changed to,
5->4->3->2->1->NULL
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 218
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 219
2. Write a program in C to create a singly linked list of n nodes and count the number of nodes.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 220
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 221
3. Write a program in C to insert a new node at the beginning of a Singly Linked List.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 222
Marks Secured:_____ Out of _____
Evaluator Signature
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 223
Lab Session - 11
Date:
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
AIM: Programs on Functions, call by value, scope and extent,
Pre–Lab|11:
1. Correct (Syntax/Logical) the following Code.
#include <stdio.h>
/* An example function that takes two parameters ‘x’ and ‘y’.
as input and returns max of two input numbers */
int max(int x, int y) {
if (x < y)
return x;
else
return y;
}
int main (void) {
int a =10, b = 20;
//Calling above function to find max of ‘a’ and ‘b’
int m = max(a, b);
printf (“m is %d”, m);
return 0;
}
o/p:
2. What is the value of j at the end of the execution of the following C program?
#include<stdio.h>
int incr (int i) {
static int count = 0;
count = count + i;
return (count);
}
void main() {
int i, j;
for (i = 0; i <= 4; i++)
j = incr (i);
o/p:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 224
3. Choose correct statements about C Language Pass By Value.
a) Pass By Value copies the variable value in one more memory location
b) Pass By Value does not use Pointers
c) Pass By Value protects your source or original variables from changes in outside functions
or called functions
d) All the above.
4. Pick the best statement for the following program.
int foo (int a) {
printf (“%d”, a);
return 0;}
int main () {
foo;
return 0;
}
o/p:
In-Lab|11:
11. i: Given two integers n and r. In how many ways can r items be chosen from n items?
Input Format
The first line contains the number of test cases T. Each of the next lines contains two integers n
and r .
Constraints:
1<=T<=105
1<=n<=109
0<=r<=n
Output Format
Output T lines, containing the required answer for the corresponding test case.
Sample Input
4
2 1
4 0
5 2
10 3
Sample Output
2
1
10
120
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 225
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 226
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 227
Program Code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 228
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 229
11. ii: You are given two strings a and b separated by a new line. Each string will consist of
lower case Latin characters ('a'-'z'). Write a C function to find the length of a string a and b
respectively(with and without built-in functions)
Output Format
In the first line print two space-separated integers, representing the length of a
and b respectively.
Sample Input
ai&ds of velagapudi ramakrishna siddhartha engineering college
cse
Sample Output
62
3
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 230
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 231
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 232
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 233
11. iii: Given a matrix of size N x M. Print transpose of the matrix.
Input Format
First line of input contains N, M - the size of the matrix. Its followed by N lines each containing
M integers - elements of the matrix.
Constraints
1 <= N, M <= 100
-109
<= ar[i] <= 109
Output Format
Print the transposed matrix.
Sample Input 0
2 2
5 -1
19 8
Sample Output 0
5 19
-1 8
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 234
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 235
Flowchart:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 236
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 237
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 238
11. iv: Write a C function to demonstrate numerical integration of differential equations using
Euler’s method
Explanation:
Euler Method is a Numerical technique used to solve ordinary differential equations. In
Euler’s Method, to solve the ordinary differential equation dy/dx = x+y. We ask the user to
give us the initial values for xi,yi and h .The value of slope at different points is calculated
using the function ‘fun’.
Sample Input
Enter xi 0
Enter yi 1
Enter h 0.1
Enter xn: 1
Sample Output
x y
0.100 1.100
0.200 1.220
0.300 1.362
0.400 1.528
0.500 1.721
0.600 1.943
0.700 2.197
0.800 2.487
0.900 2.816
1.000 3.187
Algorithm:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 239
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 240
Flowchart
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 241
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 242
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 243
Post-Lab|11:
1.Given an array, X, of N integers, calculate and print the respective mean, median. If your
array contains more than one modal value, choose the numerically smallest one.
Example :
N=6
X=[1,2,3,4,5]
The mean is 20/6=3.3
The median is 3+4/2=3.5
Input Format:
The first line contains an integer,N , the number of elements in the array.
The second line contains ,N ,space-separated integers that describe the array's elements.
Constraints
10<=N<=2500
0<=x[i]<=105, where x[i] is the ith element of the array.
Output Format
Print 3 lines of output in the following order:
Print the mean on the first line to a scale of ,1,decimal place (i.e.,12.3).
Print the median on a new line, to a scale of,1, decimal place (i.e., 12.3).
Sample Input
10
64630 11735 14216 99233 14470 4978 73429 38120 51135 67060
Sample Output
43900.6
44627.5
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 244
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 245
2. Count of distinct power of prime factor of N. Given a positive integer N, the task is
to find the total number of distinct power of prime factor of the given number N.
Examples:
Input : N = 216
Output : 4
Explanation:
216 can be expressed as 2 * 22
* 3 * 32
The factors satisfying the conditions are 2, 22
, 3 and 32
as all of them are written as
distinct positive powers of prime factors.
Input : N = 24
Output : 3
Explanation :
24 can be expressed as 2 * 22
* 3
Approach : The idea is to find all the prime factors of N and how many times each
prime factor divides N.
Suppose the prime factor ‘p’ divides N ‘z’ times, then the required distinct factors
are p, p2
, … pi .
To find the number of distinct primes factor for prime number p, find the
minimum value of ‘I’ such that (1 + 2 + … + I) <= z.
Program code:
VR23 Registration No:
23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 246
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech
Computer programming laboratory manual for b.tech

More Related Content

Similar to Computer programming laboratory manual for b.tech

I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
Jay Patel
 
Comp 220 ilab 7 of 7
Comp 220 ilab 7 of 7Comp 220 ilab 7 of 7
Comp 220 ilab 7 of 7
ashhadiqbal
 
Assignment 1 for 2nd sem
Assignment 1 for 2nd semAssignment 1 for 2nd sem
Assignment 1 for 2nd sem
home
 

Similar to Computer programming laboratory manual for b.tech (20)

Gsp 125 Education Organization -- snaptutorial.com
Gsp 125   Education Organization -- snaptutorial.comGsp 125   Education Organization -- snaptutorial.com
Gsp 125 Education Organization -- snaptutorial.com
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
Cse cpl manual-2016
Cse cpl manual-2016Cse cpl manual-2016
Cse cpl manual-2016
 
GSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.comGSP 125 Exceptional Education - snaptutorial.com
GSP 125 Exceptional Education - snaptutorial.com
 
GSP 125 Education Specialist / snaptutorial.com
  GSP 125 Education Specialist / snaptutorial.com  GSP 125 Education Specialist / snaptutorial.com
GSP 125 Education Specialist / snaptutorial.com
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
GSP 125 Final Exam Guide
GSP 125 Final Exam GuideGSP 125 Final Exam Guide
GSP 125 Final Exam Guide
 
vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdf
 
Gsp 125 Massive Success / snaptutorial.com
Gsp 125  Massive Success / snaptutorial.comGsp 125  Massive Success / snaptutorial.com
Gsp 125 Massive Success / snaptutorial.com
 
Gsp 125 Enthusiastic Study / snaptutorial.com
Gsp 125 Enthusiastic Study / snaptutorial.comGsp 125 Enthusiastic Study / snaptutorial.com
Gsp 125 Enthusiastic Study / snaptutorial.com
 
GSP 125 Technology levels--snaptutorial.com
GSP 125 Technology levels--snaptutorial.comGSP 125 Technology levels--snaptutorial.com
GSP 125 Technology levels--snaptutorial.com
 
GSP 125 Enhance teaching - snaptutorial.com
GSP 125   Enhance teaching - snaptutorial.comGSP 125   Enhance teaching - snaptutorial.com
GSP 125 Enhance teaching - snaptutorial.com
 
Question Bank DS
Question Bank DSQuestion Bank DS
Question Bank DS
 
Comp 220 ilab 7 of 7
Comp 220 ilab 7 of 7Comp 220 ilab 7 of 7
Comp 220 ilab 7 of 7
 
Assignment 1 for 2nd sem
Assignment 1 for 2nd semAssignment 1 for 2nd sem
Assignment 1 for 2nd sem
 
GSP 125 Enhance teaching/tutorialrank.com
 GSP 125 Enhance teaching/tutorialrank.com GSP 125 Enhance teaching/tutorialrank.com
GSP 125 Enhance teaching/tutorialrank.com
 
GSP 125 Effective Communication/tutorialrank.com
 GSP 125 Effective Communication/tutorialrank.com GSP 125 Effective Communication/tutorialrank.com
GSP 125 Effective Communication/tutorialrank.com
 

Recently uploaded

Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
Kamal Acharya
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdf
AbrahamGadissa
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
Kamal Acharya
 
School management system project report.pdf
School management system project report.pdfSchool management system project report.pdf
School management system project report.pdf
Kamal Acharya
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 

Recently uploaded (20)

Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
Digital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdfDigital Signal Processing Lecture notes n.pdf
Digital Signal Processing Lecture notes n.pdf
 
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 
Introduction to Casting Processes in Manufacturing
Introduction to Casting Processes in ManufacturingIntroduction to Casting Processes in Manufacturing
Introduction to Casting Processes in Manufacturing
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdfA CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
A CASE STUDY ON ONLINE TICKET BOOKING SYSTEM PROJECT.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
School management system project report.pdf
School management system project report.pdfSchool management system project report.pdf
School management system project report.pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Electrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission lineElectrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission line
 
2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge2024 DevOps Pro Europe - Growing at the edge
2024 DevOps Pro Europe - Growing at the edge
 

Computer programming laboratory manual for b.tech

  • 1. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 1 LABORATORY RECORD 23ES1152 COMPUTER PROGRAMMING LAB Department of Computer Science & Engineering VELAGAPUDI RAMAKRISHNA SIDDHARTHA ENGINEERING COLLEGE KANURU, VIJAYAWADA-520007, A.P.
  • 2. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 2 COMPUTER PROGRAMMING LAB 23ES1152 STUDENT NAME: REGISTERED NUMBER: ACADEMIC YEAR: YEAR & SEMESTER: SECTION: No. of. Experiments Recorded: ……………………. Marks Awarded : …………………….. Signature of the Faculty Signature of the HOD
  • 3. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 3
  • 4. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 4 INDEX S.No Date Name of The Experiment Page No Marks Signature 1.i 1.ii 1.iii Basic Linux environment and its editors like Vi, Vim & Emacs. Exposure to Turbo C, gcc Writing simple programs using printf(), scanf() 2.i 2.ii 2.iii Sum and average of 3 numbers Conversion of Fahrenheit to Celsius and vice versa Simple interest calculation 3.i 3.ii 3.iii 3.iv Finding the square root of a given number Finding compound interest Area of a triangle using heron’s formulae Distance travelled by an object 4.i 4.ii 4.iii 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) Find the maximum of three numbers using conditional operator Take marks of 5 subjects in integers, and find the total, average in float
  • 5. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 5 S.No Date Name of The Experiment Page No Marks Signature 5.i 5.ii 5.iii 5.iv 5.5 To find the max and min of four numbers using if-else. To generate electricity bill. Find the roots of the quadratic equation. To simulate a calculator using switch case. To find the given year is a leap year or not. 6.i 6.ii 6.iii 6.iv 6.v Find the factorial of given number using any loop. Find the given number is a prime or not. Compute sine and cos series Checking a number palindrome Construct a pyramid of numbers. 7.i 7.ii 7.iii 7.iv 7.v Find the min and max of a 1-D integer array. Perform linear search on1D array. The reverse of a 1D integer array. Find 2’s complement of the given binary number. Eliminate duplicate elements in an array.
  • 6. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 6 S.No Date Name of The Experiment Page No Marks Signature 8.i 8.ii 8.iii 8.iv Addition of two matrices. Multiplication two matrices. Sort array elements using bubble sort. Concatenate two strings without built-in functions. Reverse a string using built-in and without built-in string functions 9.i 9.ii 9.iii 9.iv 9.v To find the sum of a 1D array using malloc() . To find the total, average of n students using structures. Enter n students data using calloc() and display failed students list. Read student name and marks from the command line and display the student details along with the total. To implement realloc() 10.i 10.ii 10.iii 10.iv Create and display a singly linked list using self-referential structure. Demonstrate the differences between structures and unions using a C program. Write a C program to shift/rotate using bit fields. Write a C program to copy one structure variable to another structure of the same type
  • 7. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 7 S.No Date Name of The Experiment Page No Marks Signature 11.i 11.ii 11.iii 11.iv To calculate NCR value. To find the length of a string. To transpose of a matrix. To demonstrate numerical integration of differential equations using Euler’s Method. 12.i 12.ii 12.iii 12.iv 12.v To generate Fibonacci series. To find the lcm of two numbers. To find the factorial of a number. To implement Ackermann function using recursion. To find the sum of series. 13.i 13.ii 13.iii 13.iv To swap two numbers using call by reference. To Demonstrate Dangling pointer problem using a C program. To copy one string into another using pointer. To find no of lowercase, uppercase, digits and other characters using pointers.
  • 8. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 8 S.NO Date Name of The Experiment Page No Marks Signature 14.i 14.ii 14.iii 14.iv 14.v 14.vi To write and read text into a file. To write and read text into a binary file using fread() and fwrite(). To Copy the contents of one file to another file. To merge two files into the third file using command-line arguments. Find no. of lines, words and characters in a file To print last n characters of a given file
  • 9. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 9 COMPUTER PROGRAMMING LAB (Common to All branches of Engineering) __________________________________________________________________________________ Course Objectives: The course aims to give students hands – on experience and train them on the concepts of the C- programming language. Course Outcomes: CO1: Read, understand, and trace the execution of programs written in C language. CO2: Select the right control structure for solving the problem. CO3: Develop C programs which utilize memory efficiently using programming constructs like pointers. CO4: Develop, Debug and Execute programs to demonstrate the applications of arrays, functions, basic concepts of pointers in C. UNIT I WEEK 1: Objective: Getting familiar with the programming environment on the computer and writing the first program. Suggested Experiments/Activities: Tutorial 1: Problem-solving using Computers. Lab 1: Familiarization with programming environment i) Basic Linux environment and its editors like Vi, Vim & Emacs etc. ii) Exposure to Turbo C, gcc iii) Writing simple programs using printf(), scanf() 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 2: Converting algorithms/flow charts into C Source code. Developing the algorithms/flowcharts for the following sample programs
  • 10. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 10 i) Sum and average of 3 numbers ii) Conversion of Fahrenheit to Celsius and vice versa iii) Simple interest calculation 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. i) Finding the square root of a given number ii) Finding compound interest iii) Area of a triangle using heron’s formulae iv) Distance travelled by an object UNIT II 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: Tutorial 4: Operators and the precedence and as associativity: Lab 4: 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) 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
  • 11. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 11 WEEK 5: Objective: Explore the full scope of different variants of “if construct” namely if- else, null- else, 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. ii) Write a C program to generate electricity bill. iii) Find the roots of the quadratic equation. 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. WEEK 6: Objective: Explore the full scope of iterative constructs namely while loop, do- while loop and or loop in addition to structured jump constructs like break and continue including when each of these statements is more appropriate to use. Suggested Experiments/Activities: Tutorial 6: Loops, while and for loops Lab 6: Iterative problems e.g., the sum of series 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. UNIT III 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.
  • 12. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 12 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. WEEK 8: Objective: Explore the difference between other arrays and character arrays that can be used as 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. Lab 8: Matrix problems, String operations, Bubble sort i) Addition of two matrices ii) Multiplication two matrices iii) Sort array elements using bubble sort iv) Concatenate two strings without built-in functions v) Reverse a string using built-in and without built-in string functions UNIT IV WEEK 9: Objective: Explore pointers to manage a dynamic array of integers, including memory allocation &amp; 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()
  • 13. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 13 WEEK 10: Objective: Experiment with C Structures, Unions, bit fields and self-referential structures (Singly linked lists) and nested structures Suggested Experiments/Activities: Tutorial 10: Bitfields, Self-Referential Structures, Linked lists Lab 10: 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. UNIT V 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 Euler’s method 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
  • 14. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 14 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. 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. WEEK 14: Objective: To understand data files and file handling with various file I/O functions. Explore the differences between text and binary files. Suggested Experiments/Activities: 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.
  • 15. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 15 Textbooks: 1. Ajay Mittal, Programming in C: A practical approach, Pearson. 2. Byron Gottfried, Schaum&#39; s Outline of Programming with C, McGraw Hill Reference Books: 1. Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice- Hall of India 2. C Programming, A Problem-Solving Approach, Forouzan, Gilberg, Prasad, CENGAGE -----------------------------------*****-------------------------------------
  • 16. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 16 Lab Session - 1 Date: Objective: Getting familiar with the programming environment on the computer and writing the first program. AIM: Familiarization with programming environment. Pre-Lab|1: 1. Which of the following is the output of the program when the input values are 1 for 'a' and 2 for 'b' in the given pseudocode? A. 1 B. 2 C. Runtime error D. Compile time error 2. What is the output of this program? #include <stdio.h> int main() { printf("variable! %d", x); return 0; } A. "variable! x" B. "variable! followed by a junk value" C. Compile time error D. "variable!" 3. Which of the following is not a data type? A. _option B. amount C. sales_amount D. salesAmount E. $salesAmount
  • 17. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 17 4. One of the most common errors for new programmers is forgetting to use the address operator for variables in a scanf statement. What is that? A. The address modifier (@) B. The ampersand (&) C. The caret (^) D. The percent (%) E. The pound sign (#) 5. i. Which of the following is not a character constant in C? ii. Which of the following is not an integer constant in C? I. II. A. ‘C’ A.-320 B. ‘bb’ B.+45 C. “C” C.-31.80 D. ‘?’ D.1456 E. ‘ ‘ E.2,456
  • 18. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 18 In–Lab|1: 1. i: Basic Linux environment and its editors like Vi, Vim & Emacs etc.
  • 19. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 19 1. ii: Exposure to Turbo C, gcc.
  • 20. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 20 1. iii: Writing simple programs using printf(), scanf(). Program code:
  • 21. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 21
  • 22. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 22 Post–Lab|1: 1. Write a C program using printf statements to print the three first letters of your first name in big blocks. This program does not read anything from the keyboard. Each letter is formed using seven rows and five columns using the letter itself. For example, the letter B is formed using 17B’s as shown below as part of the initials BEF. BBB EEEEE FFFFF B B E F B B E F BBB EEE FFF B B E F B B E F BBB EEEEE F Program code:
  • 23. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 23 2. Write a program that reads nine integers and prints those three in a line separated by commas as shown below. Input: 10 31 2 73 24 65 6 87 18 Output: 10, 31, 2 73, 24, 65 6, 87,18 Program code:
  • 24. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 24 3. Write a program that reads a character, an integer, and a floating-point number. It then prints the character, first using a character format specification (%c) and then using an integer specification (%d). After printing the character, it prints the integer and floating-point numbers on separate lines. Program code: Sample Input: c 23 15. 234 Sample Output: The character is c. The integer number is 23. The real number is 15.234.
  • 25. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 25 4. Write a program that prompts the user to enter three numbers and then prints them vertically (each on one line), first forward and then reversed (the last one first), as shown in the following design. Please enter three numbers: 15 35 72 Your numbers forward: 15 35 72 Program code: Marks Secured:_____ Out of _____ Evaluator Signature Your numbers reversed: 72 35 15
  • 26. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 26 Lab Session – 2 Date: 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. AIM: Converting algorithms/flow charts into C Source code Pre–Lab|2: 1. What will be the outputs of the following program? # include <stdio.h> void main () { int a = 1, b = 2; a += b -= a; printf (“%d %d”, a, b); } o/p: 2. Which of the following is not a valid declaration in C. 1. short int x; 2. signed short x; 3. short x; 4. unsigned short x; 2. What will be the output of the following program? #include <stdio.h> int main (){ int x; char y; x = -1; y = -2; printf(“x is %d and y is %d”, x, y); } o/p:
  • 27. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 27 3. Predict the outputs of the following programs. #include <stdio.h> void main () { char a = ‘012’; printf (“%d, a); } #include <stdio.h> void main () { char c = 125; c = c + 1 0; printf (“%d”, c); } o/p: o/p: 4. If no data type is given to a variable, the compiler automatically converts it to the int data type. What will be the outputs for 16-bit and 32-bit compilers? #include <stdio.h> void main() { signed int a; // Explicitly specifying 'int' data type for clarity signed int b; // Explicitly specifying 'int' data type for clarity // The size of 'a' and 'b' is equal to the size of 'int' printf("The size of a is %dn", sizeof(a)); printf("The size of b is %d", sizeof(b)); } o/p:
  • 28. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 28 In-Lab|2: 2. i: Declare three variables of integer data type. The user has to input three valid numbers. Display the sum and average of the user-entered numbers. The approach is to take three numbers and find their sum and average using the formula given below: Sum: a + b + c Average: (a + b + c) / 3 Where 'a,' 'b,' and 'c' are the three numbers. Sample Input: Enter 3 Values: 10 20 30 Sample Output: Sum: 60 Average: 20" Algorithm:
  • 29. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 29 Flowchart:
  • 30. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 30 Program code:
  • 31. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 31 2. ii: Take input for the temperature in Fahrenheit and output the Celsius equivalent, and vice versa. Input two numbers. The first is for a Celsius value, and the second is for a Fahrenheit value. For the Celsius value input, convert it to Fahrenheit using the formula F = C × 9/5 + 32 for conversion. In case of decimals, display up to one decimal place. For the Fahrenheit value input, convert it to Celsius using the formula C = (F - 32) × 5/9 for conversion. In case of decimals, display up to one decimal place. Sample Input: 0 100 Sample Output: 32 37.7" Algorithm:
  • 32. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 32 Flowchart:
  • 33. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 33 Program code:
  • 34. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 34 2. iii: You can calculate simple interest by providing the principal amount, rate of interest, and time or periods as provided by user input. Simple interest can be calculated using the formula below: Simple Interest = (Principal * Rate * Time) / 100 Where: Principal: The principal is the initial amount borrowed (loaned) from the bank or invested, denoted as 'P.' Rate: The rate is the interest rate at which the principal amount is given to someone for a certain period. The interest rate can be 5%, 10%, or 13%, etc., and is denoted as 'R.' Time: Time is the duration for which the principal amount is given to someone, denoted as 'T.' Constraints: 1 <= Principal <= 10000 1 <= Rate <= 10 1 <= Time <= 30 Sample Input: 100 3 10 Sample Output: 30 Algorithm:
  • 35. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 35 Flowchart:
  • 36. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 36 Program code:
  • 37. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 37 Post-Lab|2: 1. Take two numbers of type int and two numbers of type float as input and output their sum. Declare four variables: two of type int and two of type float. Read two lines of input from stdin (following the sequence provided in the 'Input Format' section below) and initialize your variables. Use the + and - operators to perform the following operations: Print the sum and difference of the two int variables on a new line. Print the sum and difference of the two float variables, rounded to one decimal place, on a new line. Input Format: The first line contains two integers. The second line contains two floating-point numbers. Constraints: 1 <= integer variables <= 10^4; 1 <= float variables <= 10^4 Output Format: Print the sum and difference of both integers separated by a space on the first line and the sum and difference of both floats (rounded to 1 decimal place) separated by a space on the second line. All outputs must be left-justified. Sample Input: 10 4 4.0 2.0 Sample Output: 14 6 6.0 2.0 Test the output for the following input: Sample Input:  10 4 4.0 -2.0 Sample Output: The program should display an error message if a character is given instead of numbers. Program code:
  • 38. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 38
  • 39. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 39 2. Calculate a student’s average score for a course with 4 quizzes, 2 midterms, and a final. The quizzes are weighted at 30%, the midterms at 40%, and the final at 30%. Sample Input: Enter the score for the first quiz: 98 Enter the score for the second quiz: 89 Enter the score for the third quiz: 78 Enter the score for the fourth quiz: 79 Enter the score for the first midterm: 90 Enter the score for the second midterm: 100 Enter the score for the final: 92 Sample Output: First Quiz: 98 Second Quiz: 89 Third Quiz: 78 Fourth Quiz: 79 Quiz Total: 344 First Midterm: 90 Second Midterm: 100 Total Midterms: 190 Final: 92 Quiz: 25.8% Midterm: 38.0% Final: 27.6% Total: 91.4% Explanation: Quiz percentage = 344 * 30/400 = 25.8%, Midterm = 190 * 40/200 = 38.0%, and Final = 92 * 30/100 = 27.6%. Total = 25.8% + 38.0% + 27.6% = 91.4% Program code:
  • 40. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 40
  • 41. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 41 3. There are three types of fruits: T1, T2, and T3 in a shop. The number of fruits of type T1, T2, and T3 are Cnt1, Cnt2, and Cnt3, respectively, and each fruit costs Cost1, Cost2, and Cost3, respectively. You want to obtain a total of S energy by buying some of the fruits while spending as little as possible. Find the minimum amount you need to spend and print '-1' if the answer does not exist. Input Format: First line: S represents the total amount of energy. Second line: Three space- separated integers Cnt1, Cnt2, and Cnt3. Third line: Three space-separated integers Cost1, Cost2, and Cost3. Output Format: Print the answer. Sample Input Sample Output Explanation: There are two ways to achieve a total energy of 10: 1. Buying two T1 and two T2, which costs 20. 2. Buying one T1, one T2, and one T3, which costs 30. So, the minimum cost is 20. Program code:
  • 42. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 42 Marks Secured:_____ Out of _____ Evaluator Signature
  • 43. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 43 Lab Session – 3 Date: 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. AIM: Simple computational problems using arithmetic expressions. Pre-lab|3: 1. What will be the output of the following program? #include <stdio.h> int main () { int i = 0; for (i = 0; i < 20; i++) { switch (i) { case 0 : i += 5; case 1 : i += 2; case 5 : i += 5; default : i += 4; break; } printf (“%d”, i); }return 0; } a. 5 10 15 20 b. 7 12 17 22 c.16 21 d. Compilation Error
  • 44. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 44 2. What will be the output of the following program? #include <stdio.h> void main () { char c = ‘a’; switch (c) { case ‘a’ : case ‘e’ : case ‘i’ : case ‘o’ : case ‘u’ : printf (“Vowel character”);break; default :printf (“Not a Vowel character”);break; } } o/p: 3. What will be the output of the following program? #include <stdio.h> int main () { int x = 3; if (x ==2); x = 0; if (x == 3) x++; else x+= 2; printf (“x = %d”, x); return 0; } a. x = 4 b. x = 2 c. Compiler Error d. x = 0
  • 45. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 45 4. What will be the output of the following program? #include <stdio.h> #define EVEN 0 #define ODD 1 int main () { int i = 3; switch (i & 1) { case EVEN : printf (“Even”); break; case ODD : printf (“Odd”); break; default : printf (“Default”); }return 0; } o/p: 5. What will be the output of the following program? #include <stdio.h> int main () { int a = 100; if (a == 10) printf (“Value of a is 10 n”); else if (a == 20) { printf (“Value of a is 20 n”); else if (a == 30) { printf (“Value of a is 30 n”); else printf (“None of the values is matching n”); printf (“Exact value of a is : %d n”, a); return 0;} o/p:
  • 46. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 46 In-Lab|3: 3 .i: Watson likes to challenge Sherlock's math ability. He will provide a integer from a set of integers Sherlock must determine the square root of that number Constraints 1<=n<=109 Run Time Test cases: Method 1: (Using sqrt() Function) Test case 1: In this case, we enter the value “25” as input to find the square root. Enter number: 25 Number is 25 and its square root is: 5 Test case 2: In this case, we enter the value “64” as input to find the square root. Enter number: 64 Number is 64 and its square root is: 8 Method 2: (Using pow() Function) Run Time Test cases Test case 1: In this case, we enter the value “25” as input to find the square root. Enter number: 25 Number is 25.00 and its square root is: 5.00 Test case 2: In this case, we enter the value “16” as input to find the square root. Enter number: 16 Number is 16.00 and its square root is: 4.00 Algorithm:
  • 47. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 47
  • 48. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 48 Flowchart:
  • 49. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 49 Program code:
  • 50. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 50 3 .ii: Compound interest is the addition of interest to the principal sum of a loan or deposit, or in other words, interest on interest. It is the result of reinvesting interest, rather than paying it out, so that interest in the next period is then earned on the principal sum plus previously- accumulated interest. Compound interest is standard in finance and economics. Compound interest may be contrasted with simple interest, where interest is not added to the principal, so there is no compounding. Compound Interest formula: Formula to calculate compound interest annually is given by: Amount= P(1 + R/100)t Compound Interest = Amount – P Where, P is principal amount R is the rate and T is the time span Algorithm:
  • 51. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 51 Flowchart:
  • 52. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 52 Program code:
  • 53. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 53 3 . iii: To calculate the area of a triangle using Heron's formula, we need the lengths of all three sides of the triangle. First, take the lengths of the three sides of the triangle as input from the user using the scanf() function and store them in three floating-point variables: 'a,' 'b,' and 'c.' Calculate the semi-perimeter of the triangle as s = (a + b + c) / 2. The area of the triangle is given by the formula: Area = √(s(s-a)(s-b)(s-c)). Calculate the area of the triangle using Heron's formula as described above and store the result in a floating-point variable named 'area.' Display the area of the triangle on the screen using the printf function. Algorithm:
  • 54. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 54 Flowchart:
  • 55. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 55 Program code:
  • 56. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 56 3 .iv: When an object moves in a straight line at a constant speed, we can calculate its distance if we know the object's speedand the time it takes. This equationillustrates the relationshipbetween speed, distance traveled, and time taken: Distance = speed * time To find the distance traveled at regular intervals of time, given the values of 's' (speed) and 't' (time), the program should offer users the flexibility to choose their own time and speed. Constraints:  Speed must be provided in kilometers per hour.  Time must be provided in hours.  Distance must be measured in kilometers. Algorithm:
  • 57. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 57 Flowchart:
  • 58. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 58 Program code:
  • 59. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 59 Post –Lab|3: 1. Write a program that determines a student’s grade. It reads three test scores m1, m2, and m3 (between 0 and 100) and calculates the student’s grade based on the following rules: a. If the average score is 90% or higher, the grade is A. b. If the average score is 70% or higher but less than 90%, it checks the third score. If the third score is higher than 90%, the grade is A; otherwise, the grade is B. c. If the average score is 50% or higher but less than 70%, it checks the average of the second and third scores. If the average of the two is greater than 70%, the grade is C; otherwise, it is D. d. If the average score is less than 50%, then the grade is F. Test case: Input: Test score 1: 60 Test score 2: 70 Test score 3: 75 Output: The grade is C. Explanation: Average score: (60 + 70 + 75) / 3 = 68.33 (Check condition c). Average of the last two test scores = (70 + 75) / 2 = 72.5, which is greater than 70, so the grade is C. Program code:
  • 60. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 60 2. Write a program to compute the real roots of a quadratic equation (ax^2 + bx + c = 0). Your program should prompt the user to enter the constants (a, b, c) and then display the roots based on the following rules: a. If both 'a' and 'b' are zero, there is no solution. b. If 'a' is zero, there is only one root (-c/b). c. If the discriminant (b^2 - 4ac) is negative, there are no real roots. d. For all other combinations, there are two roots. Test your program with the data in the table: A B C 3 8 5 -6 7 8 0 9 -10 Sample Input: a: 3 b: 8 c: 5 Sample Output: There are two roots. Roots are -1 and -1.66. Program code: Marks Secured:_____ Out of _____ Evaluator Signature
  • 61. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 61 Lab Session – 4 Date: Objective: Explore the full scope of expressions, type-compatibility of variables & constants and operators used in the expression and how operator precedence works. AIM: Simple computational problems using the operator’ precedence and associativity. Pre-Lab|4: 1. Think of operator associativity as a line of people passing items to each other. If the people pass items from left to right, it's left-associative; if they pass from right to left, it's right- associative. Which operator in many programming languages is right-associative? a. Addition (+) b. Subtraction (-) c. Exponentiation (^) d. Multiplication (*) Ans: 2. Think of operator precedence as the hierarchy in a corporate organization. Some employees have higher ranks and make decisions that impact others. Which operator typically has the highest rank in this hierarchy, similar to a CEO in a company? a. Assignment operator (=) b. Arithmetic operators (+, -, *, /) c. Comparison operators (>, <, ==) d. Logical operators (&&, ||) Ans: 3. Consider a mathematical expression as a sentence. In this sentence, operators are like words, and parentheses are like punctuation marks. What role do parentheses play in determining the meaning of the sentence? a. They change the operator precedence. b. They change the operator associativity. c. They act as operands. d. They have no impact on the expression's meaning. Ans: 4. Think of operators as workers in a factory. Each worker has a specific task, and they need to know who to hand their work off to next. Which concept in programming is analogous to the order in which workers pass their work along? a. Operator Precedence b. Operator Associativity c. Operand Evaluation d. Operator Overloading Ans: 5. Imagine you have a calculator with only three buttons: "+", "-", and "=". When you enter a sequence of numbers and operators, which concept determines the order in which the calculator processes them?
  • 62. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 62 a. Operator Precedence b. Operator Associativity c. Operand Evaluation d. Operator Overloading Ans: In-Lab|4: 4 .i: Write a c program to calculate 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) Algorithm:
  • 63. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 63 Flowchart:
  • 64. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 64 Program code:
  • 65. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 65 4 .ii: Input three values. Find the maximum of three numbers using conditional operator using the following syntax Max =Expr1? Expr2: Expr3; Algorithm & Flowchart:
  • 66. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 66 Program code:
  • 67. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 67 4 .iii: Take marks of 5 subjects as integers m1, m2, m3, m4, m5. Find the total, average in float. Total = m1+m2+m3+m4+m5 Average = Total/5 Use relevant format specifier to display results. Algorithm:
  • 68. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 68 Flowchart:
  • 69. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 69 Program code:
  • 70. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 70 Post-Lab|4: 1. Consider a classroom scenario where students are graded based on their performance. If they score above a certain threshold, they pass the course; otherwise, they fail. Program code:
  • 71. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 71 2. You're driving, and you approach a traffic signal. If the light is green, you continue straight; otherwise, you stop. Write a C program that uses if and else to simulate this scenario Program code:
  • 72. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 72 3. Consider a weather forecast scenario. If the weather is sunny, you go for a picnic; otherwise, you stay at home. Write a C program that checks the weather condition (sunny or not) and uses an if-else statement to decide whether to plan a picnic or stay at home. Program Code:
  • 73. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 73 4. Think of an if-else statement as a restaurant menu. If you're hungry, you order a main course; otherwise, you order dessert. Write a C program that asks the user if they are hungry (yes/no). If they are, prompt them to order a main course; otherwise, suggest a dessert. Use if-else for this decision. Program Code: Marks Secured:_____ Out of _____ Evaluator Signature
  • 74. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 74 Lab Session – 5 Date: Objective: Explore the full scope of different variants of “if construct” namely if-else, null else, 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”. AIM: Problems involving if-then-else structures. Pre-Lab|5: 1: What would happen when we compile and run this program? #include “stdio.h” int main () { int i; goto LOOP; for (i = 0; i < 10; i++) { printf (“Hi everyone”); LOOP; break; } return 0; } o/p: 2: Trace the code and give the output. #include <stdio.h> int main () { int a = 0, i = 0, b; for (i = 0; i < 5; i++) { a++; continue; } } o/p:
  • 75. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 75 3: What will be the outputs of the codes given below? i. #include <stdio.h> int main() { int i = 0, j = 0; l1: while (i < 2) { i++; while (j < 3) { printf (“Loop n”); goto l1; } } } o/p: 4. #include <stdio.h> int main () { int i = 0, k; if (i == 0) goto label; for (k = 0; k < 3; k++) { printf (“hi n”); label: k = printf (%03d”, I); } } o/p:
  • 76. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 76 In-Lab|5: 5 .i: Write a C program that accepts 4 numbers from the keyboard and prints out the maximum and minimum values of these four numbers. Note: Use integer or real numbers as input; declare the variables with required data type. Test data and expected output: Input: 1.54 1.236 1.3625 1.002 Output: Maximum Value is 1.54 Minimum Value is 1.002 Algorithm:
  • 77. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 77 Flowchart:
  • 78. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 78 Program code:
  • 79. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 79 5.ii: Write a C program to generate electricity bill with slabs by taking input as Consumer Number, Name, Present Reading, Previous Reading. Test data and expected output: Input: 652114046358, Gupta, 35201, 35002 Calculate the number of units consumed and generate the bill amount for the consumed units basing on the following slabs. For first 50 units – Rs. 3.50/unit For next 100 units – Rs. 4.00/unit For next 100 units – Rs. 5.20/unit For units above 250 – Rs. 6.50/unit Output: ------------------------------------------------------- Consumer Number : 652114046358 Consumer Name : Gupta Billed Units : 199 Bill Amount : Rs. 829.80 Note: Declare variables with required data type. Use different number of billed units as input to cover all the slabs. Algorithm:
  • 80. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 80 Flowchart:
  • 81. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 81 Program code:
  • 82. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 82 5 .iii: Find the roots of the quadratic equation. Note: The standard form of a quadratic equation is ax2 + bx + c where a, b and c are real numbers and not equal to zero. The term b2 – 4ac is known as the discriminant (d) of a quadratic equation. It tells the nature of the roots If the d > 0 the roots are real and different If the d = 0, the roots are real and equal. If the d < 0 the roots are complex and different Test Data: 1. x2 + 5x + 6 = 0 D =b2 – 4ac D = 52 – (4×1×6) = 25 – 24= 1 Since D>0, the equation will have two real and distinct roots. The roots are: x = [(-b + √D)]/2a or [(-b – √D)]/2a x = [(-5 + √1)]/2(1) or [(-5 – √1)]/2(1) Output: The roots are -2 or -3 2: x2 + x + 1 = 0 D =b2 – 4ac D = 12 – (4×1×1) = 1 – 4= -3 Since D<0, the equation will have two distinct Complex roots. The roots are: x = [(-b + √D)]/2a or [(-b – √D)]/2a x = [(-1 + √-3)]/2(1) or [(-1 – √-3)]/2(1) x = [(-1 + √3i)]/2 or [(-1 – √3i)]/2 3: 4x2 + 12x + 9 =0 D =b2 – 4ac D = 122 – (4×4×9) = 144 – 144= 0 Since D = 0, the equation will have two real and equal roots. The roots are: x = -b/2a x = -12/2(4) x = -12/8 x = -3/2 Output: The roots are -3/2 and -3/2.
  • 83. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 83 Algorithm:
  • 84. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 84 Flowchart:
  • 85. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 85 Program code:
  • 86. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 86 5 .iv: Simulate a calculator using switch case. Note: The program should takes an arithmetic operator +, -, *, /, % and two numeric operands from the user. Then, it performs the calculation on the two operands depending upon the operator entered by the user. For the modulus operator, you have to take only integer numbers, for the rest of the operands you can declare real or integer data type. Test Cases Should test all the operators. Test Data and Output: +, 1.2, 2.3 Result = 3.5 Algorithm:
  • 87. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 87 Flowchart:
  • 88. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 88 Program code:
  • 89. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 89 5 .v: Write a C program to find the given year is a leap year or not. Note: Should take year as an input and check whether it is divisible by 4 and not divisible by 100 or can be divisible by 400. Test Data and Output: Enter the year: 2000 Output: 2000 is Leap Year Enter the year: 1900 Output: 1900 is not a Leap Year Algorithm:
  • 90. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 90 Flowchart:
  • 91. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 91 Program code:
  • 92. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 92 Post-Lab|5: 1: Develop a C program to find all possible permutations in which ‘n’ people can occupy‘t’ seats in a theater is discussed here. ‘N’friends are planning to go to a movie. Once among them suggested few movies and all others started to discuss and finally they selected a movie. One among them quickly booked their tickets online; to their surprise they are unable to select their seats. All of them got confused. Then anyhow, decided to go to the movie. They rushed to reach the theater on time. Again they are surprised that no one was there in the theater. They are the only people about to watch the movie. There is ‘r’ number of seats in which, ‘n’ number persons should sit. In how many ways they can sit inside the theater? Input Format : The number of people ‘n’ , and the number of seats ‘r’. Output Format : Total number ways ‘n’ people can be seated in ‘r’ seats. Constraint : Given the number of people ‘n’ and the number of seats ‘r’ as input as positive integers. The task is to find the different number in which ‘n’ number of people can be seated in those ‘r’ number of seats. Sample Test Case : Input : Number of people : 5 Number of Rows : 3 Output : The total number of ways in which ‘n’ people can be seated in ‘r’ seats = 60 Calculation : P(n,r) = P(5, 3) = 5!/(5-3)! = 120/2 = 60 Program code:
  • 93. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 93
  • 94. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 94 2: Develop a C program to check whether a number can be expressed as a sum of two prime numbers is discussed here. Given a positive integer N. The task is to check if the number N can be represented as a sum of two prime numbers. Use break statement whenever it is possible. Constraint : The range of N should be less than 108 .Test Cases: Input : N = 13 Output : Yes Explanation : The number 13 can be written as 11 + 2, here 11 and 2 are both prime numbers. Input : N = 11 Output : No Program code:
  • 95. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 95 3: There are two banks; Bank A and Bank B. Their interest rates vary. You have received offered from both the bank in terms of annual rate of interest. Tenure and variations of rate of interest over the entire tenure. Here use unconditional control statements, where ever it is required. You have to choose the offer, which costs you least interest and reject the other. Do the computation and make a wise choice. The loan repayment happens at a monthly frequency and Equated Monthly installment (EMI) is calculated using the formula given below: EMI = loan amount * monthly interest rate / (1–1/(1+monthly interest rate)(no. of yrs * 12)) Constraints : 1 <= P <= 1000000 1 <= T <= 50 1 <= N1 <= 30 1 <= N2 <= 30 Input Format : First Line : P – principal (Loan Amount) Second Line : T – Total Tenure (in Years) Third Line : N1 is number of slabs of interest rates for a given period by the bank A. First slab starts from the first year and second slab starts from the end of the first slab and so on. Next N1 line will contain the interest rates and their period. After N1 lines we will receive N2 viz. The number of slabs offered by the second bank. Next N2 lines are number of slabs of interest rates for a given period by the Bank B. First slab starts from the first year and second slab starts from end of first slab and so on. Output : Your decision – either Bank A or Bank B. Input : 10000 20 3 5 9 5 10 9 6 5 8 5 5 7 9 Output : Bank B Program code:
  • 96. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 96
  • 97. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 97 4: Develop a test-based game that asks the user to guess a number. The system then outputs whether the guess was right or wrong. Let’s make the program give some help to the user; i.e., output whether the guess was higher or lower than the secret number. Hint : srand(time(0)); /* see random number generator */ num = rand() % 100 + 1; /* random number between 1 and 100 */ Number Entered Message to Display 3 Too Low 5 You Win! 7 Too High 8 Too High Test Case 1 : Input : Enter the number you guess : 3 Output : The number is too low Test Case 2 : Input : Enter the number you guess : 5 Output : You Win! Program code:
  • 98. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 98 Marks Secured:_____ Out of _____ Evaluator Signature
  • 99. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 99 Lab Session – 6 Date: 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 each of these statements is more appropriate to use. Aim: Solving Iterative Problems using Loops (for, While) Pre-Lab|6: 1: What will be the output of this program. #include <stdio.h> int main() { int i = 0; printf (“Hello”); char s[4] = {‘b’, ‘t’, ‘r’, ‘n’}; for (i = 0; i < 4; i++) { printf (“%c”, s[i]); return 0; } o/p: 2: What will be the output of this program. #include <stdio.h> int main() { int i = 0; char s[4] = {‘0’, ‘0’, ‘0’, ‘0’}; for (i = 0; i < 4; i++) { printf (“%c”, s[i]); return 0; } o/p:
  • 100. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 100 3: Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ’, return the length of last word in the string. If the last word does not exist return 0. Hint : For the input value “Hello World” the output is 5. Program code:
  • 101. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 101 4: What will be the output of this program. #include <stdio.h> # define arr “abcd” int main() { printf (“%c”, arr[2]); return 0;} o/p: In-Lab|6: 6 .i: Find the factorial of given number using any loop. The factorial of a positive number n is given by: 1*2*3*4 ... Note: This program should take a positive integer from the user as the factorial of a negative number doesn't exist and, the factorial of 0 is 1. Compute the factorial using any loop. Since the factorial of a number may be very large, the type of factorial variable is declared as unsigned long long. If the user enters a negative number, the program should display a custom error message. Algorithm:
  • 102. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 102 Flowchart:
  • 103. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 103 Program code:
  • 104. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 104 6 .ii: Input a number. Check the given number is a prime or not. Note: A prime number should be a natural number greater than 1 that has no positive divisors other than 1 and itself. Test Data and Output: Enter n: 5 Output: Prime Enter n: 6 Output: Not Prime Algorithm:
  • 105. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 105 Flowchart:
  • 106. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 106 Program code:
  • 107. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 107 6. iii: Compute sine and cos series The formula for computing the sine and cosine series for a given degree, X is Sine Series Cosine Series First, you have to change the value of x to radian (radian = degrees * π/180) and then using the result compute the sine and cosine series. Test Data and Output: Sin(x) Input : 90 Output: 1 Cos(x) Input : 30 Output : 0.86602 Algorithm:
  • 108. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 108 Flowchart:
  • 109. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 109 Program code:
  • 110. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 110 6 .iv: Checking a number palindrome: Note: Number should be a positive integer having more than one digit as all the single digits are palindromes. Test Data and output: Input : 2002 Input : 1234 Output: true Output: false Algorithm:
  • 111. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 111 Flowchart:
  • 112. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 112 Program code:
  • 113. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 113 6 .v: Construct a pyramid of numbers. Note: A pyramid of numbers represents the number of individuals per unit area of various trophic areas where producers are kept at the base and the tip is occupied by top carnivores. 1. The pyramid of numbers is mostly upright. The members of successive higher trophic levels are higher than the previous one. 2. Ahigher trophic level has fewer individuals than that of the lower trophic levels. Algorithm:
  • 114. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 114 Flowchart:
  • 115. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 115 Program code:
  • 116. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 116 Post-Lab|6: 6. Print the following patterns. i. ii. Program code:
  • 117. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 117
  • 118. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 118 2. Given a string s, consisting of alphabets and digits, find the frequency of each digit in the given string. Input Format : The first line contains a string, num which is the given number. Constraints : 1 <= len(num) <= 1000; All the elements of num are made of English alphabets and digits. Output Format : Print ten space-separated integers in a single line denoting the frequency of each digit from 0 to 9. Sample Input 0 : a11472o5t6 Sample Output 0 : 0210111100 Explanation 0 : In the given string , 1 occurs two times 2, 4, 5, 6 and 7 occur one time each. The remaining digits 0, 3, 8 and 9 don’t occur at all. Sample Input 1 : 1w4n88j12n1 Sample Output 1 : 0210100020 Sample Input 2 : 1v88886l256338ar0ekk Sample Output 2 : 1112012050 Program code:
  • 119. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 119 3. Given a number N denoted the elements in an array. He wants to arrange the elements of an array such that the odd positions have sorted elements in the ascending order and even positions have sorted elements in descending order. For example, if we have 1 2 3 4 5 then the result will be 1 5 2 4 3. Input Format : The first line of the input contains an integer T denoting the number of test cases. The description of each test cases follow. First line of each test case contains N number of elements in an array. Second line contains N space separated integers A1, A2, ….., AN. Output Format : Print array in desired order. Constraints : 1 <= T <= 10; 1 <= N <= 1000000; 1 <= Ai <= 100000000 Sample Input : 2 8 3 6 9 10 12 5 15 18 6 1 6 8 9 11 12 Sample Output : 3 18 5 15 6 12 9 10 1 12 6 11 8 9 Program code:
  • 120. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 120 4.Write a C program that creates an array of 100 random integers in the range 1 to 200 and then, using the sequential search, searches the array 100 times using randomly generated targets in the same range. At the end of the program, display the following statistics: a. The number of searched completed. b. The number of successful searches. c. The percentage of successful searches. d. The average number of tests per search. To determine the average tests per search, you will need to count the number of tests for each search. Hint : Use the comma operator to count the compares. Program code: Marks Secured:_____ Out of _____ Evaluator Signature
  • 121. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 121 Lab Session – 7 Date: 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. Aim: Programs on 1-D array manipulation, Searching Pre-Lab|7: 1. Given an array arr = [3, 1, 4, 1, 5], what is the value at index 2? a. 4 b. 1 c. 3 d. 5 Ans: 2. What does it mean when we say that arrays have a fixed size? a. The size of an array cannot be changed after declaration. b. Arrays can only store integers and no other data types. c. Arrays can only have one dimension. d. Arrays can only be used in certain programming languages. Ans: 3. Which of the following statements best explains the concept of an array index? a. It is the value stored in an array element. b. It is a unique identifier for each element in an array. c. It is the total number of elements in an array. d. It is the maximum value an element in an array can have. Ans: #include <stdio.h> int main() { int arr[] = {5, 3, 7, 2, 8}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; } Answer the following MCQ’s based on the above mentioned code snippet. MCQ 1: What is the primary purpose of the C code provided above? a. To find the sum of all elements in the array. b. To sort the array in ascending order. c. To print the elements of the array.
  • 122. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 122 d. To reverse the order of elements in the array. Ans: MCQ 2: What will be the output when you run the C code? a. 5 3 7 2 8 b. 8 2 7 3 5 c. 2 3 5 7 8 d. It will not compile due to a syntax error. Ans: MCQ 3: What does the variable n represent in the code? a. The sum of all elements in the array. b. The number of elements in the array. c. The largest element in the array. d. The smallest element in the array. Ans: In–Lab|7: 7 .i: Find the min and max of a 1-D integer array. Given an array X[] of size n, write a program to find the maximum and minimum element in the array. Our goal would be to solve this problem using minimum number of comparisons. Test Data and Output: Input: X[] = [4, 2, 0, 8, 20, 9, 2], Output: max = 20, min = 0 Input: X[] = [-8, -3, -10, -32, -1], Output: max = -1, min = -32 Algorithm:
  • 123. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 123 Flowchart:
  • 124. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 124 Program code:
  • 125. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 125 7 .ii : Perform linear search on 1D array. Linear Search is defined as a sequential search algorithm that starts at one end and goes through each element of a list until the desired element is found, otherwise the search continues till the end of the data set. o Every element is considered as a potential match for the key and checked for the same. o If any element is found equal to the key, the search is successful and the index of that element is returned. o If no element is found equal to the key, the search yields “No match found Test Data and Output: Input: arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30 Output: Key found at 3rd place Input: arr[] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 60 Output: Key not found in the array Algorithm:
  • 126. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 126 Flowchart:
  • 127. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 127 Program code:
  • 128. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 128 7 .iii: The reverse of a 1D integer array The first element becomes the last, and the last element becomes the first. Similarly, the second element is transformed into the second last, and the second last element is transformed into the second and so on. Minimum array size should be 5, and elements can be any integer. Algorithm:
  • 129. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 129 Flowchart:
  • 130. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 130 Program code:
  • 131. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 131 7 .iv: Find 2’s complement of the given binary number. To get 2’s complement of a binary number, simply invert the given number and add 1 to the least significant bit (LSB) of given result. Test Data and Output: Find 2’s complement of binary number 10101110. Simply invert each bit of given binary number, which will be 01010001. Then add 1 to the LSB of this result, i.e., 01010001+1=01010010 which is answer. Find 2’s complement of binary number 10001.001. Simply invert each bit of given binary number, which will be 01110.110 Then add 1 to the LSB of this result, i.e., 01110.110+1=01110.111 which is answer. Algorithm:
  • 132. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 132 Flowchart:
  • 133. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 133 Program code:
  • 134. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 134 7 .v: Eliminate duplicate elements in an array. Note: Delete the same numbers present in an array. The resultant array consists of unique elements. You have to enter some duplicate numbers in your array to check the correctness of the program. Test Data and Output: Enter size of the array 10 Enter Elements of the array: 1 1 2 4 3 5 6 5 7 1 Entered element are: 1 1 2 4 3 5 6 5 7 1 After deleting the duplicate element, the Array is: 1 2 4 3 5 6 7 Algorithm:
  • 135. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 135 Flowchart:
  • 136. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 136 Program code:
  • 137. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 137 Post–Lab|7: 1.Given a text txt[0 … n-1] and a pattern pat[0 … m-1], write a function search (char pat[ ], char txt[ ]) that prints all the occurrences of pat[ ] in txt[ ]. You may assume that n > m. Input : txt[ ] = “THIS IS A TEST TEXT” pat[ ] = “TEST” Output : Pattern found at index 10 Input : txt[ ] = “AABAACAADAABAABA” pat[ ] = “AABA” Output : Pattern found at index 0 Pattern found at index 9 Pattern found at index 12 Program code:
  • 138. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 138 2. Given two strings string 1, and string 2, the task is to find the smallest sub-string in the string 1 containing all characters of string 2 efficiently. Input : string = “this is a test string”, pattern = “tist”. Output : Minimum window is “t stri”. Explanation : “t stri” contains all characters of pattern. Input : string = “indiahelloindia”, pattern = “ile”. Output : Minimum windows are “iahel” and “elloi”. Explanation : “iahel” and “elloi” contain all characters of pattern. Program code:
  • 139. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 139 3. Given an input string, write a function that returns the Run Length Encoded string for the input string. Input : string is “wwwwaaadexxxxxx” Output : string is “w4a3d1e1x6” Program code:
  • 140. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 140 4.Given a string of length n, print all the permutation of the given string. Repetition of characters is allowed. Print these permutations in lexicographically shorted order. Input : AB Output : All permutations of AB with repetition are : AA AB BA BB Input : ABC Output : All permutations of ABC with repetition are: AAA AAB AAC ABA … … CCB CCC Program code:
  • 141. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 141 Marks Secured:_____ Out of _____ Evaluator Signature
  • 142. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 142 Lab Session - 8 Date: Objective: Explore the difference between other arrays and character arrays that can be used as 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. Aim: Programs on 2-D arrays, Sorting and Strings Pre–Lab|8: 1.Correct (Syntax/Logical) the following Code. #include <stdio.h> /* An example function that takes two parameters ‘x’ and ‘y’.as input and returns max of two input numbers */ int max(int x, int y) { if (x < y) return x; else return y; } int main (void) { int a =10, b = 20; //Calling above function to find max of ‘a’ and ‘b’ int m = max(a, b); printf (“m is %d”, m); return 0;} o/p: 2.What will be the output of the following program? #include<stdio.h> void fun (int x) { x = 30;} int main (void) { int x = 20; fun(x); printf (“x = %d”, x); return 0; } o/p: 3. What will be the output of the following program? #include<stdio.h> void increment (int x) { printf (“%d %d %d”, x++, x++, x++); } int main (void) { int i = 5; fun(x); increment (i);
  • 143. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 143 return 0; } o/p: 4. What will be the output of the following program? #include<stdio.h> void dynamic (int s, ….) { printf (“%d”, s); } int main (void) { dynamic (2, 4, 6, 8); dynamic (3, 6, 9); return 0;} o/p: In–Lab|8: 8 .i: Amatrix can only be added to another matrix if the two matrices have the same dimensions. To add two matrices, just add the corresponding entries, and place this sum in the corresponding position in the matrix which results. Input elements in 3x3 matrix1: 1 2 3 4 5 6 7 8 9 Input elements in 3x3 matrix2: 9 8 7 6 5 4 3 2 1 Sum of both matrix = 10 10 10 10 10 10 10 10 10 Algorithm:
  • 144. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 144 Flowchart:
  • 145. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 145 Program code:
  • 146. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 146 8. ii: Matrix multiplication is a binary operation that produces a matrix from two matrices. For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The resulting matrix, known as the matrix product, has the number of rows of the first and the number of columns of the second matrix. The product of matrices A and B is denoted as AB. Algorithm:
  • 147. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 147
  • 148. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 148 Flowchart:
  • 149. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 149 Program code:
  • 150. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 150
  • 151. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 151 8.iii: Sort array elements using bubble sort . Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.  Traverse from left and compare adjacent elements and the higher one is placed at right side.  In this way, the largest element is moved to the rightmost end at first.  This process is then continued to find the second largest and place it and so on until the data is sorted. Algorithm:
  • 152. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 152 Flowchart:
  • 153. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 153 Program code:
  • 154. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 154 8 .iv: Concatenate two strings without using built-in functions Note: User would be asked to enter two strings and then the program would concatenate them. For concatenation we have not used the standard library function strcat(), instead we have written a logic to append the second string at the end of first string. Test Data and Output: Str1: Good Str2: Morning Output: Good Morning Algorithm:
  • 155. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 155 Flowchart:
  • 156. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 156 Program code:
  • 157. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 157 8 .v: Reverse a string using built-in and without built-in string functions  Using built-in function: The function is used for reversing a string. The reversed string will be stored in the same string. Algorithm:
  • 158. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 158 Flowchart:
  • 159. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 159 Program code:
  • 160. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 160 Post–Lab|8: 1.In this challenge, you will learn simple usage of functions in C. Functions are a bunch of statements glued together. A function is provided with zero or more arguments, and it executed the statements on it. Based on the return type, it either returns nothing (void) or something. A sample syntax for a function is return_type function_name (arg_type_1 arg_1, arg_type_2 arg_2, …) { … … … [if return_type is non void] return something of type ‘return_type’; } Task : You have to write a function int max_of_four (int a, int b, int c, int d), which reads four arguments and returns the greatest of them. Input Format: Input will contain four integers a, b, c, d; one in each line. Output Format: Print the greatest of the four integers. Note: I/O will be automatically handled. Sample Input 3 4 6 5 Sample Output 6 Program code:
  • 161. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 161
  • 162. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 162 2. Count of distinct power of prime factor of N. Given a positive integer N, the task is to find the total number of distinct power of prime factor of the given number N. Examples: Input : N = 216 Output : 4 Explanation: 216 can be expressed as 2 * 22 * 3 * 32 The factors satisfying the conditions are 2, 22, 3 and 32 as all of them are written as distinct positive powers of prime factors. Input : N = 24 Output : 3 Explanation : 24 can be expressed as 2 * 22 * 3 Approach: The idea is to find all the prime factors of N and how many times each prime factor divides N. Suppose the prime factor ‘p’ divides N ‘z’ times, then the required distinct factors are p, p2, … pi To find the number of distinct primes factor for prime number p, find the minimum value of ‘I’ such that (1 + 2 + … + I) <= z. Program Code:
  • 163. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 163
  • 164. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 164 3. Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of Boolean, where each Boolean represents whether the small string at that index in the array of small strings is contained in the big string. Note : That you can’t use language-built-in string-matching methods. Input : bigString = “this is a big string”, smallStrings = [“this”, “yo”, “is”, “a”, “bigger”, “string”, “kappa”] Output : [true, false, true, true, false, true, false] Input : bigString = “Mary goes to the shopping center every week”, smallStrings =[“to”, “mary”, “centers”, “shop”, “shopping”, “string”, “kappa”] Output : [true, true, false, true, true, false, false] Program code:
  • 165. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 165
  • 166. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 166 4. There is a series S, where the next term is the sum of previous three terms. Given the first three terms of the series a, b, and c respectively, you have to output the nth term of the series using recursion. Recursive method for calculating nth term is given below. Input Format: The first line contains a single integer. The next line contains 3 space-separated integers, , , and . Constraints: 1 <= n <= 20 1 < a,b,c < 100 Output Format: Print the nth term of the series, S(n). Sample Input: 5 123 Sample Output : 11 Explanation: Consider the following steps S(1) = 1 S(2) = 2 S(3) = 3 S(4) = S(3) + S(2) + S(1) S(5) = S(4) + S(3) + S(2) From steps 1, 2, 3, and 4, we can say S(4) = 3+2+1 =6; then using the values from step 2, 3, 4, and 5, we get S(5) = 2+3+6 = 11. Thus we print 11 as our answer. Program code:
  • 167. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 167 Marks Secured:_____ Out of _____ Evaluator Signature
  • 168. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 168 Lab Session – 9 Date: 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 AIM: Programs on Pointers and structures, memory dereference Pre-Lab|9: 1. What will be the output of the following program ? #include int main () { char *ptr = “2braces.com”; printf (“%c n”, *&*ptr); return 0; } o/p: 2. What will be the output of the following program? #include <stdio.h> struct classroom { int students[7]; }; int main () { struct classroom cr = {2, 3, 5, 7, 11, 13}; int *ptr; ptr = (int*)&cr;printf (“%d”, *(ptr + 4));return 0; } o/p:
  • 169. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 169 3. What is a memory leak? How to avoid it? 4. What will be the output of the following program? #include <stdio.h> void fun (int *a) { a = (int *) malloc (sizeof (int)); } int main () { int *p; fun (p); *p = 6; printf (“%d n”, *p); return 0; } o/p: 5. Mention different Dynamic memory allocation functions in c language. Ans:
  • 170. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 170 In-Lab|9: 9 .i. Sum of one – dimensional array using malloc function To create an integer array, of size , int *arr = (int*)malloc(n * sizeof(int)), where points to the base address of the array. When you have finished with the array, use free(arr) to deallocate the memory. In this challenge, create an array of size dynamically, and read the values from stdin. Iterate the array calculating the sum of all elements. Print the sum and free the memory where the array is stored. Input Format The first line contains an integer, . The next line contains space-separated integers. Constraints 1>=n<=1000 1<=a[i]<=1000 Output Format Print the sum of the integers in the array. Sample Input 0 6 16 13 7 2 1 12 Sample Output 0 51 Algorithm:
  • 171. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 171
  • 172. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 172 Flowchart:
  • 173. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 173 Program code:
  • 174. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 174 9 .ii: Structures are a way to group several related variables into one place. There are n students in a class having name, class, section, etc. So if we want to store all of its information, we can create different variables for every variable like a character array to store the name, an integer variable to store the class, and a character variable to store the section. Make a structure contains information of each student Each Student Record should have: Name Roll Number Marks of 3 subjects Create a structure to store student information of n students and calculate the total, average of n students Constraints 1<= n<= 1000 Output Format Sample Input 0 1 Input the Roll Number of the student :784 Input the Name of the Student : James Input the marks of Physics, Chemistry and Computer Application : 70 80 90 Sample Output 0 Roll No : 784 Name of Student : James Marks in Physics : 70 Marks in Chemistry : 80 Marks in Computer Application : 90 Total Marks = 240 Average = 80 Algorithm:
  • 175. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 175
  • 176. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 176 Flowchart:
  • 177. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 177 Program code:
  • 178. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 178
  • 179. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 179 9 .iii. Dynamic allocation using calloc (memory allocation) allows you to allocate memory during the runtime of the program. Using calloc, you can allocate the specified number of blocks of memory of the specified type. Make a structure contains information of each student. Each Student Record should have: Name Roll Number Marks of 3 subjects Create a structure to store student information of n students using calloc and display failed students list from ‘n’ students. Constraints 1<= n<= 1000 1<= mi <= 10 Sample Input 0 2 Input the Roll Number of the student: 784 Input the Name of the Student: James Input the marks of Physics, Chemistry and Computer Application: 70 80 90 Input the Roll Number of the student: 785 Input the Name of the Student: John Input the marks of Physics, Chemistry and Computer Application : 25 52 46 Sample Output 0 Roll No : 784 Name of Student : James Marks in Physics : 70 Marks in Chemistry : 80 Marks in Computer Application : 90 Total Marks = 240 Average = 80 Roll No: 785 Name of Student: John Marks in Physics: 25 Marks in Chemistry: 52 Marks in Computer Application: 46 Total Marks = 123 Average = 41 NO.OF.STUDENTS FAILED=1
  • 180. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 180 Algorithm:
  • 181. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 181 Flowchart:
  • 182. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 182 Program code:
  • 183. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 183
  • 184. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 184 9 .iv: The main function in c can be created with two methods: first with no parameters (void) and second with two parameters. The parameters are argc and argv,argc denotes the number of arguments given argv[] is a pointer array pointing to each parameter passed to the program. int main(int argc, char* argv[]) where argc is an integer and the argv is a list of command line arguments. Write a Program to read student name and marks from the command line and display the student details along with the total. Sample Input $ ./a.out John 34 56 78 Sample output ----Following Are The Command Line Arguments Passed---- Name= john Physics= 34 Chemistry=56 Computer Applications=78 Total=168 Algorithm:
  • 185. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 185 Flowchart:
  • 186. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 186 Program code:
  • 187. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 187
  • 188. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 188 Post–Lab|9: 1. Write a menu driven program in C to create a structure employee having fields - empid, emp name, salary. Accept the details of 'n' Employees from user and perform the following operations using function. - Search by Emp-Id - Display All - Display Names of Employee having Salary > 10000. Sample Input and output Program code:
  • 189. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 189
  • 190. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 190 2. Write a 'C' Program to calculate sum of non-diagonal elements of m X n matrix using dynamic memory allocation. Sample Input and output Program code:
  • 191. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 191
  • 192. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 192 3. Write a C program to create a student structure having fields stud_name and address. Accept the details of 'n' students, rearrange the data in alphabetical order of student name and display it. Sample Input and Output
  • 193. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 193 Program code:
  • 194. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 194
  • 195. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 195 4. Write a function that receives two integers and passes back the greatest common divisor and the least common multiplier. The calculation of the greatest common divisor can be done using Euclid’s method of repetitively dividing one number by the other and using the remainder (modulo). When the remainder is zero, the greatest common divisor has been found. For example, the greatest common divisor of 247 and 39 is 13, as given in the table. Once you know the greatest common divisor (gcd), the least common multiplier (lcm) is determined by the equation as given below(Use pointers). lcm = (num 1 * num 2) / gcd Test case : Input : num 1 : 60 num 2 : 45 Output : gcd : 15 lcm : (60 * 45) / 15 = 180 Program code:
  • 196. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 196
  • 197. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 197 5. Create an user – defined datatype using enumeration. enum tagname {value1, value2, value3,....}; (or) enum tagname {identifier list..}; enum is a keyword. It is a user defined data type. tag name is our own created variable. value1, value2, value3,.... are create set of enum values. Program Code:
  • 198. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 198 Marks Secured:_____ Out of _____ Evaluator Signature
  • 199. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 199 Lab Session – 10 Date: Objective: Experiment with C Structures, Unions, bit fields and self-referential structures (Singly linked lists) and nested structures. Aim: Programs on Bit-fields , linked lists Pre–Lab|10: 1. What is the functionality of the following piece of code? public int function(int data) { Node temp = head; int var = 0; while(temp != null) { if(temp.getData() == data) { return var; } var = var+1; temp = temp.getNext(); } return Integer.MIN_VALUE; } o/p: 2. What does the following function do for a given Linked List with first node as head? void fun1(struct node* head){ if(head == NULL) return; fun1(head->next); printf("%d ", head->data);} o/p:
  • 200. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 200 3. What will be the output of the following program? #include <stdio.h> int main () { struct node { int a, b, c; }; struct node num = {3, 5, 6}; struct node *ptr = &num; printf (“%d n”, ((int*)ptr + 1 + (3-2))); return 0; } o/p: 4. For what minimum value of x in a 32-bit Linux OS would make the size of s equal to 8 bytes? struct temp { int a : 13; int b : 8; int c : x; }s; a) 4 b) 8 c) 12 d) 32
  • 201. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 201 5. How do you insert an element at the beginning of the List? Program code:
  • 202. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 202 In–Lab|10: 10 .i. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Input Format The first line of input contains n , the number of elements in the linked list. The next n lines contain one element each, the data values for each node. Constraints 1<= n<= 1000 1<= list[i]<= 1000,where list[i] is the ith element of linklist Sample Input 2 16 13 Sample Output 16 13 Explanation There are two elements in the linked list. They are represented as 16 -> 13 -> NULL. So, the print Linked List function should print 16 and 13 each on a new line. Algorithm:
  • 203. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 203 Flowchart:
  • 204. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 204 Program code:
  • 205. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 205
  • 206. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 206 10. ii: Structure uses a separate location to store the entities whereas union uses the same location to save all the entities. Create an employee structure with the following details Name Class ID Create a person union with the following details Age Name Department Salary Declare the structure for employee and union for person. Display employee information and person information along with size of employee record and size of person record. Algorithm:
  • 207. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 207 Flowchart:
  • 208. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 208 Program code:
  • 209. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 209
  • 210. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 210 10. iii: Abit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner. Create a bitfield struct { data_type member_name : width_of_bit-field; }; data_type: It is an integer type that determines the bit-field value which is to be interpreted. The type may be int, signed int, or unsigned int.member_name: The member name is the name of the bit field.width_of_bit-field: The number of bits in the bit-field. The width must be less than or equal to the bit width of the specified type.Demonstrate shift operations (LEFT SHIFT,RIGHT SHIFT) using bit fields Algorithm:
  • 211. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 211 Flowchart:
  • 212. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 212 Program code:
  • 213. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 213
  • 214. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 214 10 .iv: Write a definition of structure type Employee, Where a value of type Employee has three fields: (1) a constant null-terminated string called name (2) a value of type double called salary (3) a constant null-terminated string called office. Write statements that create an Employee variables called John and another Employee variable Abraham, and copy all of the information from variable john into variable Abraham. Algorithm:
  • 215. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 215 Flowchart:
  • 216. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 216 Program code:
  • 217. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 217 Post-Lab|10: 1. Given a pointer to the head node of a linked list, the task is to reverse the linked list. We need to reverse the list by changing the links between nodes. Examples: Input: Head of following linked list 1->2->3->4->NULL Output: Linked list should be changed to, 4->3->2->1->NULL Input: Head of following linked list 1->2->3->4->5->NULL Output: Linked list should be changed to, 5->4->3->2->1->NULL Program code:
  • 218. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 218
  • 219. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 219 2. Write a program in C to create a singly linked list of n nodes and count the number of nodes. Program code:
  • 220. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 220
  • 221. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 221 3. Write a program in C to insert a new node at the beginning of a Singly Linked List. Program code:
  • 222. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 222 Marks Secured:_____ Out of _____ Evaluator Signature
  • 223. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 223 Lab Session - 11 Date: 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 AIM: Programs on Functions, call by value, scope and extent, Pre–Lab|11: 1. Correct (Syntax/Logical) the following Code. #include <stdio.h> /* An example function that takes two parameters ‘x’ and ‘y’. as input and returns max of two input numbers */ int max(int x, int y) { if (x < y) return x; else return y; } int main (void) { int a =10, b = 20; //Calling above function to find max of ‘a’ and ‘b’ int m = max(a, b); printf (“m is %d”, m); return 0; } o/p: 2. What is the value of j at the end of the execution of the following C program? #include<stdio.h> int incr (int i) { static int count = 0; count = count + i; return (count); } void main() { int i, j; for (i = 0; i <= 4; i++) j = incr (i); o/p:
  • 224. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 224 3. Choose correct statements about C Language Pass By Value. a) Pass By Value copies the variable value in one more memory location b) Pass By Value does not use Pointers c) Pass By Value protects your source or original variables from changes in outside functions or called functions d) All the above. 4. Pick the best statement for the following program. int foo (int a) { printf (“%d”, a); return 0;} int main () { foo; return 0; } o/p: In-Lab|11: 11. i: Given two integers n and r. In how many ways can r items be chosen from n items? Input Format The first line contains the number of test cases T. Each of the next lines contains two integers n and r . Constraints: 1<=T<=105 1<=n<=109 0<=r<=n Output Format Output T lines, containing the required answer for the corresponding test case. Sample Input 4 2 1 4 0 5 2 10 3 Sample Output 2 1 10 120
  • 225. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 225 Algorithm:
  • 226. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 226 Flowchart:
  • 227. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 227 Program Code:
  • 228. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 228
  • 229. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 229 11. ii: You are given two strings a and b separated by a new line. Each string will consist of lower case Latin characters ('a'-'z'). Write a C function to find the length of a string a and b respectively(with and without built-in functions) Output Format In the first line print two space-separated integers, representing the length of a and b respectively. Sample Input ai&ds of velagapudi ramakrishna siddhartha engineering college cse Sample Output 62 3 Algorithm:
  • 230. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 230 Flowchart:
  • 231. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 231 Program code:
  • 232. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 232
  • 233. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 233 11. iii: Given a matrix of size N x M. Print transpose of the matrix. Input Format First line of input contains N, M - the size of the matrix. Its followed by N lines each containing M integers - elements of the matrix. Constraints 1 <= N, M <= 100 -109 <= ar[i] <= 109 Output Format Print the transposed matrix. Sample Input 0 2 2 5 -1 19 8 Sample Output 0 5 19 -1 8 Algorithm:
  • 234. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 234
  • 235. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 235 Flowchart:
  • 236. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 236 Program code:
  • 237. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 237
  • 238. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 238 11. iv: Write a C function to demonstrate numerical integration of differential equations using Euler’s method Explanation: Euler Method is a Numerical technique used to solve ordinary differential equations. In Euler’s Method, to solve the ordinary differential equation dy/dx = x+y. We ask the user to give us the initial values for xi,yi and h .The value of slope at different points is calculated using the function ‘fun’. Sample Input Enter xi 0 Enter yi 1 Enter h 0.1 Enter xn: 1 Sample Output x y 0.100 1.100 0.200 1.220 0.300 1.362 0.400 1.528 0.500 1.721 0.600 1.943 0.700 2.197 0.800 2.487 0.900 2.816 1.000 3.187 Algorithm:
  • 239. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 239
  • 240. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 240 Flowchart
  • 241. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 241 Program code:
  • 242. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 242
  • 243. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 243 Post-Lab|11: 1.Given an array, X, of N integers, calculate and print the respective mean, median. If your array contains more than one modal value, choose the numerically smallest one. Example : N=6 X=[1,2,3,4,5] The mean is 20/6=3.3 The median is 3+4/2=3.5 Input Format: The first line contains an integer,N , the number of elements in the array. The second line contains ,N ,space-separated integers that describe the array's elements. Constraints 10<=N<=2500 0<=x[i]<=105, where x[i] is the ith element of the array. Output Format Print 3 lines of output in the following order: Print the mean on the first line to a scale of ,1,decimal place (i.e.,12.3). Print the median on a new line, to a scale of,1, decimal place (i.e., 12.3). Sample Input 10 64630 11735 14216 99233 14470 4978 73429 38120 51135 67060 Sample Output 43900.6 44627.5 Program code:
  • 244. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 244
  • 245. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 245 2. Count of distinct power of prime factor of N. Given a positive integer N, the task is to find the total number of distinct power of prime factor of the given number N. Examples: Input : N = 216 Output : 4 Explanation: 216 can be expressed as 2 * 22 * 3 * 32 The factors satisfying the conditions are 2, 22 , 3 and 32 as all of them are written as distinct positive powers of prime factors. Input : N = 24 Output : 3 Explanation : 24 can be expressed as 2 * 22 * 3 Approach : The idea is to find all the prime factors of N and how many times each prime factor divides N. Suppose the prime factor ‘p’ divides N ‘z’ times, then the required distinct factors are p, p2 , … pi . To find the number of distinct primes factor for prime number p, find the minimum value of ‘I’ such that (1 + 2 + … + I) <= z. Program code:
  • 246. VR23 Registration No: 23ES1152: COMPUTER PROGRAMMING LAB PAGE NO: 246