Lab Mannual
Lab Mannual
AND MANAGEMENT
Udayapura, Kanakapura Road, Opp. Art of Living, Bangalore – 560082
(Affliated to VTU, Belagavi, Approved by AICTE, New Delhi, Accredited by NBA, New Delhi)
(Autonomous to VTU)
2023-2024
Principals of Programming Using C
Laboratory Manual
(23ESCS11)
Compiled by:
Asst. Prof. Shreenidhi B S
1. Creating an academic environment to develop the younger generation and providing quality
professional engineering education at an affordable cost.
2. Create necessary infrastructure on a continuous basis the professional education with the changing
needs of society.
3. Optimum utilization of the infrastructure and resources to achieve excellence in the
engineering courses.
4. Monitor continuously the growth in technology parts of the world and address all aspects of
development of human resource (both from academic and supporting staff) and students to be in
tune with state of the art technology and engineering practices.
5. Facilitate greater Industry, Institute, and Interaction so as to empower the students with practical
knowledge.
6. Institute various quality assurance systems.
7. Adopting learning beyond curriculum process.
8. Initiate systems of learning which are based on enable students to acquire skills relevant to their
career.
9. To continuous monitor, asses evaluate the various academic programs adopting outcome-based
education.
COMPUTER PROGRAMMING LABORATORY
Outcome-Based Education (OBE) and Choice Based Credit System (CBCS)
(Effective from the academic year 2023 – 24)
List of problems for which students should develop the program and execute in the
Laboratory
Sl. No. Experiments/Programs Page No.
1 Write a C program to implement a Simple Calculator. 1
a) Compute the roots of a quadratic equation by accepting the coefficients. Print appropriate
2 messages. 4
b) Write a C program to print Pyramid of stars patterns using Looping
Implement Matrix multiplication and validate the rules of multiplication using C Program.
3 10
Write a C program for the following condition using Functions, Assume a Car servicing
Center. Every service request by the Car Service Center the given charges are levied along
with taxes.
a. Car water wash - Rs. 500 + 10% tax
b. Oil in the Engine must be at least 300 ml. If it goes below 300 ml
(Ask the user to input the current level of oil in the engine),
4 14
top up is done by the agency (the value of top up is given by the user so that level is at least
300 ml). Cost of 1 ml is Rs. 5 + 12.5% tax.
1. Define suitable variables to capture the above 2 parameters and corresponding taxes
2. Compute the total amount to be paid.
3. Display the total with 17 places which includes 7 places for fraction. The integer part of
the total must be prefixed with 0’s and a sign, if required.
Write a program in C using functions to swap two numbers using global variables concept
5 16
and call by reference concept.
Implement a C program to read the values from the user today’s date and your Date of birth
in the format dd-mm-yyyy. Consider your sleeping time 8 hours a day, read 12 hours and
spend 1.5 hours a day for eating. Calculate how many minutes have you spent as of this date
6 17
for Sleeping and Eating.
The number of years you have spent for reading as of this date (amount of time spent for
reading in years).
a) Write functions to implement string operations such as compare, concatenate, and find
7 string length. Use the parameter passing techniques. 19
b) Implement a C Program to check String is a Palindrome or Not
8 Write a C Program to Implement linear search and binary search. 24
9 Write a C Program to Implement Bubble Sort. 29
Write a C program to read employee information (Name, Designation, Salary) from the user
10 32
and write it to a file.
Write a C Program to input even & odd elements of an array in two separate arrays. The
11 program first finds the odd and even elements of the array. Then the odd elements of an array 34
are stored in one array and even elements of an array is stored in another array
Write a C program to define a structure to represent a cricketer's information (name, runs,
12 average). Read the data corresponding to N Cricketer's in a structure array. The space for the 36
array of structures should be determined at run-time by user input.
Open ended Programs
1 Develop a ‘C’ program to calculate the gravitational pull between two objects.
2 Demonstrate a simple units convertor for distance, temperature, and liquid volume.
3 Calculate the displacement for an automobile using pointers.
4 Demonstrate the use of an array of pointers.
CIE for Principles of Programming Using C (Integrated Professional Core Course (IPCC)):
This Course refers to professional theory core course integrated with practical. Credit for this course can be 03
and its Teaching Learning hours (L : T : P: PJ) can be considered as (2 : 0 : 2 : 0).
15 marks for the conduction of practical experiment and preparation of the Laboratory record, and 10 marks for
the test to be conducted after the completion of all the laboratory sessions.
On completion of every program in the laboratory, the student shall be evaluated including viva-voce and marks
shall be awarded on the same day.
Each program report can be evaluated for 15 marks (Write-up – 3 marks, Execution – 8 marks .and Viva – 4
marks)
The Laboratory test (duration 2 hours / 3 hours) after completion of all the programs shall be conducted for 50
marks and scaled down to 10 marks.
The theory part of the IPCC shall be evaluated both by CIE and SEE. The practical part shall be evaluated by
only CIE (no SEE). However, questions from the practical part of IPCC shall be included in the SEE question
paper. This course is common to all branches of first year B.E/B.Tech. 2023-24 regulation.
Note: L- Theory Lecture, T- Tutorial, P-Practical, PJ-Project, IPCC: Integrated Professional Core Course, CIE:
Continuous Internal Evaluation, SEE: Semester End Examination.
.
C PROGRAMMING LAB 23ESCS11
PROGRAM-1
Write a C program to implement a Simple Calculator
Procedure: This program takes an arithmetic operator +,-,*,/,% and two operands from the
user and performs the calculation on the two operands depending upon the operator entered by
the user.
Input: An operator and two operands.
Expected Output: Performs calculation and display result depending upon the operator.
ALGORITHM
Algorithm Calculator
Step 1: Start
Step 2: Read num1 and num2
Step 3: Enter the operator
Step 4: Evaluate operator wit case statements
Step 4.1: case ‘+’ : result = num1+num2
goto step 6
Print result
Step 4.2: case ‘-’ : result = num1-num2
goto step 6
Print result
Step 4.3: case ‘*’ : result = num1*num2
goto step 6
Print result
Step 4.4: case ‘/’ : result = (float)num1/(float)num2
goto step 6
Print result
Step 4.5: case ‘%’ : result = num1%num2
goto step 6
Print result
Step 5: Enter operator is invalid then
Print “Invalid Operation”
Step 6: Print result
Step 7: Stop
FLOWCHART
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num1, num2;
float result=0;
char ch;
printf("Choose operation to perform (+,-,*,/,%%): ");
scanf(" %c", &ch);
switch(ch)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*': result=num1*num2;
break;
case '/':result=(float)num1/num2;
break;
case '%': result=num1%num2;
break;
default: printf("Invalid operation.\n");
exit(0);
}
printf("Result: %d %c %d = %f\n",num1,ch,num2,result); //display output on screen
OUTPUT:
Choose operation to perform (+,-,*,/,%): +
Enter first number: 10
Enter second number: 20
Result: 10 + 20 = 30.000000
PROGRAM-2
a) Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages.
Procedure: The equation in the form ax2+bx+c=0 is called quadratic equation. Read the
coefficients a,b,c and calculate discriminant. Based on the discriminant value, calculate roots
and print them with suitable messages.
Input: Three coefficients of quadratic equation ax2+bx+c=0: a, b, c
Expected Output: This program computes all possible roots for a given set of coefficients with
appropriate messages. The possible roots are: Real and Equal roots, Real and distinct roots,
imaginary roots.
ALGORITHM
Algorithm: Quadratic_Equation [This algorithm takes three coefficients as input and compute
the roots]
Step 1: [Start of the algorithm]
Start
Step 2: [Read the coefficients]
Read non zero coefficients a,b,c
Step 3: [calculate the discriminant]
dßb*b-4*a*c
Step 4: [check if roots are real and equal]
if (d=0)
x1ß-b/(2*a)
x2ß-b/ (2*a)
Print “Roots are equal”
Print x1, x2
Go to step 7
Step 5: [check if roots are real and distinct]
If(d>0)
x1ß(-b+sqrt (d)/ (2*a))
x2ß(-b-sqrt (d)/ (2*a))
Print “Roots are real and distinct”
Print x1,x2
Go to step 7
Step 6: [check if roots are imaginary]
If(d<0)
x1ß-b/(2*a)
x2ßsqrt (fabs(d))/(2*a)
Print “ The roots are complex”
Print “Root1 ß “, x1+ix2
Print “ Root2ß“, x1-ix2
FLOWCHART
START
Read a,b,c
d←b*b-4*a*c
is d=0 ? is d>0 ?
STOP
PROGRAM:
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,d,rpart,ipart,root1,root2;
printf("Enter three co-efficient\n");
scanf("%f%f%f",&a,&b,&c);
{
printf(“Invalid inputs”);
}
else if(a==0)
{
printf(“Linear Equation\n”);
root1=-c\b;
printf(“Root=%f\n”,root1);
}
else
{
d=(b*b)-(4*a*c);
if(d==0)
{
printf("The roots real and equal\n");
root1= -b/(2*a);
root2=root1;
printf("The roots are root1=%.3f and root2=%.3f\n",root1,root2);
}
else if(d>0)
{
printf("The roots are real and distinct\n");
root1=(-b+sqrt(d))/(2*a);
root2=(-b-sqrt(d))/(2*a);
printf("The roots are root1=%.3f and root2=%.3f\n",root1,root2);
}
else
{
printf("The roots are imaginary\n");
rpart=-b/(2*a);
ipart=sqrt(fabs(d))/(2*a);
printf("The first root root1=%.3f+i%.3f\n",rpart,ipart);
printf("The second root root2=%.3f-i%.3f\n",rpart,ipart);
}
}
}
OUTPUT:
.....................................................................
Run1:
Enter three co-efficient
1
2
3
FLOWCHART:
PROGRAM:
#include <stdio.h>
int main()
{
int i, j, rows;
OUTPUT:
Enter number of rows: 5
*
***
*****
*******
*********
PROGRAM-3
Implement Matrix multiplication and validate the rules of multiplication using C
Program.
Procedure: Input m*n and p*q size of 2 matrices elements to compute matrix multiplication.
ALGORITHM
Algorithm: Matrix_Multipication
PROGRAM:
#include<stdio.h>
int main()
{
int m,n,p,q,i,j,k,a[10][10],b[10][10],c[10][10];
printf("Enter the size matrix A \n");
scanf("%d%d",&m,&n);
printf("Enter the size matrix B \n");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf(“Matrix multiplication is not possible\n”);
}
else
{
printf("Enter the elements of matrix A \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf ("%d",&a[i][j]);
}
printf("Enter the elements of matrix B \n");
for(i=0;i<p;i++)
{
` for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<n;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
printf(‘A-matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n");
}
OUTPUT (PASS 1)
.....................................................................
Enter the size of matrix A
23
Enter the size of matrix B
45
Matrix multiplication is not possible
OUTPUT (PASS 2)
Enter the size of matrix A
22
Enter the size of matrix B
22
Enter the elements of Matrix A
1 1
1 1
Enter the elements of Matrix B
1 1
1 1
Matrix-A is
1 1
1 1
Matrix-B is
1 1
1 1
The resultant matrix c is
2 2
2 2
PROGRAM-4
Write a C program for the following condition using Functions, Assume a Car servicing
Center. Every service request by the Car Service Center the given charges are levied
along with taxes.
a. Car water wash - Rs. 500 + 10% tax
b. Oil in the Engine must be at least 300 ml. If it goes below 300 ml (Ask the user to
input the current level of oil in the engine), top up is done by the agency (the value of
top up is given by the user so that level is at least 300 ml). Cost of 1 ml is Rs. 5 + 12.5%
tax.
1. Define suitable variables to capture the above 2 parameters and corresponding taxes
2. Compute the total amount to be paid.
3. Display the total with 17 places which includes 7 places for fraction. The integer part
of the total must be prefixed with 0’s and a sign, if required.
PROGRAM:
#include <stdio.h>
// Function to calculate the total cost for car water wash
double calculateCarWaterWashCost(double baseCharge)
{
double tax = 0.1 * baseCharge;
return baseCharge + tax;
}
int main()
{
double carWashCharge = 500.0;
double oilLevel, topUpAmount, totalCost;
topUpAmount = 0;
}
// Calculate total cost for car water wash and oil top-up
double carWashTotal = calculateCarWaterWashCost(carWashCharge);
double oilTopUpTotal = calculateOilTopUpCost(oilLevel, topUpAmount);
OUTPUT:
RUN-1
Enter current oil level in the engine (in ml): 250
Enter the amount to top up (in ml): 55
Total Amount: +00000578.1250000
RUN-2
Enter current oil level in the engine (in ml): 450
Total Amount: +00001393.7500000
PROGRAM-5
Write a program in C using functions to swap two numbers using global variables
concept and call by reference concept.
PROGRAM:
#include <stdio.h>
int num1, num2;
// Function to swap two numbers using call by reference
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int main()
{
// Input two numbers
printf("Enter first number: ");
scanf("%d", &num1);
printf("Enter second number: ");
scanf("%d", &num2);
printf("Before swapping: First number = %d, Second number = %d\n", num1, num2);
printf("After swapping: First number = %d, Second number = %d\n", num1, num2);
OUTPUT:
Enter first number: 10
Enter second number: 20
Before swapping: First number = 10, Second number = 20
After swapping: First number = 20, Second number = 10
PROGRAM - 6
Implement a C program to read the values from the user today’s date and your Date of
birth in the format dd-mm-yyyy. Consider your sleeping time 8 hours a day, read 12
hours and spend 1.5 hours a day for eating. Calculate how many minutes have you
spent as of this date for Sleeping and Eating.
The number of years you have spent for reading as of this date (amount of time spent
for reading in years).
PROGRAM:
#include <stdio.h>
// Function to convert date to days
int convertToDays(int day, int month, int year)
{
return day + (month - 1) * 30 + (year - 1) * 365;
}
int main()
{
// Variables
int todayDay, todayMonth, todayYear;
int birthDay, birthMonth, birthYear;
int sleepHours = 8;
float eatHours = 1.5;
int readHours = 12;
float totalMinutes,todayDays,birthDays;
double yearsSpentReading;
// Display results
printf("Total minutes spent on sleeping and eating: %.2f minutes\n", totalMinutes);
printf("Number of years spent on reading: %.2lf years\n", yearsSpentReading);
}
OUTPUT:
Enter today's date (dd-mm-yyyy): 28-11-2023
Enter your date of birth (dd-mm-yyyy): 13-06-1989
Total minutes spent on sleeping and eating: 6790500 minutes
Number of years spent on reading: 17.23 years
PROGRAM-7
7 a) Write functions to implement string operations such as compare, concatenate, and
find string length. Use the parameter passing techniques.
ALGORITHM
Algorithm strings
Step 1: Start
Step 2: read string s1 & s2
Step 3: [call function strlength()]
i.e length =strlength
Step 4: Display length 1 and length 2
Step 5: [call function compare string]
if(compare_ string(s1,s2)==0)
print” equal strings”
else
print”unequl strings”
Step 6: call function concatenate
if(concatenate(s1,s2))
Step 7: print”concatenate string”
Step 8: Stop
Algorithm String_length()
Step 1: Start
Step 2: repeate step 2 through while(s1[i]!=’\0’)
i++
return i
end while
Step 3: Stop
Algorithm String_compare()
Step 1: Start
Step 2: repeatr step 2 trough while(s1[i]==s2[i])
if(s[i]==’\0’|| s2[i]==’\0’)
break
i++
end while
Algorithm String_concatenate()
Step 1: Start
Step 2: Initilize i=0
Step 3: repeate step 3 through while (s1[i]!=’\0’)
i++
end while
PROGRAM
#include <stdio.h>
int compare_strings(char [], char []);
void concatenate(char [], char []);
int string_length(char []);
int main()
{
char s1[100], s2[100];
printf("Input a string1\n");
gets(s1);
printf("Input a string2\n");
gets(s2);
}
if (s1[i] == '\0' && s2[i] == '\0')
return 0;
else
return 1;
}
OUTPUT:
Input string1
dsatm
Input string2
dsi
Length of string1: 5
Length of string2: 3
Unequal string
String obtained on concatenation: dstamdsi
FLOWCHART
PROGRAM:
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, length;
int isPalindrome = 1;
length = strlen(str);
OUTPUT:
Run-1:
Enter a string: dsatm
dsatm is not a palindrome.
Run-2:
Enter a string: malayalam
malayalam is a palindrome.
PROGRAM-8
Write a C Program to Implement linear search and binary search.
Procedure: Input N array elements and to find whether element is present or not.
Input: Array elements.
Expected Output: Successful search or unsuccessful search.
ALOGRITHM
Algorithm binary_search
Step 1: Start
Step 2: Read n
Step 3: Repeat for i=0 to n-1
Read a[i]
Step 4: read key
Step 5: Initialize low =0 high = n-1
Step 6: Repeat through step 6 while (low <= high)
mid = (low+ high)/2
if(key==a[mid])
found=1
else if(key>a[mid])
low=mid+1
else
high=mid-1
end while
Step 7: if(found ==1)
print “Item found”
else
print” Item not found”
Step 8: Stop
FLOWCHART
PROGRAM:-Binary Search
#include<stdio.h>
int main()
{
int i,n,a[10],mid,low,high,key, found=0;
printf("\n Enter the number of elements:\n");
scanf("%d", &n);
printf("Enter the array element in the ascending order\n");
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
printf("\n Enter the key element to be searched\n");
scanf("%d", &key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
found=1;
break;
}
else if(key>a[mid])
low=mid+1;
else
high=mid-1;
}
if(found ==1)
printf(“Item found in position : %d”,mid+1);
else
printf("\n Item not found\n");
}
OUTPUT:
RUN 1:
Enter the number of elements:
5
Enter the array element in the ascending order
10
20
30
40
50
OUTPUT:
Enter the number of elements:
5
Enter the array element in the ascending order
11
66
33
88
23
Enter the key element to be searched
88
Item found in position : 4
PROGRAM-9
Write a C Program to Implement Bubble Sort.
ALGORITHM
Algorithm: Bubble sort
Step 1: [Start of the algorithm]
Start
Step 2: [Read the size of the array]
read n
Step 3: [Read the array elements]
Repeat for i=0 to n-1
read a[i]
Step 4: [Print the given array]
Repeat for i=0 to n-1
print a[i]
Step 5: Repeat through step 5 for iß1 to n-1
Repeat for jß0 to n-i
if(a[j]>a[j+1])
tempßa[j]
a[j] ßa[j+1]
a[j+1]ßtemp
Step 5: [Print the sorted array]
Repeat for i ß0 to n-1
print a[i]
Step 6 :[terminate the algorithm]
Stop
FLOWCHART
PROGRAM:
#include<stdio.h>
int main()
{
int a[100],n,i,j,temp;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter the %d elements of array\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
OUTPUT:
Enter the number of elements
4
Enter 4 elements of array
87
100
20
3
87 100 20 3
3 20 87 100
PROGRAM-10
Write a C program to read employee information (Name, Designation, Salary) from the
user and write it to a file.
PROGRAM:
#include <stdio.h>
int main()
{
FILE *file;
char name[50], designation[100], filename[10];
float salary;
OUTPUT:
Enter the name of the file to save employee information (e.g., employee_info.txt): cse.txt
Enter employee name: Arun
Enter employee designation: Software Developer
Enter employee salary: Employee information has been written to the file.
Text file:
PROGRAM-11
Write a C Program to input even & odd elements of an array in two separate arrays. The
program first finds the odd and even elements of the array. Then the odd elements of an
array are stored in one array and even elements of an array is stored in another array.
PROGRAM:
#include <stdio.h>
int main()
{
int n, i, j = 0, k = 0;
int a[50], even[50], odd[50];
// Finding odd and even elements and storing them in separate arrays
for (i = 0; i < n; i++)
{
if (a[i] % 2 == 0)
{
even[j] = a[i];
j++;
}
else
{
odd[k] = a[i];
k++;
}
}
printf("\n");
}
OUTPUT:
PROGRAM-12
Write a C program to define a structure to represent a cricketer's information (name,
runs, average). Read the data corresponding to N Cricketer's in a structure array. The
space for the array of structures should be determined at run-time by user input.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct Cricketer
{
char name[50];
int runs;
float average;
};
int main()
{
int n;
printf("Enter the number of cricketers: ");
scanf("%d", &n);
printf("Name: ");
scanf("%s", cricketers[i].name);
printf("Runs: ");
scanf("%d", &cricketers[i].runs);
printf("Average: ");
scanf("%f", &cricketers[i].average);
}
printf("Cricketer Information:\n");
for (int i = 0; i < n; i++)
{
printf("Cricketer #%d\n", i+1);
printf("Name: %s\n", cricketers[i].name);
printf("Runs: %d\n", cricketers[i].runs);
OUTPUT:
Enter the number of cricketers: 2
Enter details for Cricketer #1:
Name: Sachin
Runs: 10500
Average: 154
Enter details for Cricketer #2:
Name: Kohli
Runs: 10000
Average: 132
Cricketer Information:
Cricketer #1
Name: Sachin
Runs: 10500
Average: 154.00
Cricketer #2
Name: Kohli
Runs: 10000
Average: 132.00
Appendix
1. Programming errors
These errors are generated when typographical errors are made by users.
2. Compiler errors
These errors are detected by the compiler that make the program un-compilable.
3. Linker error
These errors are generated when the executable of the program cannot be generated.
This may be due to wrong function prototyping, incorrect header files.
4. Execution error
These errors occur at the time of execution. Looping and arithmetic errors falls
under this category.
5. Logical errors
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.
3. scanf() errors
There are two types of common scanf() errors:
1. Forgetting to put an ampersand (&) on arguments
scanf() must have the address of the variable to store input into. This means
that often the ampersand address operator is required to compute the addresses.
Here's an example:
scanf("%d", &x); /* & required to pass address to scanf() */
scanf("%30s", st); /* NO & here, st itself points to variable! */
2. Using the wrong format for operand
C compilers do not check that the correct format is used for arguments
of a scanf() call. The most common errors are using the %f format for
doubles (which must use the %lf format) and mixing up %c and %s
for characters and strings.
4. Size of arrays
Arrays in C always start at index 0. This means that an array of 10 integers defined as:
int a[10];
has valid indices from 0 to 9 not 10! It is very common for students go one too far in an
array. This can lead to unpredictable behavior of the program.
5. Integer division
C uses the / operator for both real and integer division. It is important to understand how
C determines which it will do. If both operands are of an integal type, integer division is
used, else real division is used. For example:
double half = 1/2;
This code sets half to 0 not 0.5! Why? Because 1 and 2 are integer constants. To fix this,
change at least one of them to a real constant.
double half = 1.0/2;
If both operands are integer variables and real division is desired, cast one of the variables
to double (or float).
int x = 5, y = 2;
double d = ((double) x)/y;
6. Loop errors
In C, a loop repeats the very next statement after the loop statement. The code:
int x = 5;
while( x > 0 );
x--;
is an infinite loop. Why? The semicolon after the while defines the statement to repeat as
the null statement (which does nothing). Remove the semicolon and the loop works as
expected.
Another common loop error is to iterate one too many times or one too few.
Check loop conditions carefully!
7. Not using prototypes
Prototypes tell the compiler important features of a function: the return type and the
parameters of the function. If no prototype is given, the compiler assumes that the
function returns an int and can take any number of parameters of any type.
One important reason to use prototypes is to let the compiler check for errors
in the argument lists of function calls. However, a prototype must be used if the function
does not return an int. For example, the sqrt() function returns a double, not an int. The
following code:
double x = sqrt(2);
will not work correctly if a prototype:
double sqrt(double);
does not appear above it. Why? Without a prototype, the C compiler assumes that sqrt()
returns an int. Since the returned value is stored in a double variable, the compiler inserts
code to convert the value to a double. This conversion is not needed and will result in the
wrong value.
The solution to this problem is to include the correct C header file that contains
the sqrt() prototype, math.h. For functions you write, you must either place the prototype
at the top of the source file or create a header file and include it.
8. String Errors
1. Confusing character and string constants
C considers character and string constants as very different things. Character
constants are enclosed in single quotes and string constants are enclosed in
double quotes. String constants act as a pointer to the actually string. Consider
the following code:
char ch = 'A'; /* correct */
char ch = "A"; /* error */
The second line assigns the character variable ch to the address of a string
constant. This should generate a compiler error.
if ( st1 == st2 )
printf("Yes");
else
printf("No");
This code prints out No. Why? Because the == operator is comparing the
pointer values of st1 and st2, not the data pointed to by them. The correct way
to compare string values is to use the strcmp() library function. (Be sure to
include string.h) If the if statement above is replaced with the following:
if ( strcmp(st1,st2) == 0 )
printf("Yes");
else
printf("No");
The code will print out Yes. For similar reasons, don't use the other relational
operators (<,>, etc.) with strings either. Use strcmp() here too.
VIVA QUESTIONS
1. What is a Computer?
2. What is a compiler?
3. Differentiate object & executable file?
4. What is execution?
5. What is compilation?
6. What are the uses of Internet?
7. Explain different parts of the computer?
8. Define tracing, debugging?
9. What are the differences between RAM and ROM?
10. What are bits? What is a byte?
11. What is booting?
12. What is a source program?
13. Explain the structure of C program with an example.
14. Who is the father of “C” Computer?
15. Steps to execute a program?
16. Which are input & output statements?
17. Explain the different types of IF statements
18. Differentiate between break and continue
19. What are operators? List out different operators?
20. List out fundamental data types in C.
21. What do you mean by type conversions?
22. Why looping is necessary?
23. What is the syntax of a function declaration & function definition?
24. Define recursion & its application?
25. What is an array? How are they declared in ‘C’? What are the rules to be followed while
using arrays?
26. Explain the single and multi-dimensional arrays?
27. Explain the different categories of functions?
28. What is a string? What is a string manipulation library functions?
29. What are preprocessor directive?
30. List out different header files?
31. What is a parallel program?
32. What is the use of clrscr ()?
33. How to execute a parallel program?
34. What is searching & sorting? Logic of bubble sort, binary search?
35. What is divide & conquer methods?
36. What is memory allocation?
37. What is a pointer?
38. Explain format specifier, escape sequence?
39. Applications of arrays, looping, conditional statements?
40. Can we have main function within a main function?
41. Difference between object oriented & procedure oriented programs?
42. Logic of all programs?
43. Explain flowchart & algorithm?