Sie sind auf Seite 1von 39

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Introduction
C is a High Level Programming Language. It is the most popular General Purpose Language. This
Language was first developed by Dennis Ritchie at AT&T Bell Labs in 1972. Before this C language low
level language was used for the computer which is very difficult for human to understand and there are so
many problems in that type of language. So C language is developed which is a High Level Language which
is very closer to human languages. C language has also many features like other high level languages like
Readability, Maintainability, Portability, Usability etc.

Character Set
Character sets means the characters and symbols that can be understand and accepted by the C language.
These are grouped to form the commands, expressions, c-statements and other tokens for C Language. There
are mainly four categories of the character set as given below.

1. Letter or Alphabet: These are represented by A-Z or a-z. C language is case sensitive so it takes
different meaning for small case and upper case letters. There are total 26 letters used in the CProgramming.

2. Digit: These are represented by 0-9 or by combination of these digits, there are total 10 digits used in
the C-Programming.

3. Special Characters: There are some special symbols and punctuation marks used for some special
purpose. Here are total 30 special characters used in the C-Programming. Special symbols used
under this category are like, +, -, *, /, @, #, $, %, ^ etc.

4. Empty space characters or white spaces: White spaces has blank space, new line return,
Horizontal tab space, vertical tab space, etc.

Identifiers
Identifiers are used for naming variables, methods, classes, labels and other programming elements.
Identifiers must enforce following rules
a) They can have alphabets (a to z), digits (0 to 9), and underscore.
sal1

Valid

sal#

Invalid (# is not a valid character)

b) They must not begin with a digit.


sal1

Valid

_sal1 Valid
1sal

Invalid (Start from digit)

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


1

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

c) Uppercase and lowercase letters are distinct


#include<iostram.h>
void main()
{

int a=2;
printf(%d,A) ;

}
O/P- This program generates compile error: Undefined Variable A because in our program we have
declared a not A
d) Keywords cannot be used as identifiers.
int float

invalid (float is a keyword)

Keywords
The keywords are also called reserved words. Keywords can not be used as variables names. These are
mainly 40 keywords among which 32 are used by many compilers for high level programming, whereas
remaining 8 reserve words are used by the programmer for low level programming. Following are the 32
Keywords of C.
auto

do

typedef

for
break

return
double

goto

start

union

case

else

if

sizeof

unsigned

char

int

static

void

continue

extern

long

struct

while

volatile
signed

constant
switch

default
double

register
enum

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


2

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Constants/Literals
Constant is one that has a fixed value throughout the program. Constants are assigned to variables in a
program. Constants can be divided into two categories
1) Numeric Constant
2) Non-Numeric Constant
Constants

Numeric Constant

Integer

Non-Numeric Constant

Real or float

Decimal Octal Hexadecimal

Single Character String Character Backslash character

with

without

Exponent

Exponent

1. Numeric Constant:
These have numeric value having combination of sequence of digits i.e. from 0-9 as alone or
combination of 0-9 with decimal points having positive or negative sign.
a. Integer Constant:
Integer numeric constant have integer data combination of 0-9 without any decimal point.
These are further subdivided into three parts:

i.

Decimal Constant: These have no decimal point in it and is either be alone or the
combination of 0-9 digits. These have either +ve or ve sign.
For example 124, -345, +45 etc.

ii.

Octal Constant: These consist of combination of digits from 0-7 with positive or
negative sign. It has leading with O or o. For example O37, -O87, O0 etc.

iii.

Hexadecimal Constant: These consist of combination of digits from 0-9 and A-F.
It has leading with Ox or ox. For example Ox37, ox87, OX0 etc.

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


3

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

b. Real or Float Constant:


Real numeric constant have data combination of 0-9 with decimal point. It may have positive
or negative values. It is also called floating point constant. These are further subdivided into two
parts:

i.

Without exponent: Real numeric constant without exponent is a simple numeric


value having combination of 0-9 with decimal point.
For example: 3.54, 34.56, -987.56 etc.

ii.

With exponent: Real numeric constant with exponent have two parts in the constant
value. One part is mantissa and other part is exponent part.
For example: 3.2e-04 (0.00032), 65.74e01(657.4) etc.

2. Non-Numeric Constant:
These Non-numeric constant have values only from alphanumeric characters. There are not any
negative values in these constants.

a.

Single Character Constant: This type of constant contains only single character from
alphanumeric character sets. This single character is written in single quotation marks.
For example: a, A, 2 valid constants,

sd invalid constants.

b. String Character Constant: This type of constant contains more than one character in it. It
contains multiple characters according to our requirements. These characters are written in
double quotation marks. For example: Welcome to IIMTetc.

c.

Backslash Character Constant: These type of constant contains some characters for some
special purposes. Following are some of the backslash character constants. These are also known
as Escape sequences.
Escape Sequence Purpose
\a

Alert/ bell/ beep

\b

Backspace

\f

Form feed

\n

New line

\t

Tab

\\

Backslash

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


4

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Single quotation mark

Double quote

Punctuators
These are symbols used for grouping and separating code. They are also known as separators or Delimiters.
Separators are given below

Parentheses ()
Braces { }
Brackets [ ]
Semicolon (;)
Colon (:)
Comma (,)
Period (.) etc.

Data Types
Data types are used to declare variables. Variable declaration tells us
1) Type of value a variable can hold
2) Name of variable
3) Range
There are mainly five types of data type used in C
1. Primary or scalar or standard or fundamental or simple data type
2. Secondary or derived data type
3. Enumerated Data types or User defined data types
4. Empty data type or void data type
5. Pointer data type
1. Primary or Scalar Data type: it is used for representing a single value only. Scalar data type is further
divided into three types
1. Integer types
2. Floating types
3. Character

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


5

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Integer type: Integer type can store integer constant i.e. numerical value without decimal points.
Numerical value can be positive as well as negative. It supports 4 types of integers as shown in table
Type

Size

Range

Int

2 bytes -32768 to 32767

Unsigned int

2 bytes 0 to 65535

Long

4 bytes -2 31 to 2 31-1

Unsigned long 4 bytes 0 to 2 32 -1


Floating Data Type: Floating data type can store real constants i.e. numerical value with decimal
points. Values can be positive as well as negative.
Type

Size

Range

Float

4 bytes

3.4 * 10 38 to 3.4 * 1038

Double

8 bytes

1.7 * 10 308 to 1.1 * 10308

Long double

10 bytes

3.4 * 10 4932 to 1.1 * 10 4932

Character Type: Character data type can hold only a single alphabet (A-Z) or digit (0-9) or special
symbol. The character data type assumes a size of one byte. It has been designed to hold 8 bit ASCII
code. Its range is from 0 to 255.
2. Secondary or Derived data type:
Secondary data types are derived from the scalar data types. Secondary data type may be used for
representing single value or multiple values. Secondary data types are divided into three categories
1. Array or Strings
2. Structures
3. Unions
3. Enumerated Data types or User defined data types:
It provides us a way to define our own data types. This is used when you know in advance the finite
number of values a variable can take in a program. Enumerated means that all values are listed.
These data types are internally treated as integers. By default first member gets value 0, second 1 and
so on.
VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road
6

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

#include<iostream.h>
enum dow{sun=1,mon,tue,wed,thu,fri,sat,sun};
void main()
{

dow d1,d2;
d1=mon;
d2=thu;
printf(%d,d2-d1);

}
Output: 3
4. Void or Empty Data Type:
Void or empty data type is used in the user defined functions. This is used when function returns
nothing. This is also used when function has no arguments.
5. Pointer Data Type:
Pointer data types are used to store memory addresses instead of values.

White spaces
White space is defined as spaces, carriage return, line feeds, tabs, vertical tabs and form feeds. These are
ignored by the compiler. But there are some exceptions:
1. The string constant can not be split.
2. #include<headerfile> must be written on a single line.
3. // symbols can be used to show comments. These are valid only for a single line; no white space
should be used between these slashes.

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


7

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

C operators
An operator is a symbol that tells the compiler to perform a certain mathematical or logical manipulators. C supports
a rich set of operators. C operators can be classified into following categories:
1. Arithmetic operators
Arithmetic operators are used for arithmetic operations like Addition, Subtraction, Multiplication, Division
& Modulus. These can operate on any built in numeric type. Following are the list of Arithmetic Operators.
Operator

Meaning
+

Addition

Subtraction or unary
minus

Multiplication

Division

Modulus division

E.g. If a=14 and b=4 we have following results


a-b=10

a+b=18

a*b=56

a/b=3( decimal part trncated )

a%b=2 (Remainder of the division)


Here a, b are known as operands. Operator is called binary operator if it requires two operands and unary
operator if it requires one operand.
Type Conversions: When two operands of different types are encountered in the same expression low type
variable is converted to the type of the higher type variable. The conversion takes place (implicitly) invisible
to the user.
Long Double Highest order
Double
Float
Long
Int

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


8

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Char

E.g.

(Lowest order)

1. a = 11/5= 2

2. a = 11/5.0=2.2

Casting: The term applies to the data conversions by the programmer as opposed to the automatic data
conversion. It is also known as explicit conversion.
E.g.

a = 11/( int ) (5.0 ) =2

Expressions:
An expression is a combination of operands and operators. In an expression there may be multiple operands
and multiple operators depends upon the situation. An operand may be a variable or a constant value. Expression are
of five types.
1. Arithmetic Expression
2. Relational Expression
3. Logical Expression
4. Assignment Expression
5. Conditional Expression
1. Arithmetic Expression: Arithmetic Expressions are the expressions which contains only the Arithmetic
Operators. These are of three types.
a) Integer Arithmetic Expression: When all the operands are of Integer type then the Expression is
known as Integer Arithmetic Expression. For Example: 5 +2, 35/3 etc.
b) Real Arithmetic Expression: When all the operands are of real type then the expression is known
as Real Arithmetic Expression. For Example: 5.4*3.2, 567.7/45.7 etc.
c) Mixed Mode Arithmetic Expression: When all the operands are of mixed type i.e. some
operands are of real type and some operands are of Integer type then the Expression is known as
Mixed Mode Arithmetic Expression. For example: 3+5.6, 567* 4.5 etc.
2. Relational Operators: The relational operators are symbols that are used to test the relation between two
expressions. These operators return true or false i.e. 1 or 0.Relational operators are binary operators because
they required two operands. There are mainly six type of relational operators used in C-Language.
Operator Meaning
==

Equal to
>

Greater than

<

Less than

!=

Not equal to

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


9

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

>=

Greater than or equal to

<=

Less than or equal to

2. Relational Expression: Relational Expressions are the expressions which contains only the Relational
Operators. These are of three types.
a) Integer Relational Expression: When all the operands are of Integer type then the Expression is
known as Integer Relational Expression. For Example: 5 < 2, 35 > 3 etc.
b) Real Relational Expression: When all the operands are of real type then the expression is known
as Real Relational Expression. For Example: 5.4= =3.2, 567.7!=45.7 etc.
c) Mixed Mode Relational Expression: When all the operands are of mixed type i.e. some operands
are of real type and some operands are of Integer type then the Expression is known as Mixed Mode
Relational Expression. For example: 345< 34.5, 23.45 >= 34 etc.
3. Logical operators: Logical operators are used to combine two or more relations. These are used in
decision making statement because they return true or false values only i.e. 1 or 0. There are mainly three
type of Logical Operators used in the C-Language.
Operator Meaning
&&

AND

||

OR

NOT

For example:
void main()
{

int a=2,b=0,c;
if( a>=2 && a<=7)
printf(\nYes);
else
printf(\nNo);
c=a || b;
printf(\t c=%d,c);

}
Output- Yes

c=1

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


10

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Truth Table of Logical AND and Logical OR Operators


A

A&&B

A||B

Truth Table of Logical NOT Operator


A

!A

3. Logical Expression: Logical Expressions are the expressions which contains only the Logical Operators.
These are of three types.
a) Integer Logical Expression: When all the operands are of Integer type then the Expression is
known as Integer Logical Expression. For Example: (5 < 2)&& (35 > 3) etc.
b) Real Logical Expression: When all the operands are of real type then the expression is known as
Real Logical Expression. For Example: (5.4= =3.2) || (567.7!=45.7) etc.
c) Mixed Mode Logical Expression: When all the operands are of mixed type i.e. some
operands are of real type and some operands are of Integer type then the Expression is known
as Mixed Mode Logical Expression. For example: (345< 34.5)&& (23.45 >= 34) etc.
4. Assignment operator: Assignment operators are used for assigning an expression or value to a variable.
It is the short hand symbol for arithmetic & bitwise operators. Assignment operators are binary operators
because they required two operands. Some of the commonly used assignment operators are given below
Statement using Assignment Operator

Equivalent statement using arithmetic operator

a+=1

a=a+1

a- =1

a=a-1

a*=5

a= a* 5

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


11

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

a\=5

a=a/5

a%=b

a=a%b

4. Assignment Expression: Assignment Expressions are the expressions which contains the Assignment
Operators. These are of three types.
a) Integer Assignment Expression: When all the operands are of Integer type then the Expression is
known as Integer Assignment Expression. For Example: a = 5+2, b= 35*3 etc.
b) Real Assignment Expression: When all the operands are of real type then the expression is
known as Real Assignment Expression. For Example: c=5.4/3.2, d=567.7*5.7 etc.
5. Conditional operator or Ternary operator: This operator is compressed version of if-else statement.
This is called ternary operator because it requires three operands. The syntax of the statement is
C=( a > b) ? a : b;
This above statement returns the greatest number as a value of C variable i.e if a is greater than b then the value of a is
assigned to c otherwise the value of b is assigned to c.
6. Increment/Decrement operator: The ++ (increment) operator adds 1 to the operand and (decrement)
subtracts 1 from the operand. Both are unary operators because they required single operand. These
operators can be used in two ways:
1. Prefix operator
2. Postfix operator
1. Prefix Increment/Decrement Operator: In this first of all value will be incremented
or decremented (according to operators ++ & --) and then that new value will be
assigned to a variable.
2. Postfix Increment/Decrement Operator: In this first of all value will be assigned to
a variable then its is incremented or decremented according to the operator used.
//Program to explain Postfix and Prefix Increment Operator
#include<iostream.h>
void main ( )
{

int a=2, b=2, c, d;


c= ++a;
d= b++;
printf(\na=%d\tc=%d,a,c);
printf(\nb=%d\td=%d,b,d);

}
Output:

a=3

c=3

b=3

d=2

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


12

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

7. Bitwise Operators:
These operators are mainly used for the operation of Binary bits i.e. 0 and 1. So these are mainly used for
low level programming. Bitwise operations are the testing, setting or shifting of the actual bit in a byte.
These operators should not be of float or double type due to binary version. There are mainly six Bitwise
Operators used in C programming.

Bitwise Operator

Meaning

&

Bitwise AND

Bitwise OR

Bitwise XOR

<<

Bitwise Left

>>

Bitwise Right

Ones Complement

8. Special Operators: These are used for special purposes in C-Language. These operators are used in
Pointers, Structures and Unions etc. Six type of Special Operators are given below.
a. Unary Operator

b. Comma Operator

c. Sizeof Operator

d. Type Operator

e. Pointer Operator

f. Member Selection Operator

Sizeof Operator
This operator returns the number of bytes occupied by operand. The operand may be a variable, a constant
or a data type. For Example
a= sizeof(int)

//a=2

a=sizeof(float)

//a=4

a=sizeof (char)

//a=1

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


13

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Precedence of operators: In an expression operators with higher precedence are evaluated before lower
precedence operator. Operators having equal precedence are evaluated on the basis of associatively.
Desc.

Operator

Associatively

Higher ( ), [ ], ->, .

Left to right

-, ++, --, ~, !

Right to left

& (address of)


* ( value of address)
( Type ) casting
Size of
*,/,%

Left to right

+-

Left to right

<< ( left shift)

Left to right

>> ( Right shift )


< ,<=, > , >=

Left to right

==, !=

Left to right

& (Bitwise AND)

Left to right

^ Bitwise XOR

Left to right

| Bitwise OR

Left to right

&&

Left to right

||

Left to right

? : ( conditional operator) Right to left


Lower

Right to left

*=

|=

%=

Right to left

+=

-=

&=

Right to left

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


14

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

^=

|=

Right to left

<<= >>==

Right to left

Control Statements or Flow Controls


A program consists of some statements which will execute in some sequiential manner but if we want to
override that flow of execution of statements then we need some type of Flow Control Statements. So there
are mainly three different categories to control the flow of execution.
1. Branching
2. Looping
3. Jumping

1. Branching
To override the sequential flow of execution branching is must. At the same time arbitrary unconditional
branches are not healthy for programming. Branching must be done on a test. C supports following control
or decision making statements
1. If statement
2. switch statement
3. conditional operator statement
If statement
If statement is used to control the flow of execution of statements. It is a two way decision statement
and used in conjunction with an expression. If statement is of further four types.
a) Simple If Statement: When there is only one statement in our program, then we need only one
block of statement. At that time we need only Simple if statement. The syntax of if statement is like
If (condition)
{true statement block;}
other statements;
In this type of statement condition will be checked. If condition is true then true statement
block will be executed and after that other statements block will be executed. If the condition is false
only other statements bock will be executed.
b) If-else Statement: This statement also contains single condition but with two different blocks one
for the true condition and one for the false condition. The syntax of if statement is like:
If (condition)
{True Statement- block;}
else
{False Statement- block;}
Statement n;

Expressi
on
?

False

True

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


15

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

In this type of statement condition will be checked. If condition is true then true statement
block will be executed and after that statement - n block will be executed. If the condition is false
then the block of false statement will be executed and after that statement n block will be executed.
c) Nested If Statement: When one if statement occurs within another if statement then that type of if
statements are known as nested if statements. These statements are used to solve some complex type
of problems. The syntax of this statement is given below:
If(condition1)
{
If (condition2)
{Statement1;}
else
{Statement2;}
}
else
{Statement3;}
Statement n;
}
In this type of statement condition1 will be checked. If condition1 is true then next condition2
will be checked. If condition2 is true then Statement1 will be executed and Statement n will be
executed and if condition2 will be false then Statement2 will be executed and then Statement n will
be executed. If condition1 becomes false then Statement3 will be executed and after that Statement
n will executed.
d) Ladder if-else statement: This type of statement is used only when there are many number of
conditions to be there to check. The program showing the structure of this statement are given below:
//Program to print the division of a student on the basis of following criteria:
Marks>=60

First

Marks>=50 AND Marks<60 Second

Marks>=40 AND Marks<50 Third

Marks<40

Fail

void main( )
{

int marks;
printf(Enter marks);
scanf(%d,&marks);
if(marks >=60)
printf(First);
else if(marks >=50)
printf(Second);
else if(marks >=40)
printf(Third);

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


16

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

else
printf(Fail);
}
2. Switch statement:
Switch statement is a multi way decision statement which tests the value of a given variable (expression)
against a list of case values and when a match is found a block of statements associated with that case is
executed. The general form of switch statement is as shown below
Switch (expression)
{
case value1: block-1; break;
case value 2: block-2;break ;
default: default block;
}
//Program to check if the given character is vowel
void main( )
{

char ch;
printf (\n Enter any character);
scanf (%c, &ch) ;
switch(ch)
{

case A :
case a : printf(Vowel); break;
case E :
case e : printf(Vowel); break;
case I :
case i : printf(Vowel); break;
case O :
case o : printf(Vowel); break;
case U :
case u : printf(Vowel); break;
default : printf(\n Not Vowel) ;

}
}

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


17

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Conditional Operator (? :) :
Conditional operator is compressed version of if statement. It is also called ternary operator because it
requires three operands. The general form of use of the conditional operator is as follows
Conditional Expression? exp1: exp2
The conditional expression is evaluated first if the result is true exp1 is evaluated and is returned otherwise
exp2 is evaluated and its value is returned.
For Example
void main( )
{

int x=2, y ;
y= ( x>2) ? ( 2 * x * 5) : (3 * x +1);
printf(%d,y) ;

}
Output : 7

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


18

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

2. Looping:
Loops are used to repeat the some portion of a program either a specified number of times or until a
particular condition is being satisfied. Mainly loops are of two types. One is Entry Controlled Loop and
another is Exit Controlled Loop.
a) Entry Control Loop: In this type of loop firstly condition is checked if it is true then body of the
loop is executed otherwise body of the loop is not executed.
b) Exit Control Loop: In this type of loop firstly body of the loop is executed then condition is checked,
now if condition is true then body executed again until the condition becomes true otherwise the
program goes out of the loop.
After the above types, there are three ways by which we can repeat a part of the program.
1. For statement
2. While statement
3. Do-while statement

1. For loop:
For loop is an entry control loop. It is one step loop, which initialize, check the condition and
increment/decrement the step in the loop in a single step. For loop is used where the loop will be traversed a
fixed number of times. The general form of for statement is as under
for( initialization; test condition; modifier expression)
{
body of the loop;
}
For Example
void main( )
{

int i;
for( i=1;i<=5; I++)
printf(ICIT);

}
output: ICIT prints 5 times.
void main( )

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


19

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

for(

cout<<Hello;
}
Output: Hello infinite times.

2. While loop:
While is an entry controlled loop statement. The test condition is evaluated and if the condition is true then
the body of the loop is executed. While loop keeps repeating an action until the test condition returns false.
The general form of while loop is as under:
initialization;
while( test condition)
{

Body of the loop;

For example
void main( )
{

int sum =0; int n=1;


while (n<=5)
{

sum= sum+n ;
n++;

}
printf(%d,sum);
}
Output: 15

3. Do-while statement:
Do While is an exit controlled loop statement. In this loop, first body of the loop is executed and then the
condition is checked. If condition is true, then the body of the loop is executed. When conditions become
false, then it will exit from the loop. The syntax of this loop is:
initializations;
do
{ body of the loop; }
while ( test condition);}
void main( )
{

int i=10;
do

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


20

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

printf(Hello);
i++;

} while( i<10);
}
Output: Hello

3. Jumping:
1. Break statement:
Break statement is used for an early exit from a loop .It is usually used with for loop, do-while, while loops
and in the switch statement.
void main( )
{
int i=1;
for(

if(i>5)
break;
printf(%d, i);
i++;
}

}
Output: 12345
2. Continue statement
Continue statement causes the loop to continue with the next iteration without executing remaining
statements. It is usually used with for loop, do-while, while loops
void main( )
{
for(int i=1;i<=10;i++)
if( i%2==0)
continue;
printf(%d, i);
}

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


21

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Output: 1 3 5 7 9
3. Goto Statement:
Goto is a powerful jumping statement. This statement moves the control on a specified address. Jump can be
either in forward direction or in backward direction.
a) Forward GOTO: In this control moves forward at some specified level in the program. The
syntax of this is like:
Statement1;
Statement2;
Goto label;
Statement3;
Label:
Statement4;
In the above example after the statement2, statement4 will be executed because after statement2 the
flow will turned towards statement4 and statement3 will be skipped.
a) Backward GOTO: In this control moves backward at some specified level in the program. The
syntax of this is like:
Statement1;
Statement2;
Label:
Statement3;
Statement4;
Goto Label:
In the above example after the statement4, statement3 and statement4 will be executed again and
again until some specified condition not met to exit from this loop.
Example of Backward Goto
void main ( )
{ int i=1;
take:
if( i>=10)
printf(%d, i);
else
{ i++;
VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road
22

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

goto take;}
}
Output: 10
Example of Forward Goto
void main ( )
{

int a=10, b=20, c, d;


c = a+ b;
d = b-a;
printf(%d, c);
goto label;
printf(%d, d);
label:
getch();

}
Output: 30

Difference Between While & Do While


SNo
1

While
While loop is entry controlled loop
i.e the test condition is evaluated
first and if the condition is true then
the body of the loop is executed.
While loop will not execute any
statement if the condition is false
e.g.
void main()
{ int i=11;
while (i<=10)
{
printf(%d, i);
}
}
Output: Blank Screen
Semi colon not required after while

Do While
Do while loop is exit controlled
loop i.e. first body of the loop is
executed and then condition is
checked
Do While loop executes at least
once
e.g.
void main()
{ int i=11;
do
{
printf(%d,i);
}while (i<=10);
}
Output: 11
Semi colon required after while

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


23

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Difference Between Break & Continue

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


24

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

SNo
1

Break

Continue

Break statement is used for an early


exit from a loop.

Continue statement causes the loop


to continue with the next iteration
without executing remaining
statements.

It is usually used with for loop, do- It is usually used with for loop, dowhile, while loops and in the switch while, while loops
statement.
e.g.

e.g.

void main( )

void main( )

{ for(int i=1;i<=10;i++)

int i=1;
for(

if( i%2==0)

continue;

if(i>5)

printf(%d, i);

break;
printf(%d, i);

i++;

Output: 13579

}
}
Output: 12345

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


25

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Functions
A function itself is a self contained block of statement that performs some specific task. It is also
called sub programs or subroutines. Function has a property that it is reusable i.e. it can be executed from
many points as required. We can pass information to the function in the form of arguments and some time
function return some value and sometimes return nothing. By default return type of function is int. Every
program in C must have main () function because execution of program starts from main () function.
Function has following advantages:
1. Remove coding redundancy because same function can be used by many programs.
2. Easy to understand and debug the entire program as a collection of functions.
3. The length of source program can be reduced by using functions
4. Less memory is required to run program if function is used
5. Reliability is high in function oriented programming
6. Testing is easier.
To define a function in C, we use three steps as:
1. Declaring of function

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


26

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

2. Calling the function


3. Definition of function
Declaring a Function means to provide the basic information about a function to the compiler.
Function declaration is also known as Function Prototyping. The syntax for the declaration of the
function is like
int mul(int a, int b);
Calling a Function: When a function call is made then the program jumps to the function definition
part and execute that part of the program. After the execution of the function definition part control
returns to the main program. The syntax for the calling of above function is like:
mul (8, 9)
Definition of Function means actual code of the function that tells the compiler what to do. The
syntax for definition is like:
int mul(int a, int b)

//Function Header

{
return (a*b);

//Function Body

E.g. 1
#include<iostream.h>
int mul(int a, int b);

// Function Declaration

void main( )
{

int a=10, b=20, c;


c= mul(a,b)

//Function Calling

printf(\n%d , c);
}
int mul(int a, int b)
{

//Function Definition

int d;
d= a*b;
return(d);

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


27

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

E.g. 2
#include<iostream.h>
void main( )
{
void star( );
star();
printf(\nWelcome to IIMT);
star( );
printf(\nGangtok);
}
void star( )
{
for( int i=0; i<5; i++ )
printf(*);
}

Function calls:
There are two types of function calls
1) Call by value
2) Call by reference
Call by value
In call by value we pass value of each actual argument (declared in the calling function) to corresponding
formal arguments (declared in called function). With this method value of the actual arguments in the calling
function remains unchanged.
void swap( int, int);
void main( )
{

int a=10, b=20;


swap (a,b);
printf(\na=%d \tb=%d, a, b);

}
void swap( int x, int y)
{

int t;

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


28

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

t=x; x=y; y=x;


}
Output: a=10 b=20
Call by reference
In call by reference we pass addresses of actual arguments (Declared in the calling function) to formal
arguments (Declared in the called function). So using this method we can change actual arguments. Using
this approach a function can return more than one value.
void swap( int *, int *)
void main( )
{

int a=10, b=20;


swap(&a, &b);
printf(\na=%d \tb=%d, a, b);

}
swap( int *x, int *y)
{

int t;
t=*x; *x=*y; *y=t;

}
Output: a=20

b=10

Recursion
When a function calls itself, then it is called recursion. If proper care not taken then recursion will create an
indefinite loop. Recursion is also called self-reference loop. A function is called recursive if a statement
within the body of a function calls the same function. For example
Example 1:

void main( )
{

printf(Hello);
main( );

}
Output: Hello Infinite times
Example2:

int rec (int);


void main( )
{

int a, fact;
printf(\n Enter the number);
scanf(%d,&a);
fact= rec(a);

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


29

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

printf(%d, fact);
}
int rec (int x)
{

int f;
if ( x= =1)
return 1;
else
f= x*rec(x-1);
return f;

}
Advantages of Recursion
1. Recursion is more efficient if the program using recursion are run on computer with multiprocessing
facilities
2. It is simple, easily understandable, compact and transparent
3. Lesser number of programming statements required with the use of recursion
4. It is very useful in solving the data structure problems like linked list, queues, stack, tree etc.
Disadvantages of Recursion
1. It requires more memory because recursive calls along with automatic variables are stored on the
stack
2. The computer may run out of memory if recursive calls are not properly checked
3. If proper precautions are not taken recursion may result infinite loop

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


30

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Array
Array is a collection of related data items that share a common name and data type. These data items are
differentiated by index number or subscript in brackets after the array name. All arrays in C start from zero.
Array can be initialized at the time of declaration an arrangement of array elements in memory is contiguous
as shown below
int a[ ]= { 1,2,3,4,10};
a[0]

a[1]
1

4002

2
4004

a[2]

a[3]

4006

4008

a[4]
10
4010

Advantages of Array:
1. Large amount of data items can be stored
2. Array helps to arrange data in sorting order
3. Searching using array is fast if array is in sorting order
4. Array can be used to create data structures like stack, queue etc.
Disadvantage of Array:
1. One array cant be assigned to another array
e.g.
int a[]={1,2 , 3, 4, 5}
int b[5]=a
//Error
VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road
31

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

2. Insertion/deletion of elements near the beginning of array is slow


3. Bound checking is the responsibility of programmer
// WAP to count odd & even nos from an array.
void main()
{
int a[10], i, ce;
for (i=1; i<=10; i++)
{
printf(\n Enter Element:);
cin>>a[i];
if(a[i]%2==0)
ce++
}
printf(\nEven Nos=%d,ce);
printf(\nOdd Nos=%d,10-ce);
}

Addresses and Pointers


Every byte in the computer memory has an address. Addresses are basically numbers that start from 0 and
end at highest address which will vary according to the amount of memory available in computer. E.g. The
highest address for 64 KB of memory is 65535 (i.e. 64* 1024=65536 bytes). & operator returns the memory
address of a variable
Pointers are memory variables that store the address of another variable instead of value. Pointers are
declared as
int *p;
The asterisk (*) also called indirection operator.
Advantages of Pointer:
1. Using pointers we can create dynamic array
2. Using pointers it is possible to pass complete array to function
3. Helpful in creating data structures like linked list, stack, queue
4. Pointers reduce the length & complexity of program.
5. Passing arguments to function when function needs to modify original arguments.
6. Pointers increase the execution speed of program and are more efficient

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


32

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

7. Pointers are very useful to handle files


Disadvantages of Pointer:
1. Uninitialized pointers cause the system to crash.
2. Difficult to understand
For Example
void main( )
{

int i=3, *x; float j=1.5, *y;

Output:

printf(\n%d\t%f, i, j);

printf(\n%d\t%d, &i, &j);

2000

2002

x=&i; y=&j;

2000

2002

printf(\n%d\t%d, x, y);

printf(\n%d\t%f, *x, *y);

30

*x=30;
printf(\n%d, i);
}
Operation on Pointers
Following operation can be performed on a pointer
1) Addition of a number to a pointer
int a[5]={11, 12, 13, 14, 15},*p;
p=&a[0];

//The address of the first element of a is stored in p i.e. 2000

p=p+2;

//p now contains the address of third element of a i.e. 2004

a[0]

a[1]

11

12
2000

a[2]
13

2002

a[3]
14

2004

2006

a[4]
15
2008

2) Subtraction of a number from pointer


int a[5]={11, 12, 13, 14, 15},*p;
p=&a[3];

//The address of the fourth element of a is stored in p i.e. 2006

p=p-1;

//p now contains the address of third element of a i.e. 2004

Pointers and array: There is a close association between pointers and arrays. The array name itself is a
pointer, which will store the base address of the array. For example

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


33

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

#include<iostream.h>
void main( )
{
int a[5]={ 31, 54, 66, 77, 16};
for( int i=0;i<5; i++)
printf(\n%d, *(a+j));
}
Here expression *(a+j) has exactly the same effect as a[j].

Structure
A structure is a collection of related fields of different types. Here fields are called structure member or
structure element. A structure represents an entity for example book. In C we can also use function in
structure. But structures are mainly used to collect data.
struct book
{

int bno, edition;


char title[20];
float price;

};
void main( )
{

struct book b1={ 101,3, DOS, 230.00 };


struct book b2, b3;
b2.bno=102; b2.edition=2;
strcpy(b2.title,Java);
b2.price=140.00;
printf(\n Enter book no.); scanf(%d, &b3.bno);
printf(\n Enter Edition.); scanf(%d, &b3.edition);
printf(\n Enter Title); scanf(%s, b3.title);
VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road
34

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

printf(\n Enter price.); scanf(%f, &b3.price);


printf(\n%d\t%d\t%s\t%f, b1.bno, b1.edition, b1.title, b1.price);
printf(\n%d\t%d\t%s\t%f, b2.bno, b2.edition, b2.title, b2.price);
printf(\n%d\t%d\t%s\t%f, b3.bno, b3.edition, b3.title, b3.price);
}
Features:
1. Structure specifier and definition can also be combined into a single statement
struct
{

int bno, edition;


char title[20];
float price;

} b1;
2. Structure members can be initialized at the time of creation of structure variables.
struct book b1={ 103, 3, C, 120.00 };
3. One structure variable can be assigned to another.
struct book b2= b1;

Union
A union is a collection of related fields of different types sharing the same memory area. Here fields are
called union member or union element. Union declaration has more than one variable declaration but only
one can be used at a time. For example
union abc
{

char a;
int b;
float c;
double d;

}v;
The storage of memory locations to these members are represented as below
1001

1008

22

2.3

242.33333367

a
b
c
VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road
35

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444
d

Difference between Array and Structure


Array

Structure

Array is collection of data items of same data type

Structure is a collection of data items of different


data types

One Array cant be assigned to another

One Structure variable can be assigned to another

It has declaration only

It has declaration and definition

No keyword required

Keyword struct is used

An array cant have bit fields

A structure may contain bit fields

Array name itself is a pointer which store base


address of array

A structure name is known as tag.

Difference between Structure and Union


Structure

Union

Every Member has its own memory

All members use the same memory

Keyword struct is used

Keyword Union is used

All members may be initialized

Only its first member may be initialized

Different interpretations of the same memory


locations are not possible

Different interpretations of the same memory


locations are possible

Consumes more space compared to union

Conservation of memory is possible

Storage classes
Storage class decides
1. Storage Location of variable
2. Default initial value of variable
3. Scope of variable
4. Life of variable

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


36

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Storage classes are following types


1. Automatic storage class
2. Static storage class
3. Register storage class
4. External storage class

Automatic

Register

Static

Storage Location
Memory

Storage LocationStorage LocationRegister if free otherwise Memory


in memory

Storage Location
Memory

Default Initial ValueGarbage Value

Default Initial ValueGarbage Value

Default Initial ValueZero

Default Initial ValueZero

External

Scope- Local i.e. Limited Scope- Local i.e. Limited Scope- Local i.e. Limited ScopeGlobal
i.e
to function/block in
to function/block in
to function/block in
variable can be shared by
which it has been defined which it has been defined which it has been defined more than one functions
Life- destroy when the
function is exited

Life- destroy when the


function is exited

A variable declared
inside a function is by
default an automatic
variable

Keeping the frequently


Value persist between
accessed variables in
different function calls
register will lead to faster
execution of programs

A Variable declared
outside a function is by
default , an external
variable.

void main( )

void main( )

void main( )

int a;

{ auto int a=10;

{ register int i;

{ inc ( );

void main( )

{ auto int b=20;


printf(%d, a); //OK

Life- Destroy when


program ends

for( i=1; i<=10; i++)

inc ( );

printf(\nICIT);

inc ( );

printf(%d, b); //OK }

Life- Destroy When the


program is exited

{ a=5;

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


37

printf(%d, a);
disp( );

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

in this example variable i void inc ( )


printf(%d, b); //Error is used frequently so i is { static int i;
stored in register using
}
i++;
register storage class
Last statement generate
printf(\n%d, i);
error because scope of b
}
is limited within the
Output: 1 2 3
block in which it is
declared
Because
value
of
variable i persist between
different function calls

}
void disp( )
{ a=a+5;
printf(%d, a);
}
Output: 5 10
Scope of variable a is
global so it can be shared
by main and disp
function.

Important Questions
Q1:

Explain Primary data types in detail?

Q2:

Explain Constants and Variables?

Q3:

Explain all the operators used in C with example?

Q4:

What do you mean by Complexity?

Q5:

Explain the difference between Call by Value and Cal by Reference with

example?
Q6:

What do you mean by Recursion? Explain with example.

Q7:

What is the difference between Structure & Union?

Q8:

What is the difference between While & Do While Loop?

Q9:

Write a Program to do the addition of two matrices?

Q10: Explain all the storage classes with example?


Q11: What are the advantages and disadvantages of Pointers?
Q12: What do you mean by Function? Explain the different types of functions?

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


38

Affiliated With

IIMT

Punjab Technical University

Ideal Institute of Management &Technology

Er. Rajwinder Sharma


+9193168-11444

Q13: What are the differences between break and continue statement?
Q14: Explain Logical Expressions?
Q15: What is Function Prototyping?
Q16: What do you mean by C Directives?
Q17: What is Array Bound Checking?
Q18: What do you mean by Local & Global Variable?
Q19: What are the modes in which file can be opened?
Q20: What are the features of C Language?

VPO Manuke Gill, Distt Moga, Barnala-Baghapurana Road


39

Das könnte Ihnen auch gefallen