C
Basic
What is language?
- A language is medium in which two or more object/person communicate their thought, information, data etc. C is computer language. Computer languages are generally two types:
1. High Level Language-Translator required must example: FORTRAN
2. Low Level Language-Not requirement translator example: machine
language(0 , 1)
- C is a high level language with low level programming features so it is also called middle level language i.e. we can write program either in machine language (0 , 1) or general English keyword (HLL).
- C is a structured programming language, that is developed by Dennis Ritchie in 1972 at AT & Bell Laboratories in USA.
- Some basic tips for C Programs and C language:
1. Each instruction in a C program is written as a
separate statement. Therefore, a complete C program would comprise a series of statements.
2. The statement in a program must appear in the same order in which we wish them to be
executed, unless the result will be differ as we want wish.
3. All statement are entered in Small case letters.
4. Every C statement
must be end with a semicolon (;). This is act that statement has been
terminated
5. C is "free
form language" i.e. there are no specific rule for where the
statement write.
- There are some other language like as C++, C# and Java, its languages are more advanced then c, then
Why we learn C today?
- There are some reason behind this question that's are following:
1. C is the basic (mother) of all other languages.When you had learned c,
you are easily deal with classes, object, template, structure, polymorphic and
with familiar terminology.
2. C++, C# and Java are OOP Object Oriented Programming) languages. So when u creating
object u must still a good command on C language.
3. Major parts of OS (Operating System) like as
Windows, UNIX, and Linux are still written in C.
4. C language is known for owns speed and execution.
5. Today daily routine apparatus like as microwave,
washing, digital camera's, microprocessor, and operating system, smart phones
are worked in C programs.
6. Maximum 3-d games are built
in C.
So now let's start to
learn C.
Constant
Constant
1.
Constant is an entity that does not
change during program execution. Example when we write number=10 than 10 is
constant in all program and never change value.
2.
There are mainly two types
constants:
1.
Primary constants
§ Integer constant
§ Real Constant
§ character Constant
2.
Secondary Constants
§ Array
§ Structure
§ Pointer
§ Union
Rules for construction Integer
Constant
- At least one digit must have an integer constant
- It can be positive or negative. The general range of integer constant is -32768 to +32767. (NOTE : Normally range depend on compiler.)
- No commas or blank spaces are allowed within integer constant.
- Integer constant must not having decimal point.
- Example of integer constant are as 364,-66,+786,-1
Rules for constructing Floating
point or Real constant
- At least one digit must have an real constant.
- Real constant must have decimal point.
- It may be positive or negative.
- No commas or blank spaces are allowed within real constant.
- Example of real point constant : +23.0, 786.786, -0.786, 0.0
Rules for constructing
Character constant
- Any single entity(like as single alphabet, single digit or single symbol) are enclosed within single inverted commas, are called character constant.
- Example of Character constant : 'a', 'A', '*', '4' etc..
Variable
Variable
1.
Variable is an entity that change
during program execution. Example when we write r = 45 i.e. x can hold
different value at different times so r is a variable.
2.
A variable may be integer, character,
float, double etc..
Rules for constructing Variable Names:
- A variable name must be start with alphabet or underscore.
- A variable name is any combination of 1 to 31 alphabets, digits or underscores.
- No commas, special symbol(rather than underscore [ _ ] ) or blanks are allowed within a variable name
- Example of valid variable names : ram, _ram, d_x, _voids, echo_,
Keywords in C
C keywords
- Keywords are standard word whose meaning has already been explained to the compiler.
- Keywords are also called "reserved words".
- There are 32 keywords available in C.
int
|
char
|
long
|
double
|
float
|
break
|
continue
|
goto
|
void
|
switch
|
case
|
default
|
short
|
signed
|
unsigned
|
if
|
else
|
for
|
while
|
auto
|
register
|
static
|
extern
|
do
|
const
|
enum
|
return
|
sizeof
|
struct
|
typedef
|
union
|
volatile
|
Data
type in C
Data Type in C Language
There are mainly three
data type in C as following:
1.
Basic Data
Type
o
int
o
char
o
float
o
long
o
double
o
long double
2.
Derived
Data Type
o
Array
o
Pointer
o
function
3.
User
Define Data Type
o
structure
o
union
o
enumerated
o
typedef
Following table tell which data type how much allocate
memory?
Data
Type
|
Memory
Allocation
|
int
|
2 byte
|
long
|
4 byte
|
float
|
4 byte
|
double
|
8 byte
|
long double
|
10 byte
|
char
|
1 byte
|
In data types we also learn about link list, file handling and more. So now we are entering in real c world i.e. C programming.
Compilation
and execution of programs
Compilation and execution
- There are many steps involved in converting a C program into an executable form, these all steps are called "build process".
- Build process are representing in the following graphically diagram :
C Source code Programs (assume file name first.c)
Expanded
source code (first.i)
Assembly
code (first.asm)
Relocatable
Object code + Object code of library function
Executable code (first.exe)
Figure: Build process
If you don't understand the build
process, don't worry, read following explanations of build process i.e. how a
source program make executable program. It is all internal process of machine, that's
done in neon seconds.
Let’s now understand the steps mentioned in above figure in detail.
1.
Editor-Type your program in editor (source code).
2.
Preprocessing-During this step, the C source code is expanded based on
the preprocessor directives like as #include, #ifdef, #define
etc. The expanded source code is stored in an intermediate file with .i
extension.
3.
Compilation- The expanded source code is then passed to the compiler, which
identifies the syntax error in the expanded source code. If the expanded source
code is error free, then the compiler transfer the expanded source code in C,
into an equivalent assembly language program. The assembly code is typically
stored in .ASM file. So our first.c file would be changed and stored in
first.ASM.
4.
Assembling
- Assembler translate the .ASM
program into Relocatable Object code. Thus assembler translate our first.asm
file into first.OBJ. .OBJ file is one of the binary file. This object file
contained header and several section.
5.
Linking - Linking is the final step of build process i.e. creating an
executable program. It's do following works :
o
Find definition of all external
function
o
Find definition of all global
variables
o
Combine Data Section
o
Combine Code Section
6.
Loading - Once the .EXE file is created and stored on the disk, it
is ready for execution. When we execute it, it is first brought from the disk
into the memory (RAM) by an OS component called Program Loader.
Algorithms
and Flowchart
Algorithms
1.
A sequential solution of any program
that written in human language, called algorithm.
2.
Algorithm is first step of the
solution process, after the analysis of problem, programmer write the algorithm
of that problem.
3.
Example of Algorithms:
Q. Write an algorithm to
find out number is odd or even?
Ans.
Step 1: start
Step 2: input number
Step 3: rem=number mod 2
Step 4: if rem=0 then
print "number even"
else
print "number odd"
endif
Step 5: stop
Flowchart
1. Graphical representation of any program is called flowchart.
2. There are some standard graphics that are used in flowchart as following:
Q. Make a flowchart to
input temperature, if temperature is less than 32 then print "below
freezing" otherwise print "above freezing"?
Ans.
Figure: Flowchart example of C program
|
Sample
C Program
/*Program to add three
numbers and calculate them average*/
#include<stdio.h>
#include<conio.h>
void
main()
{
//first we declare of variable
//first we declare of variable
int n1=10, n2=20, n3=30;
int
sum, avg;
clrscr();
sum=n1+n2+n3;
avg=sum/3;
printf("\nSum Of Threes numbers is %d",sum);
printf("\nAverage of n1,n2,n3=%d",avg);
}
Output of the above program :
Sum of Threes numbers is 60
Average of n1, n2, n3=20
Let's discuss some
useful tips of above program:
- In C language there are two types of comments written as :
1.
Single line
comment:single line comment give by two
forward slash (//).Example : // this is single
line comment
2.
Multi line
comment: Multi line comment give by this
form : /* it is a multi line comment and its can
be spilt into several lines.*/
- Comments can't be nested.
- main() is a function and gives to a set of statement. If a function is void then it is nothing return otherwise its always return value.
- Any variable used in the program must be declared before using it.
- printf() function: It is used to print the value at console. The syntax of printf() as following: printf("<format string>",<variable name>);
format string can be following
type:
|
%d=printing integer values
|
%f=printing real values
|
%c=printing character values
|
- "\n" is one of the several escape sequence in C.It is force to cursour go to next line.
What
is Data Type in C?
In
the C Programming Language, Data Types refers to an extensive system for
declaring variable of different types.
A data types tells the following things about the related variable:
A data types tells the following things about the related variable:
- What is the size of the variable?
- How much its occupies space in storage?
- How the variable bit mapped for its operation?
All data types used in C
programming, generally defined in standard library header files. In header
files, all the characteristic such as size, space etc. of data-types
has been defined.
If you want, you can create your own
custom data types in C.
There are mostly following Data Types in C as:
There are mostly following Data Types in C as:
1.
char Data Type
2.
int Data Type
3.
long Data Type
4.
double Data Type
5.
float Data Type
6.
Long
Double Data Type
7.
function Data Type
8.
pointer Data Type
9.
array Data Type
10.
enum Data Type
11.
struct Data Type
12.
typedef Data Type
16 bit V/S 32 bit compiler meaning in C
Characters
data type - signed char V/S unsigned char
Integers data types
- signed int V/S unsigned int
- short int V/S long int
float VS double data type
long double data type
Comparison of all
data types
C
Operators
What is operators?
In simple word operators are those
which operator anything like as data, maths, information etc i.e.. When we
talking about C operators, i want to say you that C
is very rich in operators. Operators tells to compiler that what do with
data. There are mainly operators in c as following:
1.
Logical Operators
2.
Bitwise Operators
3.
Relational Operators
4.
Assignment Operators
5.
Sizeof Operators
6.
Increment and Decrement operators
7.
Comma operators
8.
Type cast operator
9.
Conditional operators or ternary
operators
Sometime operators are divided
according numbers of operands. So there are three types of operators as
following :
Operators
|
|||
Unary
|
Binary
|
Ternary
|
|
operand
|
Single
|
double
|
third
|
works
|
right to left
|
left to right
|
left to right
|
Example_1
|
++ , --
|
+, -, *, /
|
? :
|
Example_2
|
! , ~
|
&& , ||
|
All of these above operators we
discuss step by step in next chapters.
Logical Operator
When we use if, for, while then use one condition at
once time what happen if we examine condition more than one? In this case we
use logical operators. So logical operators are used to combine two or more
condition.
There are three types of logical operators as following:
There are three types of logical operators as following:
Operator
symbol
|
Name
|
&&
|
Logical AND
|
||
|
Logical OR
|
!
|
Logical NOT
|
LOGICAL AND OPERATOR ( &&)
The condition is true if and only if both two
expression are true otherwise condition false. The truth table of logical AND
operators end of this chapter.
LOGICAL OR OPERATOR ( || )
The condition is true if one of expression is
true and condition will be false only if both expression are false. See example
of || operator at end of this chapter.
LOGICAL NOT OPERATOR ( ! )
It reverse the expression i.e if the expression
evaluates to a non-zero value, then applying! operator to it results
into a 0 and vice versa. The final result (after applying!) 0 or 1 is
considered to be false or true respectively.
Example of above three operators:
//following table con =
condition.
con 1
|
Con
2
|
con
1 && con 2
|
con
1 || con 2
|
! con 1
|
! con 2
|
False
|
False
|
False
|
False
|
True
|
True
|
False
|
True
|
False
|
True
|
True
|
False
|
True
|
False
|
False
|
True
|
False
|
True
|
True
|
True
|
True
|
True
|
False
|
False
|
Some numerical example :
if(10>5 && 1000<2001) // True
while( ; num>=1 || num<=100 ; ) // if num=1 True
Now some discuss of NOT operator when we write
condition if( 1 ! = 0 ) what is mean it? It
is mean "one is not equal to zero",
so is condition TRUE or False? It is true.
Let's understand following example :
if(sex!='M')
printf("Person is Female");
else
printf("Person is Male");
In above example evaluate first printf if condition
is false otherwise evaluate second printf.
!(x<22)
it is also we write (x>=22) // both are equal.
Bitwise operators
The smallest element in memory on which are able to
operate is called byte; and the programming language are byte oriented. One of
the c powerful features is a set of bit manipulation operators. There are
various bitwise operators in C as following table; we learn all step by step :
Operators
|
Name
|
&
|
Bitwise
AND
|
|
|
Bitwise
OR
|
^
|
Bitwise
XOR(exclusive OR)
|
>>
|
Left
shift
|
<<
|
right
shift
|
~
|
One's
complement
|
These operators can operate upon ints and chars but not on floats and doubles. Bits are numbered from zero onwards, increasing from right to left as following figure:
7
|
6
|
5
|
4
|
3
|
2
|
1
|
0
|
8
bit Character
|
16
|
15
|
14
|
13
|
12
|
11
|
10
|
9
|
8
|
7
|
6
|
5
|
4
|
3
|
2
|
1
|
0
|
16
bit Integer
|
Bitwise AND Operator (&)
The & operator
operates on a pair of bits to yield a resultant bit. The rules that decide the
value of the resultant bit also called truth table are shown below:
Bit
x
|
Bit
y
|
x
& y
|
0
|
0
|
0
|
0
|
1
|
0
|
1
|
0
|
0
|
1
|
1
|
1
|
The best use of the AND operator is to check whether a particular bit of an operand is ON or OFF. The meaning of ON means 1 and OFF means 0. The following program puts this logic clear:
/*Example of bitwise
AND operator*/
#include<stdio.h>
#include<conio.h>
Void
main ()
{
int x=45;
int y=37;
int z;
clrscr();
z = x & y;
printf("\nValue of z=%d",z);
}
Output of above
program:
Value of z=37
In above program compiler first calculate the binary
x and y which is 111101 and 100101 respectly. After this its work on bitwise
operator and final result is 37 which binary code are 100101. The following
table shown the result :
Values
|
binary
code
|
x
= 45
|
111101
|
y
= 37
|
100101
|
z
= x & y
|
100101
|
Bitwise
OR ( | )
Truth table for bitwise OR are as following:
x
|
Y
|
z
= x | y
|
0
|
0
|
0
|
0
|
1
|
1
|
1
|
0
|
1
|
1
|
1
|
1
|
Bitwise XOR ( ^ )
It is also called exclusive OR. If there are similar
bit then its return 0 otherwise its return 1. Let watch truth table of
x^y :
x
|
Y
|
z
= x ^ y
|
0
|
0
|
0
|
0
|
1
|
1
|
1
|
0
|
1
|
1
|
1
|
0
|
Example of exclusive OR :
x = 75
y = 64
z = x ^ y
x = 1 0 0 1 0 1 1
y = 1 0 0 0 0 0 0
z = 0 0 0 1 0 1 1
hence, the value of z=11
Bitwise right shift ( >> )
Right shift operator shifts each bit in its left
operand to the right. The number of places the bits are shifted depends on the
number following the operator i.e. its right operand.
In simple meaning of bitwise right shift as:
Insertion (zero) > deletation
Example of right shift operator:
x = 15
y = x >> 2
[x=15 before right shifting
] 0000 0000
0000 1111
[y = x >> 2 during right shifting] 000000 0000 0000 1111
[y = x >> 2 after right
shifting] 0000 0000 0000 0011
so now value of y=3.
Left Shift operator ( << )
This is similar to the right shift operator, the
only difference being that the bits are shifted to the left, and for each
shifted, a 0 is added to the right of the number. Following structure shows it:
deletation >
insertion (zero)
Example of right shift operator:
x = 15
y = x << 2
[x=15 before right shifting
] 0000
0000 0000 1111
[y = x << 2 during right
shifting] 0000
0000 0000 111100
[y = x << 2 after right
shifting] 0000 0000
0011 1100
so now value of y=60.
One's complement ( ~ ) or Tilde
It is reverse the bit i.e. if bit is 0 then its
return 1 and when bit is 1 it is return 0.
example of tilde:
x = 15
y = ~ x
(15)10 = 0000 0000 0000 1111
y = ~ x 1111 1111 1111 0000
hense, 65535 - 15 = 65520.
so the value of y is 65520.
Arithmetic Operator
Arithmetic operators are special mathematical symbol
which do all arithmetical calculation of the programs. Following table display
the operators and their works:
Name
of operators
|
Symbol
|
works
|
example
|
Addition operator
|
+
|
Add the numbers
|
sum=7+8+1=16
|
Subtract operator
|
-
|
Subtraction of numbers
|
sub=100-50=50
|
Multiply operator
|
*
|
Multiple of numbers
|
muti=8*9=72
|
Modulus operator
|
%
|
Find the reminder of numbers
|
mod=45%40=5
|
Division operator
|
/
|
Find the division of numbers
|
div=45/40=1
|
Relational Operator
When we write program, many time we requirement to
comparison of two or more data, in that case we uses relational operators.
There are following relational operators as following :
Operators
Name
> Greater than
< Less than
= Equals to
>= Greater than equals to
<= Less than equals to
<= Less than equals to
!= Not equals to
The syntax of relational expression as :
<data value 1>Relational
operator<data value 2>
Example :
10 >= 5
-50 <= 1
0 != 0
Sizeof operator
Sizeof operator calculate the size of data i.e. how
many bit a specific data having.
Syntax of sizeof operator:
Printf ("<format string>",sizeof<(data
type variable)>);
/*Program to
sizeof operator*/
#include<stdio.h>
#include<conio.h>
void
main()
{
int x=10;
clrscr();
printf("\nSize of x is %d",sizeof(x));
getch();
}
Output of above program:
Size of x is 2
Increment
and Decrement operators
Increment operators (++)
- Increment operators are increase the value of subsequent. value may be increase according to the programmer.
- Increment operator are two types as follows :
1.
Post increment
2.
Pre increment
Decrement operators ( -- )
- decrement operators decrease the value to one, two and so on.
- As like Increment operators, decrement operators are also two type as :
1.
Post decrement
2.
Pre decrement
Before we more discuss about
increment and decrement operator, let understand some expression; that's are
using in all operators.
Now some issues of pre and post increment and decrement, we will discuss after solve following programming :
Now some issues of pre and post increment and decrement, we will discuss after solve following programming :
x = 5 x = 5 x = 5
x = x+1 ++x x++
x = 6 x = 6 x=5
In above program u notice that value of x increase to one in
all three expression but after the increasing one, the final value of x in not
same, third box result is differ to another two boxes. Now you know that c
operators are mostly three types, ++ and -- operators are Unary operators.
Post increment or decrement are lowest precedence so it is solve at the
Post increment or decrement are lowest precedence so it is solve at the
End of program. Hence above program in third box first value
of x is print i.e. 5 after, it is increase.
Unary operators are solve right to left.
Unary operators are solve right to left.
Q.1 Solve the expression in C language compiler
,assuming x,z are integer variables:
z = x++ + x++
where x=7
Ans.
stepwise evaluation of this expression
is shown below :
z =
x++ + x++ +
++x
//post
increment of x=2
z = x + x + ++x
//++x
increase the value of x one so x=8
/*Now all pre
and post increment/decrement are solved so we write the the expression in
normal mathematical expression*/
z = x + x + x
//put
the current value of x i.e. 8
z = 8 + 8 + 8
z
= 24
syntax : x=current value-post
increment/decrement
so x = 8 + 2
x = 10
Q.2 Solve the following expression :
z = ++x + y-- - ++y - x--
- x-- - ++y - x--
where x = 7
y = -3
Ans.
z=++x + y-- -
++y - x-- - x-- - ++y - x—
/*
post decrement of x=3 and
post decrement of y=1 */
z= ++x + y - ++y - x - x - ++y - x
/* its unary
operator so we solve it from
right to left*/
z=++x + y - ++y - x - x - y - x
//now
y=-3+1=-2
z=++x + y - y - x - x - y - x
//now
y=-2+1=-1
z=x + y - y - x - x - y - x
//now
x=7+1=8
/*now all
increment and decrement operators
all solved so we
put the current value of x
and y.*/
z= 8 + (-1) - (-1) -8 - 8 - (-1) - 8
z= 8 - 1 + 1 - 8 - 8 + 1 - 8
z= - 16 + 1
z=
-15
x=8-3=5
y=-1-1=-2
Related some increment or decrement operators exercise:
Q.3 solve the following equations:
z = x++ + ++y - x-- + --y
where x = 7 and
y = 9
hint:(For your cross-checking, answer is x=7, y=9 and z=18).
Q.4 solve the following equations:
z = x++ * y++ / ++x -
--y % x++
where x = 5 and
y = 2
hint:(For your cross-checking, answer is x=8, y=2 and z=0).
--------------------------------------------------------------------------------
Q.3 answer with explanation :
z = x++ + ++y - x-- + --y
where x = 7 and
y = 9
Ans:
post decrement of x = 1
post increment of x = 1
z = x + ++y - x + --y
z = x + ++y - x + y // now y = 9-1 = 8
z = x + y - x + y // now y = 8+1 = 9
// now put the value of x and y
z = 7 + 9 - 7 + 9
z = 9 + 9
z = 18
Hence, our final answer will be:
x = 7 - 1 + 1 = 7
y = 9
z = 18
where x = 5 and
y = 2
hint:(For your cross-checking, answer is x=8, y=2 and z=0).
--------------------------------------------------------------------------------
Q.3 answer with explanation :
z = x++ + ++y - x-- + --y
where x = 7 and
y = 9
Ans:
post decrement of x = 1
post increment of x = 1
z = x + ++y - x + --y
z = x + ++y - x + y // now y = 9-1 = 8
z = x + y - x + y // now y = 8+1 = 9
// now put the value of x and y
z = 7 + 9 - 7 + 9
z = 9 + 9
z = 18
Hence, our final answer will be:
x = 7 - 1 + 1 = 7
y = 9
z = 18
Comma
operator
Comma operator ( , )
- Evaluate of comma operator- Left to right.
- Uses of comma operator as following :
1.
Multiples declaration
2.
Multiples initialization
3.
Multiples variation
4.
Multiples statement
- Example of comma operator
1.
int x=0,y=1,z=2;
2.
for(x=0 ,
y=1, z=2 ; condition1 , condition2 ;increment/decrement)
Type-cast
operator
The type cast operator is very important
in C. Cast operator uses in convert one data type to another data types. Type
casting may be two types:
1.
Implicit type cast
2.
Explicit type cast
Implicit
type cast
In C, implicit type cast are
automatically handled by compiler i.e. when two or more data types are getting
execution then the final data-type will be that data type as it is declared,
i.e it is not depend on conversion of data type.
It is clear understand by example
as:
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j;
float
f;
double d;
i=d*f+f*j;
}
what you think, what will be data type of i?
it is double!! No, right answer is int. You see in program that double
has high priority or precedence of float
and int, so result of data type will be comes
in double but when result is assign in i, it
will be convert in int because i is declared as
int. It is implicit type casting.
Explicit
type cast
An explicit type cast is a cast that
we should specify invoke with either the cast. The compiler does not
automatically invoke to resolve the data type conversion.
Let's understand explicit with
example:
/*A student marks of
three subject as m1,m2,m3 and calculate percentage(per)*/
#include<stdio.h>
#include<conio.h>
void main()
{
int m1=70,m2=70,m3=100,total;
float
per;
total=m1+m2+m3;
per=total/300*100;
printf("%f",per);
}
output:- 0.000000
Surprise, let's explain to me, it is a common type cast mistake, look at per=total/300*100; statement. In this statement first of all total/300 will be solve so total(240) and 300 are int hence 240/300 will be produce a float value so result is 0.000000. These mistake may me solved by three ways as:
1. We mention type cast in above program as:
/*demonstration of type casting*/
#include<stdio.h>
#include<conio.h>
void main()
{
int m1=70,m2=70,m3=100,total;
float
per;
total=m1+m2+m3;
per=(float)total/300*100;
printf("%f",per);
}
output:- 80.000000
2. We used total as float variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int m1=70,m2=70,m3=100;
float per,total;
total=m1+m2+m3;
per=total/300*100;
printf("%f",per);
}
output:- 80.000000
3. we convert int to float to the
300 by adding decimal portion.
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int m1=70,m2=70,m3=100,total;
float per;
total=m1+m2+m3;
per=total/300.0*100;
printf("%f",per);
}
output:- 80.000000
Ternary
operator
Main features of ternary operators as follows :
- There are three operand.
- It works from left to right
- Example of ternary operator is conditional operator. Symbol of conditional operator : condition ? True_parts : False_parts
Intro if-else
In C language there are three major decision making instruction as
if statement, the if-else statement, and the switch
statement. And one also minor decision making instruction is conditional
operator.
The
keyword if tells the compiler that what follows is a decision control
instruction. The condition following the keyword if is always enclosed within a
pair of parentheses. If the condition, whatever it is, is true, then the
statement is executed, and If the condition is not true, then statement is not
executed.
Let's
demonstrates the use of if-else with c program:
/*demonstrates of if-else statement*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n=10;
if(n>=15)
printf("n is greater!!");
else
printf("n is less than!!");
getch();
}
Output :
n is less than!!
On execution of this program, when compiler check condition 10>=15, the condition is false so its execute else part statement i.e. n is less than!!.
Now try to write below program for more familiar with if-else:
/*demonstrates of if-else statement*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n=10;
if(n>=15)
printf("n is greater!!");
else
printf("n is less than!!");
getch();
}
Output :
n is less than!!
On execution of this program, when compiler check condition 10>=15, the condition is false so its execute else part statement i.e. n is less than!!.
Now try to write below program for more familiar with if-else:
Q. Write a C program to read quantity and price
for each item. Calculate the total expenses, and if the quantity is more than
1000 than giving discount is 20%.
Ans.
/*Calculate the total
expenses*/
#include<stdio.h>
#include<conio.h>
void main()
{
int quant,dis=0;
float
tot,rate;
clrscr();
clrscr();
printf("Enter quantity : ");
scanf("%d",&quant);
printf ("\nEnter rate: ");
scanf("%f",&rate);
if(quant>1000)
dis=20;
tot=(quant*rate)-(quent*rate*dis/100);
Printf("\nTotal expenses = %f", tot);
getch();
}
Output :
Enter quantity :750
Enter rate : 35.54
Total expenses = 25905.000000
Enter quantity: 1450
Enter rate :
9.50
Total expenses = 12397.500000
Forms of if-else
There are many way to write if-else statement in
program, it can be single if statement, both if-else statement, If-else if
statement and etc. There are no limit on how deeply the if's and the else's can
be nested. Now let's start to form of if-else:
1. if (condition)
do this;
2. if (condition) {
do
this;
and this;
}
3. if(condition)
do this;
else
do this;
4. if(condition)
{
do this;
and this;
}
else
do this;
5. if(condition)
{
do this;
and this;
}
else
{
do this;
and this;
}
6. if(condition)
do this;
else
{
if(condition)
do this;
else
{
do this;
and this;
}
}
7. if(condition)
{
if(condition)
do this;
else
{
do this;
and this;
}
}
else
do this;
8. if(condition)
do this;
else if(condition)
do this;
else if(condition)
do this;
else
do this;
And now you thinking, what the hell condition? Don't worry, it’s quite simple and easy to use in programming. In condition part we put data, numeric values with with appropriate operator like as Logical operator, Arithmetic operator etc.
else
{
do this;
and this;
}
}
7. if(condition)
{
if(condition)
do this;
else
{
do this;
and this;
}
}
else
do this;
8. if(condition)
do this;
else if(condition)
do this;
else if(condition)
do this;
else
do this;
And now you thinking, what the hell condition? Don't worry, it’s quite simple and easy to use in programming. In condition part we put data, numeric values with with appropriate operator like as Logical operator, Arithmetic operator etc.
More if-else
Notice the following if
statement :
if(expression)
statement;
Here the expression can any valid expression
including a relational expression. We can even use arithmetic expression in the
if statement. For example all the following if statement are valid :
if(10 + 5 % 7)
statement;
if(n=20)
statement;
if(-15)
statement;
if(-2.0)
statement;
In C every expression is evaluated in terms of zero
and non-zero values.
Note: that in C a non-zero value is considered to be true, whereas a 0 is considered to be false.
Note: that in C a non-zero value is considered to be true, whereas a 0 is considered to be false.
The default scope of the if
statement is only the next statement. So, to execute more than one statement
they must be written in a pair of braces
If
else statement and flowchart
Decision
Control Statements and Flowchart
The if Statement
It is used to execute an instruction or sequence/block of instruction only if a condition is fulfilled.
Difference forms of implements if-statement are:
- Simple if statement
- if-else statement
- Nested if-else statement
- else if statement
Nested if-else statement
In nested if...else
statement, an entire if...else construct is written within either the
body of the if statement or the body of an else statement.
The syntax is as follows:
if(condition_1)
{
if(condition_2)
{
block statement_1;
}
else
{
block statement_2;
}
}
else
{
block statement_3;
}
block statement_4;
Else if statement
It is used in multi-way decision on
several conditions. This works by cascading comparisons. As soon as one of the
conditions is true, the statement or block of statements following them is
executed and no further comparison are performed.
The else...if syntax is as
follows:
if(condition_1)
block statement_1;
else if(condition_2)
block statement_2;
else if(condition_n)
block statement_n;
else
default statement;
The program that we have developed
so far used either a sequential or a decision control instruction.
The versatility of the computer lies
in its ability to perform a set of instructions repeatedly. This involves
repeating some portion of the program either a specified number of times or
until a particular condition is being satisfied. This repetitive operation is
done through a loop control instruction.
Loops can be created to executed a block of code for a fixed number of times. Alternatively, loops can be created to repetitively execute a block of code until a Boolean condition changes state.
For instance, the loop may continue until a condition changes from false to true, or from true to false. In this case, the block o code being executed must update the condition being tested in order for the loop to terminate at some point. If the test condition is not modified somehow within the loop, the loop will never terminate. This created a programming bug known as an infinite loop.
There are three method by way to
which we can repeat a part of a program. They are:
1.
Using a for statement
2.
using a while statement
3.
Using a do-while statement
for Loop
At this point you think, there is already while
loop function then what we need one more loop function? The answer is that for
is easy to use and allows us to specify three things in single line, these
three things are:
1.
Setting
a loop counter to an initial value
2.
Testing
the loop counter to determine whether its value has reached the number of
repetitions desired.
3.
Increasing
or Decreasing the value of loop counter.
The general form of for statement is as under:
for
(initialize
counter; test counter; increment/decrement
counter)
{
do this;
and this;
and this;
and that;
}
It is important to note that the initialization
,testing and incrementation part of a for loop can be
replaced by any valid expression, thus the following for loops are valid:
for(i=5; i; i--)
printf("%d",i);
for(i<=5; j=10; j=0)
printf("%d",i);
for(i=1; i<=10; printf("%d",i++))
;
for(scanf("%d",&i); i<=5; i++)
printf("%d",i);
Demonstration
of for loop
/*demonstration for loop program*/
/*program
to print cprogrammingcodes in five times*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
for(i=1;
i<=5; i++)
{
printf("cprogrammingcodes");
printf("\n");
}
getch();
}
Output of above program:
cprogrammingcodes
cprogrammingcodes
cprogrammingcodes
cprogrammingcodes
cprogrammingcodes
Versions
of for loops
Now we learn how many different types for uses
to print one to ten numbers.
(a) #include<stdio.h>
#include<conio.h>
void
main()
{
int i;
clrscr();
for(i=1;
i<=10; i++)
printf("%d\n",i);
}
(b) #include<stdio.h>
#include<conio.h>
void
main()
{
int
i;
clrscr();
for(i=1; i<=10;)
printf("%d\n",i);
i++;
}
(c) #include<stdio.h>
#include<conio.h>
void
main()
{
int
i;
clrscr();
i=1;
for(; i<=10; i++)
printf("%d\n",i);
}
(d) #include<stdio.h>
#include<conio.h>
void
main()
{
int
i;
clrscr();
i=1;
for(; i<=10 ;)
printf("%d\n",i);
i++;
}
(e) #include<stdio.h>
#include<conio.h>
void
main()
{
int
i;
clrscr();
for(i=1; i++<=10;)
printf("%d\n",i);
}
(f) #include<stdio.h>
#include<conio.h>
void
main()
{
int
i;
clrscr();
for(i=0; ++i<=10;)
printf("%d\n",i);
}
(g) #include<stdio.h>
#include<conio.h>
void
main()
{
int
i;
clrscr();
i=1
for(; i++<=10;)
printf("%d\n",i);
}
Multiple
Initializations and increment/decrement in the for loop
The initialization expression of the for loop can contain more than one statement by a comma. For example:
for(i=0, j=10; i<=j ; i++,j--)
Thus we see, that
multiple statement can uses to initialization and increment (or decrement). But
notice there must be only one statement allowed in the test expression. This
expression may contain several condition linked using logical
operators as:
for(i=0, j=10;
i<=j || i==j ;
i++,j--)
Nesting of for Loops
The way if statement can be nested, similarly whiles and fors can also be nested. Let's understand the nesting of for loops through program:
/*demonstration of nested for loop*/
#include<stdio.h>
#include<conio.h>
void main()
{
int r,c,s;
clrscr();
for(r=1;
r<=2; r++)/*outer loop*/
{
for(c=1; c<=2; c++) /*inner loop*/
{
s=r+c;
printf("r=%d c=%d sum=%d\n",r,c,s);
}
}
getch();
}
for(c=1; c<=2; c++) /*inner loop*/
{
s=r+c;
printf("r=%d c=%d sum=%d\n",r,c,s);
}
}
getch();
}
output of above program
r=1 c=1 sum=2
r=1 c=2 sum=3
r=2 c=1 sum=3
r=2 c=2 sum=4
Thus we see in above program that, the body of outer loop is indented, and the body of the inner for loop is further indented. These multiple indentations make the program easier to understand.
while
loop
It is often the case in programming
that we want to do something a fixed number of times. Perhaps we want to
calculate gross salaries, or convert temperatures form centigrade to Fahrenheit
for 20 different cities. The while loop is ideally suited f or such
cases.
Syntax of using while loop:
initialise loop counter
while(valid condition)
{
statement1;
statement2;
statement3;
statement4;
increment or decrement loop
counter;
}
some basic rule of while loop:
- The statements within the while loop would keep in getting executed till the condition being tested remains true. When the condition becomes false, the control passes to the first statement that follows the body of the while loop.
- The condition being tested may use relational or
logical operators as shown in the following examples:
while(x<=20)
while(x>=20 && x<=50)
while(x>=10 || (i>=10 && i<=20)||y==15) - Almost always, the while must test a condition that will eventually become false, otherwise the loop would be executed forever, indefinitely.
- It is not necessary that a loop counter must only be an int. It can even be a float.
- Example of while loop:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
while(i<=5)
{
printf("%d\n",i);
i=i+1; //i++;
}
getch();
}
Output of above program:
1
2
3
4
5
Nested
while loop
One or more loop which require execute again and again then these loop and loops place in separate block is known as nested loop.
Example of nested while loop:
/*demonstration of
nested while loop*/
#include<stdio.h>
#include<conio.h>
void main()
{
int r,c,s;
clrscr();
r=1;
clrscr();
r=1;
while(r<=5)
/*outer loop*/
{
c=1;
while(c<=2) /*inner loop*/
{
s=r+c;
printf("r=%d c=%d sum=%d\n",r,c,s);
c++;
}
printf("\n");
r++;
}
getch();
}
c=1;
while(c<=2) /*inner loop*/
{
s=r+c;
printf("r=%d c=%d sum=%d\n",r,c,s);
c++;
}
printf("\n");
r++;
}
getch();
}
Output of above program:
r=1 c=1 sum=2
r=1 c=2 sum=3
r=2 c=1 sum=3
r=2 c=2 sum=4
r=3 c=1 sum=4
r=3 c=2 sum=5
r=4 c=1 sum=5
r=4 c=2 sum=6
r=5 c=1 sum=6
r=5 c=2 sum=7
do-while loop
Now we know about for, while loop that
executed the statement within them finite number of times. However, in real
life programming, one comes across a situation when it is not known beforehand
how many times the statement in the loop are to be executed. In this situation
we used do-while loop.
do-while
tests the condition after having executed the statement within the loop i.e. do-while
would executed its statement at least once, even if the condition fails for the
first time. For example notice in following program:
/*demonstration
of do-while*/
#include<stdio.h>
#include<conio.h>
void
main()
{
clrscr();
do
{
printf("Its work!!");
}while(10<1);
getch();
}
Output of above
program:
Its work!!
In above program, the printf() would be
executed once, since first the body of loop is executed and then the condition
tested, 10<1 condition false so loop terminate and go to next statement.
/*program
to find factorial value of any number, and it is execute unknown number of
times when user enter no, then program should be terminate.*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n,f=1;
char choice;
clrscr();
do
{
printf("Enter number : ");
scanf("%d",&n);
while(n>=1)
{
f=f*n;
n--;
}
printf("Factroial value of %d is %d",n,f);
printf("\nCalculate another value y/n :");
scanf("%c",&choice);
}while(choice=='y');
}
output
of above program:
Enter number :5
Factorial value of 5 is
120
Calculate another value
y/n :y
Enter number :4
Factorial value of 4
is24
Calculate another value
y/n :n
In above program, the do-while loop would
keep getting executed till the user continues to answer y. When user enter
answer n,the loop terminate, since the condition fails.
Odd Loop
What is odd loop?
In real life programming, there are many times comes a situation when we don't know how many times the statements in the loop are to be executed.
There is comes concept of odd loop.
Execution of loop an unknown number of times can be done by - while, for and do...while loops.
/*A demonstration of odd loop using do...while*/
#include<stdio.h>
int main()
{
int n;
char answer;
do
{
printf("Enter any number : ");
scanf("%d", &n);
printf("Square of %d is %d",n,n*n);
fflush(stdin);
printf("\nWant to calculate more square y/n: ");
scanf("%c", &answer);
}while(answer=='y');
return 0;
}
The output of above program would be:
In real life programming, there are many times comes a situation when we don't know how many times the statements in the loop are to be executed.
There is comes concept of odd loop.
Execution of loop an unknown number of times can be done by - while, for and do...while loops.
/*A demonstration of odd loop using do...while*/
#include<stdio.h>
int main()
{
int n;
char answer;
do
{
printf("Enter any number : ");
scanf("%d", &n);
printf("Square of %d is %d",n,n*n);
fflush(stdin);
printf("\nWant to calculate more square y/n: ");
scanf("%c", &answer);
}while(answer=='y');
return 0;
}
The output of above program would be:
The above odd loop program we can write
using for loop as:
/*odd loop using for loop of calculate square number C program*/
#include<stdio.h>
int main()
{
int n;
char ans='y';
for(; ans=='y' ; )
{
printf("Enter any number : ");
scanf("%d", &n);
printf("Square of %d is %d",n,n*n);
fflush(stdin);
printf("\nWant to calculate more square y/n: ");
scanf("%c", &ans);
}
return 0;
}
The output of above program would be:
/*odd loop using for loop of calculate square number C program*/
#include<stdio.h>
int main()
{
int n;
char ans='y';
for(; ans=='y' ; )
{
printf("Enter any number : ");
scanf("%d", &n);
printf("Square of %d is %d",n,n*n);
fflush(stdin);
printf("\nWant to calculate more square y/n: ");
scanf("%c", &ans);
}
return 0;
}
The output of above program would be:
The odd loop program we can write using
while loop as:
/*odd loop using while loop of calculate square number C program*/
#include<stdio.h>
int main()
{
int n;
char ans='y';
while(ans=='y')
{
printf("Enter any number : ");
scanf("%d", &n);
printf("Square of %d is %d",n,n*n);
fflush(stdin);
printf("\nWant to calculate more square y/n: ");
scanf("%c", &ans);
}
return 0;
}
The output of above program would be:
/*odd loop using while loop of calculate square number C program*/
#include<stdio.h>
int main()
{
int n;
char ans='y';
while(ans=='y')
{
printf("Enter any number : ");
scanf("%d", &n);
printf("Square of %d is %d",n,n*n);
fflush(stdin);
printf("\nWant to calculate more square y/n: ");
scanf("%c", &ans);
}
return 0;
}
The output of above program would be:
break statement
When we writing
programming code, we often come across situations where we want to jump out of
a loop instantly, without waiting to get back to the conditional test. The
keyword break allows us to do this. When break is encountered
inside any loop, control automatically passes to the first statement after the
loop. A break is usually associated with an if.
The keyword break, breaks the control only from the while in which it is placed.
Let's understand break with c program example:
The keyword break, breaks the control only from the while in which it is placed.
Let's understand break with c program example:
/*demonstration of break statement through c program*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i=5;
clrscr();
while(i>=1)
{
if(i==2)
{
printf("\nIt is equal to two!!");
break;
}
printf("%d\n",i);
i--;
}
getch();
}
Output:
5
4
3
It is equal to two!!
Thus, it is clear that a break statement takes the execution control out of the loop.
In above program, if we omitted break statement then what will be output? The answer is
5
4
3
It is equal to two!!
2
1
because when i's value is 2, condition will be satisfy and executed printf statement, after that compiler goes to next statement i.e. printf("%d",i); because loop do not terminate and it is run till the i value is not less than 1.
#include<conio.h>
void main()
{
int i=5;
clrscr();
while(i>=1)
{
if(i==2)
{
printf("\nIt is equal to two!!");
break;
}
printf("%d\n",i);
i--;
}
getch();
}
Output:
5
4
3
It is equal to two!!
Thus, it is clear that a break statement takes the execution control out of the loop.
In above program, if we omitted break statement then what will be output? The answer is
5
4
3
It is equal to two!!
2
1
because when i's value is 2, condition will be satisfy and executed printf statement, after that compiler goes to next statement i.e. printf("%d",i); because loop do not terminate and it is run till the i value is not less than 1.
search prime
number
Q. Write a C program to find whether a
number is prime or not.
Definition of prime number:
A prime number is one,which is divisible only by one or itself. And
it’s must greater than 1.
And if number is not prime, it is called
composite number and vice versa.
Ans.
#include<stdio.h>
#include<stdio.h>
int main()
{
int x,num;
printf("Enter number : ");
scanf("%d",&num);
x=2;
while(x<=num-1)
{
if(num%x==0)
{
printf("Number is not
prime!!");
break;
}
x++;
}
if(x==num)
printf("Number is prime!!");
getch();
getch();
return 0;
}
output of above program :Enter number : 7Number is prime!!
continue statement
when we write program,
if we want to take control to the beginning of the loop, bypassing the
statements inside the loop, which have not yet been executed, in this situation
we uses continue. continue is c reserved keyword in C.
When continue is encountered inside any loop, control automatically
passes to the beginning to the loop.
A continue is usually associated with an if.
Let's understand continue with example:
/*demonstration of continue statement*/
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
for(i=1; i<=2; i++)
{
for(j=1; j<=2; j++)
{
if(i==j)
continue;
printf("\n%d %d",i,j);
}
}
getch();
return 0;
}
A continue is usually associated with an if.
Let's understand continue with example:
/*demonstration of continue statement*/
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j;
for(i=1; i<=2; i++)
{
for(j=1; j<=2; j++)
{
if(i==j)
continue;
printf("\n%d %d",i,j);
}
}
getch();
return 0;
}
Output:
1 2
2 1
Explanation: When the value of i equals that of j, the continue statement takes the control to the for loop(inner) bypassing the rest of the statements execution in the for loop(inner).
Let's understand continue statement with another example:
2 1
Explanation: When the value of i equals that of j, the continue statement takes the control to the for loop(inner) bypassing the rest of the statements execution in the for loop(inner).
Let's understand continue statement with another example:
/*demonstration of continue statement*/
#include<stdio.h>
#include<conio.h>
int main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==6)
continue;
printf("%d ",i);
}
printf("\nNow we are out of for loop");
getch();
return 0;
}
#include<conio.h>
int main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==6)
continue;
printf("%d ",i);
}
printf("\nNow we are out of for loop");
getch();
return 0;
}
Output:-
1 2 3 4 5 7 8 9 10
Now we are out of for loop
Explanation: As when the value of i will
becomes 6 it will move for the next iteration by skipping the iteration i=6.
switch-case statement
In some programming situation, when there are number
of choices and we want to choose only appropriate choice, in that situation C
provided switch statement. Thus switch statement allows us to
make a decision from the number of choices.
The switch
statement also known as switch-case-default.
Since, the switch statement known for decision maker.
Syntax of switch statement:
switch(integer expression)
{
case 1 :
do this;
break;
case 2 :
do this;
break;
case 3 :
do this;
break;
case 4 :
do this;
break;
default :
and this;
break;
}
Since, the switch statement known for decision maker.
Syntax of switch statement:
switch(integer expression)
{
case 1 :
do this;
break;
case 2 :
do this;
break;
case 3 :
do this;
break;
case 4 :
do this;
break;
default :
and this;
break;
}
Example of switch-case-default
statement:
#include<stdio.h>
#include<conio.h>
int main()
{
int r=4;
switch(r)
{
case 1 :
printf("\nI am in case 1");
break;
case 2 :
printf("\nI am in case 2");
break;
case 3 :
printf("\nI am in case 3");
break;
case 4 :
printf("\nI am in case 4");
break;
case 5 :
printf("\nI am in case 5");
break;
default :
printf("\nI am in default");
break;
}
getch();
return 0;
}
#include<conio.h>
int main()
{
int r=4;
switch(r)
{
case 1 :
printf("\nI am in case 1");
break;
case 2 :
printf("\nI am in case 2");
break;
case 3 :
printf("\nI am in case 3");
break;
case 4 :
printf("\nI am in case 4");
break;
case 5 :
printf("\nI am in case 5");
break;
default :
printf("\nI am in default");
break;
}
getch();
return 0;
}
Output: I am in case 4
Different types of switch statement
(a) In switch statement case
arrangement may be ascending order, descending order, scrambled
order. So the following program should be valid and run:
#include<stdio.h>
#include<conio.h>
int main()
{
int r=44;
switch(r)
{
case 210 :
printf("\nI am
in case 210");
break;
case 10 :
printf("\nI am
in case 10");
break;
case 1 :
printf("\nI am
in case 1");
break;
case 44 :
printf("\nI am
in case 44");
break;
default :
printf("\nI am
in defalut");
break;
}
getch();
return 0;
}
Output: I am in case 44
(b) C also allowed to use char
values in case and switch statement as:
#include<stdio.h>
#include<conio.h>
int main()
{
char a='n';
switch(a)
{
case 'm' :
printf("\nI am in case m");
case 'n' :
printf("\nI am in case n");
case 'o' :
printf("\nI am in case o");
case 'p' :
printf("\nI am in case p");
default :
printf("\nI am in default");
}
getch();
return 0;
}
Output: I am in case n
Note: When above program run, 'm', 'n', 'o', 'p' are
actually replaced by subsequent ASCII(American Standard Code for
Information Interchange) code.
(c) C language allows
us to check the value of any expression in a switch statement like as:
switch(r+c*i)
switch(10+20%2*r)
switch(r+10*c)
switch(r>10 || c<20)
Above all switch
statement are valid.
And expression can also
be used in cases provided they are constant expression.
Thus case 10+15 is correct,
and however case r+c is incorrect.
(d) The switch
statement is very useful while writing menu driven program.
(e) The break
statement when used in a switch takes the control outside the switch.
However, use of continue will not take the control to the beginning of
switch.
(f) The case keyword
is followed by an integer or a character constant.
goto statement
The goto statement is used to alter the
normal sequence of program instructions by transferring the control to some
other portion of the program.
The syntax is as follows:
goto label;
Here, label is an identifier that is used to label
the statement to which control will be transferred. The targeted statement must
be preceded by the unique label followed by colon.
label: statement;
It is recommended that as possible as skip the goto
statement because when we use goto then we can never be sure how we got to a
certain point in our code. They obscure the flow of control.
Note:- goto can
never be used to jump into the loop from outside and it should be preferably
used for forward jump.
Let us consider a program to illustrate goto
and label statement:
/*program to demonstration of goto
statement*/
#include<stdio.h>
#include<conio.h>
void main()
{
int n;
clrscr();
printf("Enter one
digit number: ");
scanf("%d",&n);
if(n<=6)
goto mylabel;
else
{
printf("Now
control in main funcion.");
exit();
}
mylabel:
printf("Now
control in mylabel.");
}
Output:-
Enter one digit number:9
Now control in main function.
Enter one digit number:4
Now control in mylabel.
Flowchart for switch-case
How to write
switch case flowchart?
switch case statement:
switch( choice )
{
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case 3:
statement 3;
break;
case n:
statement n;
}
(in above module n = number of cases.)
switch case flowchart:
switch case statement:
switch( choice )
{
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case 3:
statement 3;
break;
case n:
statement n;
}
(in above module n = number of cases.)
switch case flowchart:
Storage classes
Every variable in C or other language have two main
features namely:
1.
Data Types
2.
Storage class
From
C compiler's point of view, a variable name identifies some physical location
within the computer where the string of bits representing the variable's value
stored. There are basically two kinds of locations in a computer where such a
value may be kept- Memory and CPU registers. It is the variable's
storage class that determines in which of there two types of locations, the
value is stored.
Moreover, a variable's storage class tells us:
1.
Memory
location i.e. where variable would be stored.
2.
Initial
value or default value of variable
3.
What
is scope of the variable
4.
What
is life of the variable
Scope
of variable:
Scope of variable i.e. in which function the value
of the variable would be available.
Life of the variable:
The life of the variable i.e. how long would the
variable exists.
There are four storage classes in C :
Automatic Storage Class
Automatic storage class
is default storage class i.e. if there are nothing to add storage class in
variable then by default it would be automatic storage class.
The features of a variable defined to have an automatic storage class are as under:
The features of a variable defined to have an automatic storage class are as under:
Storage
|
Memory
|
Keyword
|
auto
|
Default initial value
|
Garbage value i.e. an unpredictable value
|
Scope
|
Local to the block, in which the variable is
defined
|
Life
|
Till the control remains within the block in which
the variable is defined
|
Scope and life of an automatic variable is illustrated in the following program:
/*program to shows the life and scope of automatic variable*/
#include<stdio.h>
int main()
{
auto int i=1;
{
auto int i=2;
{
auto int i=3;
printf("\n%d",i);
}
printf("\n%d",i);
}
printf("\n%d",i);
return 0;
}
OUTPUT:-
3
2
1
In above program, compiler treats the three i's as totally different variables, since they are defined in different block. Once the control comes out of the innermost block, the variable i with value 3 is lost, and hence the i in the second printf() refers to i with value 2. Similarly, when the control comes out of the next innermost block, the third printf() refers to the i with value 1. Hence it is clear that scope of of i is local to the block in which it is defined.
Following program shows how an automatic storage class variable is declared, and what happen if variable is not initialise i.e. garbage value.
#include<stdio.h>
int main()
{
auto int i,j;
printf("\ni=%d \nj=%d",i,j);
return 0;
}
OUTPUT:-
i=54
j=3564
Where, 54 and 3564 are garbage values of i and j. When you run this program, you may get different values, since garbage values are unpredictable.
Register Storage Class
A value stored in a CPU register can always
be accessed faster than the one that is stored in memory. Therefore, if
a variable is used at many places in a program, it is better to declare its
storage class as register.
The features of a register storage variable as following manner:
The features of a register storage variable as following manner:
Storage
|
CPU registers
|
Keyword
|
register
|
Default initial value
|
Garbage value i.e. an unpredictable value
|
Scope
|
Local to the block, in which the variable is
defined
|
Life
|
Till the control remains within the block in which
the variable is defined
|
There are no guaranty that we have declare any variable as register and it would be stored in CPU register! Why? The reason is because CPU register are limited, and they may be busy doing some other task. In this case that variable works as default storage class i.e. automatic storage class.
Note: Any variable stored in CPU register or not depend on capacity of microprocessor. For example, if the microprocessor has 16-bit register then they cannot hold a float value or a double value, which require 4 and 8 bytes respectively.
However, if you use the register storage class for float, double variable then you won't get any error messages because compiler treat it as default storage class i.e. auto storage class.
All looping program where a variable are frequently
used, declare variable as register.
/*shows uses of register storage class*/
#include<stdio.h>
int main()
{
register int i;
for(i=10; i>=0; i=i-2)
printf("%d ",i);
return 0;
}
OUTPUT:-
10 8 6 4 2 0
Static Storage Class
The features of static storage class are as
following:
Storage
|
Memory
|
Keyword
|
static
|
Default initial value
|
Zero
|
Scope
|
Local to the block, in which the variable is
defined
|
Life
|
Value of the variable persists between
different function calls.
|
Let's compare static class with auto storage class for better understanding:
/*auto class*/
#include<stdio.h>
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
auto int i=1;
printf("\n%d",i);
i=i+1;
}
OUTPUT:-
1
1
1
1
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
auto int i=1;
printf("\n%d",i);
i=i+1;
}
OUTPUT:-
1
1
1
1
/*static class*/
#include<stdio.h>
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
static int i=1;
printf("\n%d",i);
i=i+1;
}
#include<stdio.h>
void add();
int main()
{
add();
add();
add();
add();
return 0;
}
void add()
{
static int i=1;
printf("\n%d",i);
i=i+1;
}
OUTPUT:-
1
2
3
4
The above both program consist of two functions main() and add(). The function add() gets called from main() four times. Each time it prints the value of i and then increments it. The only difference in these two programs is that one uses an auto storage class for variable i, whereas the other uses static storage class.
The difference between them is that static variable do not disappear when the function is no longer active. There value persist. If control comes back to the same function again , the static variables have the same values they had last time around.
Description of static program:
In static program, i is declare as static variable so it is initialized to 1 only once. It is never initialized again. During the first call to add(), i is incremented to 2. Because i is static, this value persists. The next time add() is called, i not re-initialized to 1, on the contrary, its old value 2 is still available. This current value of i (i.e. 2) gets printed and then i=i+1; adds 1 to i to get a value of 3. When add() is called the third time , the current value of i (i.e. 3) gets printed and once again i is incremented by 1 and this process going so on till the add() called.
In summarised if the storage class is static, then the statement static int i = 1 is executed only once, irrespective of how many times the same function is called.
1
2
3
4
The above both program consist of two functions main() and add(). The function add() gets called from main() four times. Each time it prints the value of i and then increments it. The only difference in these two programs is that one uses an auto storage class for variable i, whereas the other uses static storage class.
The difference between them is that static variable do not disappear when the function is no longer active. There value persist. If control comes back to the same function again , the static variables have the same values they had last time around.
Description of static program:
In static program, i is declare as static variable so it is initialized to 1 only once. It is never initialized again. During the first call to add(), i is incremented to 2. Because i is static, this value persists. The next time add() is called, i not re-initialized to 1, on the contrary, its old value 2 is still available. This current value of i (i.e. 2) gets printed and then i=i+1; adds 1 to i to get a value of 3. When add() is called the third time , the current value of i (i.e. 3) gets printed and once again i is incremented by 1 and this process going so on till the add() called.
In summarised if the storage class is static, then the statement static int i = 1 is executed only once, irrespective of how many times the same function is called.
External storage class
External variables
are differ from remaining other variables. The main features of external
variables as following :
Storage
|
Memory
|
Keyword
|
extern
|
Default initial value
|
Zero
|
Scope
|
Global
|
Life
|
As long as the program's execution doesn't
come to an end.
|
External variables are declared outside all functions, yet are available to all functions that care to use them.
Example of external variable or Global variable as following:
/*external variable example program*/
#include<stdio.h>
void add();
void subt();
int main()
{
printf("\ni=%d",i);
add();
add();
subt();
subt();
return 0;
}
void add()
{
int i;
i=i+1;
printf("\nAdding i = %d",i);
}
void subt()
{
int i;
i=i-1;
printf("\nSubtracting i = %d",i);
}
OUTPUT:-
Adding i= 1
Adding i = 2
Subtracting i = 1
Subtracting i = 0
/*program for global variable*/
#include<stdio.h>
int i=50;
void show();
int main()
{
int i=100;
printf("\n%d",i);
show();
return 0;
}
void show()
{
printf("\n%d",i);
}
OUTPUT:-
100
50
/*Another example of external or global variable*/
#include<stdio.h>
int i=5;
int main()
{
extern int j;
printf("\ni=%d \nj=%d",i,j);
int j=10;
return 0;
}
OUTPUT:-
i=5
j=10
Explanation: Because both variables i and j are enjoy as global variable.
Comparison
storage classes
In C, storage class provides
information about their location and visibility.
C provides four storage classes as:
C provides four storage classes as:
1.
auto storage class
2.
register storage
3.
extern storage class
4.
static storage class
- Storage class determines its storage duration, scope and linkage.
- Storage duration is the period during which that identifier exists in the memory.
- Scope is where the identifier can be referenced in a program.
- Linkage determines for a multiple-source file.
Let's summarised all storage classes in C as following as:
Features
|
Automatic Storage Class
|
Register Storage Class
|
Static Storage Class
|
External Storage Class
|
||||||||||||||||||||||||||||||||||||||
Keyword
|
auto
|
register
|
static
|
extern
|
||||||||||||||||||||||||||||||||||||||
Initial
Value
|
Garbage
|
Garbage
|
Zero
|
Zero
|
||||||||||||||||||||||||||||||||||||||
Storage
|
Memory
|
CPU
register
|
Memory
|
Memory
|
||||||||||||||||||||||||||||||||||||||
Scope
|
scope
limited,local to block
|
scope
limited,local to block
|
scope
limited,local to block
|
Global
|
||||||||||||||||||||||||||||||||||||||
Life
|
limited
life of block,where defined
|
limited
life of block,where defined
|
value of
variable persist between different function calls
|
Global,till
the program execution
|
||||||||||||||||||||||||||||||||||||||
Memory
location
|
Stack
|
Register
memory
|
Segment
|
Segment
|
||||||||||||||||||||||||||||||||||||||
Example
|
|
|
|
|
FIGURE:
Table of Storage classes in C
What
is Pointer
What is Pointer?
Pointer is a special variable that represent the address/location of the data item. It provides an alternative way to access the value of a variable.
Pointer is used only store/hold memory address of any variable.
There are some reason to why Pointer used in programs:
Pointer is a special variable that represent the address/location of the data item. It provides an alternative way to access the value of a variable.
Pointer is used only store/hold memory address of any variable.
There are some reason to why Pointer used in programs:
1.
A pointer able to access a variable
that is defined outside the function.
2.
Pointer are more efficient in handle
the data table.
3.
Pointers reduce the length and
complexity of the program.
4.
Pointer increase the speed of
program execution.
5.
The use of the Pointer array to
character string, result in saving of data storage space in memory.
Pointer Notation
Let's declare a integer variable n
which value is 10:
int n = 10 ;
What is this meaning? The above
declaration tells the C compiler that:
1.
Reserve space in memory to hold the
integer value i.e. 65220
2.
Associate the name with this memory
location i.e. n
3.
Store the value at location i.e.
10
and the memory map of above declaration as:
n --------> location name
10 --------> value at location
65220 --------> location/address number
The important point to note in memory map that n's address in memory is a number ( in next chapter we see how it is important? ).
n --------> location name
10 --------> value at location
65220 --------> location/address number
The important point to note in memory map that n's address in memory is a number ( in next chapter we see how it is important? ).
Concept of Pointer
In last chapter ( what
is pointer ) , we learn what is the basic of pointer. Now we
are learning what is the concept of pointer and how to using it.
In last chapter we declare a variable
int n = 10 ;
and create a memory map, Now we learn how to do this.
Now we print the address of variable through following program:
#include<stdio.h>
int main()
{
int n = 10;
printf("\nAddress of n =%u", &n);
printf("\nValue of n =%d", n);
getch();
return 0;
}
The output of above program:
Address of n = 65220
Value of n = 10
Useful tips i.e. explanations of above programs:
In last chapter we declare a variable
int n = 10 ;
and create a memory map, Now we learn how to do this.
Now we print the address of variable through following program:
#include<stdio.h>
int main()
{
int n = 10;
printf("\nAddress of n =%u", &n);
printf("\nValue of n =%d", n);
getch();
return 0;
}
The output of above program:
Address of n = 65220
Value of n = 10
Useful tips i.e. explanations of above programs:
- Look at the first printf() statement carefully, it used & ( address of operator ). So & return the address of memory location. In our case, the expression &n return the address of variable n.
- %u is used for printing the unsigned integer.
Now,
observe carefully the output of the following program:
#include<stdio.h>
int main()
{
int n = 10;
printf("\nAddress of n =%u", &n);
printf("\nValue of n =%d", n);
printf("\nValue of n =%d", *(&n));
getch();
return 0;
}
The output of above program:
Address of n = 65220
Value of n = 10
Value of n = 10
here you can notice that the value of *(&n) is same as printing the value of n.
The expression &n gives the address of the variable n. This address can be collected in a variable, by saying:
int p = &n;
but here 1 problem, p is simple variable so we can't use of variable p.
What is solution?
So here comes the concept of pointer. Now we declare the integer variable p as integer pointer variable:
int *p;
This declaration tells the compiler that p will be used to store the address of an integer value i.e. p points to an integer.
int *p;
Now let's understand the meaning of *. It stand for value at address operator. It return the value at stored at particular address.
The "value at address" operator is
also known "indirection operator".
Thus,
int *p; would mean, the value at the address contained in p is an int.
let's check out what you grab:
Q. What will be output of following program?
#include<stdio.h>
int main()
{
int n = 10;
printf("\nOutput of n =%d", n);
printf("\nOutput of *n =%d", *n);
getch();
return 0;
}
Ans.
Output of n = 10
Output of *n = error ( invalid indirection)
Can you understand why second printf() statement generate error? if yes then congratulation... And if you can't figure out then also don't worry because our next chapter is pointer practice session, in this you grab all about pointer.
The reason second printf() statement is generating error because, "value at address ( * )" is used only pointer variable/directly address i.e. "value at address" does not work with simple variable.
In our case n is simple variable and so compiler generate error.
Pointer basic example
We has been discuss about what is pointer and
concept of pointer. Now the following program demonstrates the relationship of
our pointer discussion.
#include<stdio.h>
int main()
{
int x =
5;
int *y;
y = &x;
printf("\nAddress
of x = %u", &x);
printf("\nAddress
of x = %u", x);
printf("\nAddress
of y = %u", &y);
printf("\nValue
of y = %d", y);
printf("\nValue
of x = %d", x);
printf("\nValue
of x = %d", *(&x));
printf("\nValue
of y = %d", *y);
getch();
return 0;
}
The output of above program would be:
Address of x = 2293620
Address of x = 5
Address of y = 2293616
Value of y = 2293620
Value of x = 5
Value of x = 5
Value of y = 5
/* Screen shot for above program */
note: the address of
variable may be differ because its depend on compiler. I use Bloodshed software
"Dev-C++" so you can see that here integer occupy 4 bytes.
The above program
summarizes everything that we discussed in what is pointer and concept
of pointer chapters. If you don't understand the program output, or the
meaning of &x, &y, *y and *(&x),
re-read the last 2 chapter of pointer:
What is pointer
Concept of pointer
Now look at the following declaration:
int *n;
char *ch;
float *area;
Here, n, ch and area are declared as pointer variable, i.e. these variable capable of holding addresses.
Keep in mind: Address ( location numbers ) are always whole numbers.
In summarize "we can say pointers are variable that contain addresses and addresses are always whole numbers."
The declaration float *area does not mean that area is going to contain a floating-point value. The meaning is, *area is going to contain the address of a floating-point value.
Similarly, char *ch means that ch is going to contain the address of a char value or in other words, the value at address stored in ch is going to be a char.
Now we know that "Pointer is a variable that contains address of another variable."
Can we further extended it? The answer is Yes, we can. Read in next chapter "Pointer Extended Example".
What is pointer
Concept of pointer
Now look at the following declaration:
int *n;
char *ch;
float *area;
Here, n, ch and area are declared as pointer variable, i.e. these variable capable of holding addresses.
Keep in mind: Address ( location numbers ) are always whole numbers.
In summarize "we can say pointers are variable that contain addresses and addresses are always whole numbers."
The declaration float *area does not mean that area is going to contain a floating-point value. The meaning is, *area is going to contain the address of a floating-point value.
Similarly, char *ch means that ch is going to contain the address of a char value or in other words, the value at address stored in ch is going to be a char.
Now we know that "Pointer is a variable that contains address of another variable."
Can we further extended it? The answer is Yes, we can. Read in next chapter "Pointer Extended Example".
Pointer Extend Example
Can a pointer variable,
itself might be another pointer?
Yes, this pointer would be contains another pointer's address.
The following example/program should should make this point clear:
/*c program for pointer extend example*/
#include<stdio.h>
int main()
{
int x=5;
int *y, **z;
y = &x;
z = &y;
printf("\nAddress of x = %u", &x);
printf("\nAddress of x = %u", y);
printf("\nAddress of x = %u", *z);
printf("\nAddress of y = %u", &y);
printf("\nAddress of y = %u", z);
printf("\nAddress of z = %u", &z);
printf("\nValue of y = %u", y);
printf("\nValue of z = %u", z);
printf("\nValue of x = %u", x);
printf("\nValue of x = %u", *(&x));
printf("\nValue of x = %u", *y);
printf("\nValue of x = %u", **z);
getch();
return 0;
}
The output of the above program would be:
Yes, this pointer would be contains another pointer's address.
The following example/program should should make this point clear:
/*c program for pointer extend example*/
#include<stdio.h>
int main()
{
int x=5;
int *y, **z;
y = &x;
z = &y;
printf("\nAddress of x = %u", &x);
printf("\nAddress of x = %u", y);
printf("\nAddress of x = %u", *z);
printf("\nAddress of y = %u", &y);
printf("\nAddress of y = %u", z);
printf("\nAddress of z = %u", &z);
printf("\nValue of y = %u", y);
printf("\nValue of z = %u", z);
printf("\nValue of x = %u", x);
printf("\nValue of x = %u", *(&x));
printf("\nValue of x = %u", *y);
printf("\nValue of x = %u", **z);
getch();
return 0;
}
The output of the above program would be:
Read above program carefully, the addresses that get output might be something different.
The relationship between x, y and z can be easily summarized as:
Name ---------------- x y z
Value ------------------- 5 2293620 2293616
Address ---------------- 2293620 2293616 2293612
What is the meaning of int x, *y, **z;
Here, x is an ordinary int variable,
y is a pointer to an int i.e. integer pointer,
z is pointer to an integer pointer.
We can extend the above program still further by creating a pointer to a pointer to an integer pointer i.e. ***n
There is no limit on how far can we go on extending this definition. Possibly, till the point we can comprehend it. And that point of comprehension is usually a pointer to a pointer.
What
is Function
What is function in C?
A function is a self-contained block of statement that perform a coherent task of some kind.
There are two types of function in C:
A function is a self-contained block of statement that perform a coherent task of some kind.
There are two types of function in C:
1.
Library function or In-built
function
2.
User define function
Structure of function in C program
/* demonstration of function status in program */
#include<stdio.h>
void disp(); /* function prototype declaration */
int main()
{
disp(); /*function calling*/
printf("C is Awesome!!!");
return 0;
}
void disp() /* function definition */
{
printf("Hi, ");
}
The output of above program would be:
Hi, C is Awesome!!!
Let's grab some useful info from the above program:
In above program we have 2 function:
main()
disp()
Here you can see and thought:
1. why main() is used only once in program?
2. why disp() is used three times in program?
The answer of first question is "if a c program contains only one function then it must be main()." i.e. every C program must have main() function.
The answer of second question: let's understand the meaning of every disp() in program:
void disp();
this is the first disp() that used in program. It is function prototype.
This prototype tells the compiler that as:
What is function type ( i.e. void or not ),
What is name of function( i.e. in our program function name is disp)
Both parenthesis () indicate that disp is function.
keep in mind: void word indicating that "nothing return".
disp();
this is the second disp() that used in program. It is function calling.
Every calling function main work is as:
when compiler reached at calling function disp(); program control passes to the function disp(), (i.e. activity of main() is temporary suspend ), when disp() function runs out all his statement execute, the control returns to the main() function and begins executing code at the exact point where it is left off.
void disp()
{
printf("Hi, ");
}
this is the third disp() that used in program. It is function definition.
In function definition we can used all C language keywords, operators, variable etc.
In above program recently we have only 1 printf(); statement.
Let's exercise, what we learn:
/*exercise of function calling C program*/
#include<stdio.h>
void fun1();
void fun2();
void fun3();
int main()
{
printf("\nI am in main function!!");
fun1();
fun2();
fun3();
return 0;
}
void fun1()
{
printf("\nI am in fun 1");
}
void fun2()
{
printf("\nI am in fun 2");
}
void fun3()
{
printf("\nI am in fun 3");
}
The output of above program would be:
I am in main function!!
I am in fun 1
I am in fun 2
I am in fun 3
C Standard Library Inbuilt Function
With every C compiler, a large set of useful string handling library function are provided.
Below lists the more commonly used functions along with their name and features as:
Function name
|
Features
|
Calculate length of string
|
|
Copy from one string to another
|
|
Copies first n characters of one string into
another
|
|
Appends one string at the end of another
|
|
Appends first n characters of a string at
the end of another
|
|
Compares two string
|
|
Compares first n characters of two string
|
|
Compares two string with ignore the case
|
|
stricmp
|
Compares two string with ignore the
case(identical to strcmpi)
|
strnicmp
|
Compares first n characters of two string
with ignore the case
|
strlwr
|
Convert a string to lowercase
|
strupr
|
Convert a string to uppercase
|
strrev
|
Reverse string
|
strdup
|
Duplicate a string
|
strchr
|
Finds first occurrence of a given character
in a string
|
strrchr
|
Finds last occurrence of a given character
in a string
|
strstr
|
Finds first occurrence of a given string in
another string
|
strset
|
Sets all characters of string to a given
character
|
strnset
|
Sets first n characters of a string to a
given character
|
Table:
Standard Library String Function in C Language
(For syntax, example and use of above function, click at related function name.)
User
Define Function
What is User Define Function?
A function that is declare, calling and define by the user is called user define function.
Every user define function has three parts as:
A function that is declare, calling and define by the user is called user define function.
Every user define function has three parts as:
1.
Prototype or Declaration
2.
Calling
3.
Definition
1. Prototype or Declaration
Prototype/declaration set the
outline of function like as:
function is something
returning or not?
what is function name?
what would be the
nature of parameter?
how much parameters
used in function?
This is generally written at top of
program like as after or before the main() function.
syntax:
return_data_type
function_name(data_type parameter, ......);
Description of syntax:
In above syntax
"return_data_type" may be two types:
if return_data_type
is void: This mean that our function nothing
return.
if return_data_type
is other like as int, float, double etc.
then it would be return as int, float, double etc. respectively.
for example:
int factorial(int num); //it would return a integer value.
void display(int num); //it would nothing return.
In above syntax
"function_name" means that the name of function which we want to
make.
for example:
int myfunction(int i);
In above syntax "data_type
parameter" means that first write down the data type( int, float, double,
long, char ) and after write down the name of related
parameter/argument/variable. It is may be one, two and so on as the requirement
of function.
for example:
int sum(int x, int y);
int myfunction(int name);
In Prototype or Declaration of
function, we can write only the name of data type, not require the name of
parameter/argument( it is optional ).
for example:
int sum(int , int ); //it would
return a integer value.
int myfunction(int ); // this is valid and correct
int myfunction(char ); // this is valid and correct
2. Calling
The calling part of function work
as:
It is call the
function.
It forward the control
of main() to user define function and vice versa.
The calling is generally written as
middle of program after grab all related argument.
syntax:
//if return type is
void:
function_name(actual
argument/parameter);
//if return type is
not void:
return_parameter=function_name(actual
argument/parameter);
for example:
display(num); //void calling function- display
result=sum(x, y) //return calling function-sum
f=factorial(num) //return calling function- factorial
ex=myfunction(number) //return calling function - myfunction
3. Definition
The "definition" part is
the heart of function.
What will function do?
It define the all function body.
The definition part must be exist at
outside of main() function. i.e. it is written after making all the program.
syntax:
//if return type is
void:
function_name(data_type
argument/parameter)
{
statement 1;
statement 1;
statement 1;
.
.
.
statement n;
}
//if return type is
not void:
return_data_type
function_name(data_type parameter)
{
statement 1;
statement 1;
statement 1;
.
.
.
statement n;
return (
any_return_value);
}
example:
int sum(int x, int y)
{
int
res;
res = x+y;
return(res);
}
A complete example of user define
function:
/*demonstration of
user define function-sum*/
#include<stdio.h>
int sum(int , int); //Prototype
or Declaration
int main()
{
int x,y,result;
printf("Enter value of x and y: ");
scanf("%d %d", &x,
&y);
result=sum(x, y); //calling of function-sum
printf("Sum of %d + %d = %d",x,y,result);
return 0;
}
//Definition of
function sum
int sum(int a, int b)
{
int res;
res = a + b;
return ( res );
}
The output of above
program would be:
Array
in C
Before you kick start to reading
array, you should understand why array concept is comes? How it is requires in
C?
Let's read following program:
#include<stdio.h>
int main()
{
int r;
r=1;
r=2;
printf("The value of r = %d",r);
getch();
return 0;
}
The output of above
program would be:
The value of r = 2
So, you can understand that when the
value 2 is assigned into r, the earlier value of r (i.e. 1) is
lost. Thus the ordinary variables are capable of holding only one value at a
time.
What we do if we would want to store
more than one value at a time in a single variable?
Here, the comes the concept of
array.
What is array?
1.
Array is a collection of similar
elements.
2.
The first element in the array is
numbered 0, so the last element is 1 less than the size of the array.
3.
An array is also known as a
subscripted variable.
4.
Before using an array, its type and
dimension must be declared.
5.
The array elements are always stored
in contiguous memory locations. This is a very important features of array.
Thus, an array is collection of
similar elements. These similar elements could be all ints, or all floats,
or all chars.
Array of characters is called a
string whereas an array of ints or floats is called simply an
array.
Keep in mind that all elements of
any array must be the same type. i.e. cannot have an array of 10 numbers, of
which 5 are ints and 5 are floats.
1.
Array declaration and Initialization
2.
Bounds Checking
3.
Array and function
4.
Array and Pointers
Array of pointers
2-d Array
3-d Array
C
Preprocessor
What is C Preprocessor?
It is a program that processes our source program before it is passed to the compiler.
Preprocessor command also known as directives.
Each preprocessor directory is begin with a # symbol.
It is can be placed anywhere in the program but are most often placed at the beginning of a program.
The C program is often known as 'Source Code'. The preprocessor works on the source code and creates 'Expanded Source Code'.
If the source code is stored in a file say MYPROG.C, then the expanded source code gets stored in a file MYPROG.I. It is this expanded source code that is sent to the compiler for compilation.
Example of some preprocessor directives as:
It is a program that processes our source program before it is passed to the compiler.
Preprocessor command also known as directives.
Each preprocessor directory is begin with a # symbol.
It is can be placed anywhere in the program but are most often placed at the beginning of a program.
The C program is often known as 'Source Code'. The preprocessor works on the source code and creates 'Expanded Source Code'.
If the source code is stored in a file say MYPROG.C, then the expanded source code gets stored in a file MYPROG.I. It is this expanded source code that is sent to the compiler for compilation.
Example of some preprocessor directives as:
- Macro Expansion
- Conditional compilation
- File inclusion
- Miscellaneous directives
We discuss all above preprocessor in
detailed one by one.
Macro
Expansion
What is macro?
Let's understand macro using
following program:
/*c program for
macro expansion*/
#include<stdio.h>
#define LENGTH 3
#define WIDTH 2
int main()
{
int
r,c;
for(r=1;
r<=LENGTH; r++)
{
for(c=1;
c<=WIDTH; c++)
printf("%d%d",c,r);
printf("\n");
}
getch();
return 0;
}
The output of above
program would be:
In above program, instead of writing
5 in the for loop we are writing it in the form of text as LENGTH
and WIDTH, which have already been defined before main() through
the statement.
#define LENGTH 3
#define WIDTH 2
This statement is called 'macro
definition' or macro.
LENGTH and WIDTH in the above
program are often called 'macro templates' , whereas 5 and 3 are
called their corresponding 'macro expansions'.
What is reason of using macro in the
program?
Macro makes the program easier to
read.
For example: if the phrase
"%ls[$2]!@" cause the screen to clear, but which would you find
easier to understand in the middle of your
program "%ls[$2]!@" or "CLRSCREEN"?
#define CLRSCREEN
"%ls[$2]!@"
Macro makes the easyness if we want
to change the vale of constant in program. We can change value values of a
constant at all the places in the program by just making a change in the
#define directive.
This conversion may not matter for
small programs shown above, but with large programs, macro definitions are
almost indispensable.
Now you will be thinking, there are
any similarity in macro and variable? Can i use variable as macro?
(i recommended, before you read
next line, you should think about macro and variable properties.)
After thinking you will be find that
we also use variable as macro. Then why not use it?
Why the variable is not using as
macro because:
1.
Variable may inadvertently get
altered somewhere in the program. so it's no longer a constant that you think
it is.
2.
Variable is inefficient, since the
compiler can generate faster and more compact code for constant than it can for
variables.
3.
Using a variable for what is really
a constant encourages sloppy thinking and makes the program
more difficult to understand: if something never changes, it is hard
to imagine it as a variable.
Macro Rules and Example
Macro without argument example
A #define directive is many a time used to
define operators as shown below:
#include<stdio.h>
#define OR ||
#define AND &&
int main()
{
int p=10,q=20,r=30;
if((p==10) AND (q<25 OR r>=50))
printf("You are winner!!");
else
printf("You are loser!!");
getch();
return 0;
}
The output of above program would be:
#include<stdio.h>
#define OR ||
#define AND &&
int main()
{
int p=10,q=20,r=30;
if((p==10) AND (q<25 OR r>=50))
printf("You are winner!!");
else
printf("You are loser!!");
getch();
return 0;
}
The output of above program would be:
A #define directive could be used even to replace a condition as:
#include<stdio.h>
#define OR ||
#define AND &&
#define RESULT ((p==10) AND (q<25 OR r>=50))
int main()
{
int p=10,q=20,r=30;
if(RESULT)
printf("You are winner!!");
else
printf("You are loser!!");
getch();
return 0;
}
The output of above program would be:
A #define directive could be used to replace
even an entire C statement.
#include<stdio.h>
#define DISPLAY printf("Yes, I got iT");
int main()
{
DISPLAY;
getch();
return 0;
}
The output of above program would be:
#define DISPLAY printf("Yes, I got iT");
int main()
{
DISPLAY;
getch();
return 0;
}
The output of above program would be:
Macro with argument
example
#include<stdio.h>
#define SQUARE(p) (p*p)
int main()
{
int n,result;
printf("Enter any number: ");
scanf("%d", &n);
result = SQUARE(n);
printf("Square of %d is %d",n,result);
getch();
return 0;
}
The output of above program would be:
#define SQUARE(p) (p*p)
int main()
{
int n,result;
printf("Enter any number: ");
scanf("%d", &n);
result = SQUARE(n);
printf("Square of %d is %d",n,result);
getch();
return 0;
}
The output of above program would be:
Keep in mind some following point, when you create macro
1. If there
are two or more macro expansions then,
entire macro expansions should be enclosed within parentheses.
Example:
#define SQUARE(p)
p*p //wrong
#define SQUARE(p)
(p*p) //right
2. There
should be not a blank between the macro template and its argument while
defining the macro.
Example:
#define SQUARE
(p) p*p //wrong
#define SQUARE(p)
(p*p) //right
3. Macro can
be split into multiple lines, with a '\'(back slash) present at
the end of each line.
Example:
#include<stdio.h>
#define
MYPROG for(c=1; c<=10; c++)
\
{
\
if(c==5)
\
printf("Good C blog.");
\
}
int main()
{
int c;
MYPROG
getch();
return 0;
}
The output of above
program would be:
Figure:
Screen shot for macro split C program
|
File Inclusion
The first preprocessor directive is macro
and the second preprocessor directive is file inclusion.
File inclusion causes one file to be included in another. #include "filename" What is the meaning of above syntax? It is simply causes the entire contents of filename to be inserted into source code at that point in the program. Why file inclusion is used? If we have a very large program, the code is best divided into several different files, each containing a set of related functions. It is a good programming practice to keep different sections of a large program separate. These files are #included at the beginning of main program file. There are some functions and some macro definitions that we need almost in all program that we write. These commonly needed functions and macro definitions can be stored in a file, and that file can be included in every program we write, which would add all the statements in this file to our program as if we have typed them in. There are two way to write #include statement as: 1. #include "myfile.h" This command would look for the file myfile.h in the current directory as well as the specified list of directories as mentioned in the include search path that might have been setup. 2. #include<myfile.h> This command would look for the file myfile.h in the specified list of directories only. Conditional Compilation
What is
conditional compilation?
You can understand it by its name i.e. a program is compiling according condition. In other word, we can, if we want, have the compiler skip over part of a source code by inserting the preprocessing commands #ifdef and #endif, which have the general form: #ifdef macroname statement 1; statement 2; statement 3; statement 4; #endif if macroname has been #defined, the block of code will be processed as usual, otherwise not.
Preprocessor
directives
The #if directive can be used to test whether an
expression evaluates to a nonzero value or not. If the result of the
expression is nonzero, then subsequent lines upto a #else, #elif
or #endif are compiled, otherwise they are skipped.
Syntax of #if directive as: #if LABEL == 10 statement 1; statement 2; #else statement 3; statement 4; statement 5; #endif If we so desire, we can have nested conditional compilation directives.
#undef directive
Sometimes, it may be desirable to cause a defined name to become 'undefined'. This can be accmplished by means of the #undef directive. Syntax: #undef macro_temp_name example: #undef TEST
#pragma Directive
This is a special directive that we use to turn on or off certain features. Pragma vary from one compiler to another. Turbo c/c++ compiler has got a pragma that allows you to suppress warnings generated by the compiler. Some pragmas directives as following:
|
No comments:
Post a Comment