C Programming Laboratory
C Programming Laboratory
I SEMESTER
1901010 - ‘C’ PROGRAMMING LABORATORY
Regulation – 2019
Prepared by
1
SYLLABUS
List of Programs
TOTAL: 60 PERIODS
COURSE OUTCOMES:
Develop C programs for simple applications making use of basic constructs, arrays and strings.
Develop C programs involving functions, recursion, pointers, and structures.
Design applications using sequential and random access file processing.
2
INDEX
Page No
S.No Topic
Programs using I/O statements and expressions for sum of odd and even
1.
numbers.
4
2. Programs using decision-making constructs- Pay Calculation. 7
Write a program to find whether the given year is leap year or Not.
3. (Hint: not every centurion year is a leap. For example 1700, 1800 and 13
1900 is not a leap year)
Write a program to perform the Calculator operations, namely, addition,
4. subtraction, multiplication, division and square of a number. 15
5. Check whether a given number is Armstrong number or not. 17
6. Check whether a given number is odd or even. 19
7. Write a program to perform factorial of a number. 20
8. Write a C program to find out the average height of persons. 22
Two dimensional array with height and weight of persons and compute
9. 24
the Body Mass Index of the individuals.
10. Write a C program to perform swapping using function. 26
11. Display all prime numbers between two intervals using functions. 28
12. Reverse a sentence using recursion. 31
Write a program in C to get the largest element of an array using the
13. 32
function.
14. Write a C program to concatenate two string. 34
15. Write a C program to find the length of String. 36
16. Find the frequency of a character in a string. 37
17. Write a C program to Store Student Information in Structure and Display it. 39
18. The annual examination is conducted for 10 students for five subjects.
Write a program to read the data and determine the following:
(a) Total marks obtained by each student. 41
(b) The highest marks in each subject and the marks of the student who
secured it.(c) The student who obtained the highest total marks
Create a Railway reservation system in C with the following modules
• Booking
19. • Availability checking 44
• Cancellation
• Prepare chart
Additional C Programs for exercise 49
C Language Questions and Answers Viva – Voce 59
3
Ex.No. : 1 Program using I/O Statements and Expressions for sum of odd and even
numbers.
Date :
Aim
To write a C Program to perform I/O statements and expressions for sum of odd and even
numbers..
ALGORITHM
1. Start
6. Stop
PROGRAM
/*
* Sum the odd and even numbers, respectively, from 1 to a given upperbound.
* (SumOddEven.c)
*/
int main() {
int number = 1;
} else {
return 0;
5
OUTPUT
RESULT:
Thus a C Program using i/o statements and expressions was executed and the output was
obtained.
6
Ex.No: 2A Programs using decision-making constructs- Pay Calculation .
DATE :
AIM
To write a C Program to perform decision-making constructs- Pay Calculation.
ALGORITHM
1. Start
2. Declare variables and initializations
3. Read the Input variable.
4. Codes are given to different categories and da is calculated as follows:
For code 1,10% of basic salary.
For code 2, 15% of basic salary.
For code 3, 20% of basic salary.
For code >3 da is not given.
PROGRAM
#include <stdio.h>
#include<conio.h>
void main ()
{
float basic , da , salary ;
int code ;
char name[25];
da=0.0;
printf("Enter employee name\n");
scanf("%[^\n]",name);
printf("Enter basic salary\n");
scanf("%f",&basic);
7
printf("Enter code of the Employee\n");
scanf("%d",&code);
switch (code)
{
case 1:
da = basic * 0.10;
break;
case 2:
da = basic * 0.15;
break;
case 3:
da = basic * 0.20; break;
default :
da = 0;
}
salary = basic + da;
printf("Employee name is\n");
printf("%s\n",name);
printf ("DA is %f and Total salary is =%f\n",da, salary);
getch();
}
8
OUTPUT
RESULT
Thus a C Program using decision-making constructs was executed and the output was obtained.
9
2B. Example of if ... else if ... else statement
Aim:
To write a C program to find if a number is negative, positive or zerousing if ... else if ...
else statement.
Algorithm:
1. Start the program
2. Get the number
3. Check the number if it is negative, positive or equal to using if statement.
4. If the number is < 0print number is negative, else if the number is >0 print it is positive else
the number =0.
5. Display the result
6. Stop the program.
Program:
#include<stdio.h>
int main()
{
int n;
printf("Enter a number:");
scanf("%d",&n);
if(n<0)
printf("Number is negative");
else if(n>0)
printf("Number is positive");
else
printf("Number is equal to zero");
return 0;
}
Output
Enter a number:109
Number is positive
Enter a number:-56
Number is negative
Enter a number:0
Number is equal to zero
10
2C.Switch Statement
Switch case can be considered as simplified version of if statement. When there are large
number of conditions to be tested, it is difficult to use if statement as the number of repeated if
statements may cause confusion and makes the program unreadable. So, switch case is preferred
in such cases to simplify programmer’s job and increases code readability.
Aim:
To write a C program to check if entered alphabet is vowel or a consonant using switch case.
Algorithm:
Program:
#include <stdio.h>
int main()
{
char alphabet;
printf("Enter an alphabet:");
scanf("%c",&alphabet);
switch(alphabet)
{
case 'a':
printf("Alphabet a is a vowel.\n");
case 'e':
printf("Alphabet e is a vowel.\n");
case 'i':
printf("Alphabet i is a vowel.\n");
case 'o':
printf("Alphabet o is a vowel.\n");
case 'u':
printf("Alphabet u is a vowel.\n");
default:
printf("You entered a consonant.\n");
}
11
return 0;
}
Output
Enter an alphabet:i
Alphabet i is a vowel.
Alphabet o is a vowel.
Alphabet u is a vowel.
You entered a consonant.
Result:
Thus the C program using decision-making construct has been verified and executed
successfully.
12
Ex.No: 3. Write a program to find whether the given year is leap year or Not? (Hint:
not every centurion year is a leap. For example 1700, 1800 and 1900 is not a
leap year)
Aim:
To write a C program to find whether the given year is leap year or not using switch case.
Algorithm:
Program:
#include <stdio.h>
int main()
{
int year;
printf("Enter a year: ");
scanf("%d",&year);
if(year%4 == 0)
{
if( year%100 == 0)
{
// year is divisible by 400, hence the year is a leap year
if ( year%400 == 0)
printf("%d is a leap year.", year);
else
printf("%d is not a leap year.", year);
}
else
printf("%d is a leap year.", year );
}
else
printf("%d is not a leap year.", year);
return 0;
}
13
Output
Enter a year: 1900
1900 is not a leap year.
Result:
Thus the C program using to find whether the given year is leap or not year has been
successfully verified and executed.
14
Ex.No: 4. Write a program to perform the Calculator operations, namely, addition,
subtraction, multiplication, division and square of a number.
Aim:
To write a C program to perform calculator operation using the switch case.
Algorithm:
Program:
#include <stdio.h>
int main()
{
int num1,num2;
float result 0.0 ;
charch; //to store operator choice
result=0;
switch(ch)
{
case'+':
result=num1+num2;
break;
case'-':
result=num1-num2;
break;
15
case'*':
result=num1*num2;
break;
case'/':
result=(float)num1/(float)num2;
break;
case 's':
result=num1*num1;
break;
default:
printf("Invalid operation.\n");
}
printf("Result: %d %c %d = %f\n",num1,ch,num2,result);
return 0;
}
Output
First run:
Enter first number: 10
Enter second number: 20
Choose operation to perform (+,-,*,/,%): +
Result: 10 + 20 = 30.000000
Second run:
Enter first number: 10
Enter second number: 3
Choose operation to perform (+,-,*,/,%): /
Result: 10 / 3 = 3.333333
Third run:
Enter first number: 10
Enter second number: 3
Choose operation to perform (+,-,*,/,%): >
Invalid operation.
Result: 10 > 3 = 0.000000
Result:
Thus the C program using to perform calculator operation has been successfully verified
and executed.
16
Ex.No: 5. Check whether a given number is Armstrong number or not?
Aim:
To write a C program to check whether a given number is Armstrong number or not
using switch case.
Algorithm:
Program:
#include <stdio.h>
int main()
{
int number, originalNumber, remainder, result = 0;
printf("Enter a three digit integer: ");
scanf("%d", &number);
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber%10;
result += remainder*remainder*remainder;
originalNumber /= 10;
}
if(result == number)
printf("%d is an Armstrong number.",number);
else
printf("%d is not an Armstrong number.",number);
return 0;
}
17
Output
Result:
Thus the C program to check whether a given number is armstrongor not has been
successfully verified and executed.
18
Ex.No: 6. Write a C program to check whether a given number is odd or even.
Aim:
To write a C program to find an odd or even number.
Algorithm:
Program:
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the number is perfectly divisible by 2
if(number % 2 == 0)
printf("%d is even.", number);
else
printf("%d is odd.", number);
return 0;
}
Output
Enter an integer: -7
-7 is odd.
Result:
Thus the C program to find an odd or even number has been successfully verified and
executed.
19
Ex.No:7. Write a program to perform factorial of a number.
Aim:
To write a C program to find a factorial of a given number.
Algorithm:
Program:
#include <stdio.h>
int main()
{
int n, i;
long factorial = 1;
printf("Enter an integer: ");
scanf("%d",&n);
// show error if the user enters a negative integer
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else
{
for(i=1; i<=n; ++i)
{
factorial *= i; // factorial = factorial*i;
}
printf("Factorial of %d = %lu", n, factorial);
}
return 0;
}
20
Output
Enter an integer: 10
Factorial of 10 = 3628800
Result:
Thus the C program to find the factorial of a given number has been successfully
executed and verified.
21
Ex.No: 8. Write a C program to find out the average height of persons.
Aim:
To write a C program to find average height of persons,
Algorithm:
1. Start
2. Declare variables
3. Read the total number of persons and their height.
4. Calculate avg=sum/n and find number of persons their h>avg.
5. Display the output of the calculations .
6. Stop
Program
Output
Result
Thus a C Program average height of persons was executed and the output was obtained.
23
Ex.No:9. Compute the Body Mass Index of the individuals using 2D array.
Aim:
To write a C Program to Populate a two dimensional array with height and weight of
persons and compute the Body Mass Index of the individuals..
Algorithm
1. Start
2. Declare variables
3. Read the number of persons and their height and weight.
4. Calculate BMI=W/H2for each person
5. Display the output of the BMI for each person.
6. Stop
PROGRAM
#include<stdio.h>
#include<math.h>
int main(void){
int n,i,j;
float massheight[n][2];
float bmi[n];
for(i=0;i<n;i++){
for(j=0;j<2;j++){
switch(j){
case 0:
printf("\nPlease enter the mass of the person %d in kg: ",i+1);
scanf("%f",&massheight[i][0]);
break;
case 1:
printf("\nPlease enter the height of the person %d in meter: ",i+1);
24
scanf("%f",&massheight[i][1]);
break;}
}
}
for(i=0;i<n;i++){
bmi[i]=massheight[i][0]/pow(massheight[i][1],2.0);
printf("Person %d's BMI is %f\n",i+1,bmi[i]);
}
return 0;
}
OUTPUT
Result
Thus a C Program Body Mass Index of the individuals was executed and the output was
obtained.
25
Ex.No:10. Write a C program to perform swapping using function.
Aim:
Algorithm:
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
void swap(int,int);
inta,b,r;
clrscr();
printf("enter value for a&b: ");
scanf("%d%d",&a,&b);
swap(a,b);
getch();
}
void swap(inta,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("after swapping the value for a & b is : %d %d",a,b);
}
26
Output:
enter value for a&b: 4
5
after swapping the value for a &b : 5 4
Result:
Thus the C program to perform swapping using function has been successfully executed
and verified.
27
Ex.No: 11. Write a C program to display all prime numbers between two intervals using
functions.
Aim:
To write a C program to display all prime numbers between two intervals using
functions.
Algorithm:
Program:
#include <stdio.h>
/* Function declarations */
intisPrime(intnum);
voidprintPrimes(intlowerLimit, intupperLimit);
int main()
intlowerLimit, upperLimit;
printPrimes(lowerLimit, upperLimit);
return 0;
28
}
voidprintPrimes(intlowerLimit, intupperLimit)
while(lowerLimit<= upperLimit)
if(isPrime(lowerLimit))
lowerLimit++;
/**
intisPrime(intnum)
int i;
if(num % i == 0)
{ return 0;
return 1;
29
}
Output
Enter the lower and upper limit to list primes 20 50
Prime numbers between 20 and 50 are: 23 29 31 37 41 43 47
Result:
Thus the C program to display all prime numbers between two intervals using functions
has been successfully executed and verified.
30
Ex.No:12. Write a C program to reverse a sentence using recursion.
Aim:
Algorithm:
Program:
#include <stdio.h>
VoidreverseSentence();
int main()
{
printf("Enter a sentence: ");
reverseSentence();
return 0;
}
VoidreverseSentence()
{
char c;
scanf("%c", &c);
if( c != '\n')
{
reverseSentence();
printf("%c",c);
}
}
Output
31
Ex.No: 13. Write a program in C to get the largest element of an array using the
function.
Aim:
Algorithm:
Program:
int main()
{
int array[100], maximum, size, c, location = 1;
maximum = array[0];
32
Output:
Enter the number of elements in array
5
Enter 5 integers
4
5
6
8
2
Maximum element present at location 4 and its value is 8
Result:
Thus the C program to get the largest element of an array using the function has been
successfully executed and verified.
33
Ex.No:14. Write a C program to concatenate two strings.
Aim:
Algorithm:
Program:
#include <stdio.h>
int main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);
// calculate the length of string s1
// and store it in i
for(i = 0; s1[i] != '\0'; ++i);
for(j = 0; s2[j] != '\0'; ++j, ++i)
{
s1[i] = s2[j];
}
s1[i] = '\0';
printf("After concatenation: %s", s1);
return 0;
}
34
Output
Result:
Thus the C program to concatenate two strings has been successfully executed and
verified.
35
Ex.No: 15. Write a C program to find the length of String.
Aim:
Algorithm:
Program:
#include <stdio.h>
int main()
{
char s[1000];
inti;
printf("Enter a string: ");
scanf("%s", s);
for(i = 0; s[i] != '\0'; ++i);
printf("Length of string: %d", i);
return 0;
}
Output:
Length of string: 7
Result:
Thus the C program to find the length of String has been successfully executed and
verified.
36
Ex.No: 16. Find the frequency of a character in a string.
Aim:
Algorithm:
Program:
#include <stdio.h>
int main()
{
Charstr[1000], ch;
inti, frequency = 0;
printf("Enter a string: ");
gets(str);
printf("Enter a character to find the frequency: ");
scanf("%c",&ch);
for(i = 0; str[i] != '\0'; ++i)
{
if(ch == str[i])
++frequency;
}
printf("Frequency of %c = %d", ch, frequency);
return 0;
}
37
Output
Result:
Thus the C program to find the frequency of a character in a string has been successfully
executed and verified.
38
Ex.No: 17. Write a C program to Store Student Information in Structure and Display it.
Aim:
Algorithm:
Program:
#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s[10];
int main()
{
inti;
printf("Enter information of students:\n");
// storing information
for(i=0; i<10; ++i)
{
s[i].roll = i+1;
printf("\nFor roll number%d,\n",s[i].roll);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%f",&s[i].marks);
printf("\n");
}
printf("Displaying Information:\n\n");
39
// displaying information
for(i=0; i<10; ++i)
{
printf("\nRoll number: %d\n",i+1);
printf("Name: ");
puts(s[i].name);
printf("Marks: %.1f",s[i].marks);
printf("\n");
}
return 0;
}
Output:
Roll number: 1
Name: Tom
Marks: 98
.
.For roll number2,
Enter name: Jerry
Enter marks: 89
Result:
Thus the C program to store Student Information in Structure has been successfully
executed and verified.
40
Ex.No: 18. The annual examination is conducted for 10 students for five subjects. Write
a program to read the data and determine the following:
To write a C program to get various details regarding the marks obtained by the students.
Algorithm:
Program:
#include<stdio.h>
#define SIZE 50
struct student {
char name[30];
introllno;
int sub[3];
};
void main() {
inti, j, max, count, total, n, a[SIZE], ni;
struct student st[SIZE];
clrscr();
printf("Enter how many students: ");
scanf("%d", &n);
/* for loop to read the names and roll numbers*/
for (i = 0; i< n; i++) {
printf("\nEnter name and roll number for student %d : ", i);
scanf("%s", &st[i].name);
scanf("%d", &st[i].rollno);
41
}
/* for loop to read ith student's jth subject*/
for (i = 0; i< n; i++) {
for (j = 0; j <= 2; j++) {
printf("\nEnter marks of student %d for subject %d : ", i, j);
scanf("%d", &st[i].sub[j]);
}
}
/* (i) for loop to calculate total marks obtained by each student*/
for (i = 0; i< n; i++) {
total = 0;
for (j = 0; j < 3; j++) {
total = total + st[i].sub[j];
}
printf("\nTotal marks obtained by student %s are %dn", st[i].name,total);
a[i] = total;
}
/* (ii) for loop to list out the student's roll numbers who
have secured the highest marks in each subject */
/* roll number who secured the highest marks */
for (j = 0; j < 3; j++) {
max = 0;
for (i = 0; i< n; i++) {
if (max <st[i].sub[j]) {
max = st[i].sub[j];
ni = i;
}
}
printf("\nStudent %s got maximum marks = %d in Subject : %d",st[ni].name, max, j);
}
max = 0;
for (i = 0; i< n; i++) {
if (max < a[i]) {
max = a[i];
ni = i;
}
}
printf("\n%s obtained the total highest marks.", st[ni].name);
getch();
}
42
Output:
Enter how many students: 2
Enter name and roll number for student 0 : Pritesh 1
Enter name and roll number for student 1 :Suraj 2
Enter marks of student 0 for subject 0 : 90
Enter marks of student 0 for subject 1 : 89
Enter marks of student 0 for subject 2 : 78
Enter marks of student 1 for subject 0 : 67
Enter marks of student 1 for subject 1 : 88
Enter marks of student 1 for subject 2 : 99
Total marks obtained by student Pritesh are 257
Total marks obtained by student Suraj are 254
Student Pritesh got maximum marks = 90 in Subject : 0
Student Pritesh got maximum marks = 89 in Subject : 1
Student Suraj got maximum marks = 99 in Subject : 2
Pritesh obtained the total highest marks.
Result:
Thus the C program to get various details regarding the marks obtained by the students
has been successfully executed and verified.
43
EX.No. : 19 Railway reservation system
DATE :
Aim
Create a Railway reservation system in C with the following modules
• Booking
• Availability checking
• Cancellation
• Prepare chart
.
Algorithm
1. Start
2. Declare variables
3. Display the menu options
4. Read the option.
5. Develop the code for each option.
6. Display the output of the selected option based on existence .
7. Stop
PROGRAM
#include<stdio.h>
#include<conio.h>
int first=5,second=5,thired=5;
struct node
{
int ticketno;
int phoneno;
char name[100];
char address[100];
}s[15];
int i=0;
void booking()
{
printf("enter your details");
printf("\nname:");
44
scanf("%s",s[i].name);
printf("\nphonenumber:");
scanf("%d",&s[i].phoneno);
printf("\naddress:");
scanf("%s",s[i].address);
printf("\nticketnumber only 1-10:");
scanf("%d",&s[i].ticketno);
i++;
}
void availability()
{
int c;
printf("availability cheking");
printf("\n1.first class\n2.second class\n3.thired class\n");
printf("enter the option");
scanf("%d",&c);
switch(c)
{
case 1:if(first>0)
{
printf("seat available\n");
first--;
}
else
{
printf("seat not available");
}
break;
case 2: if(second>0)
{
printf("seat available\n");
second--;
}
else
{
printf("seat not available");
}
break;
case 3:if(thired>0)
{
printf("seat available\n");
thired--;
}
45
else
{
printf("seat not available");
}
break;
default:
break;
}
}
void cancel()
{
int c;
printf("cancel\n");
printf("which class you want to cancel");
printf("\n1.first class\n2.second class\n3.thired class\n");
printf("enter the option");
scanf("%d",c);
switch(c)
{
case 1:
first++;
break;
case 2:
second++;
break;
case 3:
thired++;
break;
default:
break;
}
printf("ticket is canceled");
}
void chart()
{
int c;
for(c=0;c<I;c++)
{
printf(“\n Ticket No\t Name\n”);
printf(“%d\t%s\n”,s[c].ticketno,s[c].name)
}
}
main()
46
{
int n;
clrscr();
printf("welcome to railway ticket reservation\n");
while(1) {
printf("1.booking\n2.availability cheking\n3.cancel\n4.Chart \n5. Exit\nenter your option:");
scanf("%d",&n);
switch(n)
{
case 1: booking();
break;
case 2: availability();
break;
case 3: cancel();
break;
case 4:
chart();
break;
case 5:
printf(“\n Thank you visit again!”);
getch();
exit(0);
default:
break;
}
}
getch();
}
Output
47
enter your option: 2
availability cheking
1.first class
2.second class
3.thired class
Result
Thus a C Program for Railway reservation system was executed and the output was obtained.
48
Additional C Programs for exercise
1. To write a C program for temperature conversion from Celsius to Fahrenheit and vice
versa.
#include<stdio.h>
main()
clrscr();
scanf(“%f”,&f);
cel=(5.0/9.0)*(f-32);
printf(“Celsius=%d”,cel);
scanf(“%f”,&c);
fah=(9.0/5.0)*c+32;
printf(“Fahrenheit=%d”,fah);
getch();
49
2. C Program to print the sine series.
#include<stdio.h>
#include<math.h>
#include<conio.h>
void main()
{
int i,n;
float x,y,z,sum,t; clrscr();
printf("\t\t PROGRAM TO PRINT SINE SERIES\t\t\n"); printf("\t\t t\t\n");
printf("\n ENTER THE ANGLE:");
scanf("%f", &x);
printf("\n ENTER THE NUMBER OF TERMS:");
scanf("%d", &n);
z=x; x=x*(3.14/180);
sum=x; t=x;
for(i=2; i<=n; i=i+2)
{
t=t*(-x*x)/((2*i-1)*(2*i-2)); sum=sum+t;
}
printf("\n\n THE VALUE OF SIN(%5.2f) IS %5.2f\n", z, sum); getch();
}
50
3. Program to print current system date.
#include <stdio.h>
#include <conio.h>
#include <dos.h>
int main()
{
struct date d;
getdate(&d);
printf("Current system date is %d/%d/%d",d.da_day,d.da_mon,d.da_year);
getch();
return 0;
}.
51
4.Program to calculate Standard Deviation.
#include <stdio.h>
#include <math.h>
float standard_deviation(float data[], int n);
int main()
{ int n, i;
float data[100];
printf("Enter number of datas( should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0; i<n; ++i)
scanf("%f",&data[i]);
printf("\n");
printf("Standard Deviation = %.2f", standard_deviation(data,n));
return 0;
}
float standard_deviation(float data[], int n)
{
float mean=0.0, sum_deviation=0.0;
int i;
for(i=0; i<n;++i)
{
mean+=data[i];
}
mean=mean/n;
for(i=0; i<n;++i)
sum_deviation+=(data[i]-mean)*(data[i]-mean);
52
return sqrt(sum_deviation/n);
}
53
6. Program to find the ASCII value of a Character.
#include <stdio.h>
int main(){
char c;
printf("Enter a character: ");
scanf("%c",&c); /* Takes a character from user */
printf("ASCII value of %c = %d",c,c);
return 0;
}
54
7. Program to find biggest of four no by using ternary numbers.
#include<stdio.h>
#include<conio.h>
void main( )
{
int a,b,c,d,big;
clrscr( );
printf(“enter value a”);
scanf(“%d”,&a);
printf(“enter the value of b”);
scanf(“%d”,&b);
printf(“enter the value of c”);
scanf(“%d”,&c);
printf(“enter the value of d”);
scanf(“%d”,&d);
big=(a>b)?(a>c)?(a>d)?a:d:(c>d)?c:d:(b>c)?(b>d)?b:d:(c>d)?c:d;
printf(“Biggest of the given 4 numbers is %d”,big);
getch();
}
55
8. Matrix Multiplication.
#include <stdio.h>
int main()
{
int m, n, p, q, c, d, k, sum = 0;
int first[10][10], second[10][10], multiply[10][10];
printf("\nEnter the number of rows and columns of first matrix:\n");
scanf("%d%d", &m, &n);
/*//Entering elements of first matrix
printf("\n Enter the elements of first matrix\n");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);*/
printf("\nEnter the number of rows and columns of second matrix:\n");
scanf("%d%d", &p, &q);
//Checking if Matrix Multiplication is possible
if ( n != p )
{
printf("\nMatrices with entered orders can't be multiplied with each other.\n");
printf("\nThe column of first matrix should be equal to row of second.\n");
}
else
{
//Entering elements of first matrix
printf("\nEnter the elements of first matrix:\n");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
scanf("%d", &first[c][d]);
//Entering elements of second matrix
printf("\nEnter the elements of second matrix:\n");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
scanf("%d", &second[c][d]);
//Carrying out matrix multiplication operation
for ( c = 0 ; c < m ; c++ )
{
56
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
//Printing the final product matrix
printf("\nThe product of entered matrices is:\n");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
}
57
9. C Program to reverse the digits of a number.
#include<stdio.h>
#include<conio.h>
void main()
{
int n, reverse = 0; clrscr();
printf("REVERSAL OF A GIVEN NUMBER\n"); printf(" \n");
printf("ENTER A NUMBER TO REVERSE: \n");
scanf("%d",&n); while (n != 0)
{
reverse = reverse * 10; reverse = reverse + n%10; n = n/10;
}
printf("REVERSE OF ENTERED NUMBER IS: %d\n", reverse);
getch();
}
58
C Language Questions and Answers Viva - Voce
1. What is C language?
C is a programming language developed at AT&T's Bell Laboratories of USA in 1972. The
C programming language is a standardized programming language developed in the early
1970s by KenThompson and Dennis Ritchie for use on the UNIX operating system. It has
since spread to manyother operating systems, and is one of the most widely used
programming languages.
2. What is an array?
Array is a variable that hold multiple elements which has the same data type.
It is a user-defined function.
Automatic
Extern
Register
Static
5. What is a structure?
59
Structure constitutes a super data type which represents several different data types in a
single unit. A structure can be initialized if it is static or global.
It also reduces the Time to run a program. In other way, it’s directly proportional to
Complexity.
It’s easy to find-out the errors due to the blocks made as function definition outside the
mainfunction.
60
The typedef help in easier modification when the programs are ported to another machine.
A descriptive new name given to the existing data type may be easier to understand the
code.
13. Differentiate between for loop and a while loop? What are it uses?
For executing a set of statements fixed number of times we use for loop while when the
number of iterations to be performed is not known in advance we use while loop.
14. What are register variables? What are the advantages of using register variables?
If a variable is declared with a register storage class, it is known as register variable. The
register variable is stored in the CPU register instead of main memory. Frequently used
variables aredeclared as register variable as it’s access time is faster.
Difficult to find.
Enumerated types allow the programmers to use more meaningful words as values to
a variable.
Each item in the enumerated type variable is actually associated with a numeric code.
With ++a, the increment happens first on variable a, and the resulting value is used.
Thisis called as prefix increment.
With a++, the current value of the variable will be used in an operation. This is called as
postfix increment.
21. What will happen when you access the array more than its dimension?
If the index of the array size is exceeded, the program will crash. But the modern compilers
will take care of this kind of errors.
62
‘\0’ is the null character. Every string literal constant is automatically terminated by ‘\0’.
The number of bytes required to store a string literal constant is one more than the number
of characters present in it. The additional byte is required for storing ‘\0’.
‘%s’ is the format specifier used in scanf function that reads all the characters up to, but
not including the white-space character. Thus, scanf function with ‘%s’ specifier can be
used to read single word strings but cannot be used to read multi-word strings.
25. Is it mandatory that the size of all elements in a union should be same?
No.The standard only guarantee that the size of a union is sufficient for the largest
member, i.e, not necessarily the same size.
****
63