C Programming: R V Yenkar Hod Ec & It G P Nagpur
C Programming: R V Yenkar Hod Ec & It G P Nagpur
R V Yenkar
HOD EC & IT
G P Nagpur
Chapter 1
3
Significance of C
• C often termed as ‘middle level Language’
• Types programming Languages
– Machine level (Low level)- Assembler
– Middle level - C, Micro-Assembler
– High level – BASIC, PASCAL, FORTRAN, COBOL
• It combines the features of both high & low
level languages.
4
C is a system programming language
• It is a blend of both high & low level languages.
• It can directly interact with microprocessor.
• Execution time will be comparatively low
C is highly portable
• It allows the manipulation of bits, bytes and
address – Computer element
• Portability means adaptability between
different computers.
• Program written in C is easily transferable from
DOS to UNIX & vice versa.
5
C is a programmers language
• High level language program can understand by non-
programmers & allows them to alter it .
• C programs has few restrictions, compact set of
keywords, block structures thus non-programmers
can’t understand .
• C environment suits for professional programmers.
7
Programming Steps
• Creating the program
• Compiling the program
• Linking the program with functions that are
needed from library
• Executing the program
8
General form of C Program
• Comments
• Declarations: •It provides more freedom to
# include statements
#define statements
programmer.
Global variables •Must have one or more functions
• Main program
main() •Each function have variables &
{ statements.
Variables;
Statements; •Every program must have main()
} function & it is the first function called
• Sub program
function1() for execution.
{ •Pair of braces are used at
Variables;
Statements; appropriate places to distinguish
} functions / code blocks.
function2()
{
•Program start with open brace &
Variables; ends with closing brace.
Statements;
}
•Statement must end with
9
semicolon.
REVIEW (Points to be remembered)
• C is middle level language.
• C is a portable, structured language, has easy
coding & it is a programmers language.
• Comparatively C programs run faster.
• C program is made of many (user/ built-in)
functions & code blocks
• Every program begins with main() function &
execution starts only from that.
• Each function / code block start with opening brace
& ends with closing brace.
• Each program statement must end with semicolon.
• C program can run in UNIX, MS-DOS & Windows
platforms.
10
GOTO Next Topic
11
Chapter 2
14
C Token
• Identifiers
• Keywords
• Operators
• Literals
• White spaces
15
Identifiers
• Variables
• Constants
• Function
first character of identifier will be
alphabet followed by either number or
alphabet. Underscore is only allowed.
Length 31 characters
volume, 1area, area_plus, _area1
16
Data Types
• Four basic data types
– Integer,
– Character,
– Float,
– Void
• Types modifiers :-
– Integer signed, unsigned; long, short.
– Float float, double, long double
17
Integer
• Number without decimal point
• C doesn’t permit unary + sign
• Signed integer:– 2 bytes, -32768 to 32767
• Unsigned integer:– 2 bytes, 0 to 65535
• Long integer:– 4 bytes, -2147483648 to
2147483647
• Unsigned long integer:– 4 bytes, 0 to 4294967295
• Short integer:– 1 bytes, -128 to 127
• Unsigned short integer:– 1 bytes, 0 to 255
18
Float
• Number with decimal point
• Float – up-to 7 decimal points
• Double up-to 12 decimal places
• Long double up-to 16 decimal places
• Floating – mantissa & exponent part
19
Variables / constants
• A variable is the storehouse for constants
• Value may change throughout program
• All variables must be declared before used
– Format
Data-type variable_list;
Short area;
Int a,b,c;
Int d=10; /* initialize the value */
• Value does not change throughout program
is called constant.
Const b=5;
20
Character
• Any single letter enclosed within single
quote
Char v_name;
v_name =‘a’;
Void
•It is valueless.
•Uses – declare function that returns no
value. Create generic pointers.
21
Keywords
• int long short signed unsigned float double
char void const typedef
• if else while do for switch case goto
continue break struct union
• Auto default enum extern register sizeof
static voiatile return
22
GOTO Next Topic
23
Chapter 3
101.75 225 R
26
Input operations:- scanf() Function
• General purpose console input function.
• Used to input a data line containing mix
mode data.
• General form
scanf( “format specifier”, variable list)
e.g.
scanf(“%d%d%d”, &A, &B, &C);
27
Format specifier
Code Meaning
%c To read single character
%d To read a decimal integer
%e To read a floating point value
%f To read a floating point value
%g To read a floating point value
%o To read an octal value
%x To read a hexadecimal value
%s To read a string
%u To read an unsigned integer
28
For reading integer : %xd
Data type
characer
Conversion Specify field
character width
Ex.
scanf(“%d%d “, &a, &b);
If Input data is 7 9
then a=7 and b=9
29
For reading float numbers : %xf
Data type
Ex. characer
character string
Ex. Ex.
scanf(“%c%c “, &no1, &no2); scanf(“%s “, name);
33
Output operations:-printf() Function
• Output statement to display the o/p such
as captions, numerical results, etc.
• General form
printf( “format specifier”, variable list)
e.g.
printf(“%d %d %d”, A, B, C);
Display values for A, B, C
printf(“%d %d \n ”, a,b);
Display values for a, b and cursor will move to new line for
next printing
34
Other escape sequences
Codes Meaning
\b Back space
\f Form feed
\r Carriage return
\t Horizontal Tab
\” Double quote mark
\’ Single quote mark
\0 Null
\\ Back slash
\v Vertical tab
\a Alert
\o Octal constant
\x Hexadecimal constant
\n New line
35
Chapter 4
Decision Making
and
Branching
Introduction
• Normally program is executed in
sequentially in the statement appears.
• In some situation
→ we need to change the order of execution
based on certain condition.
→ repeat a group of statement until specified
condition get satisfied.
→This involves in decision making statements &
controls the sequence of execution; thus also
called control statements.
41
Introduction
• Different decision making & branching
statements are as follows
if statement
switch statement
ternary operator statement
goto statement
42
Decision making with if statement
if statement is powerful decision making statement
and is used to control the flow of execution.
Entry
Test False
expression
?
True
43
Examples of decision making
1. if (room is dark)
put on light.
2. if (bank balance is zero)
borrow money
3. If (age is more than 60)
person is retired
4. If (marks less than 35)
student is fail
5. If (b < a) b is less
else a is less
44
Forms of if
• Simple if statement
• If……else statement
• Nested If……else statement
• else if ladder
45
Simple if statement
Entry
If (test expression)
Test True
{ expression
statement block; ?
Statement
} block
False
Statement-x;
Statement-x
Next-Statement
46
……..
……..
If (category == “SPORTS”)
{
marks = marks + bonus_marks;
}
Printf(“%f”, marks);
……..
……..
47
If……else statement
Entry
If (test expression)
{
Test
true-block statement(s); False True
expression
?
}
False-block True-block
else Statement Statement
{
false-block statement(s);
}
Statement-x
Statement-x;
48
……… ………
……… ………
If (code == 1) If (sales >= 30000)
{ {
boy = boy + 1; commission = sales * 0.08;
} }
else else
{ {
girl = girl + 1; commission = sales * 0.05;
} }
……… ………
……… ………
49
Nested If……else statement
Entry
Test
False True
Condition 1
?
Statement-x
50
If (test condition-1) If ( candidate is female)
{ {
If (test condition-2) If ( balance > 5000)
{ {
statement-1; bonus = balance * 0.05;
} }
else else
{ {
statement-2; bonus = balance * 0.02;
} }
} }
else else
{ {
statement-3; bonus = balance * 0.02;
} }
Statement-x; balance = balance + bonus;
51
else if ladder
Entry
Test False
Statement-3 True Condition 2
?
Statement-2 Test
True False
Condition n
?
Statement-n Default
statement
Statement-x 52
Example: If ( avg > 79 )
grade = “Honours”;
Average Grade
else if ( avg > 59 )
marks
80 to 100 Honours grade = “First Div”;
60 to 79 First Div else if ( avg > 49 )
50 to 59 Second Div grade = “Second Div”;
40 to 49 Third Div else if ( avg > 39 )
0 to 39 Fail
grade = “Third Div”;
else
grade = “Fail”;
Printf(“%s \n”, grade);
53
The switch Statement
Decision Making
and
Looping
• In looping, a sequence of statements
are executed until some conditions
for termination of the loop are
satisfied.
• Program loop consists of 2 segments
– Body of the loop
– Control statement
57
Pre-test loop
Entry
Test False
condition
?
True
58
(a) Entry control
Entry Post-test loop
Test False
condition
?
True
59
(b) Exit control
The C language provides 3
constructs for performing
loop operation
60
The while statement
while (test condition)
{
body of the loop
}
Statement-x; ==========
sum = 0 ;
n = 1;
while ( n <= 10 )
========== {
chr = ‘ ‘ ; loop printf(“%d \n”, n);
while (chr != “Y”) sum = sum + n;
{ n = n + 1;
chr = getchar();
}
}
printf(“Sum = %d \n”, sum);
xxxxxxxxx ; 61
==========
==========
The do statement
do
{
body of the loop
}
while (test-condition);
==========
========== sum = 0 ;
do i = 1;
{ do
printf (“Input a number \n”); {
number = getnum(); sum = sum + i;
} loop i = i + 2;
while (number > 0 ); }
xxxxxxxxx ; while ( i <= 10 || sum<50 )
========== printf(“Sum = %d \n”, sum);
========== 62
The for statement
for (initialization ; test-condition ; increment)
{
body of the loop
}
==========
sum = 0 ;
for ( n=1; n<=10; n=n+1)
{
loop sum = sum + n*n;
}
printf(“Sum = %d \n”, sum);
==========
63
Comparison of the 3 loops
n=1; n=1;
while (n<=10) do
{ {
-------- --------
-------- --------
n=n+1; n=n+1;
} }
while (n<=10);
Do not go to goto
statement! 67
Next :
Jumping in loop
68
Chapter 7
ARRAYS
INTRODUCTION
• Fundamental data type – char, int, float
• Variables of these types can store only one
value at a time. New value can be stored
after erasing previous value.
• To store ‘m’ number of data we need ‘m’
number of variables.
• m=5 (5 values) 5 variables
int m1,m2,m3,m4,m5;
• m=100 (100 data) 100 variables
int m1,m2,………………………………,m100;
int m[100];
70
Data Structures
Data types
Derived User
fundamental
type defined
type
type
77
Two dimensional Array
• Two dimensional Array is array of array.
• Two dimensional Array can store a table of
values.
• The general form
Data-type array-name[row-size][column-size];
int a[3][3] will have elements are
a[0][0] a[0][1] a[0][2]
a[1][0] a[1][1] a[1][2]
a[2][0] a[2][1] a[2][2]
78
Initialization of 2D array
• Similar to 1D array, 2D array can be
initialized.
– int a[2][3]= { 1,1,1,2,2,2 };
– Here first row is initialized to 1& 2nd array to 2.
– int a[2][3]= { 1,1,1 },{ 2,2,2 };
Problem
For 2D array of 3X3, Find the following
1. Sum of all elements.
2. Row wise sum
3. Column wise sum
79
Multi-dimensional array
• C allows more than 2D array
• The general for of Multi-dimensional array is
– Data-type array-name[a][b]……….[z];
• Multi-dimensional arrays occupy more memory
space.
Problem
Consider there are 2 semesters, each semesters has got 4
subjects & the mark in each subject is the sum of 3 test
result.
Array 1D - 2 semesters
Array 2D – 4 subject/semester
Array 3D - three test /subject
80
Chapter 8
Character Handling in C
String
• A string is an array of characters.
• A group of characters defined between
double quote mark is a string.
• To build more readable program, strings
are required.
• Reading & writing
• Combining two strings together.
• Copying one string into another string.
• Comparing two string
• Extracting a portion of a string
82
Declaring of string variables
• String is defined as character array.
• General form
char string-name [size];
– char sname[30];
– char country[20];
• It is terminated by a null. ‘\0’ & for this size
of string =actual size +1.
– dharamadhikari 14 char ; size = 14+1=15
– char name[15];
83
Reading a string
• char name[15];
• scanf(“%s”,name); // don't use ampersand sing //
Let we want to read “New Delhi” as a city name.
– char city[10];
– scanf(“%s”,city);
The scanf() has got limitation that it terminates its input
on the first white/blank space it encounters.
– char city1[10],city2[10];
– scanf(“%s %s”,city1,city2);
– char city[10];
– gets(city); //to read more word in a single string//
84
Writing strings
• char name[15];
• printf(“%s”,name);
• puts() to write characters.
85
String Functions
• String handling using library functions
#include<string.h>
• strcpy(st1,st2)copies st2 into st1.
• strlen(st1) returns length of string.
86
Chapter 9
Function
User defined function
• C is language of functions
• Function like main() scanf() printf() are
called library functions.
• One main strong factor of C is the user
defined functions
• C functions are very easy & versatile.
• What is the difference between these two
functions?
88
What is a ‘C’ function?
• A function in is considered as a fundamental
building block.
• In order to avoid the complexity of a program
while coding, debugging & testing; the program
is divided into function parts or subprograms.
• Each module is called a function.
• ‘C’ allows to declare a function prototype.
• From function prototype, we get number & type
data that function is expect & type of value it
returns.
• int sum(int x,int y)
89
General form of function
• The general form of ‘C’ function
Return-data-type fun-name( argument-declaration);
{
Local variable declaration;
Body of the function;
return (expression);
}
Return data type specifies the type of value that function
returns after execution of return statements.
1.int I, j, dot();
// Here function dot() returns integer value//
2.float a, b, sum();
// Here function sum() returns float value//
90
General form of function
• Example 1 • Example 2
void main() void main()
{ {
void errormsg(void); int a, b, cube(int);
| scanf(“%d”,&a);
Statements; b=cube(a);
| printf(result=%d”,b);
errormsg(); }
}
int cube(int x)
void errormsg(void) {
{
printf(“Error”); int y;
} y=x*x*x;
return(y);
}
91
The return statement
Structure
Introduction
94
What is a structure?
• A “structure “ is collection data item (fields)
or variables of different data types that are
referred under the same name.
• It provides convenient means of keeping
related information together.
• The general form
struct tag-name
{
data-type members;
} 95
What is a structure?
• “struct” is a keyword, used to declare
structure template.
• Tag-name identifies the particular structure
& its data types.
• The fields in structure is structure elements
• All elements are logically related to each
other.
96
Example
struct stdrec
{
char name[15];
char examno[10];
int eng, maths, phy, chem;
};
97
Chapter 11
Pointers
Introduction
• Pointers are one of the most important
features of c language.
• In scanf() we have used pointer.
• All variables stored have its address in the
memory.
• Pointers are used for this purpose & it has
its own benefits.
• Pointers will make the program more
efficient.
99
What is pointer?
• It is a variable, which store the address of
another variable.
• A variable contain the address of another
variable then first variable is said to point
the second variable.
• Pointer operator – to determine the
address of a variable, there are two
operators ‘&’ and ‘*’
– & is “address of” operator
– * is “content of” operator.
100
Pointer
• The general declaration form is
– Data-type *variable-name;
– In above declaration 3 aspects are conveyed.
• The ‘*’ tells that variable-name is pointer variable.
• The pointer variable needs a memory location
• The pointer variable points to a variable of type
“data-type”.
– Examples
• int *a; //a is pointer variable points to an integer data type.
• float *b; //b is pointer variable points to afloat data type.
101