You are on page 1of 74

C Programming all concepts in Depth

Why C is known as mother language ?

It can be defined by the following ways:

1. Mother language
2. System programming language
3. Procedure-oriented programming language
4. Structured programming language
5. Mid level programming language

1) C as a mother language
C language is considered as the mother language of all the modern
languages because most of the compilers, JVMs, Kernals etc. are
written in C language and most of languages follows c syntax e.g. C++,
Java etc.

It provides the core concepts like array, functions, file handling etc. that
is being used in many languages like C++, java, C# etc.

2) C as a system programming language


A system programming language is used to create system softwares. C
language is a system programming language because it can be used to do
low level programming (e.g. driver and kernel). It is generally used to
create hardware devices, OS, drivers, kernels etc. For example, linux kernel
is written in C.

It can’t be used in internet programming like java, .net, php etc.


3) C as a procedural language
A procedure is known as function, method, routine, subroutine etc. A
procedural language refers a series of steps or procedures for the
program to solve the problem.

A procedural language breaks the program into functions, data structures


etc.

C is a procedural language. In C, variables and function prototypes must be


declared before being used.

4) C as a structured programming language


A structured programming language is a subset of procedural
language. Structure means to break a program into parts or blocks so
that it may be easy to understand.

In C language, we break the program into parts using functions. It makes


the program easier to understand and modify.

5) C as a mid-level programming language


C is considered as a middle level language because it supports the feature of
both low-level and high level language. C language program is converted into
assembly code, supports pointer arithmetic (low level), but it is machine
independent (feature of high level).

Low level language is specific to one machine i.e. machine dependent. It is


machine dependent, fast to run. But it is not easy to understand.

High Level language is not specific to one machine i.e. machine independent. It is
easy to understand.
History of C Language

History of C language is interesting to know. Here we are going to discuss


brief history of c language.

C programming language was developed in 1972 by Dennis Ritchie at bell


laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.

Dennis Ritchie is known as the founder of c language.

It was developed to overcome the problems of previous languages such as


B, BCPL etc.

Initially, C language was developed to be used in UNIX operating system.


It inherits many features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C


language.

Language Year Developed By

Algol 1960 International Group

BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee


ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Features of C
C is the widely used language. It provides a lot of features that are given below.

 Simple

 Portability

 Powerful

 Platform dependent

 Structure oriented

 Case sensitive

 Compiler based
 Modularity

 Middle level language

 Syntax based language

 Use of Pointers

1) Simple
C is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed in many machines with
little bit or no change. But it is not platform-independent

3) Mid-level programming language


C is also used to do low level programming. It is used to develop system
applications such as kernel, driver etc. It also supports the feature of high level
language. That is why it is known as mid-level language.

4) Structured programming language


C is a structured programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand and modify.

5) Rich Library
C provides a lot of inbuilt functions that makes the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can
free the allocated memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C language is fast.

8) Platform dependent
A language is said to be platform dependent whenever the program is execute in the
same operating system where that was developed and compiled but not run and
execute on other operating system. C is platform dependent programming language.

Note: .obj file of C program is platform dependent.


9)Portability
It is the concept of carrying the instruction from one system to another system. In C
Language .Cfile contain source code, we can edit also this code. .exe file contain
application, only we can execute this file. When we write and compile any C program on
window operating system that program easily run on other window based system.

When we can copy .exe file to any other computer which contain window operating
system then it works properly, because the native code of application an operating
system is same. But this exe file is not execute on other operation system

8) Pointer
C provides the feature of pointers. We can directly interact with the memory by
using the pointers. We can use pointers for memory, structures, functions,
array etc.

9) Recursion
In c, we can call the function within the function. It provides code reusability
for every function.

10) Extensible
C language is extensible because it can easily adopt new features.

Installation of TC

Installation of TC is very simple just download turbo C or C++ and run .exe files

When you install the Turbo C compiler on your system, then TC directory is created on the hard disk and various sub directories

such as INCLUDE, and LIB etc. are created under TC.

 INCLUDE :Contain the header files of C.

 LIB: Contain the library files of C.

 BGI: Contain Graphics related files.

 BIN: Contain .exe, .obj etc files.

Turbo C For Window(xp, 7, 8)

Previously Turbo C are not work properly on Window 7 and its above versions. Here you can get Turbo C for Window 7 and its

above versions.

 Turbo C For Window 7 and 8 Download

Source Code Vs Object Code


Difference between source code and object code .:

Source Code

 Source code is in the form of Text form.

 Source code is Human Readable Code.

 Source code is Generated by Human or Programmer.

 Source code is receive Compiler as a Input.

Object Code

 Object Code is in the form of Binary Numbers.

 Object Code is in Machine Readable formats.

 Object Code is Generated by Compiler.

 Object Code is Generated by Compiler as a Output.

Compiler in C

A compiler is system software which converts programming language code into binary format in single steps. In other words

Compiler is a system software which can take input from other any programming language and convert it into lower level machine

dependent language.

Interpreter

It is system software which is used to convert programming language code into binary format in step by step process.

Assembler
An assembler is system software which is used to convert the assembly language instruction into binary format in step by step

process. An assembler is system software which is used to convert the assembly language instruction into binary format.

Compiler Vs Interpreter

No Compiler Interpreter

Interpreter
takes Single
1 Compiler takes Entire program as input at a time. instruction as
input at a
time.

Intermediate Object code is generated

No
Intermediate
2
Object code is
generated

It execute
conditional
control
3 It execute conditional control statements fastly.
statements
slower than
Compiler

Less memory
4 More memory is required.
is required.

Every time
higher level
program is
5 Program need not to be compiled every time
converted into
lower level
program

It display error
after each
6 It display error after entire program is checked instruction
interpreted (if
any)

Example:
7 Example: C
BASIC

First C Program -
Before starting the abcd of C language, you need to learn how to write, compile and run the first c
program. To write the first c program, open the C console and write the following code:
Different parts of C program

 Pre-processor

 Header file

 Function

 Variables

 Statements & expressions

 Comments

Pre-processor- #include is the first word of any C program. It is also known as a pre-processor. The task of a
pre-processor is to initialize the environment of the program, i.e to link the program with the header files required.
So, when we say #include <stdio.h> it is to inform the compiler to include the stdio.h header file to the program
before executing it.
Header file - A Header file is a collection of built-in(readymade) functions, which we can directly use in our
program. Header files contain definitions of the functions which can be incorporated into any C program by using pre-
processor #include statement with the header file. Standard header files are provided with each compiler, and covers
a range of areas like string handling, mathematical functions, data conversion, printing and reading of variables.
With time, you will have a clear picture of what header files are, as of now consider as a readymade piece of function
which comes packaged with the C language and you can use them without worrying about how they work, all you
have to do is include the header file in your program.
To use any of the standard functions, the appropriate header file must be included. This is done at the beginning of
the C source file.
For example, to use the printf() function in a program, which is used to display anything on the screen, the
line #include <stdio.h> is required because the header file stdio.h contains the printf() function. All header files
will have an extension .h

main() function:
main() function is a function that must be there in every C program. Everything inside this function in a C
program will be executed. In the above example, int written before the main() function is the return
type of main() function. we will discuss about it in detail later. The curly braces { } just after
the main() function encloses the body of main() function.
We will learn what functions are in upcoming tutorials.
Comments:
We can add comments in our program to describe what we are doing in the program. These comments
are ignored by the compiler and are not executed.
To add a single line comment, start it by adding two forward slashses // followed by the comment.
To add multiline comment, enclode it between /* .... */, just like in the program above.
NOTE –1. Comments are not case sensitive.

2. Nested Comments are not possible, that means comments within comments.
Example

void main()

/*

/* comments */

*/

Return statement - return 0:


A return statement is just meant to define the end of any C program.
The 0 value is used for successful execution and 1 for unsuccessful execution
All the C programs can be written and edited in normal text editors like Notepad or Notepad++ and must
be saved with a file name with extension as .c
If you do not add the extension .c then the compiler will not recognise it as a C language program file.

Flow of C Program
The C program follows many steps in execution. To understand the flow of C program well, let us see a simple
program first.

File: simple.c

#include <stdio.h>
int main(){
printf("Hello C Language"); return 0;

Execution Flow:
Let's try to understand the flow of above program by the figure given below.

1) C program (source code) is sent to preprocessor first. The preprocessor is


responsible to convert preprocessor directives into their respective values. The
preprocessor generates an expanded source code.

WHAT IS PREPROCESSOR DIRECTIVES :

2) Expanded source code is sent to compiler which compiles the code and converts
it into assembly code.

WHAT IS ASSEMBLY CODE –

Machine
or object
code

Assembler
3) The assembly code is sent to assembler which assembles the code and converts
it into object code. Now a simple.obj file is generated.

4) The object code is sent to linker which links it to the library such as header files.
Then it is converted into executable code. A simple.exe file is generated.

5) The executable code is sent to loader which loads it into memory and then it is
executed. After execution, output is sent to console.
Moduler Approach:
It is better to divide a large system into modules. In terms of programming, module is logically a welldefined
part of program. Each module is a separate part of the program. It is easy to modify a program
written with modular approach because changes in one module don't affect other modules of program.
It is also easy to check bugs in the program in module level programming.

Programming Languages:
The programming languages can be classified into
Two types-
1. High level languages
2. Low level languages

High-Level Languages:
High-level languages are designed keeping in mind the features of portability i.e. these languages are
machine independent. These are English like languages, so it is easy to write and understand the programs
of high-level language. While programming in a high level languag\e, the programmer is not concerned
with the low level details, and so the whole attention can be paid to the logic of the problem being
solved. For translating a high-level language program into machine language, compiler or interpreter is
used. Every language has its own compiler or interpreter. Some languages in this category are- FORTRAN,
COBOL, BASIC, Pascal etc.

Low level languages:


The languages in this category are the Machine level language and Assembly language.

Machine Level Language:


Computers can understand only digital signals, which are in binary digits i.e. 0 and 1. So the instructiom
given to the computer can be only in binary codes. The machine language consists of instructions that
are in binary 0 or 1. Computers can understand only machine level language.
Writing a program in machine level language is a difficult task because it is not easy for programming
to write instructions in binary code. A machine level language program is error-prone and its maintenance
is very difficult. Furthermore machine language programs are not portable. Every computer has its own machine
language instructions, so the programs written for one computer are not valid for other computers.

Assembly Language:
The modified form Of machine level language called assembly language. In assembly language instructions are
given in English
Like words, such as MOV, ADD, and SUB etc. So it is easier to write and understand assembly programs,
Since a computer can understand only machine level language, hence assembly language program must
be translated into machine language. The translator that is used for translating is called "assembler"
Although writing programs in assembly language is a bit easier, but still the programmer has to know
all the low level details related with the hardware of a computer. In assembly language, data is stored
in computer registers and each computer has different set of registers. Hence the assembly language
program is also not portable. Since the low level languages are related with the hardware, hence the
execution of a low-level program is faster.

Translators :
We know that computers can understand only machine level language, which is in binary 1 or O. It
Is difficult to write and maintain programs in machine level language. So the need to convert
the code of high-level and low-level languages into machine level language and translators are used for
this purpose.
The three types of translators used are-

• Assembler
• Compiler
• Interpreter

Assembler: Assembler is used for converting the code of low-level language (assembly language) into
machine level Language.

Compilers and interpreters are used to convert the code of high-level language into machine language.

Compiler and interpreter perform the same task. But difference in their working. A compiler searches all the
errors of program and lists them. If the program is error free then it converts the code of program into machine

code.

An interpreter checks the errors of program statement by statement. After checking one statement, it
converts that statement into machine code and then executes that statement. This process continues
until the last statement of program or an errorless statement occurs.

1. The high level program is known as source program.


2. Machine level program is known as object program.
What are Keywords in C?
Keywords are preserved words that have special meaning in C language. The meaning of C language

keywords has already been described to the C compiler. These meaning cannot be changed. Thus, keywords

cannot be used as variable names. There are total 32 keywords in C language.

auto double int struct

break else long switch

case enum register typedef

const extern return union

char float short unsigned

continue for signed volatile

default goto sizeof void

do if static while You can think of an Identifier int


x to be a variable's name, but it can
also be a function's name int x()
{ } and still be an identifier.
Just like Obama is a name of a
person, but also the name of a
foundation.

What are Identifiers?


In C language identifiers are the names given to variables, constants, (functions) and user-define data. These identifier are defined against a set of
rules.

A variable is a name of memory location. It is used to store data. Its value can be changed and it can be reused many times.

NOTE (1.
If no input values are assigned by the user than system will gives a default value called
garbage value.

Example - a

Rules for an Identifier

1. An Identifier can only have alphanumeric characters(a-z , A-Z , 0-9) and underscore(_).
2. The first character of an identifier can only contain alphabet(a-z , A-Z) or underscore (_).
3. Identifiers are also case sensitive in C. For example name and Name are two different identifiers in C.
4. Keywords are not allowed to be used as Identifiers.
5. No special characters, such as semicolon, period, whitespaces, slash or comma are permitted to be used in or as

6. Maximum length of variable is 8 characters depend on compiler and operation system. Ansi

compiler recognize 31.

7. Every variable name always should exist in the left hand side of assignment operator (invalid ->

10=a; valid -> a=10;).

Identifier.

Example -

Valid variable names:

1. int a;
2. int _ab;
3. int a30;

Inalid variable names:


1. int 2; (keyword)
2. int a b;
3. int long;

Types of Variables in C

There are many types of variables in c:

1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable

Local Variable

A variable that is declared inside the function or block is called local variable.

It must be declared at the start of the block.

1. void function1(){
2. int x=10;//local variable
3. }

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called global variable. Any function can
change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

1. int value=20;//global variable


2. void function1(){
3. int x=10;//local variable
4. }

Static Variable

A variable that is declared with static keyword is called static variable.

It retains its value between multiple function calls.

1. void function1(){
2. int x=10;//local variable
3. static int y=10;//static variable
4. x=x+1;
5. y=y+1;
6. printf("%d,%d",x,y);
7. }

If you call this function many times, local variable will print the same value for each function call
e.g, 11,11,11 and so on. But static variable will print the incremented value in each function call
e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that is declared inside the block, are automatic variables by default. By we can
explicitly declare automatic variable using auto keyword.

1. void main(){
2. int x=10;//local variable (also automatic)
3. auto int y=20;//automatic variable
4. }

External Variable

We can share a variable in multiple C source files by using external variable. To declare a external
variable, you need to use extern keyword.

myfile.h

1. extern int x=10;//external variable (also global)


program1.c

1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue(){
4. printf("Global variable: %d", global_variable);
5. }

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 a certain mathematical or logical manipulation. Operators are used in programs to manipulate
data and variables.
C operators can be classified into following types:

 Arithmetic operators
 Relational 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 denominator

% remainder of division

++ Increment operator - increases integer value by one

-- Decrement operator - decreases integer value by one

Relational 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 How to use (?)


Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bits from right
to left. Bitwise operators are not applied to float or double(These are datatypes, we will learn about them in the next
tutorial).

Operator Description

& 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 operator, 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 have 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 operand a=b

+= adds right operand to the left operand and assign the result to a+=b is same as
left a=a+b

-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b

*= mutiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b

/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b

%= calculate modulus using two operands and assign the result to a%=b is same as
left operand a=a%b

Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ? : Operator

It is actually the if condition that we use in C language decision making, but using conditional operator, we turn
the if condition statement into a short and simple operator.
The syntax of a conditional operator is :
expression 1 ? expression 2: expression 3
Explanation:

 The question mark "?" in the syntax represents the if part.

 The first expression (expression 1) generally returns either true or false, based on which it is decided whether (expression 2) will be executed or

(expression 3)
 If (expression 1) returns true then the expression on the left side of " : " i.e (expression 2) is executed.
 If (expression 1) returns false then the expression on the right side of " : " i.e (expression 3) is executed.

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


Data Types in C

A data type specifies the type of data that a variable can store such as integer, floating, character
etc.

There are 4 types of data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed
and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating system.

Let's see the basic data types. Its size is given according to 32 bit architecture.

Data Types Memory Size Range


char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Data type determines the type of data a variable will hold. If a variable x is declared as int. it means x
can hold only integer values. Every variable which is used in the program must be declared as what data-
type it is.
Types of Constant in C

It is an identifier whose value can not be changed at the execution time of program. In general constant can be used to represent

as fixed values in a C program. Constants are classified into following types.


If any single character (alphabet or numeric or special symbol) is enclosed between single cotes ' ' known as single character constant.

If set of characters are enclosed between double cotes " " known as string character constant.

Declare constant

const keyword are used for declare a constant.


Syntax

const int height = 100;

Example

#include<stdio.h>

#include<conio.h>

void main()

const int a=10;

printf("%d",a);

a=20; // gives error you can't modify const

getch();
}

Precedence of Operators in C : First know about binary and tiercry


The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to left.

Let's understand the precedence by the example given below:

1. int value=10+20*10;

The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive
operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

Escape Sequence in C
Escape Sequence Meaning

Backslash \a Alarm or
Beep
\b Backspace

\f Form Feed

\n New Line

\r Carriage
Return

\t Tab
(Horizontal)

\v Vertical Tab

\\ Backslash

\' Single
Quote

\" Double
Quote

Escape Sequence Example

1. #include<stdio.h>
2. int main(){
3. int number=50;
4. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");
5. return 0;

} Output:

You
are
learning
'c' language
"Do you know C language"
6.

\? Question
Mark

\nnn octal
number

\xhh hexadecimal
number
\0 Null

List of Constants in C

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint" etc.


only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits).
Register variable

Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in

main CPU memory.

Advantages: The register variables are faster than remaining variables, because register variable are stored in

register memory not in main memory..

Limitation: But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64

bits).

Example

void main()

register int a=10;

++a;

printf("\n value of a: %d",a);

printf("Enter a value:");

scanf("%d",&a);

--a;

printf("\n value of a: %d",a);

getch();

Output

Input data is 50.

Error, must take address of a memory location.

Explanation

 In scanf() function if address is provided for the register variable then it will give error, if addition is not provided it normally work.

 Register storage class specifier just recommended to the compiler to hold the variable in CPU register if the memory is available or else stored in

stack area of data segment.

Storage classes in C
In C language, each variable has a storage class which decides the following things:

 scope i.e where the value of the variable would be available inside a program.

 default initial value i.e if we do not explicitly initialize that variable, what will be its default initial value.
 lifetime of that variable i.e for how long will that variable exist.

The following storage classes are most oftenly used in C programming,

1. Automatic variables

2. External variables

3. Static variables
4. Register variables

Automatic variables: auto


Scope: Variable defined with auto storage class are local to the function block inside which they are defined.
Default Initial Value: Any random value i.e garbage value.
Lifetime: Till the end of the function/method block where the variable is defined.
A variable declared inside a function without any storage class specification, is by default an automatic variable. They are created when a function is
called and are destroyed automaticallywhen the function's execution is completed. Automatic variables can also be called local variablesbecause
they are local to a function. By default they are assigned garbage value by the compiler.

#include<stdio.h>

void main()
{
int detail;
// or
auto int details; //Both are same
}

External or Global variable


Scope: Global i.e everywhere in the program. These variables are not bound by any function, they are available everywhere.
Default initial value: 0(zero).
Lifetime: Till the program doesn't finish its execution, you can access global variables.
A variable that is declared outside any function is a Global Variable. Global variables remain available throughout the program execution. By default,
initial value of the Global variable is 0(zero). One important thing to remember about global variable is that their values can be changed by any function
in the program.

#include<stdio.h>

int number; // global variable

void main()
{
number = 10;
printf("I am in main function. My value is %d\n", number);
fun1(); //function calling, discussed in next topic
fun2(); //function calling, discussed in next topic
}

/* This is function 1 */
fun1()
{
number = 20;
printf("I am in function fun1. My value is %d", number);
}
/* This is function 1 */
fun2()
{
printf("\nI am in function fun2. My value is %d", number);
}

I am in function main. My value is 10

I am in function fun1. My value is 20

I am in function fun2. My value is 20

Here the global variable number is available to all three functions and thus, if one function changes the value of the variable, it gets changed in every
function.
Note: Declaring the storage class as global or external for all the variables in a program can waste a lot of memory space because these variables
have a lifetime till the end of the program. Thus, variables, which are not needed till the end of the program, will still occupy the memory and thus,
memory will be wasted.

extern keyword
The extern keyword is used with a variable to inform the compiler that this variable is declared somewhere else. The extern declaration does not
allocate storage for variables.
Problem when extern is not used

int main()
{
a = 10; //Error: cannot find definition of variable 'a'
printf("%d", a);
}

Example using extern in same file

int main()
{
extern int x; //informs the compiler that it is defined somewhere else
x = 10;
printf("%d", x);
}
int x; //Global variable x

Static variables
Scope: Local to the block in which the variable is defined
Default initial value: 0(Zero).
Lifetime: Till the whole program doesn't finish its execution.
A static variable tells the compiler to persist/save the variable until the end of program. Instead of creating and destroying a variable every time when
it comes into and goes out of scope, staticvariable is initialized only once and remains into existence till the end of the program. A staticvariable can
either be internal or external depending upon the place of declaration. Scope of internal static variable remains inside the function in which it is
defined. External static variables remain restricted to scope of file in which they are declared.
They are assigned 0 (zero) as default value by the compiler.

#include<stdio.h>

void test(); //Function declaration (discussed in next topic)

int main()
{
test();
test();
test();
}

void test()
{
static int a = 0; //a static variable
a = a + 1;
printf("%d\t",a);
}

1 2 3

Register variable
Scope: Local to the function in which it is declared.
Default initial value: Any random value i.e garbage value
Lifetime: Till the end of function/method block, in which the variable is defined.
Register variables inform the compiler to store the variable in CPU register instead of memory. Register variables have faster accessibility than a
normal variable. Generally, the frequently used variables are kept in registers. But only a few variables can be placed inside registers. One application
of register storage class can be in using loops, where the variable gets used a number of times in the program, in a very short span of time.
NOTE: We can never get the address of such variables.
Syntax :

register int number;


Note: Even though we have declared the storage class of our variable number as register, we cannot surely say that the value of the variable would be
stored in a register. This is because the number of registers in a CPU are limited. Also, CPU registers are meant to do a lot of important work. Thus,
sometimes they may not be free. In such scenario, the variable works as if its storage class is auto.

Which storage class should be used and when


To improve the speed of execution of the program and to carefully use the memory space occupied by the variables, following points should be kept in
mind while using storage classes:
 We should use static storage class only when we want the value of the variable to remain same every time we call it using different function calls.

 We should use register storage class only for those variables that are used in our program very oftenly. CPU registers are limited and thus should

be used carefully.

 We should use external or global storage class only for those variables that are being used by almost all the functions in the program.

 If we do not have the purpose of any of the above mentioned storage classes, then we should use the automatic storage class.

Function

A function is a group of statements that together perform a specific task. Every C program has at least one function, which is

main().

Why use function ?

Function are used for divide a large code into module, due to this we can easily debug and maintain the code. For

example if we write a calculator programs at that time we can write every logic in a separate function (For addition

sum(), for subtraction sub()). Any function can be called many times.
Advantage of Function

 Code Re-usability

 Develop an application in module format.

 Easily to debug the program.

 Code optimization: No need to write lot of code.

Type of Function

There are two type of function in C Language. They are;

 Library function or pre-define function.

 User defined function.

Library function

Library functions are those which are predefined in C compiler. The implementation part of pre-defined functions is

available in library files that are .lib/.obj files. .lib or .obj files are contained pre-compiled code. printf(), scanf(),

clrscr(), pow() etc. are pre-defined functions.

Limitations of Library function

 All predefined function are contained limited task only that is for what purpose function is designed

for same purpose it should be used.


 As a programmer we do not having any controls on predefined function implementation part is there

in machine readable format.

 In implementation whenever a predefined function is not supporting user requirement then go for

user defined function.

User defined function

These functions are created by programmer according to their requirement for example suppose you want to

create a function for add two number then you create a function with name sum() this type of function is called user

defined function.

calling a function.

When we call any function control goes to function body and execute entire code. For call any function just write name of function and if any parameter is

required then pass parameter.

Example calling of Function

#include<stdio.h>

#include<conio.h>

void sum(); // declaring a function

clrsct();

int a=10,b=20, c;

void sum() // defining function

c=a+b;

printf("Sum: %d", c);

void main()
{

sum(); // calling function

Output

Sum: 30

Decision making in C
Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain
specified conditions are met. C language handles decision-making by supporting the following statements,

 if statement

 switch statement

 conditional operator statement (? : operator)

 goto statement

Decision making with if statement


The if statement may be implemented in different forms depending on the complexity of conditions to be tested. The different forms are,

1. Simple if statement

2. if....else statement

3. Nested if....else statement


4. Using else if statement

Simple if statement
The general form of a simple if statement is,
if(expression)
{
statement inside;
}
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-inside is skipped and only the statement-outside is
executed.
Example:

#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}

x is greater than y

if...else statement
The general form of a simple if...else statement is,

if(expression)
{
statement block1;
}
else
{
statement block2;
}
If the expression is true, the statement-block1 is executed, else statement-block1 is skipped and statement-block2 is executed.
Example:

#include <stdio.h>

void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}

y is greater than x

Nested if....else statement


The general form of a nested if...else statement is,

if( expression )
{
if( expression1 )
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block3;
}
if expression is false then statement-block3 will be executed, otherwise the execution continues and enters inside the first if to perform the check for
the next if block, where if expression 1 is true the statement-block1 is executed otherwise statement-block2 is executed.
Example:

#include <stdio.h>

void main( )
{
int a, b, c;
printf("Enter 3 numbers...");
scanf("%d%d%d",&a, &b, &c);
if(a > b)
{
if(a > c)
{
printf("a is the greatest");
}
else
{
printf("c is the greatest");
}
}
else
{
if(b > c)
{
printf("b is the greatest");
}
else
{
printf("c is the greatest");
}
}
}

else if ladder
The general form of else-if ladder is,

if(expression1)
{
statement block1;
}
else if(expression2)
{
statement block2;
}
else if(expression3 )
{
statement block3;
}
else
default statement;
The expression is tested from the top(of the ladder) downwards. As soon as a true condition is found, the statement associated with it is executed.
Example :
#include <stdio.h>

void main( )
{
int a;
printf("Enter a number...");
scanf("%d", &a);
if(a%5 == 0 && a%8 == 0)
{
printf("Divisible by both 5 and 8");
}
else if(a%8 == 0)
{
printf("Divisible by 8");
}
else if(a%5 == 0)
{
printf("Divisible by 5");
}
else
{
printf("Divisible by none");
}
}

Points to Remember

1. In if statement, a single statement can be included without enclosing it into curly braces { ... }

2. int a = 5;
3. if(a > 4)
printf("success");

No curly braces are required in the above case, but if we have more than one statement inside ifcondition, then we must enclose them inside curly

braces.

4. == must be used for comparison in the expression of if condition, if you use = the expression will always return true, because it performs

assignment not comparison.


5. Other than 0(zero), all other values are considered as true.

6. if(27)
printf("hello");

In above example, hello will be printed.

Switch statement in C
When you want to solve multiple option type problems, for example: Menu like program, where one value is
associated with each option and you need to choose only one at a time, then, switchstatement is used.
Switch statement is a control statement that allows us to choose only one choice among the many given choices. The
expression in switch evaluates to return an integral value, which is then compared to the values present in different
cases. It executes that block of code which matches the case value. If there is no match, then default block is
executed(if present). The general form of switch statement is,

switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
Rules for using switch statement

1. The expression (after switch keyword) must yield an integer value i.e the expression should be an integer or a variable or an expression that

evaluates to an integer.
2. The case label values must be unique.

3. The case label must end with a colon(:)


4. The next line, after the case statement, can be any valid C statement.

Points to Remember

1. We don't use those expressions to evaluate switch case, which may return floating point values or strings or characters.

2. break statements are used to exit the switch block. It isn't necessary to use break after each block, but if you do not use it, then all the consecutive

blocks of code will get executed after the matching block.

3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
11. printf("C");
12. break;
}

A B C

The output was supposed to be only A because only the first case matches, but as there is no break statement after that block, the next blocks are

executed too, until it a break statement in encountered or the execution reaches the end of the switch block.

13. default case is executed when none of the mentioned case matches the switch expression. The default case can be placed anywhere in

the switch case. Even if we don't include the default case, switch statement works.

14. Nesting of switch statements are allowed, which means you can have switch statements inside another switch block. However,
nested switch statements should be avoided as it makes the program more complex and less readable.

Example of switch statement


#include<stdio.h>
void main( )
{
int a, b, c, choice;
while(choice != 3)
{
/* Printing the available options */
printf("\n 1. Press 1 for addition");
printf("\n 2. Press 2 for subtraction");
printf("\n Enter your choice");
/* Taking users input */
scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}

Difference between switch and if

 if statements can evaluate float conditions. switch statements cannot evaluate floatconditions.

 if statement can evaluate relational operators. switch statement cannot evaluate relational operators i.e they are not allowed in switch statement.
How to use Loops in C
In any programming language including C, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

How it Works
The below diagram depicts a loop execution,

As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the execution breaks out of the loop. After the
loop is successfully executed the execution again starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After every execution of the loop
body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not
executed, and execution breaks out of the loop.

Types of Loop
There are 3 types of Loop in C language, namely:

1. while loop

2. for loop

3. do while loop
while loop
while loop can be addressed as an entry control loop. It is completed in 3 steps.

 Variable initialization.(e.g int x = 0;)

 condition(e.g while(x <= 10))

 Variable increment or decrement ( x++ or x-- or x = x + 2 )

Syntax :

variable initialization;
while(condition)
{
statements;
variable increment or decrement;
}

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}

1 2 3 4 5 6 7 8 9 10

for loop
for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. We can say it is an open ended loop.. General
format is,

for(initialization; condition; increment/decrement)


{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the condition. In this loop we can have more than one initialization
or increment/decrement, separated using comma operator. But it can have only one condition.
The for loop is executed as follows:

1. It first evaluates the initialization code.

2. Then it checks the condition expression.

3. If it is true, it executes the for-loop body.

4. Then it evaluate the increment/decrement condition and again follows from step 2.
5. When the condition expression becomes false, it exits the loop.

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )
{
int x;
for(x = 1; x <= 10; x++)
{
printf("%d\t", x);
}
}

1 2 3 4 5 6 7 8 9 10

Nested for loop


We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,

for(initialization; condition; increment/decrement)


{
for(initialization; condition; increment/decrement)
{
statement ;
}
}
Example: Program to print half Pyramid of numbers

#include<stdio.h>

void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}

21

321

4321

54321

do while loop
In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-
while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. It means that the body of
the loop will be executed at least once, even though the starting condition inside while is initialized to be false. General syntax is,

do
{
.....
.....
}
while(condition)

Example: Program to print first 10 multiples of 5.

#include<stdio.h>
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}

5 10 15 20 25 30 35 40 45 50

Jumping Out of Loops


Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true.
This is known as jumping out of loop.
1) break statement
When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately
following the loop.

2) continue statement
It causes the control to go directly to the test-condition and then continue the loop process. On encountering continue, cursor leave the current cycle of
loop, and starts with the next cycle.
Arrays in C
In C language, arrays are reffered to as structured data types. An array is defined as finite ordered collection of
homogenous data, stored in contiguous memory locations.
Here the words,

 finite means data range must be defined.


 ordered means data must be stored in continuous memory addresses.
 homogenous means data must be of similar data type.

Example where arrays are used,

 to store list of Employee or Student names,


 to store marks of students,
 or to store list of numbers or characters etc.

Since arrays provide an easy way to represent data, it is classified amongst the data structures in C. Other data structures in c
are structure, lists, queues, trees etc. Array can be used to represent not only simple list of data but also table of data in two or
three dimensions.

Declaring an Array
Like any other variable, arrays must be declared before they are used. General form of array declaration is,

data-type variable-name[size];
/* Example of array declaration */

int arr[10];

Here int is the data type, arr is the name of the array and 10 is the size of array. It means array arr can only contain 10 elements
of int type.
Index of an array starts from 0 to size-1 i.e first element of arr array will be stored at arr[0]address and the last element will
occupy arr[9].

Initialization of an Array
After an array is declared it must be initialized. Otherwise, it will contain garbage value(any random value). An array can be
initialized at either compile time or at runtime.

Compile time Array initialization


Compile time initialization of array elements is same as ordinary variable initialization. The general form of initialization of array is,

data-type array-name[size] = { list of values };

/* Here are a few examples */


int marks[4]={ 67, 87, 56, 77 }; // integer array initialization

float area[5]={ 23.4, 6.8, 5.5 }; // float array initialization

int marks[4]={ 67, 87, 56, 77, 59 }; // Compile time error


One important thing to remember is that when you will give more initializer(array elements) than the declared array size than
the compiler will give an error.

#include<stdio.h>

void main()
{
int i;
int arr[] = {2, 3, 4}; // Compile time array initialization
for(i = 0 ; i < 3 ; i++)
{
printf("%d\t",arr[i]);
}
}

Output - 2 3 4

next>><<prev

String and Character Array


String is a sequence of characters that is treated as a single data item and terminated by null character '\0'. Remember that C language does not
support strings as a data type. A string is actually one-dimensional array of characters in C language. These are often used to create meaningful and
readable programs.
For example: The string "hello world" contains 12 characters including '\0' character which is automatically added by the compiler at the end of the
string.

Declaring and Initializing a string variables


There are different ways to initialize a character array variable.

char name[13] = "StudyTonight"; // valid character array initialization

char name[10] = {'L','e','s','s','o','n','s','\0'}; // valid initialization


Remember that when you initialize a character array by listing all of its characters separately then you must supply the '\0' character explicitly.
Some examples of illegal initialization of character array are,

char ch[3] = "hell"; // Illegal

char str[4];
str = "hell"; // Illegal

String Input and Output


Input function scanf() can be used with %s format specifier to read a string input from the terminal. But there is one problem with scanf() function, it
terminates its input on the first white space it encounters. Therefore if you try to read an input string "Hello World" using scanf() function, it will only
read Hello and terminate after encountering white spaces.
However, C supports a format specification known as the edit set conversion code %[..] that can be used to read a line containing a variety of
characters, including white spaces.

#include<stdio.h>
#include<string.h>
void main()
{
char str[20];
printf("Enter a string");
scanf("%[^\n]", &str); //scanning the whole string, including the white spaces
printf("%s", str);
}
Another method to read character string with white spaces from terminal is by using the gets()function.

char text[20];
gets(text);
printf("%s", text);

String Handling Functions


C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. These functions are
packaged in string.h library. Hence, you must include string.h header file in your programs to use these functions.
The following are the most commonly used string handling functions.

Method Description

strcat() It is used to concatenate(combine) two strings

strlen() It is used to show length of a string

strrev() It is used to show reverse of a string

strcpy() Copies one string into another

strcmp() It is used to compare two string

strcat() function

strcat("hello", "world");
strcat() function will add the string "world" to "hello" i.e it will ouput helloworld.

strlen() function
strlen() function will return the length of the string passed to it.

int j;
j = strlen("studytonight");
printf("%d",j);
12

strcmp() function
strcmp() function will return the ASCII difference between first unmatching character of two strings.

int j;
j = strcmp("study", "tonight");
printf("%d",j);

-1

strcpy() function
It copies the second string argument to the first string argument.

#include<stdio.h>
#include<string.h>

int main()
{
char s1[50];
char s2[50];

strcpy(s1, "StudyTonight"); //copies "studytonight" to string s1


strcpy(s2, s1); //copies string s1 to string s2

printf("%s\n", s2);

return(0);
}

StudyTonight

strrev() function
It is used to reverse the given string expression.

#include<stdio.h>

int main()
{
char s1[50];
printf("Enter your string: ");
gets(s1);
printf("\nYour reverse string is: %s",strrev(s1));
return(0);
}

Enter your string: studytonight

Your reverse string is: thginotyduts

C continue statement
The continue statement in C language is used to continue the execution of loop (while,
do while and for). It is used with if condition within the loop.

In case of inner loops, it continues the control of inner loop only.

Syntax:
1. jump-statement;
2. continue;

The jump statement can be while, do while and for loop.

Example of continue statement in c


1. #include<stdio.h>
2. int main(){
3. int i=1;//initializing a local variable
4. //starting a loop from 1 to 10
5. for(i=1;i<=10;i++){
6. if(i==5){//if value of i is equal to 5, it will continue the loop
7. continue;
8. }
9. printf("%d \n",i);
10. }//end of for loop
11. return 0;
12. }

Output
1
2
3
4
6
7
8
9
10
As you can see, 5 is not printed on the console because loop is continued at i==5.

continue statement with inner loop


In such case, C continue statement continues only inner loop, but not outer loop.

1. #include<stdio.h>
2. int main(){
3. int i=1,j=1;//initializing a local variable
4. for(i=1;i<=3;i++){
5. for(j=1;j<=3;j++){
6. if(i==2 && j==2){
7. continue;//will continue loop of j only
8. }
9. printf("%d %d\n",i,j);
10. }
11. }//end of for loop
12. return 0;
13. }

Output
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
As you can see, 2 2 is not printed on the console because inner loop is continued at i==2 and j==2.

C goto statement
The goto statement is known as jump statement in C language. It is used to unconditionally jump to other label. It
transfers control to other parts of the program.

It is rarely used today because it makes program less readable and complex.
Syntax:

1. goto label;

goto example
Let's see a simple example to use goto statement in C language.

1. #include <stdio.h>
2. int main() {
3. int age;
4. ineligible:
5. printf("You are not eligible to vote!\n");
6.
7. printf("Enter you age:\n");
8. scanf("%d", &age);
9. if(age<18)
10. goto ineligible;
11. else
12. printf("You are eligible to vote!\n");
13.
14. return 0;
15. }

Output:

You are not eligible to vote!


Enter you age:
11
You are not eligible to vote!
Enter you age:
44
You are eligible to vote!

Type Casting in C
Type casting allows us to convert one data type into other. In C language, we use cast operator for
type casting which is denoted by (type).

Syntax:

1. (type)value;
Note: It is always recommended to convert lower value to higher for avoiding data loss.

Without Type Casting:

1. int f= 9/4;
2. printf("f : %d\n", f );//Output: 2

With Type Casting:

1. float f=(float) 9/4;


2. printf("f : %f\n", f );//Output: 2.250000

Type Casting example


Let's see a simple example to cast int value into float.

1. #include<stdio.h>
2. int main(){
3. float f= (float)9/4;
4. printf("f : %f\n", f );
5. return 0;
6. }

Output:

f : 2.250000

You might also like