Post on 08-Jan-2017
transcript
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
#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
Course Title: C PROGRAMMING LAB
Course Code:15ME47P
Name of the Student
Register Number
Branch
Batch
Vidya Vikas Polytechnic, College, Mysuru
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 Objectives:
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
Linked PO Teaching
Hrs Exercise
CO1
Acquire logical thinking, Implement
the algorithms and analyze their
complexity, Identify the correct and
efficient ways of solving problems
U/A 1 to 10 1,2,3,5,10 69
CO2
Implement real time applications
using the power of C language
features.
U/A 11,12,13 1,2,3,4,5,10 9
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)
Course Title: C PROGRAMMING LAB
Scheme (L:T:P) : 0:2:4 Total Contact Hours: 78 Course
Code:15ME47P
Type of Course: Tutorial and
practice Credit :03
Core/ Elective:
Core(practice)
CIE- 25 Marks SEE- 50 Marks
Vidya Vikas Polytechnic, College, Mysuru
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
2 Ask the students to take the simple problems in Strength of Materials , develop a C
Programme
3 Ask the students to take the simple problems in Thermal engineering, develop a C
Programme
Course Delivery: The course will be delivered through lectures and presentations
Course Assessment and Evaluation Scheme:
What To
whom
When/Where
(Frequency in the
course)
Max
Marks
Evidence
collected
Course
outcomes
Dir
ect
A
sses
smen
t
met
h
CIE IA Students Student Activities 10 Activities
sheet
1,2
Record – Average
marks of graded
exercises to be
computed
15 Graded
exercises
1,2
End of the course 50 Answer scripts
at BTE
1,2
Ind
irec
t A
sses
smen
t
Student
Feedback on
course
Students Middle of the course Feedback
forms
1 Delivery of
course
End of Course
Survey
End of the course Questionnaires 1,2
Effectiveness
of Delivery
of
instructions
&
Assessment
Methods
*CIE – Continuous Internal Evaluation
*SEE – Semester End Examination
Note: Rubrics to be devised appropriately by the concerned faculty to assess Student activities.
Scheme of Valuation for End Examination Serial no Description Marks
1 Writing Programme 20
2 Execution 20
4 Viva 10
TOTAL 50
Vidya Vikas Polytechnic, College, Mysuru
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 Lab In-Charge Signature of H.O.D
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Marks Index Sheet
RUBRICS FOR ACTIVITY( 10 Marks)
Dimension
Unsatisfactory Developing Satisfactory Good Exemplary Student
Score
out of
10
Marks 2 4 6 8 10
Collection
of data
Does not collect
any information
relating to the
topic
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
team’s roles
& duties
Does not perform
any duties
assigned to the
team role
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
Average / Total marks=(___+____+____+___) / 4=_____/ 4 = _______~ X1=____ / 10
Record X2 =_________ / 15
Total: X1 + X2 = _________+__________ =
Contents
Syllabus
/ 25
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Certificate
Marks Index Sheet
Introductions
Sl
No. Practical/Exercise
1 to convert the temperature in degree Celsius to degree Fahrenheit.
2 To find the sum and average of 3 real numbers.
3 To find the sum of even and odd numbers from 1 to N.
4 To find the sum of digits of a number.
5 To reverse the given integer and check whether it is a palindrome or not
6 To find the roots of a quadratic equation using switch statement.
7 To arrange N numbers in ascending order using Bubble sort technique
8 To perform addition of two matrices.
9 To perform a multiplication of two matrices after checking the
compatibility for multiplication.
10 To find the largest of 3 numbers using functions (functions with
arguments and return value)
11 To find the distance travelled by a vehicle, given it’s initial velocity
‘u’, acceleration ‘a’ and time ‘t’ [ S = ut + 1/2at2]
12 To find out Clearance volume of an Engine, given its bore diameter,
Length of stroke and Compression ratio
13 To find the power transmitted by shaft by inputting the value speed and
torque transmitted
14 Activity 1
15 Activity 2
Vidya Vikas Polytechnic, College, Mysuru
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.
1.1 History of C-Programming
C is a general-purpose language which has been closely associated with the UNIX operating
system for which it was developed - since the system and most of the programs that run it are
written in C.
Many of the important ideas of C stem from the language BCPL, developed by Martin
Richards. The influence of BCPL on C proceeded indirectly through the language B, which
was written by Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a DEC PDP-
7. BCPL and B are "type less" languages whereas C provides a variety of data types.
Vidya Vikas Polytechnic, College, Mysuru
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.
1.2 Running C Programs
Developing a program in a compiled language such as C requires at least four steps:
1. editing (or writing) the program
2. compiling it
3. linking it
4. executing it
1.2.1 Editing
Write a computer program with words and symbols that are understandable to human beings.
This is the editing part of the development cycle. As you type the program directly into a
window on the screen and save the resulting text as a separate file. This is often referred to as
the source file (you can read it with the TYPE command in DOS or the cat command in unix).
The custom is that the text of a C program is stored in a file with the extension .c for C
programming language
1.2.2 Compiling
You cannot directly execute the source file. To run on any computer system, the source file
must be translated into binary numbers understandable to the computer's Central Processing
Unit (for example, the 80*87 microprocessor). This process produces an intermediate object
file - with the extension .obj, the .obj stands for Object.
1.2.3 Linking
The main reason is that many compiled languages come with library routines which can be
added to your program. Theses routines are written by the manufacturer of the compiler to
perform a variety of tasks, from input/output to complicated mathematical functions. In the
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
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.
1.3 Pre-processor Directives
C is a small language but provides the programmer with all the tools to be able to write powerful
programs. C uses libraries of standard functions which are included when we build our
programs. This library is called stdin.h and it is declared in our programs before the main
function. The .h extension indicates that this is a header file. The only exception are statements
associated with the pre-processor. All pre-processor directives begin with a # and the must start
in the first column. The commonest directive to all C programs is: #include <stdio.h> Note the
use of the angle brackets (< and >) around the header's name.
“C” packages are supplied with containing a lrge number of predefined function containing
and code that have already been unwritten in order to use the contents of any particular library
that has to be specified in header file such libraries are:
Math.h - for mathematical function
Stdio.h - for input and output functions
Time.h - fro data and time function.
1.4 Your First Program
A C program basically consists of the following parts −
Preprocessor Commands
Functions
Variables
Statements & Expressions
Comments
Vidya Vikas Polytechnic, College, Mysuru
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.5 Input and Output Functions and Data Types
1. input functions, called scanf
2. output functions, called printf
1.5.1 Data types:
1. int - integer: a whole number.
2. float - floating point value: ie a number with a fractional part.
3. double - a double-precision floating point value.
4. char - a single character.
5. void - valueless special purpose type which we will examine closely in later sections.
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
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.
1.6 The % Format Specifiers
%c char single character
%d (%i) int signed integer
%e (%E) float or double exponential
format
%f float or double signed decimal
%g (%G) float or double use %f or %e as
required
%o int unsigned octal value
%p pointer address stored in pointer
%s array of char sequence of characters
%u int unsigned decimal
%x (%X) int unsigned hex value
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
1.7 Operators in C programming
1 Arithmetic Operators 5 Logical Operators
2 Increment and Decrement Operators 6 Conditional Operators
3 Assignment Operators 7 Bitwise Operators
4 Relational Operators 8 Special Operators
1.7.1 C Arithmetic Operators
An arithmetic operator performs mathematical operations such as addition, subtraction and
multiplication on numerical values (constants and variables).
Operator Meaning of Operator Operator Meaning of Operator
+ addition or unary plus / division
- subtraction or unary minus % remainder after division( modulo division)
* multiplication
Example #1: Arithmetic Operators
#include <stdio.h>
int main()
{
int a = 9,b = 4, c;
c = a+b;
printf("a+b = %d \n",c);
c = a-b;
printf("a-b = %d \n",c);
c = a*b;
printf("a*b = %d \n",c);
c=a/b;
printf("a/b = %d \n",c);
c=a%b;
printf("Remainder when a divided by b = %d \n",c);
return 0;
}
Output: a+b = 13, a-b = 5, a*b = 36, a/b = 2
In normal calculation, 9/4 = 2.25. However, the output is 2 in the program. It is because both
variables a and b are integers. Hence, the output is also an integer. The compiler neglects the
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
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 // Because both operands are integers
1.7.2 Increment and decrement operators
Example #2: Increment and Decrement Operators
// C Program to demonstrate the working of increment and decrement operators
#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output
++a = 11
--b = 99
++c = 11.500000
-- d = 99.500000
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 =
Vidya Vikas Polytechnic, College, Mysuru
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
Example #3: Assignment Operators
#include <stdio.h>
int main()
{
int a = 5, c;
c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);
c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
Output
c = 5
c = 10
c = 5
c = 25
c = 5
c = 0
1.7.4 C Relational Operators
Relational operators are used in decision making and loops.
Operator Meaning of Operator Operator Meaning of Operator
== Equal to != Not equal to
> Greater than >= Greater than or equal to
< Less than <= Less than or equal to
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Example #4: Relational Operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true
printf("%d == %d = %d \n", a, c, a == c); // false
printf("%d > %d = %d \n", a, b, a > b); //false
printf("%d > %d = %d \n", a, c, a > c); //false
printf("%d < %d = %d \n", a, b, a < b); //false
printf("%d < %d = %d \n", a, c, a < c); //true
printf("%d != %d = %d \n", a, b, a != b); //false
printf("%d != %d = %d \n", a, c, a != c); //true
printf("%d >= %d = %d \n", a, b, a >= b); //true
printf("%d >= %d = %d \n", a, c, a >= c); //false
printf("%d <= %d = %d \n", a, b, a <= b); //true
printf("%d <= %d = %d \n", a, c, a <= c); //true
return 0;
}
Output
5 == 5 = 1
5 == 10 = 0
5 > 5 = 0
5 > 10 = 0
5 < 5 = 0
5 < 10 = 1
5! = 5 = 0
5! = 10 = 1
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1
1.7.5 C Logical Operators
Logical operators are commonly used in decision making in C programming.
Operator Meaning of Operator Example
&& Logial AND. True only if all operands are
true
If c = 5 and d = 2 then, expression ((c == 5) && (d >
5)) equals to 0.
|| Logical OR. True only if either one
operand is true
If c = 5 and d = 2 then, expression ((c == 5) || (d > 5))
equals to 1.
! Logical NOT. True only if the operand is 0 If c = 5 then, expression! (c == 5) equals to 0.
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Example #5: Logical Operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
result = (a = b) && (c > b);
printf("(a = b) && (c > b) equals to %d \n", result);
result = (a = b) && (c < b);
printf("(a = b) && (c < b) equals to %d \n", result);
result = (a = b) || (c < b);
printf("(a = b) || (c < b) equals to %d \n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d \n", result);
result = !(a != b);
printf("!(a == b) equals to %d \n", result);
result = !(a == b);
printf("!(a == b) equals to %d \n", result);
return 0;
}
Output
(a = b) && (c > b) equals to 1
(a = b) && (c < b) equals to 0
(a = b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
Explanation of logical operator program
(a = b) && (c > 5) evaluates to 1 because both operands (a = b) and (c > b) is 1 (true).
(a = b) && (c < b) evaluates to 0 because operand (c < b) is 0 (false).
(a = b) || (c < b) evaluates to 1 because (a = b) is 1 (true).
(a != b) || (c < b) evaluates to 0 because both operand (a != b) and (c < b) are 0 (false).
!(a != b) evaluates to 1 because operand (a != b) is 0 (false). Hence, !(a != b) is 1 (true).
!(a == b) evaluates to 0 because (a == b) is 1 (true). Hence, !(a == b) is 0 (false).
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
1.7.6 Bitwise Operators
Bitwise operators are used in C programming to perform bit-level operations.
Operators Meaning of operators Operators Meaning of operators
& Bitwise AND ~ Bitwise complement
| Bitwise OR << Shift left
^ Bitwise exclusive OR >> Shift right
Decision Making Layout Loop Layout
1.8 Defining a Function
A function definition in C programming consists of a function header and a function body.
Here are all the parts of a function −
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.
Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
Vidya Vikas Polytechnic, College, Mysuru
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.
Vidya Vikas Polytechnic, College, Mysuru
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 *var-
name;)
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.
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Directive Description Directive Description
#define Substitutes a preprocessor
macro. #ifndef
Returns true if this macro is not
defined.
#include Inserts a particular header from
another file. #if
Tests if a compile time condition
is true.
#undef Undefines a preprocessor
macro. #else The alternative for #if.
#ifdef Returns true if this macro is
defined. #elif #else and #if in one statement.
#ifndef Returns true if this macro is not
defined. #endif Ends preprocessor conditional.
#error Prints error message on stderr. #pragma Issues special commands to the
compiler
2.3 Error Handling
As such, C programming does not provide direct support for error handling but being a system
programming language, it provides you access at lower level in the form of return values. Most
of the C or even Unix function calls return -1 or NULL in case of any error and set an error
code errno. It is set as a global variable and indicates an error occurred during any function
call. You can find various error codes defined in <error.h> header file. So a C programmer can
check the returned values and can take appropriate action depending on the return value. It is a
good practice, to set errno to 0 at the time of initializing a program. A value of 0 indicates that
there is no error in the program.
errno, perror(). and strerror()
The C programming language provides perror() and strerror() functions which can be used
to display the text message associated with errno.
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.
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 01 Aim: to convert the temperature in degree Celsius to degree Fahrenheit.
#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
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 02: To find the sum and average of 3 real numbers.
#include <stdio.h>
main()
{
float a, b, c, sum, avg;
printf("\nEnter value of three numbers: ");
scanf("%f %f %f", &a, &b, &c);
sum = a+b+c;
avg = sum/3;
printf("\nSum = %.2f", sum);
printf("\nAverage = %.2f", avg);
getch();
}
Output
Sum = answer of a+b+c
Average = Sum / 3
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
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 04: C program to find the sum of its digits
#include <stdio.h>
void main()
{
long num, temp, digit, sum = 0;
printf("Enter the number \n");
scanf("%ld", &num);
temp = num;
while (num > 0)
{
digit = num % 10;
sum = sum + digit;
num /= 10;
}
printf("Given number = %ld\n", temp);
printf("Sum of the digits %ld = %ld\n", temp, sum);
}
Output
Enter the number
16789
Given number = 16789
Sum of the digits 16789 = 31
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
Vidya Vikas Polytechnic, College, Mysuru
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
Vidya Vikas Polytechnic, College, Mysuru
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
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 08: To perform addition of two matrices. #include <stdio.h>
int main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter the elements of second matrix\n");
for (c = 0; c < m; c++)
for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);
printf("Sum of entered matrices:-\n");
for (c = 0; c < m; c++) {
for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}
return 0;
}
Output
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
1 2
3 4
Enter the elements of second matrix
5 6
2 1
Sum of entered matrices
6 8
5 5
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
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
// storing result in result matrix
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k)
{
result[i][j]+=a[i][k]*b[k][j];
}
// Displaying the result
printf("\nOutput Matrix:\n");
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
{
printf("%d ", result[i][j]);
if(j == c2-1)
printf("\n\n");
}
return 0;
}
Output
Enter rows and column for first matrix: 3
2
Enter rows and column for second matrix: 3
2
Error! column of first matrix not equal to row of second.
Enter rows and column for first matrix: 2
3
Enter rows and column for second matrix: 3
2
Enter elements of matrix 1:
Enter elements a11: 3
Enter elements a12: -2
Enter elements a13: 5
Enter elements a21: 3
Enter elements a22: 0
Enter elements a23: 4
Enter elements of matrix 2:
Enter elements b11: 2
Enter elements b12: 3
Enter elements b21: -9
Enter elements b22: 0
Enter elements b31: 0
Enter elements b32: 4
Output Matrix:
24 29
6 25
Vidya Vikas Polytechnic, College, Mysuru
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
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
Problem 11: To find the distance travelled by a vehicle, given it’s 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; // int may also be used
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); // use i to store time
for(t=0; t<=i; t++) // use for loop to segment time in incriment
{
S= (u*a) + (a*pow(t,2))/2; // solve the equation with time step
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 Distance Travelled = 0.000000
Time Step = 1.000000 Distance Travelled = 40.000000
Time Step = 2.000000 Distance Travelled = 100.000000
Time Step = 3.000000 Distance Travelled = 180.000000
Time Step = 4.000000 Distance Travelled = 280.000000
Time Step = 5.000000 Distance Travelled = 400.000000
Time Step = 6.000000 Distance Travelled = 540.000000
Time Step = 7.000000 Distance Travelled = 700.000000
Time Step = 8.000000 Distance Travelled = 880.000000
Time Step = 9.000000 Distance Travelled = 1080.000000
Time Step = 10.000000 Distance Travelled = 1300.000000
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
C-Programming VivA Questions 1) What do you mean by Hardware and Software?
All the electronic/electrical components and circuits used in a computer system are called
hardware. A computer is actuated and controlled with the help of computer programs called
software.
2) Mention the main components of a computer and their funtions.
CPU (cenral processing unit) – to process the data
Input Device – to enter the dat into the computer.
Output Device – to display / print results by the computer.
3) What is Operating System(OS) ?
An operating system is a collection of programs used to connect the user with the hardware It
has the set of programs which controls the operations of the hardware components such as
CPU, main memory, keyboard, monitor, printer and so on.
4) What is Algorithms?
An algorithms refer to the step by step instructions written to solve any problem.
5) What is Flowchart ?
A flowchart is a diagrammatic or symbolic representation of an algorithms. It uses various
symbols to represent the operations to be performed.
6) Name the four basic data types in “C” language?
The four basic data types in “c” language are as follows
char – a character
int – an integer, in the range -32,767 to 32,767
long int – a larger integer (up to +-2,147,483,647)
float – a floating-point number
double – a floating-point number, with more precision and perhaps greater range than float
7) Describe at least five different format specifiers?
%d: -An integer whole number
%f: -a floating point number
%c: -a single character
%s: -a string of value of characters.
8) Define and explain scanf () function?
The Scanf () function can be used to get input into a program and it requires two arguments.
First a format specifier defines the type of data to be entered, then the name of the variable in
which the input will be stored. This scanf () function is responsible for giving input into the
program.
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
9) Define and explain printf () function?
The printf() function is used to display/output values of variable in the monitor. The printf
function has general form: printf (“format specifiers”,variables)
10) What are the maximum and minimum possible ranges of values for long and short
type?
If the int variable is created by default as a ‘long’ type it typically will have a possible range of
values from a maximum of +214748347 and a minimum of -2147483648. For ‘short’ type
these are the maximum and minimum values +327676 and minimum -32768.
11) What is preprocessor?
The preprocessor is a program which is executed before the compilation of a source program
written by the user. The preprocessor directives begines with hash (#) followed by the
command. e.g #include – it is a directive to include file.
12) What exactly is a ‘variable scope’, ‘local variables’ and ‘global variables’?
The extent to which a variable is accessible in a program is called the ‘variable scope’.
Variables declared internally inside a function are known as ‘local’ variables. Variables
declared externally outside a function are known as ‘global’ variables.
13) What are signed values?
When an int variable is declared it can by default contain either positive of negative integer
values. These are known as ‘signed’ values. The range of positive values is determined by your
system.
14) Define reserved words.
C programs are constructed from a set of reserved words which provide control and from
libraries which perform special functions. The basic instructions are built up using a reserved
set of words, such as main, for, if,while, default, double, extern, for, and int, to name just a few.
15) What is the purpose of type declaration in C ?
All variables used in a C program are declared using the appropriate data types to enable the
compiler to allocate the required number by bytes in RAM to store values of these variables in
memory
16) What is identifier?
An identifier is a name used to identify a variable, function, symbolic constant and so on.
17) Mention the different types of operators used in C ?
1. Arithmetic operator
2. Relational operators
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
3. Logical Operators
4. Increment and decrements operators
5. Assignment operators
6. Conditional operator
7. Bitwise oprators
18) What is Loop control statements?
Loop control structures are used to execute and repeat a block of statements depending on the
value of a condition. There are 3 types of loop control statements in C
1. for loop
2. while loop
3. do – while loop
19) explain while loop.
A while loop has one control expression, and executes as long as that expression is true. The
general syntax of a while loop is
While ( expression ){
statements
}
we use a while loop when a statement or group of statements which may have to be executed
a number of times to complete their task. The controlling expression represents the condition
20) explain for loop .
A for loop is used to execute and repeat a block of statements depending on a condition. The
syntax of a for loop is
for( ; ; )
{
statements
}
21) What do mean by network ?
Computer networking refers to connecting computers to share data, application software and
hardware divices. Networks allow sharing of information among various computers and permit
users to share files
22) List a few unconditional control statement in C.
1. break statement
2. continue statement
3. goto statement
4. Exit () function
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
23) What is an array?
An array is a collection of values of the same data type. Values in array are accessed using
array name with subscripts in brackets []. Synatax of array declaration is = data type array_
name[size];
24) What is Multidimensional Arrays
An array with more than one index value is called a multidimensional array. To declare a
multidimensional array you can do follow syntax= data type array_ name[] [] []….;
25) Define string?
An array of characters is known as a string.for example
char st[8]; this statement declares a string array with 80 characters .
26) Mention four important string handling functions in C languages.
There are four important string handling functions in C languages.
1. strlen();
2. trcpy();
3. strcat();
4. strcmp();
The header file #include is used when these functions are called in a C program.
27) Explain about the constants which help in debugging?
A #if directive test can be offered with #else and #else if directives. This allows conditional
branching of the program to run sections of the code according to the result. Constants defined
with a #define directive can be undefined with the #undef directive. The #ifdef directive has a
companion directive #ifndef. These commands can be useful when debugging problem code to
hide and unhide sections of the program.
28) Define and explain about ! Operator?
The logical operator ! NOT is a unary operator that is used before a single operand. It returns
the inverse value of the given operand so if the variable “c” had a value of true then! C would
return value of false.
The not operator is very much useful in C programs because it can change the value of variables
with successful iterations. This ensures that on each pass the value is changed.
29) What is operator precedence?
Operator precedence defines the order in which C evaluates expressions. e.g. in the expression
a=6+b*3, the order of precedence determines whether the addition or the multiplication is
completed first. Operators on the same row have equal precedence.
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
30) Explain about the functions strcat() and strcmp()?
This function concatenates the source string at the end of the target string. Strcmp() function
compares two strings to find out whether they are the same or different. The two strings are
compared character by character until there is a mismatch or end of one of the strings is reached,
whichever occurs first. If in case two strings are identical, a value of zero is returned. If there
is no matches between two strings then a difference of the two non matching values are returned
according to ASCII values.
31) How does the type float differ from double in C language ?
Float data type refers real number in single precision and has 6 decimal digits. It takes 4 bytes
in memory to refer values ranging from 3.4e-38 to 3.4e+38
double data type also refers to real number but in double precision and has 12 decimal digits.
It takes 8 bytes of memory to refer values ranging from 1.7e-308 to 1.7e+308
32) What is an operator and operand?
An operator performs an operation like addition, subtraction and so on and produce a value.
Variables and constants upon which operations are performed are called operands.
33) What is RAM ?
RAM – Random Access Memory is a temporary storage medium in a computer. RAM is a
volatile memory i.e all data stored in RAM will be erased when the computer is switched off.
34) What is ROM ?
ROM – Read Only Memory is permanent storage medium which stores start up programs
(operating system programs) and BIOS programs which are recorded by the manfacturer of
the compiler system. ROM is a non-volatile memory.
35) Define system software.
System software is a collection of programs which are used to assist the user to handle the
computer hardware like printer, disk and so on and execute the application programs.
36) Define application software
application softwares are programs which are used to solve specific problems /tasks.
Examples include railway reservation, banking and so on.
37) What are control ststements ?
All the statements written in a program are executed from top to bottom one by one. Control
statements are used to execute / transfer the control from one part of the program to another
depending on a conditions.
Vidya Vikas Polytechnic, College, Mysuru
Prepared by: Mr.Thanmay J.S, HOD Mechanical, Vidya Vikas Polytechnic College, Mysuru.
38) Mention the types of memory
Two major types of memory storage is primary memory and secondary memory. Primary
storage (or main memory or internal memory), often referred to simply as memory, is the
only one directly accessible to the CPU.
Secondary memory (or external memory) differs from primary storage in that it is not directly
accessible by the CPU. Some of the example for secondary memory includes floopy disks,
flash memory, mengetic tape, hard drives etc.
39) What are input and output device?
Input and Output Devices: Input devices are the hardware that are used for providing
information to the computer like mouse and keyboard and output devices are the hardware
that are used for receiving information from computer like monitor, printer or the sound
system.
40) what is a Flowchart?
Flowchart are the graphical representation of a solution to a particular problem, which comes
under the category of Programming Practices and Techniques, in simple words flowchart is a
graphical representation of a program.