Create A New File Using Gedit/vi Filename.c: Solutions To Lab Programs With Expected Input and Output
Create A New File Using Gedit/vi Filename.c: Solutions To Lab Programs With Expected Input and Output
Create A New File Using Gedit/vi Filename.c: 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:
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(.)
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'
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
#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
// 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
// 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");
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
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;
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:
1-ADD
2-SUB
3-MULTI
4-DIVIDE
The result is 5
Run 3:
1-ADD
2-SUB
3-MULTI
4-DIVIDE
The result is 30
Run 4:
1-ADD
2-SUB
3-MULTI
4-DIVIDE
The result is 3
Run 5:
1-ADD
2-SUB
3-MULTI
4-DIVIDE
Run 6:
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);
}
Output
Run 1:
Enter the coefficients:
1
2
1
Run 2:
Enter the coefficients:
1
5
4
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
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
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 */
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;
-----------------------------------------------------------------------------------------------------
-------
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.
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
--------------------------------------------------------------------------------------------------------
Output
Run 1:
Run 2:
Enter a string to check if it is a palindrome
Madam
mam
The entered word is a palindrome.
Run 1:
153 is Armstrong
1253 is not Armstrong
#define ROWS 3
#define COLS 3
int main()
{
int mat1[ROWS][COLS], mat2[ROWS][COLS], res[ROWS][COLS];
return 0;
}
/**
* Function to print elements of matrix on console.
*
* @mat Two dimensional integer array to print.
*/
void matrixPrint(int mat[][COLS])
{
int i, j;
/**
* 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.
*/
-----------------------------------------------------------------------------------------------------
--------
Output:
Run 1:
Enter elements in first matrix of size 3x3:
123
456
789
#include<stdio.h>
int main()
{
int array[10];
int i,sum=0,n;
int *ptr;
for(i=0;i<n;i++)
{
//*ptr refers to the value at address
sum = sum + *ptr;
ptr++;
}
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);
if(num1>num2)
lcm = find_lcm(num1,num2);
else
lcm = find_lcm(num2,num1);
return temp;
}
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:
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;
}
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:
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 )