SlideShare a Scribd company logo
1 of 22
Download to read offline
Visvesvaraya Technological University
(Jnana Sangama, Machhe, Visvesvaraya Technological University, Belagavi, Karnataka 590018)
BTL INSTITUTE OF TECHNOLOGY & MANAGEMENT
(259/B, Hosur Rd, Bommasandra Industrial Area, Bengaluru, Karnataka 560099)
YEAR: FIRST PROGRAMME: UG COURSE: BE
LABORATORY MANUAL
for
C PROGRAMMING LAB
( 18CPL17/27)
Prepared by :
Mr. Manjunatha Reddy G
Asst. Professor,
Department of CSE.
Department of Computer Science/Mechanical/Electronics & Communication and Civil Engineering
Supplied by: B.T.L.I.T Co-operative Society, Bangalore – 560 099
Phone: 78-33055, 35250, 35251 Telefax: 080-7833831
Student Name : _________________________________________________
USN : 1BT18_____________ Section : __________ Batch No : _______
Department: ________________________________________________
Semester : First / Second Academic Year : 2018-19
C PROGRAMMING LABORATORY SYLLABUS
Semester : I/II CIE Marks : 40 SEE Marks : 60 Exam Hours: 03
Course Code : 18CPL17 Credits : 01 Teaching Hours/week (L:T:P): 0:0:2
Course Learning Objectives:
This course (18CPL17/27) will enable students to:
 Write flowcharts, algorithms and programs.
 Familiarize the processes of debugging and execution.
 Implement basics of C programming language.
 Illustrate solutions to the laboratory programs.
Descriptions (if any):
 The laboratoryshouldbe precededorfollowedbyatutorialtoexplaintheapproach or algorithm being implemented or implemented for the problems given.
Note that experiment 1 is mandatory and written in the joumal.
 Questions related withexperiment 1, needto be askedduring viva-voce for all experiments.
 Everyexperiment shouldhave algorithmandflowchart be writtenbeforewriting the program.
 Code should be traced using minimum two test cases which should berecorded.
 It is preferred to implement using Linux and GCC.
Laboratory Programs:
1. Familiarization with computer hardware and programming environment, concept of naming the program files, storing, compilation,
execution and debugging, taking any simple C- code. [Not included in the Lab Exam ]
PART A
2. Develop a program to solve simple computational problems using arithmetic expressions and use of each operator leading to simulation of
a commercial calculator. (No built-in math function)
3. Develop a program to compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages.
4. Develop a program to find the reverse of a positive integer and check for palindrome or not. Display appropriate messages.
5. An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paisa per unit: for the next 100 units 90
paisa 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 total amount is charged. Write a program to read the name of the user, number of
units consumed and print out the charges.
6. Introduce 1D An-
ay manipulation and implement Binary search.
7. Implement using functions to check whether the given number is prime and display appropriate messages. (No built-in math function)
PART B
8. Develop a program to introduce 2D Array manipulation and implement Matrix multiplication and ensure the rules of multiplication are
checked.
9. Develop a Program to compute Sin(x) using Taylor series approximation. Compare your result with the built- in Library function. Print
both the results with appropriate messages.
10. Write functions to implement string operations such as compare, concatenate, string length. Convince the parameter passing techniques.
11. Develop a program to sort the given set of N numbers using Bubble sort.
12. Develop a program to find the square root of a given number N and execute for all possible inputs with appropriate messages.
Note: Don't use library function sqrt(n).
13. 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.
14. Develop a program using pointers to compute the sum, mean and standard deviation of all elements stored in an array of n real numbers.
15. Implement Recursive functions for Binary to Decimal Conversion.
Laboratory Outcomes:
The student should be able to:
 Write algorithms, flowcharts and program for simple problems.
 Correct syntax and logical errors to execute a program.
 Write iterative and wherever possible recursive programs.
 Demonstrate use of functions, arrays, strings, structures and pointers in problem solving.
Conduct of Practical Examination:
 All laboratory experiments, excluding the first, are to be included for practical examination.
 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.
 Strictly follow the instructions as printed on the cover page of answer script for breakup of marks
 Change of experiment is allowed only once and marks allotted for procedure part to be made zero.
 Marks Distribution (Subjected to change in accordance 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 = 30 Marks
ii. Part B — Procedure + Execution + Viva = 10 + 49 + 11 = 70 Marks
INDEX
Exp
No
Date LaboratoryProgramsinShort
ObtainedMarks
A
/F
P E V Signature
1
PART–A 2 2 21 5
2
3
4
5
6
7
PART–B 4 6 49 11
8
9
10
11
12
13
14
15
A–Algorithms F–Flowchart P–Procedure E–Execution V–Viva
AftertheeachexperimentexecutionstudentmustgetsignaturebytheInchargefacultywithdate.
Thefacultyastoentertheobtainmarksfortheeachexperiment. MaximummarksgivenforPart-A&Part-B
Note:
1. Everyexperiment shouldhave algorithmandflowchart be writtenbeforewriting the program.
2. Code should be traced using minimum two test cases which should berecorded.
ClassInternalEvaluationMarks (FilledbyInchargeFaculty)
Part-A
Exp.No. 2 3 4 5 6 7 Total Average
(Total/6)
Signature
MaxMarks 30 30 30 30 30 30 180
MarksObtain
Part-B
Exp.No. 8 9 10 11 12 13 14 15 Total Average
(Total/8)
Signature
MaxMarks 70 70 70 70 70 70 70 70 560
MarksObtain
CIEMarksObtained [ (Part-A+Part-B)x0.40]
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 1
Program – 1 : Familiarization with computer hardware and programming environment, concept of naming the program files, storing,
compilation, execution and debugging, taking any simple C- code. [Not included in the Lab Exam ]
Generally, the programs created using programming languages like C, C++, Java etc., are written
using high level language like English. But, computer cannot understand the high level language. It
can understand only low level language. So, the program written in high level language needs to be
converted into low level language to make it understandable for the computer. This conversion is
performed using either Interpreter or Compiler.
Popular programming languages like C, C++, Java etc., use compiler to convert high level language
instructions into low level language instructions. Compiler is a program that converts high level
language instructions into low level language instructions. Generally, compiler performs two
things, first it verifies the program errors, if errors are found, it returns list of errors otherwise it
converts the complete code into low level language.
To create and execute C programs in Windows Operating System, we need to install Turbo C
software. We use the following steps to create and execute C programs in Windows OS…
Step 1: Creating Source Code
Source code is a file with C programming instructions in high level language. To create source
code, we use any text editor to write the program instructions. The instructions written in the
source code must follow the C programming language rules. The following steps are used to create
source code file in Windows OS…
 Click on Start button
 Select Run
 Type cmd and press Enter
 Type cd c:TCbin in the command prompt and press Enter
 Type TC press Enter
 Click on File -> New in C Editor window
 Type the program
 Save it as FileName.c (Use shortcut key F2 to save)
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 2
Step 2: Compile Source Code (Alt + F9)
Compilation is the process of converting high level language instructions into low level language
instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C.
Compilation is the process of converting high level language instructions into low level language
instructions.
Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On receiving
a source file, the compiler first checks for the Errors. If there are any Errors then compiler returns
List of Errors, if there are no errors then the source code is converted into object code and stores it
as file with .obj extension. Then the object code is given to the Linker. The Linker combines both
the object code and specified header file code and generates an Executable file with .exe extension.
Step 3: Executing / Running Executable File (Ctrl + F9)
After completing compilation successfully, an executable file is created with .exe extension. The
processor can understand this .exe file content so that it can perform the task specified in the
source file.
We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file is
submitted to the CPU. On receiving .exe file, CPU performs the task according to the instruction
written in the file. The result generated from the execution is placed in a window called User
Screen.
Step 4: Check Result (Alt + F5)
After running the program, the result is placed into User Screen. Just we need to open the User
Screen to check the result of the program execution. We use the shortcut key Alt + F5 to open the
User Screen and check the result.
Execution Process of a C Program
When we execute a C program it undergoes with following process…
The file which contains c program instructions in high level language is said to be source code.
Every c program source file is saved with .c extension, for example Sample.c.
Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for the
errors, if there are any errors, it returns list of errors, otherwise generates object code in a file
with name Sample.obj and submit it to the linker. Linker combines the code from specified header
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 3
file into object file and generates executable file as Sample.exe. With this compilation process
completes.
Now, we need to Run the executable file (Sample.exe). To run a program we press Ctrl + F9. When
we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs the task
according to the instructions written in that program and place the result into UserScreen.
Then we press Alt + F5 to open UserScreen and check the result of the program.
Important Points
 C program file (Source file) must save with .c extension.
 Compiler converts complete program at a time from high level language to low level
language.
 Input to the compiler is .c file and output from the compiler is .exe file, but it also
generates .obj file in this process.
 Compiler converts the file only if there are no errors in the source code.
 CPU places the result in User Screen window.
Overall Process
 Type the program in C editor and save with .c extension (Press F2 to save).
 Press Alt + F9 to compile the program.
 If there are errors, correct the errors and recompile the program.
 If there are no errors, then press Ctrl + F9 to execute / run the program.
 Press Alt + F5 to open User Screen and check the result.
Program Development Life Cycle
When we want to develop a program using any programming language, we follow a sequence of steps.
These steps are called phases in program development. The program development life cycle is a set of steps
or phases that are used to develop a program in any programming language.
Generally, program development life cycle contains 6 phases, they are as follows….
 Problem Definition
 Problem Analysis
 Algorithm Development
 Coding & Documentation
 Testing & Debugging
 Maintenance
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 4
1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of the problem. In this phase
we need to understand the problem statement, what is our requirement, what should be the output of the
problem solution. These are defined in this first phase of the program development life cycle.
2. Problem Analysis
In phase 2, we determine the requirements like variables, functions, etc. to solve the problem. That means
we gather the required resources to solve the problem defined in the problem definition phase. We also
determine the bounds of the solution.
3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem using the specification given in
the previous phase. This phase is very important for program development. That means we write the
solution in step by step statements.
4. Coding & Documentation
This phase uses a programming language to write or implement actual programming instructions for the
steps defined in the previous phase. In this phase, we construct actual program. That means we write the
program to solve the given problem using programming languages like C, C++, Java etc.,
5. Testing & Debugging
During this phase, we check whether the code written in previous step is solving the specified problem or
not. That means we test the program whether it is solving the problem for various input data values or not.
We also test that whether it is providing the desired output or not.
6. Maintenance
During this phase, the program is actively used by the users. If any enhancements found in this phase, all
the phases are to be repeated again to make the enhancements. That means in this phase, the solution
(program) is used by the end user. If the user encounters any problem or wants any enhancement, then we
need to repeat all the phases from the starting, so that the encountered problem is solved or enhancement
is added.
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 5
Program 2 : PART A
Develop a program to solve simple computational problems using arithmetic expressions and use of each operator leading to
simulation of a commercial calculator. (No built-in math function)
Source Code
#include <stdio.h>
int main()
{
int op1,op2,res;
char opr;
clrscr();
printf("Enter the expression n");
scanf("%d %c %d",&op1, &opr, &op2);
if (opr == '+')
res = op1 + op2;
else if (opr == '-')
res = op1 - op2;
else if (opr == '*')
res = op1 * op2;
else if (opr == '/')
res = op1 / op2;
else if ( opr == '%' )
res = op1 % op2;
else if ( opr == '^')
res = pow(op1,op2);
else
{
printf("Invalid Expression");
return 0;
}
printf("Result of %d %c %d = %d ",op1,opr,op2, res);
return 0;
getch();
}
Output :
//Using Switch Can replace the if..else..if …else logic
switch( opr )
{
case '+': res = op1 + op2 ;
break;
case '-': res = op1 - op2 ;
break;
case '*': res = op1 * op2 ;
break;
case '/': res = op1 / op2 ;
break;
case '%': res = op1 % op2 ;
break;
default :
printf("Invalid Expression");
return 0;
}
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 6
Program 3 : PART A
Develop a program to compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages.
Source Code
#include<stdio.h>
#include<math.h>
int main ()
{
float a, b, c, d, r1, r2;
printf ("Enter any three Numbers : ");
scanf ("%f %f %f", &a, &b, &c);
d = b * b - 4 * a * c;
if (d < 0)
{
printf ("n Roots are complex number.n");
printf ("The Roots of quadratic equation are imaginaryn ");
r1 = -b / (2 * a);
r2 = sqrt (abs ((int) d)) / (2 * a);
printf ("n Root1 = %.3f+i%.3f", r1, r2);
printf ("n Root2 = %.3f-i%.3f", r1, r2);
}
else if (d == 0)
{
printf ("n Roots of quadratic equation is equal.n");
r1 = -b / (2 * a);
printf ("n Root of quadratic equation is : %.3f ", r1);
}
else
{
printf ("n Roots of quadratic equation are real numbers.n");
r1 = (-b + sqrt ((int) d)) / (2 * a);
r2 = (-b - sqrt ((int) d)) / (2 * a);
printf ("n Roots of quadratic equation are : %.3f and %.3f", r1,
r2);
}
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 7
Program 4 : PART A
Develop a program to find the reverse of a positive integer and check for palindrome or not. Display appropriate messages.
Source Code
#include <stdio.h>
int main ()
{
int n, rev = 0, num;
do
{
printf ("nEnter an Positive Integer Number( > 2 digits): ");
scanf ("%d", &n);
}
while (n < 10);
num = n;
while (n != 0)
{
rev = rev * 10 + n % 10;
n /= 10;
}
if (num == rev)
printf ("%d is a palindrome.", num);
else
printf ("%d is not a palindrome.", num);
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 8
Program 5 : PART A
An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paisa per unit: for the next 100
units 90 paisa 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 total amount is charged. Write a program to read the name
of the user, number of units consumed and print out the charges.
Source Code
#include <stdio.h>
int main ()
{
char name[20];
int unit;
float amount, scharge = 0.0;
printf ("Enter your namen”);
scanf(“%s”,name);
printf(“nEnter unit Consumed(>0):");
scanf ("%d", &unit);
if (unit <= 200)
amount = unit * .80;
else if ( unit <= 300 )
amount = (unit - 200) * 0.90 + 160;
else
amount = (unit - 300) + 250; // I-slab(160) + II-Slab(90)
amount = amount + 100 ; //Minimum Charge to be Added for all
if (amount > 400)
scharge = amount * 0.15;
printf ("n_________________________________________________________");
printf("nName : %s",name);
printf("nUnit Consumed: %d",unit);
printf ("nAmount : %8.2f nSurcharge : %8.2f", amount, scharge);
printf ("n_______________________________________________________");
printf ("nAmount Due : %8.2f ", amount + scharge);
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 9
Program 6 : PART A
Introduce 1D An-ay manipulation and implement Binary search.
Source Code
#include <stdio.h>
int main ()
{
int c, first, last, middle, n, search, A[100];
printf ("Enter number of elementsn");
scanf ("%d", &n);
printf ("Enter %d integersn", n);
for (c = 0; c < n; c++)
scanf ("%d", &A[c]);
printf ("Enter value to findn");
scanf ("%d", &search);
first = 0;
last = n - 1;
while (first <= last)
{
middle = (first + last) / 2;
if (A[middle] == search)
{
printf ("%d found at location %d.n", search, middle + 1);
return 0;
}
else if (A[middle] < search)
first = middle + 1; //search in right most part
else
last = middle - 1; //search in left most part
}
if (first > last)
printf ("Not found! %d isn't present in the list.n", search);
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 10
Program 7 : PART A
Implement using functions to check whether the given number is prime and display appropriate messages. (No built-in math
function).
Source Code
#include <stdio.h>
int isPrime(int n)
{
int i;
for(i=2; i<=n/2; ++i)
{
if(n%i == 0) // condition for non-prime number
{
return 0;
}
}
return 1;
}
int main() // Driver Function
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
// Check prime number
if ( isPrime( n) )
printf("%d is a prime number.n", n);
else
printf("%d is not a prime number.n", n);
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 11
Program 8 : PART- B
Develop a program to introduce 2D Array manipulation and implement Matrix multiplication and ensure the rules of
multiplication are checked.
Source Code
#include <stdio.h>
int main()
{
printf("Enter number of rows and columns of first matrixn");
scanf("%d%d", &m, &n);
printf("Enter number of rows and columns of second matrixn");
scanf("%d%d", &p, &q);
if (n != p)
{
printf("The matrices can't be multiplied with each other.n");
printf("Error! column of first matrix not equal to row of second.nn");
return 0;
}
printf("Enter elements of first matrixn");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter elements of second matrixn");
for (c = 0; c < p; c++)
for (d = 0; d < q; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++)
{
for (d = 0; d < q; d++)
{
sum = 0;
for (k = 0; k < p; k++)
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
}
}
printf("Product of the matrices:n");
for (c = 0; c < m; c++) {
for (d = 0; d < q; d++)
printf("%dt", multiply[c][d]);
printf("n");
}
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 12
Program 9 : PART - B
Develop a Program to compute Sin(x) using Taylor series approximation. Compare your result with the built- in Library function.
Print both the results with appropriate messages.
Source Code
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int n, x1;
float accuracy, term, denominator, x, sinx, sinval;
printf ("Enter the value of x (in degrees) n");
scanf ("%f", &x);
x1 = x;
/* Converting degrees to radians */
x = x * (3.142 / 180.0);
sinval = sin (x);
printf ("Enter the accuracy for the result n");
scanf ("%f", &accuracy);
term = x;
sinx = term;
n = 1;
do
{
denominator = 2 * n * (2 * n + 1);
term = -term * x * x / denominator;
sinx = sinx + term;
n = n + 1;
}
while (accuracy <= fabs (sinval - sinx));
printf ("Sum of the sine series = %f n", sinx);
printf ("Using Library function sin(%d) = %fn", x1, sin (x));
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 13
Program 10 : PART-B
Write functions to implement string operations such as compare, concatenate, string length. Convince the parameter passing
techniques.
Source Code
#include<stdio.h>
int string_length (char *pointer)
{
int c = 0;
while (*(pointer + c) != '0')
c++;
return c;
}
int match_strings (char *Str1, char *Str2)
{
int i = 0;
while (Str1[i] == Str2[i])
{
if (Str1[i] == '0' && Str2[i] == '0')
break;
i++;
}
return Str1[i] - Str2[i];
}
void join_strings (char s1[], char s2[])
{
int i, j;
for (i = 0; s1[i] != '0'; i++);
for (j = 0; s2[j] != '0'; i++, j++)
{
s1[i] = s2[j];
}
s1[i] = '0';
}
int main ()
{
char string1[20], string2[20];
int choice;
printf ("n1. Find Length n2. Concatenate n3. Compare n4.Exitn");
printf ("Enter your choice: ");
scanf ("%d", &choice);
switch (choice)
{
case 1:
printf ("Enter the string: ");
scanf ("%s", string1);
printf ("The length of string is %d", string_length (string1));
break;
case 2:
printf ("Enter two strings: ");
scanf ("%s%s", string1, string2);
join_strings (string1, string2);
printf ("The concatenated string is %s", string1);
break;
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 14
case 3:
printf ("Enter two strings: ");
scanf ("%s%s", string1, string2);
if (match_strings (string1, string2) == 0)
{
printf ("They are equal");
}
else
{
printf ("They are not equal");
}
break;
case 4:
return 0;
}
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 15
Program 11: PART-B
Develop a program to sort the given set of N numbers using Bubble sort.
Source Code
#include <stdio.h>
#define MAXSIZE 10
void main()
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num n");
scanf("%d", &num);
printf("Enter the elements one by one n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is n");
for (i = 0; i < num; i++)
{
printf("%dn", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...n");
for (i = 0; i < num; i++)
{
printf("%dn", array[i]);
}
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 16
Program 12 : PART-B
Develop a program to find the square root of a given number N and execute for all possible inputs with appropriate messages.
Note: Don't use library function sqrt(n).
Source Code
#include<stdio.h>
float squareRoot(float n)
{
/*We are using n itself as first estimate This can surely be better */
float x , y = 1, e = 0.000001; /* e decides the accuracy level*/
x = n ;
while(x - y > e)
{
x = (x + y)/2;
y = n/x;
}
return x;
}
/* Driver program to test above function*/
void main()
{
int n = 50;
printf ("Square root of %d is %f", n, squareRoot(n));
getch();
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 17
Program 13 : PART-B
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..
Source Code
#include<stdio.h>
struct stud
{
int rollno, s1, s2, tot ;
char name[10] ;
float avg ;
} s[10] ;
float compute( struct stud S[], int n )
{
int i;
float sum=0 ;
for ( i = 0 ; i < n ; i++ )
{
sum = sum + S[i].avg ;
}
return (sum/n);
}
void display( struct stud s )
{
printf("%d t %s tt %d t %d t %d t %.2f n", s.rollno,s.name,s.s1,s.s2,s.tot,s.avg);
}
int main()
{
int i, n ;
float mean;
printf("Enter the number of students : ") ;
scanf("%d", &n) ;
for(i = 0 ; i < n ; i++)
{
printf("nEnter the roll number : ") ;
scanf("%d", &s[i].rollno) ;
printf("nEnter the name : ") ;
scanf("%s", s[i].name) ;
printf("nEnter the marks in 2 subjects : ") ;
scanf("%d %d", &s[i].s1, &s[i].s2) ;
s[i].tot = s[i].s1 + s[i].s2 ;
s[i].avg = s[i].tot / 2.0 ;
}
mean = compute( s,n);
printf("nBelow Average Studentsn");
printf("nRoll No. Name ttSub1t Sub2t Totalt Averagenn") ;
for(i = 0 ; i < n ; i++)
{
if( s[i].avg < mean )
display(s[i]);
}
printf("nAbove Average Studentsn");
printf("nRoll No. Name ttSub1t Sub2t Totalt Averagenn") ;
for(i = 0 ; i < n ; i++)
{
if( s[i].avg >= mean )
display(s[i]);
}
return(0) ;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 18
Program 14 : PART-B
Develop a program using pointers to compute the sum, mean and standard deviation of all elements stored in an array of n real
numbers.
Source Code
#include<stdio.h>
#include<math.h>
int main ()
{
float a[20], sum1 = 0, sum2 = 0, mean, var, dev;
int i, n;
printf ("enter no of elen");
scanf ("%d", &n);
printf ("enter array elen");
for (i = 0; i < n; i++)
{
scanf ("%f", a + i);
sum1 = sum1 + *(a + i);
}
mean = sum1 / n;
for (i = 0; i < n; i++)
{
sum2 = sum2 + pow ((*(a + i) - mean), 2);
}
var = sum2 / n;
dev = sqrt (var);
printf ("sum is%fn", sum1);
printf ("mean is%fn", mean);
printf ("variance is%fn", var);
printf ("devn is%fn", dev);
return 0;
}
Output :
18CPL17/27 C Programming Lab
BTLIT CSE P a g e | 19
Program 15 : PART-B
Implement Recursive functions for Binary to Decimal Conversion..
Source Code
#include <stdio.h>
#include <math.h>
int bin_to_dec(long long int num)
{
if (!(num / 10))
return (num);
return (num % 10 + bin_to_dec (num / 10) * 2);
}
int main()
{
long long n;
printf("Enter a Valid binary number < (10 Digits): ");
scanf("%lld", &n);
printf("%lld in binary = %d in decimal", n, bin_to_dec (n));
return 0;
}
Output :
Algorithms and proper flowcharts will be update soon.

More Related Content

What's hot

C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
indrasir
 
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
Malikireddy Bramhananda Reddy
 

What's hot (20)

Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
Decision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, StringsDecision Making Statements, Arrays, Strings
Decision Making Statements, Arrays, Strings
 
Programming in c notes
Programming in c notesProgramming in c notes
Programming in c notes
 
Computer programming chapter ( 4 )
Computer programming chapter ( 4 ) Computer programming chapter ( 4 )
Computer programming chapter ( 4 )
 
Chapter 4 5
Chapter 4 5Chapter 4 5
Chapter 4 5
 
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTTC programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
C programming notes BATRACOMPUTER CENTRE IN Ambala CANTT
 
Project 2 the second project involves/tutorialoutlet
Project 2 the second project involves/tutorialoutletProject 2 the second project involves/tutorialoutlet
Project 2 the second project involves/tutorialoutlet
 
C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)C basics 4 std11(GujBoard)
C basics 4 std11(GujBoard)
 
Abc c program
Abc c programAbc c program
Abc c program
 
C++ Tutorial
C++ TutorialC++ Tutorial
C++ Tutorial
 
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
C notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit orderC notes by m v b  reddy(gitam)imp  notes  all units notes  5 unit order
C notes by m v b reddy(gitam)imp notes all units notes 5 unit order
 
Unit4
Unit4Unit4
Unit4
 
(D 15 180770107240)
(D 15 180770107240)(D 15 180770107240)
(D 15 180770107240)
 
Book ppt
Book pptBook ppt
Book ppt
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C_Programming_Notes_ICE
C_Programming_Notes_ICEC_Programming_Notes_ICE
C_Programming_Notes_ICE
 
Handout#12
Handout#12Handout#12
Handout#12
 
Compiler gate question key
Compiler gate question keyCompiler gate question key
Compiler gate question key
 
Handout#02
Handout#02Handout#02
Handout#02
 
Overview of c
Overview of cOverview of c
Overview of c
 

Similar to CBCS 2018 Scheme I sem Lab Manual for 18CPL17

Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
AASTHA76
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
MMRF2
 
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docxELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
jack60216
 

Similar to CBCS 2018 Scheme I sem Lab Manual for 18CPL17 (20)

Problem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to CProblem Solving Techniques and Introduction to C
Problem Solving Techniques and Introduction to C
 
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORYGE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
 
COMP 122 Entire Course NEW
COMP 122 Entire Course NEWCOMP 122 Entire Course NEW
COMP 122 Entire Course NEW
 
Cp manual final
Cp manual finalCp manual final
Cp manual final
 
Unit 1 python (2021 r)
Unit 1 python (2021 r)Unit 1 python (2021 r)
Unit 1 python (2021 r)
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
 
L1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdfL1. Basic Programming Concepts.pdf
L1. Basic Programming Concepts.pdf
 
Module 1 python.pptx
Module 1 python.pptxModule 1 python.pptx
Module 1 python.pptx
 
Book management system
Book management systemBook management system
Book management system
 
LMmanual.pdf
LMmanual.pdfLMmanual.pdf
LMmanual.pdf
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
C++ Lab Maual.pdf
C++ Lab Maual.pdfC++ Lab Maual.pdf
C++ Lab Maual.pdf
 
EC6612 VLSI Design Lab Manual
EC6612 VLSI Design Lab ManualEC6612 VLSI Design Lab Manual
EC6612 VLSI Design Lab Manual
 
Jeremiah Yancy - Objectives for Software design and testing
Jeremiah Yancy - Objectives for Software design and testingJeremiah Yancy - Objectives for Software design and testing
Jeremiah Yancy - Objectives for Software design and testing
 
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docxELE2303 Assign 1  Page  1 ELE2303 Embedded Systems Design.docx
ELE2303 Assign 1 Page 1 ELE2303 Embedded Systems Design.docx
 
2.2 Demonstrate the understanding of Programming Life Cycle
2.2 Demonstrate the understanding of Programming Life Cycle2.2 Demonstrate the understanding of Programming Life Cycle
2.2 Demonstrate the understanding of Programming Life Cycle
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
PPS Unit-1.pdf
PPS Unit-1.pdfPPS Unit-1.pdf
PPS Unit-1.pdf
 

Recently uploaded

"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Recently uploaded (20)

Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 

CBCS 2018 Scheme I sem Lab Manual for 18CPL17

  • 1. Visvesvaraya Technological University (Jnana Sangama, Machhe, Visvesvaraya Technological University, Belagavi, Karnataka 590018) BTL INSTITUTE OF TECHNOLOGY & MANAGEMENT (259/B, Hosur Rd, Bommasandra Industrial Area, Bengaluru, Karnataka 560099) YEAR: FIRST PROGRAMME: UG COURSE: BE LABORATORY MANUAL for C PROGRAMMING LAB ( 18CPL17/27) Prepared by : Mr. Manjunatha Reddy G Asst. Professor, Department of CSE. Department of Computer Science/Mechanical/Electronics & Communication and Civil Engineering Supplied by: B.T.L.I.T Co-operative Society, Bangalore – 560 099 Phone: 78-33055, 35250, 35251 Telefax: 080-7833831 Student Name : _________________________________________________ USN : 1BT18_____________ Section : __________ Batch No : _______ Department: ________________________________________________ Semester : First / Second Academic Year : 2018-19
  • 2. C PROGRAMMING LABORATORY SYLLABUS Semester : I/II CIE Marks : 40 SEE Marks : 60 Exam Hours: 03 Course Code : 18CPL17 Credits : 01 Teaching Hours/week (L:T:P): 0:0:2 Course Learning Objectives: This course (18CPL17/27) will enable students to:  Write flowcharts, algorithms and programs.  Familiarize the processes of debugging and execution.  Implement basics of C programming language.  Illustrate solutions to the laboratory programs. Descriptions (if any):  The laboratoryshouldbe precededorfollowedbyatutorialtoexplaintheapproach or algorithm being implemented or implemented for the problems given. Note that experiment 1 is mandatory and written in the joumal.  Questions related withexperiment 1, needto be askedduring viva-voce for all experiments.  Everyexperiment shouldhave algorithmandflowchart be writtenbeforewriting the program.  Code should be traced using minimum two test cases which should berecorded.  It is preferred to implement using Linux and GCC. Laboratory Programs: 1. Familiarization with computer hardware and programming environment, concept of naming the program files, storing, compilation, execution and debugging, taking any simple C- code. [Not included in the Lab Exam ] PART A 2. Develop a program to solve simple computational problems using arithmetic expressions and use of each operator leading to simulation of a commercial calculator. (No built-in math function) 3. Develop a program to compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages. 4. Develop a program to find the reverse of a positive integer and check for palindrome or not. Display appropriate messages. 5. An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paisa per unit: for the next 100 units 90 paisa 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 total amount is charged. Write a program to read the name of the user, number of units consumed and print out the charges. 6. Introduce 1D An- ay manipulation and implement Binary search. 7. Implement using functions to check whether the given number is prime and display appropriate messages. (No built-in math function) PART B 8. Develop a program to introduce 2D Array manipulation and implement Matrix multiplication and ensure the rules of multiplication are checked. 9. Develop a Program to compute Sin(x) using Taylor series approximation. Compare your result with the built- in Library function. Print both the results with appropriate messages. 10. Write functions to implement string operations such as compare, concatenate, string length. Convince the parameter passing techniques. 11. Develop a program to sort the given set of N numbers using Bubble sort. 12. Develop a program to find the square root of a given number N and execute for all possible inputs with appropriate messages. Note: Don't use library function sqrt(n). 13. 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. 14. Develop a program using pointers to compute the sum, mean and standard deviation of all elements stored in an array of n real numbers. 15. Implement Recursive functions for Binary to Decimal Conversion. Laboratory Outcomes: The student should be able to:  Write algorithms, flowcharts and program for simple problems.  Correct syntax and logical errors to execute a program.  Write iterative and wherever possible recursive programs.  Demonstrate use of functions, arrays, strings, structures and pointers in problem solving. Conduct of Practical Examination:  All laboratory experiments, excluding the first, are to be included for practical examination.  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.  Strictly follow the instructions as printed on the cover page of answer script for breakup of marks  Change of experiment is allowed only once and marks allotted for procedure part to be made zero.  Marks Distribution (Subjected to change in accordance 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 = 30 Marks ii. Part B — Procedure + Execution + Viva = 10 + 49 + 11 = 70 Marks
  • 3. INDEX Exp No Date LaboratoryProgramsinShort ObtainedMarks A /F P E V Signature 1 PART–A 2 2 21 5 2 3 4 5 6 7 PART–B 4 6 49 11 8 9 10 11 12 13 14 15 A–Algorithms F–Flowchart P–Procedure E–Execution V–Viva AftertheeachexperimentexecutionstudentmustgetsignaturebytheInchargefacultywithdate. Thefacultyastoentertheobtainmarksfortheeachexperiment. MaximummarksgivenforPart-A&Part-B Note: 1. Everyexperiment shouldhave algorithmandflowchart be writtenbeforewriting the program. 2. Code should be traced using minimum two test cases which should berecorded. ClassInternalEvaluationMarks (FilledbyInchargeFaculty) Part-A Exp.No. 2 3 4 5 6 7 Total Average (Total/6) Signature MaxMarks 30 30 30 30 30 30 180 MarksObtain Part-B Exp.No. 8 9 10 11 12 13 14 15 Total Average (Total/8) Signature MaxMarks 70 70 70 70 70 70 70 70 560 MarksObtain CIEMarksObtained [ (Part-A+Part-B)x0.40]
  • 4. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 1 Program – 1 : Familiarization with computer hardware and programming environment, concept of naming the program files, storing, compilation, execution and debugging, taking any simple C- code. [Not included in the Lab Exam ] Generally, the programs created using programming languages like C, C++, Java etc., are written using high level language like English. But, computer cannot understand the high level language. It can understand only low level language. So, the program written in high level language needs to be converted into low level language to make it understandable for the computer. This conversion is performed using either Interpreter or Compiler. Popular programming languages like C, C++, Java etc., use compiler to convert high level language instructions into low level language instructions. Compiler is a program that converts high level language instructions into low level language instructions. Generally, compiler performs two things, first it verifies the program errors, if errors are found, it returns list of errors otherwise it converts the complete code into low level language. To create and execute C programs in Windows Operating System, we need to install Turbo C software. We use the following steps to create and execute C programs in Windows OS… Step 1: Creating Source Code Source code is a file with C programming instructions in high level language. To create source code, we use any text editor to write the program instructions. The instructions written in the source code must follow the C programming language rules. The following steps are used to create source code file in Windows OS…  Click on Start button  Select Run  Type cmd and press Enter  Type cd c:TCbin in the command prompt and press Enter  Type TC press Enter  Click on File -> New in C Editor window  Type the program  Save it as FileName.c (Use shortcut key F2 to save)
  • 5. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 2 Step 2: Compile Source Code (Alt + F9) Compilation is the process of converting high level language instructions into low level language instructions. We use the shortcut key Alt + F9 to compile a C program in Turbo C. Compilation is the process of converting high level language instructions into low level language instructions. Whenever we press Alt + F9, the source file is going to be submitted to the Compiler. On receiving a source file, the compiler first checks for the Errors. If there are any Errors then compiler returns List of Errors, if there are no errors then the source code is converted into object code and stores it as file with .obj extension. Then the object code is given to the Linker. The Linker combines both the object code and specified header file code and generates an Executable file with .exe extension. Step 3: Executing / Running Executable File (Ctrl + F9) After completing compilation successfully, an executable file is created with .exe extension. The processor can understand this .exe file content so that it can perform the task specified in the source file. We use a shortcut key Ctrl + F9 to run a C program. Whenever we press Ctrl + F9, the .exe file is submitted to the CPU. On receiving .exe file, CPU performs the task according to the instruction written in the file. The result generated from the execution is placed in a window called User Screen. Step 4: Check Result (Alt + F5) After running the program, the result is placed into User Screen. Just we need to open the User Screen to check the result of the program execution. We use the shortcut key Alt + F5 to open the User Screen and check the result. Execution Process of a C Program When we execute a C program it undergoes with following process… The file which contains c program instructions in high level language is said to be source code. Every c program source file is saved with .c extension, for example Sample.c. Whenever we press Alt + F9 the source file is submitted to the compiler. Compiler checks for the errors, if there are any errors, it returns list of errors, otherwise generates object code in a file with name Sample.obj and submit it to the linker. Linker combines the code from specified header
  • 6. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 3 file into object file and generates executable file as Sample.exe. With this compilation process completes. Now, we need to Run the executable file (Sample.exe). To run a program we press Ctrl + F9. When we press Ctrl + F9 the executable file is submitted to the CPU. Then CPU performs the task according to the instructions written in that program and place the result into UserScreen. Then we press Alt + F5 to open UserScreen and check the result of the program. Important Points  C program file (Source file) must save with .c extension.  Compiler converts complete program at a time from high level language to low level language.  Input to the compiler is .c file and output from the compiler is .exe file, but it also generates .obj file in this process.  Compiler converts the file only if there are no errors in the source code.  CPU places the result in User Screen window. Overall Process  Type the program in C editor and save with .c extension (Press F2 to save).  Press Alt + F9 to compile the program.  If there are errors, correct the errors and recompile the program.  If there are no errors, then press Ctrl + F9 to execute / run the program.  Press Alt + F5 to open User Screen and check the result. Program Development Life Cycle When we want to develop a program using any programming language, we follow a sequence of steps. These steps are called phases in program development. The program development life cycle is a set of steps or phases that are used to develop a program in any programming language. Generally, program development life cycle contains 6 phases, they are as follows….  Problem Definition  Problem Analysis  Algorithm Development  Coding & Documentation  Testing & Debugging  Maintenance
  • 7. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 4 1. Problem Definition In this phase, we define the problem statement and we decide the boundaries of the problem. In this phase we need to understand the problem statement, what is our requirement, what should be the output of the problem solution. These are defined in this first phase of the program development life cycle. 2. Problem Analysis In phase 2, we determine the requirements like variables, functions, etc. to solve the problem. That means we gather the required resources to solve the problem defined in the problem definition phase. We also determine the bounds of the solution. 3. Algorithm Development During this phase, we develop a step by step procedure to solve the problem using the specification given in the previous phase. This phase is very important for program development. That means we write the solution in step by step statements. 4. Coding & Documentation This phase uses a programming language to write or implement actual programming instructions for the steps defined in the previous phase. In this phase, we construct actual program. That means we write the program to solve the given problem using programming languages like C, C++, Java etc., 5. Testing & Debugging During this phase, we check whether the code written in previous step is solving the specified problem or not. That means we test the program whether it is solving the problem for various input data values or not. We also test that whether it is providing the desired output or not. 6. Maintenance During this phase, the program is actively used by the users. If any enhancements found in this phase, all the phases are to be repeated again to make the enhancements. That means in this phase, the solution (program) is used by the end user. If the user encounters any problem or wants any enhancement, then we need to repeat all the phases from the starting, so that the encountered problem is solved or enhancement is added.
  • 8. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 5 Program 2 : PART A Develop a program to solve simple computational problems using arithmetic expressions and use of each operator leading to simulation of a commercial calculator. (No built-in math function) Source Code #include <stdio.h> int main() { int op1,op2,res; char opr; clrscr(); printf("Enter the expression n"); scanf("%d %c %d",&op1, &opr, &op2); if (opr == '+') res = op1 + op2; else if (opr == '-') res = op1 - op2; else if (opr == '*') res = op1 * op2; else if (opr == '/') res = op1 / op2; else if ( opr == '%' ) res = op1 % op2; else if ( opr == '^') res = pow(op1,op2); else { printf("Invalid Expression"); return 0; } printf("Result of %d %c %d = %d ",op1,opr,op2, res); return 0; getch(); } Output : //Using Switch Can replace the if..else..if …else logic switch( opr ) { case '+': res = op1 + op2 ; break; case '-': res = op1 - op2 ; break; case '*': res = op1 * op2 ; break; case '/': res = op1 / op2 ; break; case '%': res = op1 % op2 ; break; default : printf("Invalid Expression"); return 0; }
  • 9. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 6 Program 3 : PART A Develop a program to compute the roots of a quadratic equation by accepting the coefficients. Print appropriate messages. Source Code #include<stdio.h> #include<math.h> int main () { float a, b, c, d, r1, r2; printf ("Enter any three Numbers : "); scanf ("%f %f %f", &a, &b, &c); d = b * b - 4 * a * c; if (d < 0) { printf ("n Roots are complex number.n"); printf ("The Roots of quadratic equation are imaginaryn "); r1 = -b / (2 * a); r2 = sqrt (abs ((int) d)) / (2 * a); printf ("n Root1 = %.3f+i%.3f", r1, r2); printf ("n Root2 = %.3f-i%.3f", r1, r2); } else if (d == 0) { printf ("n Roots of quadratic equation is equal.n"); r1 = -b / (2 * a); printf ("n Root of quadratic equation is : %.3f ", r1); } else { printf ("n Roots of quadratic equation are real numbers.n"); r1 = (-b + sqrt ((int) d)) / (2 * a); r2 = (-b - sqrt ((int) d)) / (2 * a); printf ("n Roots of quadratic equation are : %.3f and %.3f", r1, r2); } return 0; } Output :
  • 10. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 7 Program 4 : PART A Develop a program to find the reverse of a positive integer and check for palindrome or not. Display appropriate messages. Source Code #include <stdio.h> int main () { int n, rev = 0, num; do { printf ("nEnter an Positive Integer Number( > 2 digits): "); scanf ("%d", &n); } while (n < 10); num = n; while (n != 0) { rev = rev * 10 + n % 10; n /= 10; } if (num == rev) printf ("%d is a palindrome.", num); else printf ("%d is not a palindrome.", num); return 0; } Output :
  • 11. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 8 Program 5 : PART A An electricity board charges the following rates for the use of electricity: for the first 200 units 80 paisa per unit: for the next 100 units 90 paisa 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 total amount is charged. Write a program to read the name of the user, number of units consumed and print out the charges. Source Code #include <stdio.h> int main () { char name[20]; int unit; float amount, scharge = 0.0; printf ("Enter your namen”); scanf(“%s”,name); printf(“nEnter unit Consumed(>0):"); scanf ("%d", &unit); if (unit <= 200) amount = unit * .80; else if ( unit <= 300 ) amount = (unit - 200) * 0.90 + 160; else amount = (unit - 300) + 250; // I-slab(160) + II-Slab(90) amount = amount + 100 ; //Minimum Charge to be Added for all if (amount > 400) scharge = amount * 0.15; printf ("n_________________________________________________________"); printf("nName : %s",name); printf("nUnit Consumed: %d",unit); printf ("nAmount : %8.2f nSurcharge : %8.2f", amount, scharge); printf ("n_______________________________________________________"); printf ("nAmount Due : %8.2f ", amount + scharge); return 0; } Output :
  • 12. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 9 Program 6 : PART A Introduce 1D An-ay manipulation and implement Binary search. Source Code #include <stdio.h> int main () { int c, first, last, middle, n, search, A[100]; printf ("Enter number of elementsn"); scanf ("%d", &n); printf ("Enter %d integersn", n); for (c = 0; c < n; c++) scanf ("%d", &A[c]); printf ("Enter value to findn"); scanf ("%d", &search); first = 0; last = n - 1; while (first <= last) { middle = (first + last) / 2; if (A[middle] == search) { printf ("%d found at location %d.n", search, middle + 1); return 0; } else if (A[middle] < search) first = middle + 1; //search in right most part else last = middle - 1; //search in left most part } if (first > last) printf ("Not found! %d isn't present in the list.n", search); return 0; } Output :
  • 13. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 10 Program 7 : PART A Implement using functions to check whether the given number is prime and display appropriate messages. (No built-in math function). Source Code #include <stdio.h> int isPrime(int n) { int i; for(i=2; i<=n/2; ++i) { if(n%i == 0) // condition for non-prime number { return 0; } } return 1; } int main() // Driver Function { int n; printf("Enter a positive integer: "); scanf("%d", &n); // Check prime number if ( isPrime( n) ) printf("%d is a prime number.n", n); else printf("%d is not a prime number.n", n); return 0; } Output :
  • 14. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 11 Program 8 : PART- B Develop a program to introduce 2D Array manipulation and implement Matrix multiplication and ensure the rules of multiplication are checked. Source Code #include <stdio.h> int main() { printf("Enter number of rows and columns of first matrixn"); scanf("%d%d", &m, &n); printf("Enter number of rows and columns of second matrixn"); scanf("%d%d", &p, &q); if (n != p) { printf("The matrices can't be multiplied with each other.n"); printf("Error! column of first matrix not equal to row of second.nn"); return 0; } printf("Enter elements of first matrixn"); for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &first[c][d]); printf("Enter elements of second matrixn"); for (c = 0; c < p; c++) for (d = 0; d < q; d++) scanf("%d", &second[c][d]); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) { sum = 0; for (k = 0; k < p; k++) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; } } printf("Product of the matrices:n"); for (c = 0; c < m; c++) { for (d = 0; d < q; d++) printf("%dt", multiply[c][d]); printf("n"); } return 0; } Output :
  • 15. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 12 Program 9 : PART - B Develop a Program to compute Sin(x) using Taylor series approximation. Compare your result with the built- in Library function. Print both the results with appropriate messages. Source Code #include <stdio.h> #include <math.h> #include <stdlib.h> int main () { int n, x1; float accuracy, term, denominator, x, sinx, sinval; printf ("Enter the value of x (in degrees) n"); scanf ("%f", &x); x1 = x; /* Converting degrees to radians */ x = x * (3.142 / 180.0); sinval = sin (x); printf ("Enter the accuracy for the result n"); scanf ("%f", &accuracy); term = x; sinx = term; n = 1; do { denominator = 2 * n * (2 * n + 1); term = -term * x * x / denominator; sinx = sinx + term; n = n + 1; } while (accuracy <= fabs (sinval - sinx)); printf ("Sum of the sine series = %f n", sinx); printf ("Using Library function sin(%d) = %fn", x1, sin (x)); return 0; } Output :
  • 16. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 13 Program 10 : PART-B Write functions to implement string operations such as compare, concatenate, string length. Convince the parameter passing techniques. Source Code #include<stdio.h> int string_length (char *pointer) { int c = 0; while (*(pointer + c) != '0') c++; return c; } int match_strings (char *Str1, char *Str2) { int i = 0; while (Str1[i] == Str2[i]) { if (Str1[i] == '0' && Str2[i] == '0') break; i++; } return Str1[i] - Str2[i]; } void join_strings (char s1[], char s2[]) { int i, j; for (i = 0; s1[i] != '0'; i++); for (j = 0; s2[j] != '0'; i++, j++) { s1[i] = s2[j]; } s1[i] = '0'; } int main () { char string1[20], string2[20]; int choice; printf ("n1. Find Length n2. Concatenate n3. Compare n4.Exitn"); printf ("Enter your choice: "); scanf ("%d", &choice); switch (choice) { case 1: printf ("Enter the string: "); scanf ("%s", string1); printf ("The length of string is %d", string_length (string1)); break; case 2: printf ("Enter two strings: "); scanf ("%s%s", string1, string2); join_strings (string1, string2); printf ("The concatenated string is %s", string1); break;
  • 17. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 14 case 3: printf ("Enter two strings: "); scanf ("%s%s", string1, string2); if (match_strings (string1, string2) == 0) { printf ("They are equal"); } else { printf ("They are not equal"); } break; case 4: return 0; } return 0; } Output :
  • 18. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 15 Program 11: PART-B Develop a program to sort the given set of N numbers using Bubble sort. Source Code #include <stdio.h> #define MAXSIZE 10 void main() { int array[MAXSIZE]; int i, j, num, temp; printf("Enter the value of num n"); scanf("%d", &num); printf("Enter the elements one by one n"); for (i = 0; i < num; i++) { scanf("%d", &array[i]); } printf("Input array is n"); for (i = 0; i < num; i++) { printf("%dn", array[i]); } /* Bubble sorting begins */ for (i = 0; i < num; i++) { for (j = 0; j < (num - i - 1); j++) { if (array[j] > array[j + 1]) { temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } printf("Sorted array is...n"); for (i = 0; i < num; i++) { printf("%dn", array[i]); } } Output :
  • 19. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 16 Program 12 : PART-B Develop a program to find the square root of a given number N and execute for all possible inputs with appropriate messages. Note: Don't use library function sqrt(n). Source Code #include<stdio.h> float squareRoot(float n) { /*We are using n itself as first estimate This can surely be better */ float x , y = 1, e = 0.000001; /* e decides the accuracy level*/ x = n ; while(x - y > e) { x = (x + y)/2; y = n/x; } return x; } /* Driver program to test above function*/ void main() { int n = 50; printf ("Square root of %d is %f", n, squareRoot(n)); getch(); } Output :
  • 20. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 17 Program 13 : PART-B 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.. Source Code #include<stdio.h> struct stud { int rollno, s1, s2, tot ; char name[10] ; float avg ; } s[10] ; float compute( struct stud S[], int n ) { int i; float sum=0 ; for ( i = 0 ; i < n ; i++ ) { sum = sum + S[i].avg ; } return (sum/n); } void display( struct stud s ) { printf("%d t %s tt %d t %d t %d t %.2f n", s.rollno,s.name,s.s1,s.s2,s.tot,s.avg); } int main() { int i, n ; float mean; printf("Enter the number of students : ") ; scanf("%d", &n) ; for(i = 0 ; i < n ; i++) { printf("nEnter the roll number : ") ; scanf("%d", &s[i].rollno) ; printf("nEnter the name : ") ; scanf("%s", s[i].name) ; printf("nEnter the marks in 2 subjects : ") ; scanf("%d %d", &s[i].s1, &s[i].s2) ; s[i].tot = s[i].s1 + s[i].s2 ; s[i].avg = s[i].tot / 2.0 ; } mean = compute( s,n); printf("nBelow Average Studentsn"); printf("nRoll No. Name ttSub1t Sub2t Totalt Averagenn") ; for(i = 0 ; i < n ; i++) { if( s[i].avg < mean ) display(s[i]); } printf("nAbove Average Studentsn"); printf("nRoll No. Name ttSub1t Sub2t Totalt Averagenn") ; for(i = 0 ; i < n ; i++) { if( s[i].avg >= mean ) display(s[i]); } return(0) ; } Output :
  • 21. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 18 Program 14 : PART-B Develop a program using pointers to compute the sum, mean and standard deviation of all elements stored in an array of n real numbers. Source Code #include<stdio.h> #include<math.h> int main () { float a[20], sum1 = 0, sum2 = 0, mean, var, dev; int i, n; printf ("enter no of elen"); scanf ("%d", &n); printf ("enter array elen"); for (i = 0; i < n; i++) { scanf ("%f", a + i); sum1 = sum1 + *(a + i); } mean = sum1 / n; for (i = 0; i < n; i++) { sum2 = sum2 + pow ((*(a + i) - mean), 2); } var = sum2 / n; dev = sqrt (var); printf ("sum is%fn", sum1); printf ("mean is%fn", mean); printf ("variance is%fn", var); printf ("devn is%fn", dev); return 0; } Output :
  • 22. 18CPL17/27 C Programming Lab BTLIT CSE P a g e | 19 Program 15 : PART-B Implement Recursive functions for Binary to Decimal Conversion.. Source Code #include <stdio.h> #include <math.h> int bin_to_dec(long long int num) { if (!(num / 10)) return (num); return (num % 10 + bin_to_dec (num / 10) * 2); } int main() { long long n; printf("Enter a Valid binary number < (10 Digits): "); scanf("%lld", &n); printf("%lld in binary = %d in decimal", n, bin_to_dec (n)); return 0; } Output : Algorithms and proper flowcharts will be update soon.