LabManual 3865 Content Document 20220620103958AM
LabManual 3865 Content Document 20220620103958AM
Management
Udayapura, Kanakapura Road, Opp. Art of Living, Bangalore – 560082
2021-2022
Compiled by:
• To serve its region, state, the nation and globally by preparing students to make meaningful
contributions in an increasing complex global society.
• To encourage, reflection on and evaluation of emerging needs and priorities with state of art
infrastructure.
• To support research and services establishing enhancements in technical, health, economic,
human and cultural development.
• To establish inter disciplinary center of excellence.
• To increase the number of Doctorate holders to promote research culture on campus.
QUALITY POLICY
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.
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY &
MANAGEMENT
(Affiliated to Visvesvaraya Technological University, Belagavi and Approved by AICTE, New
Delhi, Accredited by NBA for 3 years, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
Department of Computer Science & Engineering
(Accredited 3 years by NBA, New Delhi, (Validity: 26-07-2018 to 30-06-2021))
Department Vision:
Epitomize CSE graduate to carve a niche globally in the field of computer science to
excel in the world of technology and automation by imparting sustainable and
inclusive knowledge.
Department Mission:
M2. Enhancing the knowledge in the recent technology by conducting continuing education
programs, organizing and participating in various technical events.
M3. Impart Skills in the field of CSE and its related areas with a focus on developing the
required competencies and virtues to meet the requirement of the Industries.
M4. Ensure Quality research to serve the needs of industry, Government & society.
M5. Import the Knowledge to student for acquiring skills in entrepreneurship, Consultancy &
develop sustainability to changing environment.
Program Educational Outcomes:
PSO2: Computer Science Specific Skills: Ability to formulate, simulate and use knowledge
in various domains like data engineering, IOT, image ssprocessing, Information and network
security, artificial intelligence etc., and provide solutions to new ideas and innovations.
COMPUTER PROGRAMMING LABORATORY
Course Code 21CPL17/27 CIE Marks 50
Teaching Hours/Week (L: T:P: S) 0:0:2:0 SEE Marks 50
Total Hours of Pedagogy -- Total Marks 100
Credits 01 Exam Hours 03
Course Objectives:
1. Explain problem statements and identify appropriate solutions
2. Demonstrate the use of IDE, C Compiler, and identify and rectify the syntax and
syntactic errors during programming.
3. Development of algorithms and programs using constructs of C programming language
4. Reporting the observations
Sl. No. Practice Programs
1 Calculation of Simple Interest,
2 Check whether the given number is even or odd
3 Convert string case
4 Check for the palindrome, prime number, perfect square.
5 Development of linear search algorithm Etc.…
PART A
List of problems for which students should develop the program and execute in the
Laboratory
1 Simulation of a Simple Calculator.
2 Compute the roots of a quadratic equation by accepting the coefficients. Print
appropriate messages.
3 An electricity board charges the following rates for the use of electricity: for the first
200 units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units
Rs 1 per unit. All users are charged a minimum of Rs. 100 as meter charge. If the total
amount is more than Rs 400, then an additional surcharge of 15% of the total amount is
charged. Write a program to read the name of the user,
the number of units consumed, and print out the charges.
4 Implement Binary Search on Integers / Names.
5 Implement Matrix multiplication and validate the rules of multiplication.
6 Compute sin(x)/cos(x) using Taylor series approximation. Compare your result
with the built-in library function. Print both the results with appropriate inferences.
7 Sort the given set of N numbers using Bubble sort.
8 Write functions to implement string operations such as compare, concatenate,
string length. Convince the parameter passing techniques.
9 Implement structures to read, write and compute average- marks and the students
scoring above and below the average marks for a class of N students.
10 Develop a program using pointers to compute the sum, mean and standard
deviation of all elements stored in an array of N real numbers.
11 Implement Recursive functions for Binary to Decimal Conversion.
PART B – Practical Based Learning
A problem statement for each batch is to be generated in consultation with
the co-examiner and the student should develop an algorithm, program and
execute the program for the given problem with appropriate outputs.
1. All laboratory experiments, excluding the first, are to be included for practical
examination.
2. Experiment distribution.
o For questions having only one part: Students are allowed to pick one experiment
from the lot and are given equal opportunity.
o For questions having part A and B: Students are allowed to pick one experiment
from part A and one experiment from part B and are given equal opportunity.
3. Strictly follow the instructions as printed on the cover page of answer script for breakup
of marks.
4. Change of experiment is allowed only once and marks allotted for procedure part to be
made zero.
5. Marks Distribution (Subjected to change in accoradance with university regulations)
A. For questions having only one part –
Procedure + Execution + Viva-Voce: 15+70+15 = 100 Marks.
B. For questions having part A and B.
I. Part A–Procedure + Execution + Viva=4+21+5=30Marks
II. Part B – Procedure + Execution + Viva = 10 + 49+ 11 = 70 Marks
DAYANANDA SAGAR ACADEMY OF TECHNOLOGY & MANAGEMENT
(Affiliated to VTU, Belagavi and Approved by AICTE, New Delhi)
Opp. Art of Living, Udayapura, Kanakapura Road, Bangalore- 560082
(Accredited 3 years by NBA, New Delhi, (Validity: 26-07-2018 to 30-06-2021))
C PROGRAMMING LABORATORY
21CPL17/27
[Outcome-Based Education (OBE) and Choice Based Credit System (CBCS)]
(Effective from the academic year 2021-22)
SEMESTER - I/II
CO1: Define the problem statement and identify the need for computer programming
CO2: Make use of C compiler, IDE for programming, identify and correct the syntax and
syntactic errors in programming
CO3: Develop algorithm, flowchart and write programs to solve the given problem
CO4: Demonstrate use of functions, recursive functions, arrays, strings, structures and
pointers in problem solving.
CO5: Document the inference and observations made from the implementation.
CO1 3
CO2 3 3
CO3 3 2
CO4 3
CO5 2
C Programming Lab 21CPL17/27
PART-A
PROGRAM-1
Simulation of 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 '/': if(num2==0)
{
printf("Error: divid by zero\n");
exit(0);
}
result=(float)num1/(float)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
INPUT-OUTPUT:
PROGRAM-2
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.
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]
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
Read a,b,c
Is a=0 Print
is a=0 ?
and Invalid
roots
d←b*b-4*a*c
is d=0 ? is d>0 ?
root1=(b+sqrt(d))/(2*a) real=-b/(2*a)
root1=-b/ (2*a)
root1=-c/b
root1=(-b-sqrt(d))/(2*a)
root1=root2 img=sqrt(fabs(d))/(2*a)
STOP
PROGRAM:
#include<stdio.h>
#include<math.h>
#include<stdlib.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);
}
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:
Run2:
Run3:
PROGRAM-3
An electricity board charges the following rates for the use of electricity: for the first 200
units 80 paise per unit: for the next 100 units 90 paise per unit: beyond 300 units Rs 1 per
unit. All users are charged a minimum of Rs. 100 as meter charge. If the total amount is
more than Rs 400, then an additional surcharge of 15% of the total amount is charged.
Write a program to read the name of the user, the number of units consumed, and print
out the charges.
Expected Output: This program checks all else if ladder conditions as per number of units
consumed by consumer and display appropriate output
ALGORITHM
Algorithm power
Step 1: Start
Step 2: Read name & unit
Step 3: if(unit <=200)
charge = unit *0.8+ 100
else if(unit<=300)
charge=(unit-200) *0.90+160;
else if(unit>300)
charge=(unit-300) *1+250;
if(charge>=400)
charge=charge + charge*0.15;
FLOWCHART
PROGRAM:
#include <stdio.h>
int main()
{
char name[10];
float unit, charge, min=100 ;
printf("Enter your name and unit Consumed:\n");
scanf("%s%f",name, &unit);
if(unit<=200)
charge=unit*.80+min;
else if(unit<=300)
charge=(unit-200)*0.90+160+min;
else
{
if(unit>300)
charge=(unit-300) *1+250+min;
}
if(charge>=400)
charge=charge + charge*0.15;
OUTPUT:
Enter your name and unit Consumed:
Arun
340
Name: Arun
Charge:390
PROGRAM-5
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 bubble_sort
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:
#include<stdio.h>
int main()
{
int i,n,a[10],mid,low,high,key, found=0;
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
Enter the key element to be searched
30
RUN 2:
Enter the number of elements:
5
Enter the array element in the ascending order
10
20
30
40
50
Enter the key element to be searched
70
Item not found
PROGRAM-5
Procedure: Input m*n and p*q size of 2 matrices elements to compute matrix multiplication.
ALGORITHM
Algorithm: Matrix_Multipication
Program:
#include<stdio.h>
#include<conio.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");
}
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
printf("%d\t",b[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-6
Compute sin(x)/cos(x) using Taylor series approximation. Compare your result with the
built-in library function. Print both the results with appropriate inferences.
ALGORITHM
Algorithm: Sine_series
Step 1:[Start the algorithm]
Start
Step 2:[Read the value of x]
Read x
Step 3:[Initialize the variables]
x1ßx;
xßx*(3.142/180.0)
Step 4;[Read the value of no of terms]
Read n
Step 5:[Initialize the variables]
termßx;
sinxßterm;
Step 6:[Repeat the following steps for n=1 to n terms
denß2*n*(2*n+1)
termß-term*x*x/den;
sum=sum+term;
Step 7:Print the result
sum of sine series=sum
sum using library function=sin(x)
Step 8: Stop
FLOWCHART
START
Read degree
x←degree*(PI/180)
nume←x
fact←1
sum←x
Term← nume/fact
nume← -nume*x*x
fact← fact*i *(i+1)
sum←sum+term
i-i+2
if
term>=
True 0.00001
STOP
Program:
#include<stdio.h>
#include<math.h>
#define PI 3.142
int main()
{
int i, degree;
float x,sum=0,term,nume,fact;
printf("Enter value of degree \n");
scanf("%d", °ree);
x=degree*(PI/180);
nume=x;
fact=1;
i=2;
do
{
term= nume/fact;
nume=-nume*x*x;
fact=fact*i*(i+1);
sum= sum+term;
i=i+2;
}while(fabs(term)>=0.00001);
printf("The sine of %d is %.3f",degree,sum);
printf("Using inbuilt function sin(%d) is %.3f",degree,sin(x));
}
OUTPUT:
.....................................................................
Enter value of degree
0
The sine of 0 is 0.000
Using inbuilt function sin (0) is 0
PROGRAM-7
ALGORITHM
FLOWCHART
Program:
#include<stdio.h>
int main()
{
int a[100],n,i,j,temp;
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:
.....................................................................
Run1:
87 100 20 3
3 20 87 100
PROGRAM-8
ALGORITHM
Algorithm strings
Step 1: Start
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
Step 4: initialize j=0
Step 5: repeate step 5 through while(s2[i]1=’\0’)
s1[i]=s2[j]
i++ j++
end while
Step 6: s1[i]=’\0’
Step 7: Stop
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 (compare_strings(s1, s2) == 0)
printf("Equal strings.\n");
else
printf("Unequal strings.\n");
concatenate(s1, s2);
printf("String obtained on concatenation: \"%s\"\n", s1);
return i;
}
OUTPUT:
Input string1
dsatm
Input string2
dsi
Length of string1: 5
Length of string2: 3
Unequal string
String obtained on concatenation: dstamdsi
PROGRAM-9
Implement structures to read, write and compute average- marks and the students
scoring above and below the average marks for a class of N students.
ALGORITHM
Algorithm STUDENT
Step 1: Start
Step 2: create the structure student with fields usn, name and marks and structure variable s[10].
Step 3: Initialize the variables countav=0, countbv=0
Step 4: read the number of students ‘n’
Step 5: read the value of usn name & marks for n number of students using structure variable
s[i] for i=0 to n-1
Step 6: Display the details
Step 7: repeat for i=0 to n-1
Compute the sum of students
Step 8: compute the average
Step 9: repeat for i=0 to n-1
if(s[i].marks >= average)
printf” total number of students above average”
else
printf” total number of students below average”
Step 10: Stop
PROGRAM
#include <stdio.h>
struct student
{
char usn[50];
char name[50];
int marks;
}
int main()
{
struct student s[10];
int i,n,countav=0,countbv=0;
float sum,average;
printf("Enter number of Students\n");
scanf("%d", &n);
scanf("%s",s[i].usn);
printf("Enter name: ");
scanf("%s",s[i].name);
printf("Enter marks: ");
scanf("%d",&s[i].marks);
printf("\n");
}
printf("Displaying Information:\n\n");
for(i=0; i<n; i++)
{
printf("\nUSN: %s\n",s[i].usn);
printf("Name: %s\n ", s[i].name);
printf("Marks: %d",s[i].marks);
printf("\n");
}
for(i=0;i<n;i++)
{
sum=sum+s[i].marks;
}
average=sum/n;
printf("\nAverage marks: %f",average);
for(i=0;i<n;i++)
{
if(s[i].marks>=average)
countav++;
else
countbv++;
}
printf("\nTotal No of students above average= %d",countav);
printf("\nTotal No of students below average= %d",countbv);
}
OUTPUT:
.....................................................................
Enter number of Students
2
Enter USN: 11
Enter name: arun
Enter marks: 23
Enter USN: 12
Enter name: ram
Enter marks: 25
Displaying Information:
USN:11
Name: arun
Marks: 23
USN:12
Name: ram
Marks: 25
Average marks: 24
PROGRAM-10
Develop a program using pointers to compute the sum, mean and standard deviation of
all elements stored in an array of N real numbers.
ALGORITHM
Algorithm Mean
Step 1: Start
Step 2: read n
Step 3: read for i=0 to n-1
Read a[i]
Step 4: prt=a
Step 5: repeat for i=0 to n-1
sum = sum+*prt
prt++
Step 6: mean=sum/n
Step 7: ptr=a
Step 8: repeat for i=0 to n-1
sumstd=sumstd+pow((*ptr-mean),2)
ptr++
Step 9: std=sqrt(stdsum/n)
Step 10: print mean sun and standard deviation
Step 11: Stop
FLOWCHART
Program:
#include<stdio.h>
#include<math.h>
int main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
int n,i;
printf("Enter the number of elements\n");
scanf("%d",&n);
printf("Enter array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+*ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd = sumstd + pow((*ptr-mean),2);
ptr++;
}
std=sqrt(sumstd/n);
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard Deviation =%.3f\t",std)
OUTPUT:
.....................................................................
Enter the number of elements
5
Enter array elements
1
2
3
4
5
Sum=15.000
Mean=3.000
Standard Deviation =1.414
PROGRAM-11
ALGORITHM
Algorithm Binary
Step 1: Start
Step 2: read binary number
Step 3: call function convert(bin)
Step 4: print decimal number
Step 5: Stop
Algorithm function
Step 1: Start
Step 2: if (bin==0)
return 0
else
return (bin%10+2*convert(bin/10))
FLOWCHART
PROGRAM:
#include <stdio.h>
int convert(int);
int main()
{
int dec, bin;
printf("Enter a binary number only: \n");
scanf("%d", &bin);
dec = convert(bin);
printf("The decimal equivalent of %d is %d.\n", bin,dec);
}
int convert(int bin)
{
if (bin == 0)
{
return 0;
}
else
{
return (bin % 10 + 2 * convert(bin / 10));
}
}
OUTPUT:
.....................................................................
Enter a binary number:
1010
The decimal equivalent of 1010 is 10
Appendix
Common ‘C’ Errors
switch(x)
{
case 2: printf("Two\n");
case 3: printf("Three\n");
}
prints output:
Two
Three
Put a break to break out of the switch:
int x = 2;
switch(x)
{
case 2: printf("Two\n");
break;
case 3: printf("Three\n");
break; /* not necessary, but good if additional cases are added
later */
}
2. Using = instead of ==
C's = operator is used exclusively for assignment and returns the value assigned.
The == operator is used exclusively for comparison and returns an integer value
(0 for false, not 0 for true). Because of these return values, the C compiler often
does not flag an error when = is used when one really wanted an ==. For example:
int x = 5;
if ( x = 6 )
printf("x equals 6\n");
This code prints out x equals 6! Why? The assignment inside the if sets x to 6 and returns the
value 6 to the if. Since 6 is not 0, this is interpreted as true.
One way to have the compiler find this type of error is to put any constants (or any r-value
expressions) on the left side. Then if an = is used, it will be an error:
if ( 6 = x)
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.
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?