Create A New File Using Gedit/vi Filename.c: Solutions To Lab Programs With Expected Input and Output

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

SOLUTIONS TO LAB PROGRAMS WITH EXPECTED INPUT AND OUTPUT

Pg Program Description
no
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.
Sol #include <stdio.h>
n 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;
}
b Write a C program that produces the following output and also test for
other
Patterns: (Print using * or #)
* ****
* *
* *
*
*
*
*
* *
* *
*****
Sol #include <stdio.h>
n int main() {
printf(" *****\n");
printf(" * *\n");
printf(" * *\n");
printf(" *\n");
printf(" *\n");
printf(" *\n");
printf(" *\n");
printf(" * *\n");
printf(" * *\n");
printf(" *****\n");
return 0;
}
c. 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.)
Sol #include <stdio.h>
n #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;
}
d. 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.
Sol #include<stdio.h>
n #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;
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;
}
2 Debug the errors and understand the working of input statements in a given
program by compiling the following C –code:
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

2a 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;
}
2b 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;
}
Sol An error free code for the same is as follows
n /* 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;
}

2c 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;
}
3 Operators
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++
4. Simple computational problems using arithmetic expressions and use of
each operator leading to implementation of a Commercial calculator with
appropriate message:
a) Read two values from the key board.
b) Handle divide by zero error and print appropriate message
c) Handling the modulus operator for floating point numbers.

Sol #include<stdio.h>
#include<math.h>
void main()
{
int a,b,c;
int ch; //stores the choice of operation

// input section
printf("\nEnter two numbers\n" );
scanf("%d%d",&a,&b);
printf("\n\n");
printf("\n 1-ADD\n");
printf("\n 2-SUB\n");
printf("\n 3-MULTI\n");
printf("\n 4-DIVIDE\n");
printf("\n 5-MODULO\n");
printf("\nEnter your choice of operation\n");
scanf("%d",&ch);
switch(ch)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: if(b==0)
{
printf("\n Divide by zero error! \n");
break;
}
else
{
c=a/b; //perform division operation
break;
}
case 5: c=a%b; //perform modulo operation
break;

default: //erroneous input


printf("\nInvalid choice! \n");
break;
}
printf("\nThe result is %d\n",c);
}
-------------------------------------------------------------------------------------------
-----------------

Output
Run 1:
Enter two numbers
5
7

1-ADD

2-SUB

3-MULTI

4-DIVIDE
Enter your choice of operation
1

The result is 12

Run 2:

Enter two numbers


9
4

1-ADD

2-SUB

3-MULTI

4-DIVIDE

Enter your choice of operation


2

The result is 5

Run 3:

Enter two numbers


6
5

1-ADD

2-SUB

3-MULTI

4-DIVIDE

Enter your choice of operation


3

The result is 30
Run 4:

Enter two numbers


9
3

1-ADD

2-SUB

3-MULTI

4-DIVIDE

Enter your choice of operation


4

The result is 3

Run 5:

Enter two numbers


8
0

1-ADD

2-SUB

3-MULTI

4-DIVIDE

Enter your choice of operation


4

Divide by zero error!

Run 6:

Enter two numbers


4
6
1-ADD
2-SUB
3-MULTI
4-DIVIDE
Enter your choice of operation
5
Invalid choice!
5 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 = b 2−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.
b) No solution if both a and b are zero. The program terminates with
appropriate message.
c) 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.
d) Calculate the discriminant D and determines the corresponding roots.
e) Display all possible roots of a quadratic equation with appropriate
message.
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 =%d\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
6 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!

Sine Series is a series which is used to find the value of Sin(x).where, x is the angle
in degree which is converted to Radian.
The formula used to express the Sin(x) as Sine Series is

 
Expanding the above notation, the formula of Sine Series is

For example, Let the value of x be 30.

 
So, Radian value for 30 degree is 0.52359.

#include<stdio.h>
 
void main()
{
    int i, n;
    float x, sum, t;
    clrscr();
     
    printf(" Enter the value for x : ");
    scanf("%f",&x);
     
    printf(" Enter the value for n : ");
    scanf("%d",&n);
     
    x=x*3.14159/180;
    t=x;
    sum=x;
     
    /* Loop to calculate the value of Sine */
    for(i=1;i<=n;i++)
    {
        t=(t*(-1)*x*x)/(2*i*(2*i+1));
        sum=sum+t;
    }
     
    printf(" The value of Sin(%f) = %.4f",x,sum);
  }

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

Output
Run 1:
Enter the value for x: 45

Enter the value of n: 5

The value of Sin (0.785398) = 0.7071

7 Develop a C program for one dimensional and two dimensional array manipulations
(insertion, deletion, modification, search). Demonstrate a C program that reads N
integer numbers and arrange them in ascending or descending order using bubble
sort technique
soln #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]);
// Bubble Sorting
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
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

8 Develop and demonstrate a C program for Matrix multiplication:

a) Read the sizes of two matrices and check the compatibility for multiplication.
b) Print the appropriate message if the condition is not satisfied and ask user to
enter
proper input.
c) Read the input matrix
d) Perform matrix multiplication and print the result along with the input matrix.

#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
9 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

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. 

10 Develop and implement C Program to check whether a given n digit number is an


armstrong number or not.
// C program to find Armstrong number
  
#include <stdio.h>
  
/* Function to calculate x raised to the power y */
int power(int x, unsigned int y)
{
    if (y == 0)
        return 1;
    if (y % 2 == 0)
        return power(x, y / 2) * power(x, y / 2);
    return x * power(x, y / 2) * power(x, y / 2);
}
  
/* Function to calculate order of the number */
int order(int x)
{
    int n = 0;
    while (x) {
        n++;
        x = x / 10;
    }
    return n;
}
  
// Function to check whether the given number is
// Armstrong number or not
int isArmstrong(int x)
{
    // Calling order function
    int n = order(x);
    int temp = x, sum = 0;
    while (temp) {
        int r = temp % 10;
        sum += power(r, n);
        temp = temp / 10;
    }
  
    // If satisfies Armstrong condition
    if (sum == x)
        return 1;
    else
        return 0;
}
  
// Driver Program
int main()
{
    int x = 153;
    if (isArmstrong(x) == 1)
        printf("%d is Armstrong\n", x);
    else
        printf("%d is not Armstrong\n", x);
  
    x = 1253;
if (isArmstrong(x) == 1)
printf("%d is Armstrong\n", x);
    else
        printf("%d is not Armstrong\n", x);  
    return 0;
}
Output:

Run 1:
153 is Armstrong
1253 is not Armstrong

11 Implement a C program to maintain a record of n students using an array of


structures and write function to perform following operations.
a) Declare a structure with the structure members USN Number, Name, Marks
and Grade by assuming appropriate data type.
b) Read and write n students structure data.
c) Search on roll no and display all the records.
d) Average marks in each test.
e) Highest marks in each test.
sol #include<stdio.h>
typedef struct student
{
char name[10];
int rollno,t[3];
}stud;
int main()
{
int i,roll,n,a,msum=0,grt,j;
stud s[20];
printf("enter the number of students= ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nenter the name of %d student= ",i+1);
scanf("%s",s[i].name);
printf("\nenter the roll no of %d student= ",i+1);
scanf("%d",&s[i].rollno);
printf("\nenter the 3 test scores of %d student= ",i+1);
scanf("%d%d%d",&s[i].t[0],&s[i].t[1],&s[i].t[2]);
}
printf("\nenter the rollno of the student details required= ");
scanf("%d",&roll);
for(i=0;i<n;i++)
{
if(s[i].rollno==roll)
break;
else
continue;
}
a=i;
printf("\nthe name of the student is= ");
printf("%s",s[a].name);
printf("\nthe 3 test scores of the student= ");
printf("%d %d %d",s[a].t[0],s[a].t[1],s[a].t[2]);
for(i=0;i<n;i++)
{
msum=(s[i].t[0]+s[i].t[1]+s[i].t[2])/3;
if(s[i].t[0] > s[i].t[1])
{
if(s[i].t[0] > s[i].t[2])
grt=s[i].t[0];
else
grt=s[i].t[2];
}
else if(s[i].t[1] > s[i].t[2])
grt=s[i].t[1];
else
grt=s[i].t[2];
printf("\n the average mark of %d student is %d",i+1,msum);
printf("\n greatest mark of %d student is %d",i+1,grt);
printf("\n ");
}
return 0;
}
12 Develop and demonstrate addition of one dimensional and two dimensional array
elements using Pointer concept.
sol /*** C program to add two matrix using pointers. */
#include <stdio.h>

#define ROWS 3
#define COLS 3

/* Function declaration to input, add and print matrix */

void matrixInput(int mat[][COLS]);


void matrixPrint(int mat[][COLS]);
void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS]);

int main()
{
int mat1[ROWS][COLS], mat2[ROWS][COLS], res[ROWS][COLS];

// Input elements in first matrix


printf("Enter elements in first matrix of size %dx%d: \n", ROWS, COLS);
matrixInput(mat1);

// Input element in second matrix


printf("\nEnter elemetns in second matrix of size %dx%d: \n", ROWS, COLS);
matrixInput(mat2);

// Find sum of both matrices and print result


matrixAdd(mat1, mat2, res);

printf("\nSum of first and second matrix: \n");


matrixPrint(res);

return 0;
}

/** * Function to read input from user and store in matrix. *


* @mat Two dimensional integer array to store input.
*/

void matrixInput(int mat[][COLS])


{
int i, j;

for (i = 0; i < ROWS; i++)


{
for (j = 0; j < COLS; j++)
{
// (*(mat + i) + j) is equal to &mat[i][j]
scanf("%d", (*(mat + i) + j));
}
}
}

/**
* Function to print elements of matrix on console.
*
* @mat Two dimensional integer array to print.
*/
void matrixPrint(int mat[][COLS])
{
int i, j;

for (i = 0; i < ROWS; i++)


{
for (j = 0; j < COLS; j++)
{
// *(*(mat + i) + j) is equal to mat[i][j]
printf("%d ", *(*(mat + i) + j));
}
printf("\n");
}
}

/**
* Function to add two matrices and store their result in given res
* matrix. * * @mat1 First matrix to add.
* @mat2 Second matrix to add.
* @res Resultant matrix to store sum of mat1 and mat2.
*/

void matrixAdd(int mat1[][COLS], int mat2[][COLS], int res[][COLS])


{
int i, j;

// Iterate over each matrix elements


for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
// res[i][j] = mat1[i][j] + mat2[i][j]
*(*(res + i) + j) = *(*(mat1 + i) + j) + *(*(mat2 + i) + j);
}
}
}

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

Output:

Run 1:
Enter elements in first matrix of size 3x3:
123
456
789

Enter elemetns in second matrix of size 3x3:


987
654
321

Sum of first and second matrix:


10 10 10
10 10 10
10 10 10
-----------------------------------------------------------------------------------------------------
----------------

#include<stdio.h>
int main()
{
int array[10];
int i,sum=0,n;
int *ptr;

printf(“Enter the size of array\n”):


scanf(%d”,&n);
printf("\nEnter array elements:");
for(i=0;i<n;i++)
scanf("%d",&array[i]);

/* array is equal to base address


* array = &array[0] */
ptr = array;

for(i=0;i<n;i++)
{
//*ptr refers to the value at address
sum = sum + *ptr;
ptr++;
}

printf("\nThe sum is: %d",sum);


}

Output:

Run 1:
Enter the size of array
5
Enter array elements: 1 2 3 4 5
The sum is: 15
13 Write a C program to perform the following operations using recursive functions:
i)GCD, LCM (Using GCD method)
ii) Binary to Decimal Conversion
sol
#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;
}

ii) 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:

Run 1:

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

VIVA QUESTIONS
TUTORIAL QUESTIONS

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 )

You might also like