Professional Documents
Culture Documents
#127-128, Mysuru - Bannur Road, Alanahally, Alanahally Post, Mysuru - 570 028
Tel : (0821) 247 1232 / 247 1635, Fax : (0821) 247 3586, E-mail : info@vidyavikas.edu.in
Lab Manual
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Government of Karnataka
Department of Technical Education
Board of Technical Examinations, Bangalore
Course Title: C PROGRAMMING LAB
Scheme (L:T:P) : 0:2:4
Credit :03
Course
Code:15ME47P
Core/ Elective:
Core(practice)
SEE- 50 Marks
1. Apply the specification of syntax rules for numerical constants and variables, data types,
2. Usage of Arithmetic operator, Conditional operator, logical operator and relational operators
and other C constructs.
3. Write C programs using decision making, branching, looping constructs
4. Apply and Write C programs to implement one dimensional and two dimensional arrays
5. Writing programs using functions
Course Outcome:
On successful completion of the course, the students will be able to:
Course Outcome
CL
Linked
Teaching
Linked PO
Hrs
Exercise
CO1
U/A
CO2
1 to 10
1,2,3,5,10
69
Total sessions
78
Legend: R; Remember, U: Understand A: Application
TUTORIAL SESSION ACTIVITIES
Introduction to C programming- Need for a computer language, types of computer languages,
features of C, Character set- Structure of C program., keywords, statements, standard library
functions, pre-processor, main function, comments, variables, data types, operators,
assignments, strings, format specifies, escape sequences, control structures-sequential,
conditional, repetitive/looping, arrays-one & two dimensions, user defined functions
LIST OF GRADED PRACTICAL EXERCISES
The practical/Graded exercises should be properly designed and implemented with an attempt
to develop different types of learning out comes in affective domain and psychomotor domain,
so that students are able to acquire the necessary skills. Following is the list of experiments to
be carried out
SUGGESTED LIST OF STUDENT ACTIVITYS
Note: the following activities or similar activities for assessing CIE (IA) for 5 marks (Any one)
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
1. Each student should do any one of the following type activity or any other similar
activity related to the course and before conduction, get it approved from concerned
Teacher and HOD.
2. Each student should conduct different activity and no repeating should occur
1
Ask the students to take the simple problems in Hydraulics , develop a C Programme
Ask the students to take the simple problems in Strength of Materials , develop a C
Programme
Ask the students to take the simple problems in Thermal engineering, develop a C
3
Programme
Course Delivery:
The course will be delivered through lectures and presentations
2
Direct Assessment
meth
CIE
To
whom
IA
Indirect Assessment
Student
Feedback
on
course
End of Course
Survey
Students
Students
When/Where
(Frequency in the
course)
Student Activities
Max
Marks
Evidence
collected
Course
outcomes
10
1,2
Record Average
marks
of
graded
exercises
to
be
computed
End of the course
15
Activities
sheet
Graded
exercises
Answer scripts
at BTE
Feedback
forms
1,2
Questionnaires
1,2
Effectiveness
of Delivery
of
instructions
&
Assessment
Methods
50
1,2
1 Delivery of
course
Description
Marks
Writing Programme
20
Execution
20
Viva
10
TOTAL
50
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Certificate
This is to Certify that Mr / Ms---------------------------------------------bearing register number----------------------------, student of Vidya
Vikas Polytechnic College, Mysore, studying in 4th Semester,
Mechanical Department has successfully completed C-Programming
Lab bearing code 15ME47P prescribed by The Directorate of
Technical Education, Bengaluru.
Signature of Student
Signature of H.O.D
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Developing
Satisfactory
Good
Exemplary
10
Collection
of data
Collects very
limited
information;
some relate to
the topic
Collect much
information;
but very
limited relate
to the topic
Collects
some basic
information;
most refer to
the topic
Collects a
great deal of
information;
all refer to
the topic
Fulfil
teams roles
& duties
Performs very
little duties but
unreliable.
Performs very
little duties
Performs
nearly all
duties
Performs all
duties of
assigned
team roles
Shares
work
equally
Always relies on
others to do the
work
Rarely does
the assigned
work; often
needs
reminding
Usually does
the assigned
work; rarely
needs
reminding
Normally
does the
assigned
work
Always does
the assigned
work without
having to be
reminded.
Listen to
other Team
mates
Is always talking;
never allows
anyone else to
speak
Usually does
most of the
talking; rarely
allows others
to speak
Talks good;
but never
show interest
in listening
others
Listens, but
sometimes
talk too
much
Listens and
speaks a fair
amount
Dimension
Record X2 =_________ / 15
Total: X1 + X2 = _________+__________ =
/ 25
Contents
Syllabus
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Student
Score
out of
10
Marks
Practical/Exercise
10
11
14
15
Activity 2
13
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
1.0 Introduction
C has been used successfully for every type of programming problem imaginable from
operating systems to spreadsheets to expert systems and efficient compilers are available for
machines ranging in power from the Apple Macintosh to the Cray supercomputers. The largest
measure of C's success seems to be based on purely practical considerations:
1. the portability of the compiler;
2. the standard library concept;
3. a powerful and varied repertoire of operators;
4. an elegant syntax;
5. ready access to the hardware when needed;
6. and the ease with which applications can be optimized by hand-coding isolated
procedures
C is often called a "Middle Level" programming language. This is not a reflection on its lack
of programming power but more a reflection on its capability to access the system's low level
functions. Most high-level languages (e.g. Fortran) provides everything the programmer might
want to do already built into the language. A low level language (e.g. assembler) provides
nothing other than access to the machines basic instruction set. A middle level language, such
as C, probably doesn't supply all the constructs found in high-languages - but it provides you
with all the building blocks that you will need to produce the results you want.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C
Programming Language by Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to provide
a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or
"ANSI C", was completed late 1988.
case of C the standard input and output functions are contained in a library (stdio.h) so even
the most basic program will require a library function. After linking the file extension is .exe
which are executable files.
1.2.4 Executable files
Thus the text editor produces .c source files, which go to the compiler, which produces .obj
object files, which go to the linker, which produces .exe executable file. You can then run .exe
files as you can other applications, simply by typing their names at the DOS prompt or run
using windows menu.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Aim: All your first program is going to do is print the message "Hello World" on the screen.
#include <stdio.h>
main()
{
printf("Hello World\n");
}
The first line is the standard start for all C programs - main (). After this comes the program's
only instruction enclosed in curly brackets {}. The curly brackets mark the start and end of the
list of instructions that make up the program - in this case just one instruction. Notice the
semicolon marking the end of the instruction.
You might as well get into the habit of ending every C instruction with a semicolon. Also notice
that the semicolon marks the end of an instruction - it isn't a separator as is the custom in other
languages.
why the curly brackets are on separate lines, it's just a layout convention to help you spot
matching brackets. C is very unfussy about the way you lay it out. For example, you could
enter the Hello World program as: main (){printf("Hello World\n");}
The printf function does what its name suggest it does: it prints, on the screen, whatever you
tell it to. The "\n" is a special symbol that forces a new line on the screen. Type it in and save
it as Hello.c. Then use the compiler to compile it, then the linker to link it and finally run it.
The output is as follows: Hello World
1) int variable
For example:
int a;
declares that you want to create an int variable called a.
To assign a value to our integer variable we would use the following C statement: a=10;
2) float
A float, or floating point, number has about seven digits of precision and a range of about
1.E-36 to 1.E+36. A float takes four bytes to store.
3) double
A double, or double precision, number has about 13 digits of precision and a range of about
1.E-303 to 1.E+303. A double takes eight bytes to store.
4) char c;
To assign, or store, a character value in a char data type is easy - a character variable is just a
symbol enclosed by single quotes.
Arithmetic Operators
Logical Operators
Conditional Operators
Assignment Operators
Bitwise Operators
Relational Operators
Special Operators
division
multiplication
term after decimal point and shows answer 2 instead of 2.25. The modulo operator % computes
the remainder. When a = 9 is divided by b = 4, the remainder is 1. The % operator can only be
used with integers. Suppose a = 5.0, b = 2.0, c = 5 and d = 2. Then in C programming,
a/b = 2.5 // Because both operands are floating-point variables
a/d = 2.5 // Because one operand is floating-point variable
c/b = 2.5 // Because one operand is floating-point variable
c/d = 2
Here, the operators ++ and -- are used as prefix. These two operators can also be used as postfix
like a++ and a--. Visit this page to learn more on how increment and decrement operators work
when used as postfix.
1.7.3 C Assignment Operators
An assignment operator is used for assigning a value to a variable. The most common
assignment operator is =
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Operator
Example
Same as
Operator
Example
Same as
a=b
a=b
*=
a *= b
a = a*b
+=
a += b
a = a+b
/=
a /= b
a = a/b
-=
a -= b
a = a-b
%=
a %= b
a = a%b
Operator
Meaning of Operator
==
Equal to
!=
Not equal to
>
Greater than
>=
<
Less than
<=
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
||
Example
Logial AND. True only if all operands are If c = 5 and d = 2 then, expression ((c == 5) && (d >
true
5))
equals to 0.
Logical OR. True only if either one If c = 5 and d = 2 then, expression ((c == 5) || (d > 5))
operand is true
equals to 1.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
(a = b) && (c > 5)
(a = b) && (c < b)
(a = b) || (c < b)
(a != b) || (c < b)
!(a != b)
!(a == b)
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Meaning of operators
Operators
Meaning of operators
&
Bitwise AND
Bitwise complement
Bitwise OR
<<
Shift left
Bitwise exclusive OR
>>
Shift right
Loop Layout
Return Type A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
Function Name This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
argument. The parameter list refers to the type, order, and number of the parameters
of a function. Parameters are optional; that is, a function may contain no parameters.
Function Body The function body contains a collection of statements that define
what the function does.
Example # 6
Given below is the source code for a function called max(). This function takes two
parameters num1 and num2 and returns the maximum value between the two
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
1.9 C- Array
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers [0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific element in an array is accessed by an
index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
2.0 Pointers
A pointer is a variable whose value is the address of another variable, i.e., direct address of
the memory location. Like any variable or constant, you must declare a pointer before using it
to store any variable address. The general form of a pointer variable declaration is (type *varname;)
int
*ip;
/* pointer to an integer */
double *dp;
/* pointer to a double */
float *fp;
/* pointer to a float */
char *ch
/* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise,
is the same, a long hexadecimal number that represents a memory address. The only difference
between pointers of different data types is the data type of the variable or constant that the
pointer points to.
2.1 String
Strings are actually one-dimensional array of characters terminated by a null character '\0'.
Thus a null-terminated string contains the characters that comprise the string followed by a
null. The following declaration and initialization create a string consisting of the word "Hello".
To hold the null character at the end of the array, the size of the character array containing the
string is one more than the number of characters in the word "Hello."
2.2 C Preprocessor
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the
compiler to do required pre-processing before the actual compilation. We'll refer to the C
Preprocessor as CPP. All preprocessor commands begin with a hash symbol (#). It must be the
first nonblank character, and for readability, a preprocessor directive should begin in the first
column.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Directive Description
#define
#include
#undef
preprocessor
macro.
Inserts a particular header from
another file.
Undefines
preprocessor
macro.
Returns true if this macro is
#ifdef
defined.
#ifndef
#error
Substitutes
Directive Description
#ifndef
#if
#else
#elif
#endif
#pragma
The perror() function displays the string you pass to it, followed by a colon, a space,
and then the textual representation of the current errno value.
The strerror() function, which returns a pointer to the textual representation of the
current errno value.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
#include<stdio.h>
int main() {
float celsius, fahrenheit;
printf("\nEnter temp in Celsius : ");
scanf("%f", &celsius);
fahrenheit = (1.8 * celsius) + 32;
printf("\nTemperature in Fahrenheit : %f ", fahrenheit);
return (0);
}
Output
Enter temp in Celsius : 32
Temperature in Fahrenheit : 89.59998
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 03: To find the sum of even and odd numbers from 1 to N.
#include <stdio.h>
void main()
{
int i, num, odd_sum = 0, even_sum = 0;
printf("Enter the value of num\n");
scanf("%d", &num);
for (i = 1; i <= num; i++)
{
if (i % 2 == 0)
even_sum = even_sum + i;
else
odd_sum = odd_sum + i;
}
printf("Sum of all odd numbers = %d\n", odd_sum);
printf("Sum of all even numbers = %d\n", even_sum);
}
Output
Enter the value of num
10
Sum of all odd numbers = 25
Sum of all even numbers = 30
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 05: To reverse the given integer and check whether it is a palindrome or not
#include <stdio.h>
#include <string.h>
int main()
{
char a[100], b[100];
printf("Enter the string to check if it is a palindrome\n");
gets(a);
strcpy(b,a);
strrev(b);
if (strcmp(a,b) == 0)
printf("Entered string is a palindrome.\n");
else
printf("Entered string is not a palindrome.\n");
return 0;
}
Output
Enter the string to check if it is a palindrome
Wow
Entered string is a palindrome
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 06: To find the roots of a quadratic equation using switch statement.
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, determinant, root1,root2, realPart, imaginaryPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf",&a, &b, &c);
determinant = b*b-4*a*c;
// condition for real and different roots
if (determinant > 0)
{
// sqrt() function returns square root
root1 = (-b+sqrt(determinant))/(2*a);
root2 = (-b-sqrt(determinant))/(2*a);
printf("root1 = %.2lf and root2 = %.2lf",root1 , root2);
}
//condition for real and equal roots
else if (determinant == 0)
{
root1 = root2 = -b/(2*a);
printf("root1 = root2 = %.2lf;", root1);
}
// if roots are not real
else
{
realPart = -b/(2*a);
imaginaryPart = sqrt(-determinant)/(2*a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imaginaryPart, realPart,
imaginaryPart);
}
return 0;
}
Output
Enter coefficients a, b and c: 2.3
4
5.6
Roots are: -0.87+1.30i and -0.87-1.30i
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 07: To arrange N numbers in ascending order using Bubble sort technique
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap
= array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:\n");
for ( c = 0 ; c < n ; c++ )
printf("%d\n", array[c]);
return 0;
}
Output
Enter number of elements
6
Enter 6 Integer
2
-4
7
8
4
7
Sorted list in ascending
-4
2
4
7
7
8
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 09: To perform a multiplication of two matrices after checking the compatibility for
multiplication.
#include <stdio.h>
int main()
{
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
// Column of first matrix should be equal to column of second matrix and
while (c1 != r2)
{
printf("Error! column of first matrix not equal to row of second.\n\n");
printf("Enter rows and column for first matrix: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for second matrix: ");
scanf("%d %d",&r2, &c2);
}
// Storing elements of first matrix.
printf("\nEnter elements of matrix 1:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c1; ++j)
{
printf("Enter elements a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
// Storing elements of second matrix.
printf("\nEnter elements of matrix 2:\n");
for(i=0; i<r2; ++i)
for(j=0; j<c2; ++j)
{
printf("Enter elements b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}
// Initializing all elements of result matrix to 0
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
result[i][j] = 0;
}
// Multiplying matrices a and b and
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
25
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 10: To find the largest of 3 numbers using functions (functions with arguments
and return value)
#include <iostream>
int main()
{
float n1, n2, n3;
clrscr();
printf(\n Enter three Numbers = \n);
scanf(%f %f %f , &n1, &n2, &n3);
if (n1>=n2 && n1>=n3);
printf(The greatest of three numbers is =%f \n, n1);
if (n2>=n1 && n2>=n3);
printf(The greatest of three numbers is =%f \n, n2);
if (n3>=n1 && n1>=n2);
printf(The greatest of three numbers is =%f \n, n3);
return 0;
}
Output
Enter three numbers:
2.3
8.3
-4.2
The greatest of three numbers is = 8.3
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 11: To find the distance travelled by a vehicle, given its initial velocity u,
acceleration a and time t
#include<stdio.h>
#include<conio.h>
#include<math.h>
Void main()
{
float i, s, u, a, t;
clrscr();
printf( Enter Initial Velocity = );
// get velocity
scanf(%f, &u);
printf( Enter Acceleration = );
// get acceleration
scanf(%f, &a);
printf( Enter Time= );
// get time
scanf(%f, &i);
{
S= (u*a) + (a*pow(t,2))/2;
Printg(\n Time Step = %f Distance Travelled = %f\n, t,s) // show both time and Distance
}
getch();
}
OUTPUT
Enter Initial Velocity =30
Enter Acceleration =20
Enter Time=10
Time Step = 0.000000
Time Step = 1.000000
Time Step = 2.000000
Time Step = 3.000000
Time Step = 4.000000
Time Step = 5.000000
Time Step = 6.000000
Time Step = 7.000000
Time Step = 8.000000
Time Step = 9.000000
Time Step = 10.000000
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
3.
4.
5.
6.
7.
Logical Operators
Increment and decrements operators
Assignment operators
Conditional operator
Bitwise oprators
break statement
continue statement
goto statement
Exit () function
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.