PIC Instructor Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Instructor Manual
COURSE NAME: PRINCIPLES OF
PROGRAMMING USING C
COURSE CODE:22CS23
Pg PART A
no Practice Programs
1. Familiarization with programming environment, concept of naming the
program files storing, compilation, execution and debugging. Create a new
file using gedit/vi filename.c
a. Write C statement(s) in the file which produces the following output:

a)Have a Good day! b) Have/ \a / \Good / \ day!


c) Laughter is the best “Medicine”. Share the “Knowledge”.
d) Hello
World! (Using a only one printf statement)
e) Hello
World! (Using a single printf statement that has no blank space)
f) How are you?
I am Fine.
g) How are you?
I am Fine. (Using two printf statements which have no blank
spaces)
h) How are you?
I am Fine. Thank You. (Using a single printf statement that has no blank
space)
i )Bank interest is 9% in the year 2018.
Soln #include <stdio.h>
int main()
{ printf("Have a Good day!\n"); //a
printf("Have /\\a /\\Good /\\ day!\n");//b
printf(“Laughter is the best \"Medicine\" .Share the \”Knowledge\”\n"); //c
printf("Hello\n world!\n"); //d
printf("Hello\vworld!\n"); //e
printf("How are you?\n"); //f
printf("I am Fine.\n"); //f
printf("How\tare\tyou?\n");//g
printf("I\tam\tFine.\n"); //g
printf("How\tare\tyou?\nI\tam\tFine\nThank\tYou\n"); //h
printf("Something has gone crazy\a\n"); //i
printf("Bank interest is 9%% in the year 2018.\n"); //j
return 0;
}
2 Implementation and execution of simple programs to understand working of
 Formatted input and output functions- printf() and scanf().
 Escape sequences in C.
 Using formula in a C program for specific computation: For example:
computing area of circle, converting Celsius to Fahrenheit, area of a triangle,
converting distance in centimeters to inches, etc.
 Preprocessor directives (#include, #define).
a Write a C program that produces the following output and also test for other
Patterns: (Print using * or #)
* ****
* *
* *
*
*
*
*
* *
* *
*****
Soln #include <stdio.h>
int main() {
printf(" *****\n");
printf(" * *\n");
printf(" * *\n");
printf(" *\n");
printf(" *\n");
printf(" *\n");
printf(" *\n");
printf(" * *\n");
printf(" * *\n");
printf(" *****\n");
return 0;
}
b Design and develop C program that accepts a distance in centimeters and
prints the corresponding value in inches. (Note that 1 inch = 2.54 cm.)
Soln #include <stdio.h>
#define INCH_TO_CM 2.54
int main()
{
double inch,cm;
printf("Enter the distance in cm:");
scanf("%lf",&cm);
inch=cm/INCH_TO_CM;
printf("Distance %0.2lf cms is = %0.2lf inches\n",cm,inch); return 0;
}
c Design and develop a C program to find the area of the following: Triangle,
Square, Rectangle and Circle. Implement the C program for all possible
inputs appropriate message.
Soln #include<stdio.h>
#define PI 3.14
int main()
{
float ba,he,len,bre,ra;
float area_tri,area_squ,area_rect,area_circle;
printf(“Enter the base and height\n”);
scanf(“%f%f”,&ba,&he);
printf(“Enter the length and breadth\n”);
scanf(“%f%f”,&len,&bre);
printf(“Enter the radius\n”);
scanf(“%f%f”,&ra);
area_tri=1/2*ba*he;
area_squ=le*bre;
area_rect=len*bre;
area_circle=3.14*r
a*ra;
printf(“Area of Triangle=%f\n”,area_tri);
printf(“Area of Square=%f\n”,area_tsqu);
printf(“Area of Rectangle=%f\n”,area_rect);
printf(“Area of Circle=%f\n”,area_circle);
return 0;
}
3 Execution of erroneous C programs to understand debugging and correcting the errors like:
 Syntax / compiler errors.
 Run-time errors.
 Linker errors.
 Logical errors.
 Semantical errors.

Errors in C/C++
Error is an illegal operation performed by the user which results in abnormal
working of the program.
Programming errors often remain undetected until the program is compiled or
executed. Some of the errors inhibit the program from getting compiled or executed.
Thus errors should be removed before compiling and executing.
The most common errors can be broadly classified as follows.

Type of errors

1. Syntax errors: Errors that occur when you violate the rules of writing C/C++
syntax are known as syntax errors. This compiler error indicates something that
must be fixed before the code can be compiled. All these errors are detected by
compiler and thus are known as compile-time errors.
Most frequent syntax errors are:
 Missing Parenthesis (})
 Printing the value of variable without declaring it
 Missing semicolon like this
// C program to illustrate syntax error
a)
#include<stdio.h>
void main()
{ int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}
Error:
error: expected ';' before '}' token
b)
#include<stdio.h>
int main(void)
{
// while() cannot contain "." as an argument.
while(.)
{ printf("hello");
}
return 0;
}
Error:
error: expected expression before '.' token
while(.)

2. Run-time Errors : Errors which occur during program execution(run-time) after


successful compilation are called run-time errors. One of the most common run-time
error is division by zero also known as Division error. These types of error are hard
to find as the compiler doesn’t point to the line at which the error occurs.

// C program to illustrate run-time error


#include<stdio.h>
void main()
{ int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
printf("resut = %d", div);
}
Error:
warning: division by zero [-Wdiv-by-zero]
div = n/0;

3. Linker Errors: These error occurs when after compilation we link the different
object files with main’s object using Ctrl+F9 key(RUN). These are errors generated
when the executable of the program cannot be generated. This may be due to wrong
function prototyping, incorrect header files. One of the most common linker error is
writing Main() instead of main().
// C program to illustrate
// linker error
#include<stdio.h>
void Main() // Here Main() should be main()
{ int a = 10;
printf("%d", a);
}
Error:
(.text+0x20): undefined reference to `main'

4. Logical Errors : On compilation and execution of a program, desired output is not


obtained when certain input values are given. These types of errors which provide
incorrect output but appears to be error free are called logical errors. These are one
of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy
to detect if we follow the line of execution and determine why the program takes
that path of execution.
// C program to illustrate logical error
int main()
{ int i = 0;
// logical error : a semicolon after loop
for(i = 0; i < 3; i++);
{ printf("loop ");
continue;
}
getchar();
return 0;
}
No output

5. Semantic errors : This error occurs when the statements written in the program are
not meaningful to the compiler.
// C program to illustrate semantic error
void main()
{ int a, b, c;
a + b = c; //semantic error
}
Error
error: lvalue required as left operand of assignment
a + b = c; //semantic error

a. Find the errors in the following program:/* Is it a C program?*/

#include <stdio.h>
int main( )
{
inta,b ,c;
a= 5.54;
b =a+2;
scanf( "%d", &c);
printf( "%d %d %d\n",a, b,c);
return 0;
}
b. Find the errors in the following program:
/* There are errors in /*the*/ code.*/
#include <stdio.h>
#define CUBE(Y) (Y)*(Y)*(Y) ;
#define SQUARE(Y) (Y)*(Y);
int main()
{ double Int,y,_y1,2yb,a-b,y3z;
int Float,char,a,b,c,d,xy@c,qa.b; check it in the question variable names
char int,u,_2v,w=t;
a=2,b=3;
a+b;
c=a+b;
a+b=1;
b-a==c;
d=w;
a=CUBE(d);
b=SQUARE(d)
u=d+62;
c=u-1;
u=’y’;
_2v=z;
y3z=CUBE(c);
y=SQUARE(c);
_y1=SQUARE(c)*2;
c=y+u;
return 0;
}
Soln An error free code for the same is as follows
/* There are errors in the code.*
/ #include <stdio.h>
#define CUBE(Y) (Y)*(Y)*(Y)
#define SQ(Y) (Y)*(Y)
int main()
{
double Int,y,_y1,2yb,a_b,y3z;
int Float,cHar,a,b,c,d,xy_c,qab;
char inT,u,_2v,w=’t’;
a=2,b=3;
a+b;
c=a+b;
a+b==1;
b-a==c;
d=w;
a=CUBE(d);
b=SQ(d);
u=d+62;
c=u-1;
u=’y’;
_2v=’z’;
y3z=CUBE(c);
x=SQ(c);
_x1=2*SQ(c);
c=x+u;
return 0;
}

3.c Type the program in a file and examine the output of the following code:.

#include<stdio.h>
int main(void)
{
int a=234,b= -234,c=54321;
printf("%2d\n",c);
printf("%10.2d\n",c);
printf("%-10.2d\n",c);
printf("%-7d\n",a);
printf("%07.2d\n",a);
printf("%07d\n",a);
printf("%+0-9.4d\n",a);
printf("%+09.4d\n",a);
printf("%+07d\n",a);
printf("%+07.4d\n",a);
printf("%+-07.4d\n",a);
printf("%-08d\n",b);
printf("%-08.2d\n",b);
printf("%-8.4d\n",b);
return 0;
}
4 Implementation and execution of simple programs to understand working of
operators like:
 Unary.
 Arithmetic.
 Logical.
 Relational.
 Conditional.
 Bitwise.
a C program to demonstrate working of Unary arithmetic operators
#include <stdio.h>
int main()
{ int a = 10, b = 4, res;
// post-increment example:
// res is assigned 10 only, a is not updated yet
res = a++;
printf("a is %d and res is %d\n", a, res); // a becomes 11 now
// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
printf("a is %d and res is %d\n", a, res); // a becomes 10 now
// pre-increment example:
// res is assigned 11 now since a is updated here itself
res = ++a;
// a and res have same values = 11
printf("a is %d and res is %d\n", a, res);
// pre-decrement example:
// res is assigned 10 only since a is updated here itself
res = --a;
// a and res have same values = 10
printf("a is %d and res is %d\n", a, res);
return 0;
}
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10

b C program to demonstrate working of relational operators


#include <stdio.h>
int main()
{ int a = 10, b = 4;
// greater than example
if (a > b)
printf("a is greater than b\n");
else
printf("a is less than or equal to b\n");

// greater than equal to


if (a >= b)
printf("a is greater than or equal to b\n");
else
printf("a is lesser than b\n");

// less than example


if (a < b)
printf("a is less than b\n");
else
printf("a is greater than or equal to b\n");

// lesser than equal to


if (a <= b)
printf("a is lesser than or equal to b\n");
else
printf("a is greater than b\n");
// equal to
if (a == b)
printf("a is equal to b\n");
else
printf("a and b are not equal\n");

// not equal to
if (a != b)
printf("a is not equal to b\n");
else
printf("a is equal b\n");

return 0;
}
Output:
a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b

c C program to demonstrate working of logical operators


#include <stdio.h>
int main()
{
int a = 10, b = 4, c = 10, d = 20;
// logical operators
// logical AND example
if (a > b && c == d)
printf("a is greater than b AND c is equal to d\n");
else
printf("AND condition not satisfied\n");
// logical OR example
if (a > b || c == d)
printf("a is greater than b OR c is equal to d\n");
else
printf("Neither a is greater than b nor c is equal "
" to d\n");

// logical NOT example


if (!a)
printf("a is zero\n");
else
printf("a is not zero");

return 0;
}
Output:
AND condition not satisfied
a is greater than b OR c is equal to d
a is not zero
Note: Following additional exercises can be carried out by students who finish
above programs

Implement a C Program to demonstrate the working of relational operator, logical


and bitwise operator. Print the value for the following expressions and analyze the
output.

a)a=a +b+c b)d= a+b+c c)a=(b+c)*d d)a=a&&b||c


e)a=!a&&b||c!||d&&e f) a= (b&&c)!d g)a=a++ + a++ h)b=a++ +a++
i) a= ++a + a++
Lab Programs
1. Develop a C program to compute the roots of the equation ax2 + bx + c = 0.
sol #include<stdio.h>
#include<math.h>
#include<stdlib.h>
main()
{
float a,b,c,root,disc,root1,root2;
printf("\nEnter the coefficients:\n");
scanf("%f%f%f",&a,&b,&c);

if(a==0 && c==0)


{
printf (“Not Possible\n”);
exit(0);
}
else if(a==0 && b!=0)
{
root=-c/b;
printf(“Linear root =%f\n”,root);
}
else
{
disc=b*b-4*a*c; // ‘disc’ indicates discriminant
//Find the distinct roots
if(disc>0)
{
root1=(-b + sqrt(disc)) / (2*a);
root2=(-b - sqrt(disc)) / (2*a);
printf("\n Roots are real & distinct! \n");
printf("\n The roots are: \n%f\n%f\n",root1,root2);
}

else if(disc==0) //Find the equal roots


{
root1=root2= -b / (2*a);
printf("\n Roots are real & equal! \n");
printf("\n The roots are \n%f\n%f\n",root1,root2);
}
else
{
//Find the complex roots
root1= -b / (2*a);
root2= sqrt(abs(disc)) / (2*a);
printf("\n The roots are imaginary!\n");
printf("\n The first root is %f + i%f \n",root1,root2);
printf("\n The second root is %f - i%f \n",root1,root2);
}
}
}
Output
Run 1:
Enter the coefficients:
1
2
1

Roots are real & equal!

The roots are


-1.000000
-1.000000

Run 2:
Enter the coefficients:
1
5
4

Roots are real & distinct!

The roots are:


-1.000000
-4.000000
Run 3:
Enter the coefficients:
2
4
6
The roots are imaginary!

The first root is -1.000000 + i1.414214


The second root is -1.000000 - i1.414214

2 Develop a C program that reads N integer numbers and arrange them in ascending or
descending order using selection sort and bubble sort technique.

soln //SELECTION SORT


#include <stdio.h>
#define MAX 100
int main() {
int arr[MAX],i,j,n,temp,min;
printf("Enter the number of elements : ");
scanf("%d", &n);
for(i=0; i<n; i++) {
printf("Enter element %d : ",i+1);
scanf("%d", &arr[i]);
}
for(i=0; i<n-1; i++) {
min = i;
for(j=i+1; j<n; j++) {
if(arr[min]>arr[j])
min=j;
}
if(i!=min) {
temp=arr[i];
arr[i]=arr[min];
arr[min]=temp;
}
}
printf("Sorted list is : \n");
for(i=0; i<n; i++) {
printf(" %d", arr[i]);
}
printf("\n");
}
//BUBBLE SORT
#include<stdio.h>
main()
{
int a[10],n,i,j,temp;
printf("\n Enter the size of n:\n" );
scanf("%d",&n);
printf("\n Enter the array elements: \n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++) /* ith smallest number bubbles up to its
right spot in ith iteration */
{
for(j=0;j<n-i;j++) /* bubbling starts from the "deepest numbers"
and proceeds upwards */

/* element at jth position is "lighter" than the one on top,


therefore jth element bubbles up */
if(a[j]>=a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
printf("\n The sorted array is: \n" );
for(i=0;i<n;i++)
printf("%d\n",a[i]);
}

Output (SELECTION SORT)


Run1:
Enter Number of elements
6
Enter 6 elements
12 89 980 9 0 8 18
Sorted elements:
0 9 12 18 89 980

Output(BUBBLE SORT)
Run 1:
Enter the size of n:
5

Enter the array elements:


65
84
91
20
8

The sorted array is:


8
20
65
84
91

3 Develop a C program for Matrix multiplication.


#include <stdio.h>

int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;

printf("Enter rows and column for first matrix: ");


scanf("%d %d", &r1, &c1);

printf("Enter rows and column for second matrix: ");


scanf("%d %d",&r2, &c2);

// Column of first matrix should be equal to column of second matrix and


while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}

// Storing elements of first matrix.


printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}

// Storing elements of second matrix.


printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}

// Initializing all elements of result matrix to 0


for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}

// Multiplying matrices a and b and


// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}

// Displaying the result


printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return 0;
}
Output
Run 1:
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.

Enter rows and column for first matrix: 2


3
Enter rows and column for second matrix: 3
2

Enter elements of matrix 1:


Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4

Enter elements of matrix 2:


Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4

Output Matrix:
24 29

6 25
4 Develop a C program to search an element using Binary search and linear search techniques.
// BINARY SEARCH
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}
//LINEAR SEARCH
#include <stdio.h>
int main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}
OUTPUT
BINARY SEARCH
Enter number of elements
7
Enter 7 integers
-4 5 8 9 11 43 485
Enter the value to find
11
11 found at location 5.
LINEAR SEARCH
Enter the number of elements in array
5
Enter 5 numbers
56429
Enter the number to search
4
4 is present at location
5 Using functions develop a C program to perform the following tasks by parameter passing to
read a string from the user and print appropriate message for palindrome or not palindrome
sol #include <stdio.h>
#include <string.h>
void check(char [], int);
int main()
{
char word[15];
printf("Enter a string to check if it is a palindrome\n");
scanf("%s", word);
check(word, 0);
return 0;
}
void check (char word [], int index)
{
intlen = strlen(word) - (index + 1);
if (word[index] == word[len])
{
if (index + 1 == len || index == len)
{
printf("The entered word is a palindrome\n");
return;
}
check(word, index + 1);
}
else
{
printf("The entered word is not a palindrome\n");
}
}
}

Output
Run 1:

Enter a string to check if it is a palindrome

How are you

The entered word is not a palindrome


Run 2:
Enter a string to check if it is a palindrome

Madam

The entered word is a palindrome.

Run 3:
Enter a string to check if it is a palindrome

mam

The entered word is a palindrome.

6 Develop a C program to compute average marks of ‘n’ students (Name, Roll_No, Test Marks)
and search a particular record based on ‘Roll_No’.
sol #include<stdio.h>
#include<string.h>
struct student
{
char name[50];
int roll;
float marks[3];
}st[60];
int main()
{
int i,n,rollno;
float sum=0,avg;
printf("Enter the number of
students\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter The name of %d
student\n",i+1);
scanf("%s",st[i].name);
printf("Enter The Roll no of
%d student\n",i+1);
scanf("%d",&st[i].roll);
printf("Enter The Marks of %d
student\n",i+1);

scanf("%f%f%f",&st[i].marks[0],&st[i]
.marks[1],&st[i].marks[2]);
}
for(i=0;i<n;i++)
{
sum= sum+ st[i].marks[0] +
st[i].marks[1] + st[i].marks[2];
}
avg= sum/n;
printf("The Average Marks Of %d
Students is : %f\n",n,avg);
printf("Enter the roll no. of student
detail required : ");
scanf("%d",&rollno);
for(i=0;i<n;i++)
{
if(st[i].roll==rollno)
{
printf("The name of
student is : %s\n",st[i].name);
printf("The 3 test
scores are :\n %f %f
%f",st[i].marks[0],st[i].marks[1],st[i].marks[2]
);
break;
}
else
continue;
}
if(i==n)
printf("Roll No. not found\n");

}
OUTPUT
enter the name of 1 student= Ramesh

enter the roll no of 1 student= 43

enter the 3 test scores of 1 student= 45 48 50

enter the name of 2 student= Ganesh

enter the roll no of 2 student= 23

enter the 3 test scores of 2 student= 35 38 40

enter the name of 3 student= Vagesh

enter the roll no of 3 student= 50

enter the 3 test scores of 3 student= 41 43 45

enter the rollno of the student details required= 23

the name of the student is= Ganesh


the 3 test scores of the student= 35 38 40

7 Develop a C program using pointers to function to find given two strings are equal or not.
#include<stdio.h>
int compare_string(char*, char*);
main()
{
char first[100], second[100], result;
printf("Enter first string\n");
gets(first);
printf("Enter second string\n");
gets(second);
result = compare_string(first, second);
if ( result == 0 )
printf("Both strings are same.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}
int compare_string(char *first, char *second)
{
while(*first==*second)
{
if ( *first == '\0' || *second == '\0' )
break;

first++;
second++;
}
if( *first == '\0' && *second == '\0' )
return 0;
else
return -1;
}

OUTPUT
Run 1
Enter first string
RVCE
Enter second string
BANGALORE
Entered strings are not equal.
Run 2
Enter first string
CSE
Enter second string
CSE
Both strings are same.
8 Develop a C program using recursion, to determine GCD , LCM of two numbers and to
perform binary to decimal conversion.
sol (a)GCD and LCM
#include <stdio.h>
int find_gcd(int,int);
int find_lcm(int,int);
int main()
{
int num1,num2,gcd,lcm;
printf("\nEnter two numbers:\n ");
scanf("%d %d",&num1,&num2);
gcd=find_gcd(num1,num2);

printf("\nGCD of %d and %d is: %d\n",num1,num2,gcd);

if(num1>num2)
lcm = find_lcm(num1,num2);
else
lcm = find_lcm(num2,num1);

printf("\nLCM of %d and %d is: %d\n",num1,num2,lcm);


return 0;
}
int find_gcd(int n1,int n2){
while(n1!=n2){
if(n1>n2)
return find_gcd(n1-n2,n2);
else
return find_gcd(n1,n2-n1);
}
return n1;
}
int find_lcm(int n1,int n2){

static int temp = 1;

if(temp % n2 == 0 && temp % n1 == 0)


return temp;
temp++;
find_lcm(n1,n2);

return temp;
}

(b) Binary to Decimal Conversion


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int binary_to_decimal(int binum,int decnum,int bit)


{
int bitwt;
if(binum>0)
{
bitwt=binum%10;
decnum=decnum+bitwt*pow(2,bit);
binum=binum/10;
bit++;
decnum=binary_to_decimal(binum,decnum,bit);//recursion taking place.
}
return decnum;
}

void main ()
{
int decimalnum=0,binarynum,bitweight=0;
printf("Enter the binary number\n");
scanf("%d",&binarynum);
decimalnum=binary_to_decimal( binarynum,decimalnum,bitweight);
printf("%d in binary %d",decimalnum, binarynum);
}
-------------------------------------------------------------------------------------------------------------------------
Output:

Enter two numbers: 366 60


GCD of 366 and 60 is: 6
L.C.M of 366 and 60 is 3660.

Enter a binary number:


110110111 110110111 in
binary = 439
9 a. Program to calculate the sum of n numbers entered by the user using malloc().
b. Program to calculate the sum of n numbers entered by the user using calloc().
c. Program in C using realloc().
Sol. (a)
#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, *ptr, sum = 0;

printf("Enter number of elements: ");


scanf("%d", &n);

ptr = (int*) malloc(n * sizeof(int));

// if memory cannot be allocated


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);

// deallocating the memory


free(ptr);

return 0;
}

-----------------------------------------------------------------------------------------------------------

Output

Enter number of elements: 3


Enter elements: 100
20
36
Sum = 156

(b)
#include <stdio.h>
#include <stdlib.h>

int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);

ptr = (int*) calloc(n, sizeof(int));


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

-----------------------------------------------------------------------------------------------------------

Output

Enter number of elements: 3


Enter elements: 100
20
36
Sum = 156

(c)
#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);

ptr = (int*) malloc(n1 * sizeof(int));

printf("Addresses of previously allocated memory:\n");


for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);

printf("\nEnter the new size: ");


scanf("%d", &n2);

// rellocating the memory


ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");


for(i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);

free(ptr);

return 0;
}

-----------------------------------------------------------------------------------------------------------

Output

Enter size: 2
Addresses of previously allocated memory:
26855472
26855476

Enter the new size: 4


Addresses of newly allocated memory:
26855472
26855476
26855480
26855484

10 C Program to implement Singly Linked List to insert and delete a node from front and
display the contents of the Singly List.
Sol #include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

struct node
{
int info;
struct node *link;
};

typedef struct node* NODE;

NODE getnode();
NODE insert_front(NODE , int);
NODE delete_front(NODE);
void display(NODE);

void main()
{
NODE first;
int choice, item;

first = NULL;

while(1)
{
printf("Enter\n");
printf("1. Insert Front\n");
printf("2. Delete Front\n");
printf("3. Display the list\n");
printf("4. Exit\n");

scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter item to be inserted\n");
scanf("%d", &item);
first = insert_front(first, item);

break;

case 2:
first = delete_front(first);

break;

case 3:
display(first);
break;

default:
exit(0);
}
}
}

NODE getnode()
{
NODE x;

x = (NODE) malloc(sizeof(struct node));

if(x == NULL)
{
printf("Node creation error\n");
return;
}

return x;
}

NODE insert_front(NODE first , int item)


{
NODE temp;

temp = getnode();
temp->info = item;

temp->link = first;

return temp;
}

NODE delete_front(NODE first)


{
NODE temp;

if(first == NULL)
{
printf("Cannot delete. Empty List\n");
return first;
}

temp = first;
first = first->link;

printf("Deleted node is %d\n", temp->info);


free(temp);

return first;
}

void display(NODE first)


{
NODE temp;

printf("Contents of linked list is:\n");

if(first == NULL)
{
printf("Cannot print. Empty list\n");
return;
}

temp = first;

while(temp != NULL) //as long as there are elemens in the linked list
{
printf("%d\t", temp->info);
temp = temp->link;
}

printf("\n");
}
---------------------------------------------------------------------------------------------------------
Output
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
2
Cannot delete. Empty List
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
3
Contents of linked list is:
Cannot print. Empty list
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
1
Enter item to be inserted
10
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
1
Enter item to be inserted
20
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
1
Enter item to be inserted
30
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
1
Enter item to be inserted
40
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
1
Enter item to be inserted
50
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
3
Contents of linked list is:
50 40 30 20 10
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
2
Deleted node is 50
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
2
Deleted node is 40
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
2
Deleted node is 30
Enter
1. Insert Front
2. Delete Front
3. Display the list
4. Exit
3
Contents of linked list is:
20 10

11 Write a C program to count no of lines, blank lines and comments in a given program
using files.
Sol
#include <stdio.h>
void main()
{
int line_count = 0, n_o_c_l = 0, n_o_n_b_l = 0, n_o_b_l = 0, n_e_c = 0;
FILE *fp1;
char ch;
fp1 = fopen("file.txt", "r");

while (((ch = fgetc(fp1)))!= EOF)


{
if (ch == '\n')
{
line_count++;
}
if (ch == '\n')
{
if ((ch = fgetc(fp1)) == '\n')
{
fseek(fp1, -1, 1);
n_o_b_l++;
}
}
if (ch == ';')
{
if ((ch = fgetc(fp1)) == '\n')
{
fseek(fp1, -1, 1);
n_e_c++;
}
}
}
fseek(fp1, 0, 0);
while ((ch = fgetc(fp1))!= EOF)
{
if (ch == '/')
{
if ((ch = fgetc(fp1)) == '/')
{
n_o_c_l++;
}
}
}
printf("Total no of lines: %d\n", line_count);
printf("Total no of comment line: %d\n", n_o_c_l);
printf("Total no of blank lines: %d\n", n_o_b_l);
printf("Total no of non blank lines: %d\n", line_count-n_o_b_l);
printf("Total no of lines end with semicolon: %d\n", n_e_c);
}
input file contents: file.txt

department of
CSE RVCE
//this is a comment
--------------------------------------------------------------------------------------------------------------------
Output:
Total no of lines: 5
Total no of comment line:1
Total no of blank lines:2
Total no of non blank lines:3
Total no of lines end with semicolon:0

PART B
 Design and development of a working model using any of the following combination of hardware
and software.
 Develop a model that helps the user to monitor weather, health condition, environment
parameters, etc. using Arduino board.
 Develop a simple Robot that can assist the user to perform simple activities home sanitization,
lifting things etc. using Raspberry pi.
 Hardware interfacing (Ardunio Board, Finch, Lego WeDo 2.0) with scratch to design various
models to solve simple problems.
 Develop applications using Nvidia Jetson Kit.
Laboratory Evaluation
Each program is evaluated for 10 marks.
Lab Write-up &Execution rubrics (Max: 6 marks) and Viva Voce rubrics (Max: 4 marks)

Lab Write-up and Execution rubrics (Max: 6 marks)


Sl Criteria Measuring Excellent Good Poor C
no methods O

1 Understanding Student exhibits Student has sufficient Student does not CO


of problem and Observations thorough understanding of have clear 1
requirements understanding of program requirements understanding of
program and applies C program
(2 Marks) requirements and concepts. (1.5M - requirements and
applies C concepts. 1M) is unable to apply
(2M) C concepts. (0M)

2 Design Student demonstrates Student demonstrates Student has not CO


&Execution Observations the execution of the the execution of the executed the 3
program with program without program. CO
(2Marks) optimized code with optimization of the (0 M) 4
all the necessary code and handles only
conditions and test few test cases.
cases handled. (1M)
(2M)

3 Results and Documentation with Documentation with Documentation CO


Documentation Observations appropriate only few comments with no comments 3
comments and output and only few output and no output
(2Marks) is covered in data cases is covered in cases is covered in
sheets and record. data sheets and data sheets and
(2M) record.(1M) record.
(0 M)
Viva Voce rubrics (Max: 4 marks)
1 Conceptual Explains C and Adequately explains Unable to explain
Understanding related concepts the C and related the concepts. CO
Viva Voce involved.(2M) concepts (0M) 1
(2 Marks) involved.(1M)

2 Use of Insightful Sufficiently explains Unable to explain


appropriate explanation of the use of appropriate the design CO
Design Viva Voce appropriate design design techniques for techniques for the 2
Techniques techniques for the the given problem to given problem.
(1 Mark) given problem to derive solution. (0 M)
derive solution. (0.5 M)
(1 M)
3 Communication Communicates the Sufficiently Unable to
of Concepts concept used in communicates the communicate the
Viva Voce problem solving concepts used in concepts used in CO
(1 Mark) well. problem solving. problem. 3,C
(1 M) (0.5 M) (0 M) O4

Part B program will be evaluated for 10 marks and rubrics is :


PART B Rubrics
Sl Criteria Measuring Excellent Good Poor CO
no methods
1 Identify and Application Identified and Identified and Not identified and CO1
Understand developed Understood the Understood the well understood the
the problem problem exceptionally problem problem
(2M) moderately (1M)
(1.5M)
2 Design and Application Well designed by Moderately Not well Designed CO2
development developed considering all the designed by (1M)
constraints considering few
(3M) constraints
(2M)
3 Testing and Application Validated the obtained Validated the Not Validated the CO3
Analysis developed result for all test cases obtained result for obtained result ,
(3M) few test cases (1M) CO4
(2M)
4 Demonstration, Application Submitted the work on Submitted the work Not submitted CO4
Documentation developed time along with the along with the (0M)
and submission report. report
(2M) (1M)

PROGRAM BANK

SET 1
Sl Question
NO.
1 Distinguish between system software, application software and utility software.
2 Write the algorithm and flowchart to do the following :

(a) Check whether a year given by the user is a leap year or not.
(b) Given an integer number in seconds as input, print the equivalent time in hours,
minutes, and seconds as output. The recommended output format is something like:
7,322 seconds is equivalent to 2 hours 2 minutes 2seconds.
(c) Print the numbers that do not appear in the Fibonacci series. The number of terms to
be printed should be given by the user.
(d) Convert the binary equivalent of an integer number.
(e) Find the prime factors of a number given by the user.
(f) Check whether a number given by the user is a Krishnamurthy number or not. A
Krishnamurthy number is one for which the sum of the factorials of its digits equals the
number.
For example, 145 is a Krishnamurthy number.
(g) Print the second largest number of a list of numbers given by the user.
(h) Find the sum of N odd numbers given.
(i) Compute the sum of squares of integers from 1 to 50.
3 Which of the following is an incorrect assignment statement?
(a) n = m = 0
(b) value += 10
(c) mySize = x < y ? 9 : 11
(d) testVal = (x > 5 || x < 0)
(e) none of the above
4 What will be the output:
(a)
int main()
{
fl oat c= 3.14;
printf(“%f”, c%2);
return 0;
}

(b) int main()


{
printf(“%d”, ‘A’);
return 0;
}
(c) int main()
{
double d= 1/2.0 – 1/2;
printf(“d=%.2lf”, d);
return 0;
}
(d)int main()
{
int c = 1;
c=c+2*c++;
printf(“\n%f”,c);
return 0;
}
5. Use the following values for the next four questions.
int a = 8, b = 3, x1, x2, x3, x4
x1 = a * b
x2 = a / b
x3 = a % b
x4 = a && b
(a) The value of x1 is:
(b) The value of x2 is
(c) The value of x3 is
(d) The value of x4 is
6 What is the output of this C code?
int main()
{
char chr;
chr = 128;
printf("%d\n", chr);
return 0;
}
7. How many time the statement will be printed:
#include <stdio.h>
int main()
{
int i = 100;
for (; i; i >>= 1)
printf("Inside for");
return 0;
}

8. What is the output of the below program?


#include <stdio.h>
int main()
{
int i = 0;
switch (i)
{
case '0': printf("0");
break;
case '1': printf("1");
break;
default: printf("Default");
}
return 0;
}

9. #include <stdio.h>
int main()
{
int i = 3;
switch (i)
{
case 0+1: printf("1");
break;
case 1+2: printf("2");
break;
default: printf("3");
}
return 0;
}

10. #include <stdio.h>


int i;
int main()
{
if (i);
else
printf("Ëlse");
return 0;
}

11. #include<stdio.h>
int main()
{
int n;
for (n = 9; n!=0; n--)
printf("n = %d", n--);
return 0;
}
12. #include <stdio.h>
int main()
{
int c = 5, no = 10;
do {
no /= c;
} while(c--);

printf ("%dn", no);


return 0;
}
13 #include <stdio.h>

int main()
{
int arr[5];
arr[0] = 5;
arr[2] = -10;
arr[3 / 2] = 2; // this is same as arr[1] = 2
arr[3] = arr[0];

printf("%d %d %d %d", arr[0], arr[1], arr[2], arr[3]);

return 0;
}

14 #include <stdio.h>

int main()
{
int arr[2];

printf("%d ", arr[3]);


printf("%d ", arr[-2]);

return 0;
}
15. Write the program to solve following Problems:
1. Accept a list of data items and find the second largest and second smallest elements
in it
2. Copy element of one array into another
3. Cyclically permute the elements of an array
4. Delete duplicate elements in an array
5. Delete the specified integer from the list
6. Find unique element in two arrays
7. Minimum element location in array
8. Accept an array of 10 elements and swap 3rd element with 4th element using
pointers

16. #include <stdio.h>


int main()
{
char p;
char buf[10] = {1, 2, 3, 4, 5, 6, 9, 8};
p = (buf + 1)[5];
printf("%d\n", p);
return 0;
}
17. Which of the following is true about arrays in C.
(A) For every type T, there can be an array of T.
(B) For every type T except void and function type, there can be an array of T.
(C) When an array is passed to a function, C compiler creates a copy of array.
(D) 2D arrays are stored in column major form
18. An array elements are always stored in memory locations.

A. Sequential
B. Random
C. Sequential and Random
D. None of the above
19 void main()
{
char str1[] = "abcd";
char str2[] = "abcd";
if(str1==str2)
printf("Equal");
else
printf("Unequal");
}
20. What will be the output of the program ?

#include
void main()
{
float arr[] = {12.4, 2.3, 4.5, 6.7};
printf("%d", sizeof(arr)/sizeof(arr[0]));
}
21. The function that is used to find the first occurrence of a given string in another string is:
22. #include <stdio.h>

int main()
{
char st[] = "CODING";
printf("While printing ");
printf(", the value returned by printf() is : %d",
printf("%s", st));

return 0;
}
23 Print the following pattern on the screen
****
**
*
**
****
24 #include <stdio.h>
int main()
{
long int n = 123456789;

printf("While printing ");


printf(", the value returned by printf() is : %d",
printf("%d", n));

return 0;
}
25 #include <stdio.h>
int main()
{
char a[100], b[100], c[100];

// scanf() with one input


printf("\n First scanf() returns : %d",
scanf("%s", a));

// scanf() with two inputs


printf("\n Second scanf() returns : %d",
scanf("%s%s", a, b));

// scanf() with three inputs


printf("\n Third scanf() returns : %d",
scanf("%s%s%s", a, b, c));

return 0;
}
26 Write a program to reverse digits of a number.
27 Write a program to reverse an array or string.
28.
List of switch case statement programs in C:
C program to read weekday number and print weekday name.
C program to check whether a character is VOWEL or CONSONANT
29
Examples for sentinel control loop & counter control Loop?
30 #include <stdio.h>
void main()
{
int x=22;
if(x=10)
printf("TRUE");
else
printf("FALSE");
}
31 What will be the output of following program?
#include <stdio.h>
void main()
{
if(!printf(""))
printf("IF");
else
printf("ELSE");
}

32 #include <stdio.h>
int main()
{
if( (-100 && 100)||(20 && -20) )
printf("%s","Condition is true.");
else
printf("%s","Condition is false.");
return 0;
}
33 #include<stdio.h>
int main()
{
int i = 5, j = 6, k = 7;
if(i > j == k)
printf("%d %d %d", i++, ++j, --k);
else
printf("%d %d %d", i, j, k);
return 0;
}
34. # 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;
}
35. #include<stdio.h>
int main()
{
int a = 5;
switch(a)
{
default:
a = 4;
case 6:
a--;
case 5:
a = a+1;
case 1:
a = a-1;
}
printf("%d n", a);
return 0;
}

36 Which combination of the integer variables x, y and z makes the variable a get the value 4
in the following expression?
a = ( x > y ) ? (( x > z ) ? x : z) : (( y > z ) ? y : z )
SET 2
1 Simple computational problems using arithmetic expressions and use of each operator
leading to implementation of a commercial calculator with appropriate output.
2 Write a C program to swap two numbers using pointers (Call by reference).
3 Create a structure called student with the following members student name, roll no, and a
structure with marks details in three tests. Write a C program to create N records and
a) Search on roll no and display all the records.
b) Average marks in each test.
c) Highest marks in each test.
4 Write a C program to check whether the entered year is leap or not.
5 Design a structure 'Complex' and write a C program to perform the following operations:
i. Reading a complex number.
ii. Addition of two complex numbers.
6 Write a C program to input a number and check whether the number is palindrome or not.
7 Compute the roots of the equation ax2 + bx + c = 0 and print using three-decimal places.
The roots are real −b±√D/ 2aif the discriminant D = b2−4ac is non-negative. If the
discriminate is negative, then the roots are complex conjugate−b /2a ±√−Di/ 2a.The
program proceeds in the following steps.

a) The program should accept the values of a, b and c from the keyboard.
a) No solution if both a and b are zero. The program terminates with appropriate
message.
b) Linear equation if a = 0 but b ≠ 0 and the root is −c/b. The program prints out the
root with appropriate message and the program terminates.
c) Calculate the discriminant D and determines the corresponding roots.
d) Display all possible roots of a quadratic equation with appropriate message.
8 Write a program to print the prime numbers in a range entered by user.
9 Design and develop using an iterative problem solving approach for Taylor series
approximation for five decimal digits to compute Sin(x)= x - x3/3! + x5/5! - x7/7! +
x9/9!. ............ Xn / n!. Read the value for N.
10 Write a program to print out a multiplication table as given below.
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
11 Write a C program to read a list of N integer numbers in an array and print the following:
(i) the maximum value
(ii) the minimum value
(iii) the range
Hint: This is computed as maximum-minimum.
(iv) the average value
Hint: To compute this, add all the numbers together into sum and count them all in Count.
The average is Sum/Count
12 Write a C program to find the length of the string without using library function.
13 Write a C program to count vowels and consonants in a string using pointer.

14 Write a C program to generate any one patterns as given below : (Accept the number of rows
from user)
i) ( to print * if it is even number) ii)
1 55555
** 4444
333 333
**** 22
55555 1

15 Develop and demonstrate a C program for Matrix multiplication:


a) Read the sizes of two matrices and check the compatibility for multiplication.
b) Perform matrix multiplication and print the result along with the input matrix.
16 Using functions develop a C program to perform the following tasks by parameter passing
concept:
a) To read a string from the user
b) Print appropriate message for palindrome or not palindrome
17 Write a C program to perform the following operations using recursive functions:
a)GCD, LCM (Using GCD method)
b)Factorial of a Number
18 Write a C program to generate Fibonacci series using recursion.
19 Write a C program to read matrix of m X n order from the user and display whether it is
lower triangular matrix or upper triangular matrix.
20 Write a C program to check whether the entered number is positive, negative or zero.
21 Write C user defined functions
a) To input N integer numbers into a single dimension array.
b) To sort the integer numbers in descending order using selection sort technique.
c) To print the single dimension array elements.
Using these functions, write a C program to input N integer numbers into a single
dimension array, sort them in descending order, and print both the given array & the
sorted array with suitable headings. (Not simple selection sort)
22 Write a C program to insert a character at specified position and move the remaining
character to right.
23 Write a program to enter a sentence and print total number of vowels and each vowel
count separately.
24 Write a C program to read a string and sort it alphabetically.
25 Write a C program to read and find the frequency of characters in a given string.
26 Write a C program to search an element using Binary search.
27 Demonstrate a C program that reads N integer numbers and arrange them in ascending or
descending order using bubble sort technique.
28 Write a C program to read a matrix A[m*n] and to find the following using functions:
a) Sum of elements of each row.
b) Sum of elements of each column.
c) Sum of all the elements of matrix.
d) Sum of principle diagonal elements
29 Write a C program to check whether a number is a power of 2 or not.
30 Write a C program to check whether the number entered is prime or not.

You might also like