You are on page 1of 25

By

Hare Krishna P.Vemana

INTRODUCTION
 KEY-WORDS

 PROGRAM: A Program is set of executable instructions given to a computer to perform a task.


o A program takes input and process that input and provides output.
 ALGORITHM: An Algorithm is finite no. of statements to perform an operation.
 FLOW-CHART: A flow-char is set of graphical symbols that denotes the flow of statement
execution.

 Types of programming languages:

 Machine language: These language instructions are directly executed by CPU.which is in


terms of 0’s and 1’s
 Assembly language: The Language which is the form of mnemonics or symbols is called
assembly language. These are partially understood by programmers and computers.
 High Level Language: The user friendly language. More natural language than assembly
language.which is English like language and only understood by programmers directly but not
by computers.
o Examples : C,CPP,JAVA
 Language Translators
 Assembler is needed to convert assembly language into machine language
 Complier is needed to convert high-level to machine language.
 Interpreter is used to translate a high level language program’s one line into machine
language code.
 Linker: a linker is a program that combines object modules to form an executable program.
o  linker or link editor is a computer program that takes one or more object files
generated by a compiler and combines them into a single executable file, library file, or
another object file.
 Loader is the part of an Operating System that is responsible for loading programs into the
memory.
o It is one of the essential stages in the process of starting a program. Because it places
programs into memory and prepares them for execution
// My first C-program to read 2-nos and An Algorithm
perform addition and print that resut
ADD(a,b,sum)
#include<stdio.h> Step 1: Start;
Step 2: Read a,b;
void main() Step 3: process sum:=a+b;
{ Step 4: Print sum;
int a,b,sum; Step 5: Stop.
printf(“enter 2-nos for addition”);
scanf(“%d%d”&num1,&num2);
sum=a+b;
printf(“The Result is %d”,sum);
}

1
By
Hare Krishna P.Vemana

Flowcharts

A flowchart is a symbolic diagram that describes a sequence of events or steps in a process/program.


FLOWCHART SYMBOLS

SYMBOL EXAMPLE

START

Terminal symbol

Calculate new
value

General process/simple sequence

Sort table
of data
Subprocess/subprogram

Check temperature

Input/output (I/O) operation

Decision symbol

Flow of events from symbol to symbol

C-HISTORY:

2
By
Hare Krishna P.Vemana

 C is a programming language which born at “AT & T’s Bell Laboratory” of USA in 1972.
 C was written by Dennis Ritchie, thats why he is also called as father of c programming
language.
 C language was created for the UNIX operating system (which is currently base of many UNIX
based OS).
 Its use quickly spread beyond Bell Labs in the late 70’s because of its long list of strong
features.
 Many of C’s principles and ideas were derived from the earlier language B. (Ken Thompson
was the developer of B Language.)
 BCPL and CPL are the earlier ancestors of B Language
 CPL is “common Programming Language” .In 1967, BCPL Language ( Basic CPL ) was
created as a scaled down version of CPL
 As many of the features were derived from “B” Language thats why it was named as “C”.
 After 7-8 years C++ came into existence which was first example of object oriented
programming.
Summary of C Programming Language History
Summary

1 B Language Developed By Ken Thompson

2 Operating System Developed in C UNIX

3 Developed at AT & T Bell Laboratory

4 Creator of Traditional C Dennis Ritchie

5 Year 1972
C Programming Language Timeline:
Programming Development
Developed by
Language Year

ALGOL 1960 International Group

BCPL 1967 Martin Richards

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

Brain Kernighan and Dennis


K&R C 1978
Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

3
By
Hare Krishna P.Vemana

Why use C? OR C Language features


Features of C

Low Level Language Support Portability

Powerful Bit Manipulation

High Level Features Modular Programming

Efficient Use of Pointers


1. Low Level Features:
 C Programming provides low level features that are generally provided by the Lower level
languages. C is Closely Related to Lower level Language such as “Assembly Language“.
 It is easier to write assembly language codes in C programming.
2. Portability:
 C Programs are portable i.e they can be run on any Compiler with Little or no Modification
 Compiler and Preprocessor make it Possible for C Program to run it on Different PC
3. Powerful
 Provides Wide verity of ‘Data Types‘
 Provides Wide verity of ‘Functions’
 Provides useful Control & Loop Control Statements
4. Bit Manipulation
 C Programs can be manipulated using bits. We can perform different operations at bit level.
We can manage memory representation at bit level. [Eg. We can use Structure to manage
Memory at Bit Level]
 It provides wide verity of bit manipulation Operators. We have bitwise operators to manage
Data at bit level.
5. High Level Features:
 It is more User friendly as compare to previous languages.
 Previous languages such as BCPL, Pascal and other programming languages never provide
such great features to manage data.
 Previous languages have their pros and cons but C Programming collected all useful features
of previous languages thus C become more effective language.
6. Modular Programming
 Modular programming is a software design technique that increases the extent to which
software is composed of separate parts, called modules.
 It reduces the complexity of a program.
 C Program Consist of Different Modules that are integrated together to form complete program
7. Efficient Use of Pointers
 A pointer has direct access to memory.
 C Supports efficient use of pointer.

4
By
Hare Krishna P.Vemana

C- Program Structure or Various sections in C-Program


A C program may contain one or more sections. They are illustrated below.
Documentation Section

Link Section
Definition Section

Global Declaration Section

main ()
{
Declaration Section
Executable part
……
}

Subprogram section
Function 1
Function 2
.
.
Function n

Explanation:
Sections Description
Documentation section  We can give comments about the program, creation or
modified date, author name etc in this section. 
 The characters or words or anything which are given
between “/*” and “*/”, won’t be considered by C compiler
for compilation process.
 These will be ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
Link Section  Header files that are required to execute a C program are
written in this section.
 Example #include<stdio.h>
Definition Section  In this section, variables, symbolic constants are defined
and values are set to these variables. Ex #define X 123
 #define is a pre-processor directive not a statement so it
not end with ;
Global declaration section  Global variables are defined in this section.
and  Global variable is a variable which is to be used
throughout the program, can be defined in this section.
Function prototype  Function prototype gives much information about a
declaration section function like return type, parameter names used inside
the function.
 All user defined functions are declared inside in this
section
main( ) function  Every C program is started from main function and this

5
By
Hare Krishna P.Vemana

function contains two major parts called declaration


section and executable section.
 Declaration part is used to declare all variables.
 Executable part contains at least one executable
statements
User-defined function  User can define their own functions in this section which
section or sub-program perform particular task as per the user requirement.
section

KEY POINTS TO REMEMBER IN C PROGRAMMING BASICS:


 C programming is a case sensitive programming language. i.e upper case and lower case
words are different ( main() is not equal to MAIN() and Main())
 Each C programming statement is ended with semicolon (;) which are referred as statement
terminator.
 printf() command is used to print the output onto the screen. And scanf() is used to take input
into c program
 C programs are compiled using C compilers and displays output when executed.

A SIMPLE C PROGRAM:

#include <stdio.h>
int main()
{
   /* Our first simple C basic program */
   printf("Hello World! ");
   getch();
   return 0;
}
Program Explanation:
Program code/line Explanation
#include <stdio.h>  This is a preprocessor command that includes,links standard
input output header file(stdio.h) from the C library before
compiling a C program
int main()  This is the main function from where execution of any C
program begins.
{  This indicates the beginning of the main function.

/*Our first simple c basic  Thisi is a comment in c.


program*/  Whatever is given inside the command /*   */ or // is called a
comment.
 In any C program, comments are won’t be considered for
compilation and execution.
printf(“Hello_World! “);  printf command prints the output onto the screen.

getch();  This command waits for any character input from keyboard.

6
By
Hare Krishna P.Vemana

return 0;  This command terminates C program (main function) and


returns 0.
}  This indicates the end of the main function.

Another simple Hello World C Program

This is a program to print “Hello World”

#include<stdio.h>

void main()
{
printf("Hello World");
}

Output
Hello World

Now try to understand this program step by step.

1. #include<stdio.h>:
 First statement started with # it is called pre-processor directive.
 #include<stdio.h> is used to include the stdio.h header file in our program.
 Header files contains the functions that we use in our program.
 Here we have used printf() function which is present in stdio.h header file.

2. void main():
 Here main() is the function.
 A program always starts with the main() function and every program must have main().
 Here void is the return type of this function.void means main() function will not return
anything.
 The opening curly braces { and closing curly braces } shows the body of the function.
o main() can also be called as a collection of statements.

3. printf():
 Here printf() is output function.
 This is used to print the values on the screen.
 Its general form is
 printf(“Statement you want to print on screen”);

4. Semicolon (;)
 is used for denoting the termination of statement.
 It is also called statement terminator in C Language.

How to compile and execute?

Here we are using TURBO C compiler. If you have not downloaded it yet than download it from here.

7
By
Hare Krishna P.Vemana

1. Open Turbo C and type the program.


2. After that press F2 to save the program with .c extension. Eg: program.c
3. Now Press ALT + F9 to compile and CTRL + F9 to run the program.
4. Press ALT + F5 to view the output.

Well this is the easiest C program. Now lets move on and try slightly complicated program of
multiplication of two numbers.

C Program to multiply two numbers

#include<stdio.h>

void main()
{
int a, b, c;
a=3;
b=4;
c=a*b;
printf("Answer is %d",c);
}

Output
Answer is 12

Now let’s try to understand this program.

1. First two statements are same as above program. In the third statement I have written

int a, b, c;

Here int is the keyword for integer and a, b and c are the integer variables. So they can only store
integer values.

2. In the next two statements I have written

a=3;
b=4;

In these statements we are storing the values 3 and 4 in a and b variables respectively.

3. In the next statement

c=a*b;

We are multiplying the values in a and b, and storing them in the variable c.

5. Now in the last statement we are printing the value which is in c.


o A new thing %d (int),which we have used in this program.
o It is called format specifier. It usually tell the compiler that it has to print the integer
value on screen which is present in a variable.

8
By
Hare Krishna P.Vemana

Some common format specifies are given below

 %d for integers
 %c for characters
 %f for floating point numbers or real numbers

 The elaborated form of printf() is given below

o printf(“string you want to print ”, variable);

 Suppose we have to print the value in b so we will use the function.

 printf(“%d”,b);

Things to keep in mind

1. Use semicolon at the end of each statement.


2. Type the statements in main program as the way you want them to be executed.
3. Never try to memorise any program. Just try to understand it.
4. Learning programming is all about practical. So start doing practical from now.

scanf() in C
scanf() is used to take data(input) from the user.
Till now we have wrote programs in which we declared variables with some values. But in practice we
need to take/give/read input from users by using scanf().

#include<stdio.h>
 
void main()
{
int a,b,c;
printf("Enter two values to do multiplication");
scanf("%d%d",&a,&b);
c=a*b;
printf("Your answer is %d",c);
}
Now let’s try to understand this program.
1. First two instructions are same like our previous programs.
2. In the third instruction we are declaring three variables of integer(int) type.
3. In the fourth instruction we are printing the statement using printf() function.
4. In the fifth instruction we are taking input from the user through scanf() function.
In this scanf() function we have done two things.
a. We have given the format specifier %d instructed the compiler that we want to input integer value.
b. We have used ampersand (&) which is also called “address of operator”. By using this we
instruct the compiler we want to store that input in that variable (a and b).
Why do we use ampersand operator (&)?
As I have said already it is a “address of operator”. By using this operator we specify the address of
variable to the compiler.
Try making these programs yourself (take values from user)

9
By
Hare Krishna P.Vemana

1. Make a program to add two numbers.


2. Make a program which will convert distance in km to meter.

 DATA-TYPES

 Data-type represents the type, size and range of data values in a program inside a memory.
 C-supports a variety of data-types to handle different type of data values.

char  To store character data values. such as ‘1’ ‘a’ ‘A’ ‘@’
 1 byte ( 8 bits ) with range -128 to 127
int  To Store whole number values such as 327,786,777,123..
 16-bit OS : 2 bytes with range -32768 to 32767
 32-bit OS : 4 bytes with range -2,147,483,648 to
2,147,483,647
float  To store Real number values(decimals).such as
123.45,99.99
 4 bytes with range 10-38 to 1038 with 7 digits of precision
double  8 bytes with range 10-308 to 10308 with 15 digits of
precision

10
By
Hare Krishna P.Vemana

void  generic pointer, used to indicate no function parameters etc.

There are 2 types of qualifiers


 Sign qualifier- signed & unsigned
 Size qualifier- short & long

 The signed and unsigned modifiers may be applied to types char and int and will simply
change the range of possible values.
 For example an unsigned char has a range of 0 to 255, all positive, as opposed to a signed
char which has a range of -128 to 127. An unsigned integer on a 16-bit system has a range of
0 to 65535 as opposed to a signed int which has a range of -32768 to 32767.
Note however that the default for type int or char is signed so that the type signed char is always
equivalent to type char and the type signed int is always equivalent to int.

 The long modifier may be applied to type int and double only.
 A long int will require 4 bytes of storage no matter what operating system is in use and has a
range of -2,147,483,648 to 2,147,483,647.
 A long double will require 10 bytes of storage and will be able to maintain up to 19 digits of
precision.
 The short modifier may be applied only to type int and will give a 2 byte integer independent of
the operating system in use.

Note: Note that the keyword int may be omitted without error so that the type unsigned is the same as
type unsigned int, the type long is equivalent to the type long int, and the type short is equivalent to
the type short int.

C Data types / storage Size Range


char (1 byte) –127 to 127
int (2 bytes) –32,767 to 32,767
float (4 bytes) 1E–37 to 1E+37 with six digits of precision
double (8 bytes) 1E–37 to 1E+37 with ten digits of precision
long double (10 bytes) 1E–37 to 1E+37 with ten digits of precision
long int (4 bytes) –2,147,483,647 to 2,147,483,647
short int (2 bytes) –32,767 to 32,767
unsigned short int (2 bytes) 0 to 65,535
signed short int (2 bytes) –32,767 to 32,767
long long int (8 bytes) –(2power(63) –1) to 2(power)63 –1
signed long int (4 bytes) –2,147,483,647 to 2,147,483,647
unsigned long int (4 bytes) 0 to 4,294,967,295
unsigned long long int (8 bytes) 2(power)64 -1

 Enumeration is a user-defined data type that consists of integral constants.


 To define an enumeration, keyword enum is used.

11
By
Hare Krishna P.Vemana

oenum flag { const1, const2, ..., constN };


 Here, name of the enumeration is flag.
o And, const1, const2,...., constN are values of type flag.
 By default, const1 is 0, const2  is 1 and so on. You can change default values of enum
elements during declaration (if necessary).
 Changing default values of enum example:
o enum suit { club = 0,diamonds = 10,hearts = 20,spades = 3,};

Secondary Data Types:


Array: an array is collection of homogeneous elements which share same name and memory.
Ex int a[3]={55,88,123};
Int a[2][2]={45,32,45,78};

Pointer: A pointer is a variable which holds the address of another variable. Pointers are memory
related variables.
Ex int *p,a;
P=&a;
Structure: A structure is a collection of heterogeneous elements. i.e we can store different types of
elements inside a structure.
Ex struct student
{
int no,
char sname,
float fees
};
Size of a structure is sum of its data elements size, the above structure size is(2+1+4)=7 bytes

Union: the union is similar to structures but in which union elements are stored in same memory
location.
The size of union is it largest data-element size.
union emp
{
int eno;
char name;
float sal;
};

 The size of union is it largest data-element size. Here, float sal has 4 bytes size which is largest among
union. so it will be the size of the union emp

 Review Questions:
o Define data-type?
o Define type-qualifiers in C.
o What is long and short?
o Define signed and unsigned.
o What is enum?

12
By
Hare Krishna P.Vemana

o Write a c-program to input different input values from keyboard and print them.

13
By
Hare Krishna P.Vemana

INTERVIEW TOPIC-WRITE VARIOUS FORMAT SPECIFIERS IN C

Supported data
Format specifier Description
types

char
%c Character
unsigned char

short
Signed unsigned short
%d
Integer int
long

Scientific
float
%e or %E notation of
double
float values

%f Floating point float

Similar as %e float
%g or %G
or %E double

Signed
%hi short
Integer(Short)

Unsigned
%hu unsigned short
Integer(Short)

short
Signed unsigned short
%i
Integer int
long

Signed
%l or %ld or %li long
Integer

%lf Floating point double

%Lf Floating point long double

Unsigned unsigned int


%lu
integer unsigned long

Signed
%lli, %lld long long
Integer

Unsigned
%llu unsigned long long
Integer

short
Octal unsigned short
%o representatio int
n of Integer. unsigned int
long

%p Address of void *
pointer to

14
By
Hare Krishna P.Vemana

void void *

%s String char *

Unsigned unsigned int


%u
Integer unsigned long

short
Hexadecimal
unsigned short
representatio
%x or %X int
n of Unsigned
unsigned int
Integer
long

%n Prints nothing

Prints %
%%
character

15
By
Hare Krishna P.Vemana

C TOKENS
 C tokens, Identifiers and Keywords are the basics in a C program. All are explained in this
page with definition.
C TOKEN:
 C tokens are the basic buildings blocks in C language which are constructed together to write
a C program.
 Each and every smallest individual units of a program are known as tokens.
 C tokens are of six types.
They are,
1. Keywords (eg: int, while,auto),
2. Identifiers (eg: main, total),
3. Constants (eg: 10, 20),
4. Strings (eg: “total”, “hello”),
5. Special symbols (eg: (), {}),
6. Operators (eg: +, /,-,*)
IDENTIFIERS IN C LANGUAGE:
•Each program elements in a C program are given a name called identifiers.
•Names given to identify Variables, functions and arrays are examples for identifiers.
eg. x is a name given to integer variable in above program.
RULES FOR CONSTRUCTING IDENTIFIER NAME IN C:
1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.
KEYWORDS IN C LANGUAGE:
 Keywords are pre-defined, reserved words in a C .
 Each keyword is meant to perform a specific function in a C program.
 Since keywords are referred names for compiler, they can’t be used as variable name.
 C language supports 32 keywords which are given below.

Keywords in C Language
auto double int struct
break else long switch
case enum register  typedef
char extern return union
continue for signed void
do if static  while
default goto sizeof volatile
const float short unsigned

Variables
 In programming, a variable is a container (storage area) to hold data.
 A variable is a name for the memory location.
 To indicate the storage area, each variable should be given a unique name (identifier).
Variable names are just the symbolic representation of a memory location. For example:
 int playerScore = 95;
 Here, playerScore is a variable of integer type. The variable is assigned value: 95.
 The value of a variable can be changed, hence the name 'variable'.
 In C programming, you have to declare a variable before you can use it.

16
By
Hare Krishna P.Vemana

 Rules for naming a variable in C


o A variable name can have letters (both uppercase and lowercase letters), digits and
underscore only.
o The first letter of a variable should be either a letter or an underscore. However, it is
discouraged to start variable name with an underscore. It is because variable name
that starts with an underscore can conflict with system name and may cause error.
o There is no rule on how long a variable can be. However, only the first 31 characters of
a variable are checked by the compiler. So, the first 31 letters of two variables in a
program should be different.
o C is a strongly typed language. What this means it that, the type of a variable cannot
be changed.

Constants

 A constant is a value or an identifier whose value cannot be altered/chanaged in a program.


For example: 1, 2.5, "C programming is easy", etc.
 As mentioned, an identifier also can be defined as a constant.
 const double PI = 3.14
 Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
 Below are the different types of constants you can use in C.
1. Integer constants
 An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
 decimal constant(base 10)
 octal constant(base 8)
 hexadecimal constant(base 16)
For example:
Decimal constants: 0, -9, 22 etc
Octal constants: 021, 077, 033 etc
Hexadecimal constants: 0x7f, 0x2a, 0x521 etc
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.

17
By
Hare Krishna P.Vemana

2. Floating-point constants
 A floating point constant is a numeric constant that has either a fractional form or an exponent
form. For example:
 -2.0
 0.0000234
 -0.22E-5
 Note: E-5 = 10-5

3. Character constants
A character constant is a constant which uses single quotation around characters. For example: 'a', 'l',
'm', 'F'
4. Escape Sequences
 Sometimes, it is necessary to use characters which cannot be typed or has special meaning in
C programming. For example: newline(enter), tab, question mark etc. In order to use these
characters, escape sequence is used.

 For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way
the characters are interpreted by the compiler.

Escape Sequences
Escape
Character
Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\' Single quotation mark

\" Double quotation mark


\? Question mark
\0 Null character
5. String constants
 String constants are the constants which are enclosed in a pair of double-quote marks.
 For example:
 "good" //string constant
 "" //null string constant
 " " //string constant of six white space
 "x" //string constant having single character.
 "Earth is round\n" //prints string with newline
6. Enumeration constants
 Keyword enum is used to define enumeration types.
 For example: enum color {yellow, green, black, white};
 Here, color is a variable and yellow, green, black and white are the enumeration constants
having value 0, 1, 2 and 3 respectively.

18
By
Hare Krishna P.Vemana

Operators in C Language
 C language supports a rich set of built-in operators. An operator is a symbol that tells the
compiler to perform certain mathematical or logical manipulations. Operators are used in
program to manipulate data and variables.
 C operators can be classified into following types,
 Arithmetic operators
 Relation operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Special operators

Arithmetic operators
C supports all the basic arithmetic operators. The following table shows all the basic arithmetic
operators.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
++ Unary-Increment operator increases integer value by one
-- Unary-Decrement operator decreases integer value by one

Relation operators
The following table shows all relation operators supported by C.
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand

Logical operators
C language supports following 3 logical operators. Suppose a=1 and b=0,

Operator Description Example


&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false

Bitwise operators
Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of
bitsfrom right to left. Bitwise operators are not applied to float or double.
Operator Description

19
By
Hare Krishna P.Vemana

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted and
the right operand specifies the number of positions that the bits in the value are to be shifted. Both
operands have the same precedence.
Example :
a = 0001000
b= 2
a << b = 0100000
a >> b = 0000010

Assignment Operators
Assignment operators supported by C language are as follows.

Operator Description Example


assigns values from right side operands to left side
= a=b
operand
adds right operand to the left operand and assign the
+= a+=b is same as a=a+b
result to left
subtracts right operand from the left operand and assign
-= a-=b is same as a=a-b
the result to left operand
mutiply left operand with the right operand and assign
*= a*=b is same as a=a*b
the result to left operand
divides left operand with the right operand and assign the
/= a/=b is same as a=a/b
result to left operand
calculate modulus using two operands and assign the
%= a%=b is same as a=a%b
result to left operand

Conditional operator
It is also known as ternary operator and used to evaluate conditional expression.
epr1 ? expr2 : expr3
If epr1 Condition is true ? Then value expr2 : Otherwise value expr3

Special operator
Operator Description Example
sizeof Returns the size of an variable sizeof(x) return size of the variable x
& Returns the address of an variable &x ; return address of the variable x
* Pointer to a variable *x ; will be pointer to a variable x

20
By
Hare Krishna P.Vemana

Increment &Decrement operators:


 Increment operators are used to increase the value of the variable by one
 and decrement operators are used to decrease the value of the variable by one in C programs.
 Syntax:
o Increment operator: ++var_name; (or) var_name++;
o Decrement operator: – -var_name; (or) var_name – -;
 Example:
o Increment operator : ++ i ; i ++ ;
o Decrement operator : – – i ; i – – ;
Operator Operator/Description

Pre increment operator (++i) value of i is incremented before assigning it to the


variable i

Post increment operator (i++) value of i is incremented after assigning it to the


variable i

Pre decrement operator (--i) value of i is decremented before assigning it to the


variable i

Post decrement operator (i--) value of i is decremented after assigning it to variable


i

Pre Increment Operator

 Pre-increment operator is used to increment the value of variable before using in the
expression.
 In the Pre-Increment value is first incremented and then used inside the expression.
 b = ++y;
 In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6
because the value of ‘y’ gets modified before using it in a expression.

Post Increment Operator

 Post-increment operator is used to increment the value of variable as soon as after executing
expression completely in which post increment is used.
 In the Post-Increment value is first used in a expression and then incremented.
 b = x++;
 In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5
because old value of ‘x’ is used.

21
By
Hare Krishna P.Vemana

Cast operator/ type casting


 Cast operator can be used to explicitly convert the value of an expression to a different data
type. To do so, the name of the data type to which the conversion is to be made is enclosed in
parenthesis and placed directly to the left of the expression whose value is to be converted.
 (data type) expression
 Example:inti=(int)3.14;
float j= (float)10/2.
 Note :to avoid data loss convert a small data-type into its next larger data-type as
 Byteintfloatdouble

Storage classes
 Storage class represents variables life-time and scope
 Storage class specifies in C language tells the compiler
 where to store a variable,
 how to store the variable,
 what is the initial value of the variable and
 Life time of the variable.
Syntax:
storage_specifier data_type variable _name;
 here,Storage_specifier is auto,extern,static or register and
 data-type is any valid data type such as int ,float ,char..
 and variable name is valid name of the variable

TYPES OF STORAGE CLASS SPECIFIERS IN C:

There are 4 storage class specifiers available in C language. They are,


1. auto
2. extern
3. static
4. register
Storage Specifier  Description
auto  Storage place: CPUMemory
Initial/default value: Garbage value
Scope: local
Life: Within the function only.
extern Storage place: CPU memory
Initial/default value: Zero
Scope: Global
Life: Till the end of the main program.
Variable definition might be anywhere in the C program.
static Storage place: CPU memory
Initial/default value: Zero
Scope: local
Life: Retains the value of the variable between different
function calls.
register Storage place: Register memory
Initial/default value: Garbage value
Scope: local
Life: Within the function only.

22
By
Hare Krishna P.Vemana

NOTE:
 For faster access of a variable, it is better to go for register specifiers rather than auto
specifiers.
 Because, register variables are stored in register memory whereas auto variables are stored in
main CPU memory.
 Only few variables can be stored in register memory. So, we can use variables as register that
are used very often in a C program.

1. EXAMPLE PROGRAM FOR AUTO VARIABLE IN C:

 The scope of this auto variable is within the function only.


 It is equivalent to local variable.
 All local variables are auto variables by default.
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}

void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
i++;
}

0000

2. EXAMPLE PROGRAM FOR “STATIC VARIABLE” IN C:


Static variables retain the value of the variable between different function calls.
//C static example
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;

23
By
Hare Krishna P.Vemana

printf ( "%d ", i ) ;


i++;
}
OUTPUT:

0123

3. EXAMPLE PROGRAM FOR “EXTERN VARIABLE” IN C:

The scope of this extern variable is throughout the main program. It is equivalent to global variable.
Definition for extern variable might be anywhere in the C program.

#include<stdio.h>

int x = 10 ;
int main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;
OUTPUT:

The value of x is 10
The value of y is 50

4. EXAMPLE PROGRAM FOR “REGISTER VARIABLE” IN C:


Register variables are also local variables, but stored in register memory. Whereas, auto variables are
stored in main CPU memory.
Register variables will be accessed very faster than the normal variables since they are stored in
register memory rather than main memory.
But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64
bits)
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);

24
By
Hare Krishna P.Vemana

}
return 0;
}
OUTPUT:

value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

25

You might also like