Anda di halaman 1dari 85

C Tutorial

C is a computer programming language developed in 1972 by Dennis M. Ritchie at the Bell

Telephone Laboratories to develop the UNIX Operating System. C is a simple and structure

oriented programming language.

C is also called mother Language of all programming Language. It is the most widely use

computer programming language, This language is used for develop system software and

Operating System. All other programming languages were derived directly or indirectly from C

programming concepts. Here we discuss complete C Tutorial in simple and easy way.

History of C

C language is developed by Mr. Dennis Ritchie in the year 1972 at bell laboratory at USA, C is a

simple and structure Oriented Programming Language.

In the year 1988 C programming language standardized by ANSI (American national standard

institute), that version is called ANSI-C. In the year of 2000 C programming language

standardized by ISO that version is called C-99. All other programming languages were derived

directly or indirectly from C programming concepts.

Prerequisites

Before learning C Programming language or this C Tutorial no need of knowledge of any

Computer programming language, C is the basic of all high level programming languages. C is

also called mother Language.

Overview of C

C is a computer programming language developed in 1972 by Dennis M. Ritchie at the Bell

Telephone Laboratories to develop the UNIX Operating System. C is a simple and structure

oriented programming language.


C is also called mother Language of all programming Language. It is the most widely use

computer programming language, This language is used for develop system software and

Operating System. All other programming languages were derived directly or indirectly from C

programming concepts.
In the year 1988 'C' programming language standardized by ANSI (American national standard

institute), that version is called ANSI-C. In the year of 2000 'C' programming Language

standardized by 'ISO' that version is called C-99

Where we use C Language

C Language is mainly used for;

 Design Operating system

 Design Language Compiler

 Design Database

 Language Interpreters

 Utilities

 Network Drivers

 Assemblers

Features of C

It is a very simple and easy language, C language is mainly used for develop desktop based

application. All other programming languages were derived directly or indirectly from C

programming concepts. This language have following features;


 Simple

 Portability

 Powerful

 Platform dependent

 Structure oriented

 Case sensitive

 Compiler based

 Modularity

 Middle level language

 Syntax based language

 Use of Pointers
Simple

Every c program can be written in simple English language so that it is very easy to understand

and developed by programmer.

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.

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.

Powerful

C is a very powerful programming language, it have a wide verity of data types, functions, control

statements, decision making statements, etc.

Structure oriented

C is a Structure oriented programming language.Structure oriented programming language aimed

on clarity of program, reduce the complexity of code, using this approach code is divided into

sub-program/subroutines. These programming have rich control structure.

Modularity

It is concept of designing an application in subprogram that is procedure oriented approach. In c

programming we can break our code in subprogram.

For example we can write a calculator programs in C language with divide our code in

subprograms.

Example
void sum()
{
.....
.....
}
void sub()
{
.....
.....
}

Case sensitive

It is a case sensitive programming language. In C programming 'break and BREAK' both are

different.

If any language treats lower case latter separately and upper case latter separately than they can

be called as case sensitive programming language [Example c, c++, java, .net are sensitive

programming languages.] other wise it is called as case insensitive programming language

[Example HTML, SQL is case insensitive programming languages].

Middle level language

C programming language can supports two level programming instructions with the combination

of low level and high level language that's why it is called middle level programming language.

Compiler based

C is a compiler based programming language that means without compilation no C program can

be executed. First we need compiler to compile our program and then execute.
Syntax based language

C is a strongly tight syntax based programming language. If any language follow rules and

regulation very strictly known as strongly tight syntax based language. Example C, C++, Java,

.net etc. If any language not follow rules and regulation very strictly known as loosely tight syntax

based language.

Example HTML.

Efficient use of pointers

Pointers is a variable which hold the address of another variable, pointer directly direct access to

memory address of any variable due to this performance of application is improve. In C language

also concept of pointer are available.

TC Editor

TC Editor is very simple and easy to use; here i will give you all tips related to TC Editor and

some shortcut keys related to TC Editor which is very useful at the time of coding. Turbo C is a

most common C language compiler. Below i will discuss all about its Interfaces.
TC Editor

The interface of Turbo C is very simple. When IDE screen appears, the menu bar is activated. It

contains various menus such as;

 File: This menu contains group of commands used for save , edit , print program, exit
from Turbo C editor etc.
 Edit: This menu contains group of commands used for editing C program source
code. Example Copy, Cut, Paste, Undo etc.
 Search: This menu contains group of commands used for searching specific word as
well as replacing it with another one.
 Run: This menu contains group of commands used for running C program.
 Compile: This menu contains group of commands used for compiling C program.
 Debug: This menu contains group of commands used for debugging C program.
 Project: This menu contains group of commands used for opening, closing and
creating projects.
 Options: This menu contains group of commands used for configuring IDE of Turbo
C and setting up directories etc.
 Windows: This menu contains group of commands used for opening, closing various
windows of IDE.
 Help: This menu is used to get help about specific topic of C language. Similarly to
get help about a specific keyword or identifier of C.

Shortcut keys Related to TC Editor

 Alt + x : Close TC Editor.


 Clt + f9 : Run C Program.
 Alt + f9 : Compile C Code.
 Alt + Enter : Get Full Screen or Half Screen TC Editor.
 Clt + y : Delete complete line above the cursor.
 Shift + Right arrow : Select Line of Code.
 Clt + Insert : Copy.
 Shift + Insert : Paste.
 Shift + Delete : Delete.

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

 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

Compiler takes Entire program as input Interpreter takes Single instruction as


1
at a time. input at a time.

No Intermediate Object code is


2 Intermediate Object code is generated
generated

It execute conditional control It execute conditional control


3
statements fastly. statements slower than Compiler

4 More memory is required. Less memory is required.

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

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

7 Example: C Example: BASIC


Difference between Local variable and Global variable

In C language, a variable can be either of global or local scope.

Global variable

Global variables are defined outside of all the functions, generally on top of the program. The

global variables will hold their value throughout the life-time of your program.

Local variable

A local variable is declared within the body of a function or a block. Local variable only use within

the function or block where it is declare.

Example of Global and Local variable


Example

#include<stdio.h>
#include<conio.h>

int a; // global variable


void main()
{
int b; // local variable
a=10, b=20;
printf("Value of a : %d",a);
printf("Value of b : %d",b);
getch();
}

Output

Value of a: 10

Value of b: 20
DataType in C Language

Data type is a keyword used to identify type of data. Data types are used for storing the input of

the program into the main memory (RAM) of the computer by allocating sufficient amount of

memory space in the main memory of the computer.

In other words data types are used for representing the input of the user in the main memory

(RAM) of the computer.

In general every programming language is containing three categories of data types. They are

 Fundamental or primitive data types

 Derived data types

 User defined data types

Primitive data types

These are the data types whose variable can hold maximum one value at a time, in C language it

can be achieve by int, float, double, char.

Example

int a; // valid

a = 10,20,30; // invalid

Derived data types


These data type are derived from fundamental data type. Variables of derived data type allow us

to store multiple values of same type in one variable but never allows to store multiple values of

different types. These are the data type whose variable can hold more than one value of similar

type. In C language it can be achieve by array.

Example

int a[] = {10,20,30}; // valid


int b[] = {100, 'A', "ABC"}; // invalid

User defined data types

User defined data types related variables allows us to store multiple values either of same type or

different type or both. This is a data type whose variable can hold more than one value of

dissimilar type, in C language it is achieved by structure.

Syntax

struct emp
{
int id;
char ename[10];
float sal;
};

In C language, user defined data types can be developed by using struct, union, enum etc.

Data type modifiers in C

In c language Data Type Modifiers are keywords used to change the properties of current

properties of data type. Data type modifiers are classified into following types.

 long
 short

 unsigned

 signed

Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of

storage space allocated to a variable.

For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the

range by using long int which is 8 byte. We can decrease the range by using short int which is 2

byte.

long:

This can be used to increased size of the current data type to 2 more bytes, which can be applied

on int or double data types. For example int occupy 2 byte of memory if we use long with integer

variable then it occupy 4 byte of memory.

Syntax

long a; --> by default which represent long int.

short

In general int data type occupies different memory spaces for a different operating system; to

allocate fixed memory space short keyword can be used.


Syntax

short int a; --> occupies 2 bytes of memory space in every operating system.

unsigned

This keyword can be used to make the accepting values of a data type is positive data type.

Syntax

unsigned int a =100; // right


unsigned int a=-100; // wrong

Signed

This keyword accepts both negative or positive value and this is default properties or data type

modifiers for every data type.

Example

int a=10; // right


int a=-10; // right
signed int a=10;// right
signed int a=-10; // right

Note: in real time no need to write signed keyword explicitly for any data type.
Operators

Operator is a special symbol that tells the compiler to perform specific mathematical or logical

Operation.

 Arithmetic Operators

 Relational Operators

 Logical Operators

 Bitwise Operators

 Assignment Operators

 Ternary or Conditional Operators

Arithmetic Operators

Given table shows all the Arithmetic operator supported by C Language. Lets suppose

variable Ahold 8 and B hold 3.


Operator Example (int A=8, B=3) Result
+ A+B 11
- A-B 5
* A*B 24
/ A/B 2
% A%4 0

Relational Operators

Which can be used to check the Condition, it always return true or false. Lets suppose

variable Ahold 8 and B hold 3.


Operators Example (int A=8, B=3) Result
< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
!= A!=(-4) True

Logical Operator

Which can be used to combine more than one Condition?. Suppose you want to combined two

conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C).

Here &&is Logical Operator.


Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True

Truth table of Logical Operator

C1 C2 C1 && C2 C1 || C2 !C1 !C2


T T T T F F
T F F T F T
F T F T T F
F F F F T T
Assignment operators

Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.
Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A-3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
=a=b Value of b will be assigned to a

Increment and Decrement Operator in C

Increment Operators are used to increased the value of the variable by one and Decrement

Operators are used to decrease the value of the variable by one in C programs.

Both increment and decrement operator are used on a single operand or variable, so it is called

as a unary operator. Unary operators are having higher priority than the other operators it means

unary operators are executed before other operators.

Syntax

++ // increment operator

-- // decrement operator

Note: Increment and decrement operators are can not apply on constant.
Example

x= 4++; // gives error, because 4 is constant


Type of Increment Operator

 pre-increment

 post-increment

pre-increment (++ variable)

In pre-increment first increment the value of variable and then used inside the expression

(initialize into another variable).

Syntax

++ variable;

Example pre-increment

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=++i;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 11

i: 11

In above program first increase the value of i and then used value of i into expression.
post-increment (variable ++)

In post-increment first value of variable is used in the expression (initialize into another variable)

and then increment the value of variable.

Syntax

variable ++;

Example post-increment

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=i++;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 10

i: 11

In above program first used the value of i into expression then increase value of i by 1.

Type of Decrement Operator

 pre-decrement

 post-decrement
Pre-decrement (-- variable)

In pre-decrement first decrement the value of variable and then used inside the expression

(initialize into another variable).

Syntax

-- variable;

Example pre-decrement

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=--i;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 9

i: 9

In above program first decrease the value of i and then value of i used in expression.

post-decrement (variable --)

In Post-decrement first value of variable is used in the expression (initialize into another variable)

and then decrement the value of variable.

Syntax
variable --;

Example post-decrement

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=i--;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 10

i: 9

In above program first used the value of x in expression then decrease value of i by 1.

Example of increment and decrement operator

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
printf("x: %d",x);
getch();
}

Output

x: 0

Increment and Decrement Operator in C

Increment Operators are used to increased the value of the variable by one and Decrement

Operators are used to decrease the value of the variable by one in C programs.

Both increment and decrement operator are used on a single operand or variable, so it is called

as a unary operator. Unary operators are having higher priority than the other operators it means

unary operators are executed before other operators.

Syntax

++ // increment operator

-- // decrement operator

Note: Increment and decrement operators are can not apply on constant.
Example

x= 4++; // gives error, because 4 is constant


Type of Increment Operator

 pre-increment

 post-increment

pre-increment (++ variable)

In pre-increment first increment the value of variable and then used inside the expression

(initialize into another variable).

Syntax

++ variable;

Example pre-increment

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=++i;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 11

i: 11

In above program first increase the value of i and then used value of i into expression.
post-increment (variable ++)

In post-increment first value of variable is used in the expression (initialize into another variable)

and then increment the value of variable.

Syntax

variable ++;

Example post-increment

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=i++;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 10

i: 11

In above program first used the value of i into expression then increase value of i by 1.

Type of Decrement Operator

 pre-decrement

 post-decrement
Pre-decrement (-- variable)

In pre-decrement first decrement the value of variable and then used inside the expression

(initialize into another variable).

Syntax

-- variable;

Example pre-decrement

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=--i;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 9

i: 9

In above program first decrease the value of i and then value of i used in expression.

post-decrement (variable --)

In Post-decrement first value of variable is used in the expression (initialize into another variable)

and then decrement the value of variable.

Syntax
variable --;

Example post-decrement

#include<stdio.h>
#include<conio.h>

void main()
{
int x,i;
i=10;
x=i--;
printf("x: %d",x);
printf("i: %d",i);
getch();
}

Output

x: 10

i: 9

In above program first used the value of x in expression then decrease value of i by 1.

Example of increment and decrement operator

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int x,a,b,c;
a = 2;
b = 4;
c = 5;
x = a-- + b++ - ++c;
printf("x: %d",x);
getch();
}

Output

x: 0

First Program

Programming in C language is very simple and it is easy to learn here i will show you how to write

your first program. For writing C program you need Turbo C Editor. First you open TC and write

code.

Example

#include<stdio.h>
#include<conio.h>

void main()
{
printf("This is my first program");
getch();
}

Output

This is my first program

 After writing complete code save the program using F2


 Save your code with .c extension for example: hello.c
 After save the code you need to compile your code using alt+f9
 Finally Run the program using clt+f9

Save C program

Save any C program using .c Extension with file name. For example your program name is sum,

then it save with sum.c.


Syntax

filename.c

Compile and Run C Program

for compile any C program you just press alt+f9 , after compilation of your c program you

press clt+f9 for run your C program.


Syntax

Compile -> alt+f9

Run -> clt+f9

Ternary Operator in C

If any operator is used on three operands or variable is known as Ternary Operator. It can be

represented with ? : . It is also called as conditional operator


Advantage of Ternary Operator

Using ?: reduce the number of line codes and improve the performance of application.
Syntax

expression-1 ? expression-2 : expression-3

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either

value or variable or statement or any mathematical expression. If condition will be true

expression-2 will be execute otherwise expression-3 will be executed.

Syntax

a<b ? printf("a is less") : printf("a is greater");

Flow Diagram
Find largest number among 3 numbers using ternary operator
Example

#include<stdio.h>
#include<conio.h>

void main()
{
int a, b, c, large;
clrscr();
printf("Enter any three number: ");
scanf("%d%d%d",&a,&b,&c);
large=a>b ? (a>c?a:c) : (b>c?b:c);
printf("Largest Number is: %d",large);
getch();
}

Output

Enter any three number: 5 7 2

Largest number is 7

sizeof operator

The sizeof operator is used to calculate the size of data type or variables. This operator returns

the size of its variable in bytes.

For example: sizeof(a), where a is interger, will return 4.

Syntax

sizeof(variable)

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int a;
float b;
double c;
char d;
printf("Size of Integer: %d bytes\n",sizeof(a));
printf("Size of float: %d bytes\n",sizeof(b));
printf("Size of double: %d bytes\n",sizeof(c));
printf("Size of character: %d byte\n",sizeof(d));
getch();
}

Output

Size of Integer: 2

Size of float: 4

Size of double: 8

Size of character: 1

Expression evaluation

In c language expression evaluation is mainly depends on priority and associativity.

Priority

This represents the evaluation of expression starts from "what" operator.

Associativity

It represents which operator should be evaluated first if an expression is containing more than

one operator with same priority.

Operator Priority Associativity

{}, (), [] 1 Left to right

++, --, ! 2 Right to left

*, /, % 3 Left to right
+, - 4 Left to right

<, <=, >, >=, ==, != 5 Left to right

&& 6 Left to right

|| 7 Left to right

?: 8 Right to left

=, +=, -=, *=, /=, %= 9 Right to left

Example 1:
Example 2:

Decision Making Statement

Decision making statement is depending on the condition block need to be executed or not

which is decided by condition.

If the condition is "true" statement block will be executed, if condition is "false" then statement

block will not be executed.

In this section we are discuss about if-then (if), if-then-else (if else), and switch statement. In C

language there are three types of decision making statement.

 if

 if-else

 switch
if-then Statement

if-then is most basic statement of Decision making statement. It tells to program to execute a

certain part of code only if particular condition is true.

Syntax

if(condition)
{
.......
.......
}

 Constructing the body of "if" statement is always optional, Create the body when we
are having multiple statements.

 For a single statement, it is not required to specify the body.

 If the body is not specified, then automatically condition part will be terminated with
next semicolon ( ; ).
else

It is a keyword, by using this keyword we can create a alternative block for "if" part. Using else is

always optional i.e, it is recommended to use when we are having alternate block of condition.

In any program among if and else only one block will be executed. When if condition is false then

else part will be executed, if part is executed then automatically else part will be ignored.

if-else statement

In general it can be used to execute one block of statement among two blocks, in C language if

and else are the keyword in C.

Syntax

if(condition)

........

statements
........

else

........

statements

........

In the above syntax whenever condition is true all the if block statement are executed remaining

statement of the program by neglecting else block statement. If the condition is false else block

statement remaining statement of the program are executed by neglecting if block statements.

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int time=10;
clrscr();
if(time>12)
{
printf("Good morning");
}
{
printf("Good after noon");
}
getch();
}
Output

Good morning

Switch Statement

A switch statement work with byte, short, char and int primitive data type, it also works with

enumerated types and string.

Syntax

switch(expression/variable)

{
case value:

//statements

// any number of case statements

break; //optional

default: //optional

//statements

Rules for apply switch

1. With switch statement use only byte, short, int, char data type.
2. You can use any number of case statements within a switch.
3. Value for a case must be same as the variable in switch .

Limitations of switch

Logical operators cannot be used with switch statement. For instance

Example

case k>=20: //is not allowed

Switch case variables can have only int and char data type. So float data type is not allowed.

Syntax

switch(ch)
{
case1:
statement 1;
break;
case2:
statement 2;
break;
}

In this ch can be integer or char and cannot be float or any other data type.

Example of Switch case

#include<stdio.h>
#include<conio.h>

void main()
{
int ch;
clrscr();
printf("Enter any number (1 to 7)");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Today is Monday");
break;
case 2:
printf("Today is Tuesday");
break;
case 3:
printf("Today is Wednesday");
break;
case 4:
printf("Today is Thursday");
break;
case 5:
printf("Today is Friday");
break;
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Only enter value 1 to 7");
}
getch();
}

Output

Enter any number (1 to 7): 5

Today is Friday

Note: In switch statement default is optional but when we use this in switch default is executed at

last whenever all cases are not satisfied the condition.

if-then Statement

if-then is most basic statement of Decision making statement. It tells to program to execute a

certain part of code only if particular condition or test is true.

Syntax

if(condition)
{
..........
..........
}

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int a=10;
if(a<=10)
{
printf("a is less than 10");
}
getch();
}

Output

a is less than 10

 Constructing the body of "if" statement is always optional, Create the body when we
are having multiple statements.

 For a single statement, it is not required to specify the body.


 If the body is not specified, then automatically condition part will be terminated with
next semicolon ( ; ).

else

It is a keyword, by using this keyword we can create a alternative block for "if" part. Using else is

always optional i.e, it is recommended to use when we are having alternate block of condition.

In any program among if and else only one block will be executed. When if condition is false then

else part will be executed, if part is executed then automatically else part will be ignored.

Syntax

if(condition)
{
..........
..........
}
else
{
........
........
}

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int age=40;
if(age<18)
{
printf("you are child");
}
else
{
printf("you are young");
}
getch();
}

Output

you are young

If Else Statement in C

In general it can be used to execute one block of statement among two blocks, in C

language ifand else are the keyword in C.

Syntax

if(condition)
{
........
statements
........
}
else
{
........
statements
........
}

In the above syntax whenever condition is true all the if block statement are executed remaining

statement of the program neglecting. If the condition is false then else block statement will

executed and neglecting if block statements.

Example

#include<stdio.h>
#include<conio.h>

void main()
{
int time=10;
clrscr();
if(time>12)
{
printf("Good morning");
}
else
{
printf("Good after noon");
}
getch();
}

Output
Good morning

Switch Statement in C

The switch statement in C language is used to execute the code from multiple conditions or case.

It is same like if else-if ladder statement.

A switch statement work with byte, short, char and int primitive data type, it also works with

enumerated types and string.

Syntax

switch(expression or variable)
{
case value:
//statements
// any number of case statements
break; //optional
default: //optional
//statements
}
Flow chart

Rules for apply switch

 The switch expression must be of integer or character type.

 With switch statement use only byte, short, int, char data type.

 With switch statement not use float data type.

 You can use any number of case statements within a switch.

 The case value can be used only inside the switch statement.

 Value for a case must be same as the variable in switch.

Valid statement for switch


Example

int x;
byte y;
short z;
char a,b;

Limitations of switch

Logical operators can not be used with switch statement. For instance

Example

case k>20&&k=20: // is not allowed

Switch case variables can have only int and char data type. So float data type is not allowed.

case 4.2: // Invalid

Syntax

switch(ch)
{
case 1:
statement 1;
break;
case 2:
statement 2;
break;
}

In this ch can be integer or char and can not be float or any other data type.
Rulse table of switch

Valid Switch Invalid Switch Valid Case Invalid Case

switch(a) switch(2.3) case 3; case 2.5;

switch(a>b) switch(a+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(a,b)) case 'a'>'b'; case 1,2,3;

Example of switch case

#include<stdio.h>
#include<conio.h>

void main()
{
int ch;
clrscr();
printf("Enter any number (1 to 7)");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Today is Monday");
break;
case 2:
printf("Today is Tuesday");
break;
case 3:
printf("Today is Wednesday");
break;
case 4:
printf("Today is Thursday");
break;
case 5:
printf("Today is Friday");
break;
case 6:
printf("Today is Saturday");
break;
case 7:
printf("Today is Sunday");
break;
default:
printf("Only enter value 1 to 7");
}
getch();
}

Output
Enter any number (1 to 7): 5 Today is Friday

Note: In switch statement default is optional but when we use this in switch default is executed at

last whenever all cases are not satisfied the condition.


Example of Switch without break

#include<stdio.h>
#include<conio.h>

void main()
{
int ch;
clrscr();
printf("Enter any number (1 to 7)");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Today is Monday");
case 2:
printf("Today is Tuesday");
case 3:
printf("Today is Wednesday");
case 4:
printf("Today is Thursday");
case 5:
printf("Today is Friday");
case 6:
printf("Today is Saturday");
case 7:
printf("Today is Sunday");
default:
printf("Only enter value 1 to 7");
}
getch();
}

Output
Enter any number (1 to 7): 4 Today is Thursday Today is Friday Today is Saturday Today is Sunday

Note: In switch statement when you not use break keyword after any statement then all the case

after matching case will be execute. In above code case 4 is match and after case 4 all case are

execute from case-4 to case-7.

C Program for calculator


Example

#include<stdio.h>
#include<conio.h>

void main()
{
char choice;
int a,b,res=0;
clrscr();
printf("Enter first value: ");
scanf("%d",&a);
printf("\n Enter operator: ");
choice=getch();
printf("\n Enter second value: ");
scanf("%d",&b);

switch(choice)
{
case '+':
res=a+b;
printf("Sum: %d",res);
break;
case '-':
res=a-b;
printf("Difference: %d",res);
break;
case '*':
res=a*b;
printf("Product: %d",res);
break;
case '/':
res=a/b;
printf("Quotient: %d",res);
break;
default:
printf("Enter Valid Operator!!");
}
getch();
}

Example

Enter First number: 6

Enter operator : +

Enter Second number: 10

Sum: 16
Explanation: In above code choice=getch(); is used for scan or get one value by using getch()

function from keyboard, and store is choice.

Looping Statement in C

Looping statement are the statements execute one or more statement repeatedly several

number of times. In C programming language there are three types of loops; while, for and do-

while.

Why use loop ?

When you need to execute a block of code several number of times then you need to use looping

concept in C language.

Advantage with looping statement

 Reduce length of Code

 Take less memory space.

 Burden on the developer is reducing.

 Time consuming process to execute the program is reduced.


Types of Loops.

There are three type of Loops available in 'C' programming language.

 while loop

 for loop

 do..while

Difference between conditional and looping statement

Conditional statement executes only once in the program where as looping statements executes

repeatedly several number of time.

While loop

In while loop First check the condition if condition is true then control goes inside the loop body

other wise goes outside the body. while loop will be repeats in clock wise direction.
Syntax

Assignment;

while(condition)

Statements;

......

Increment/decrements (++ or --);

Note: If while loop condition never false then loop become infinite loop.
Example of while loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
while(i<5)
{
printf("\n%d",i);
i++;
}
getch();
}

Output

For loop

for loop is a statement which allows code to be repeatedly executed. For loop contains 3 parts

Initialization, Condition and Increment or Decrements.


Example of for loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
{
printf("\n%d",i);
}
getch();
}

Output

do-while

A do-while loop is similar to a while loop, except that a do-while loop is execute at least one time.

A do while loop is a control flow statement that executes a block of code at least once, and then

repeatedly executes the block, or not, depending on a given condition at the end of the block (in

while).

Syntax

do

Statements;

........

Increment/decrement (++ or --)

} while();

For Loop in C
When you need to execute a block of code several number of times then you need to use looping

concept in C language. In C Programming Language for loop is a statement which allows code

to be repeatedly executed. It contains 3 parts.

 Initialization

 Condition

 Increment or Decrements
Syntax

for ( initialization; condition; increment )

statement(s);

 Initialization: This step is execute first and this is execute only once when we are
entering into the loop first time. This step is allow to declare and initialize any loop
control variables.
 Condition: This is next step after initialization step, if it is true, the body of the loop
is executed, if it is false then the body of the loop does not execute and flow of control
goes outside of the for loop.
 Increment or Decrements: After completion of Initialization and Condition steps
loop body code is executed and then Increment or Decrements steps is execute. This
statement allows to update any loop control variables.
Note: In for loop everything is optional but mandatory to place 2 semicolons (; ;)
Example

for() // Error
for( ; ; ) // valid

Flow Diagram
Control flow of for loop

 First initialize the variable, It execute only once when we are entering into the loop
first time.

 In second step check condition

 In third step control goes inside loop body and execute.

 At last increase the value of variable

 Same process is repeat until condition not false.

See in Detail
Example of for loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
for(i=1;i<5;i++)
{
printf("\n%d",i);
}
getch();
}

Output

Important Points

 In for loop if condition part is not given then it will repeats infinite times, because
condition part will replace it non-zero. So it is always true like.
for( ; 1; )

 For loop is repeats in anti lock wise direction.

 In for loop also rechecking process will be occurred that is before execution of the
statement block, condition part will evaluated.
Example

while(0) // no repetition
for( ; 0; ) // it will repeats 1 time

Note: Always execution process of for loop is faster than while loop.

do-while in C
A do-while loop is similar to a while loop, except that a do-while loop is execute at least one

time.

A do while loop is a control flow statement that executes a block of code at least once, and then

repeatedly executes the block, or not, depending on a given condition at the end of the block (in

while).
Syntax

do
{
Statements;
........
Increment or Decrements (++ or --)
}
while(condition);
Flow Diagram

When use do..while loop

when we need to repeat the statement block at least one time then use do-while loop. In do-

while loop post-checking process will be occur, that is after execution of the statement block

condition part will be executed.

In below example you can see in this program i=20 and we check condition i is less than 10, that

means condition is false but do..while loop execute once and print Hello world ! at one time.

Example of do..while loop

#include<stdio.h>
#include<conio.h>
void main()
{
int i=20;
do
{
printf("Hello world !");
i++;
}
while(i<10);
getch();
}

Output

Hello world !

Example of do..while loop

#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<5);
getch();
}

Output
1

When use do..while Loop

When we need to repeat the statement block at least 1 time then we use do-while loop.

Example of do..while loop


#include<stdio.h>
#include<conio.h>

void main()
{
int i;
clrscr();
i=1;
do
{
printf("\n%d",i);
i++;
}
while(i<5);
getch();
}

Output

Nested loop

In Nested loop one loop is place within another loop body.

When we need to repeated loop body itself n number of times use nested loops. Nested loops

can be design upto 255 blocks.

Array in C Language
An array is a collection of similar data type value in a single variable. It is a derived data type in

C, which is constructed from fundamental data type of C language.

Advantage of array

 Code Optimization: Less code is required, one variable can store numbers of value.
 Easy to traverse data: By using array easily retrieve the data of array.
 Easy to sort data: Easily short the data using swapping technique
 Random Access: With the help of array index you can randomly access any
elements from array.

Dis-Advantage of array

Fixed Size: Whatever size, we define at the time of declaration of array, we can not change their

size, if you need more memory in that time you can not increase memory size, and if you need

less memory in that case also wastage of memory.

Declaring Array

To declare an array in C you need to declare datatype and size of an array.

Syntax

datatype arrayName[SIZE];
Example

int roll_no[10];

Initializing Array

Initializing is a process to initialize the value in array variable. This is happen in two ways,

initialize array one by one or all elements are initializing once.

Initialization of array one by one

int arr[5];
arr[0]=10;
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;

Initialization of array at once

int arr[]={10,20,30,40,50};

Accessing Array Elements

We can access array elements with the help of index value of element.

Example

int arr[]={10,20,30,40,50};
arr[3] // here 3 is index value and it return 40

Example of array
#include<stdio.h>
#include<conio.h>

void main()
{
int i, marks[]={80, 62, 70, 90, 98}; //declaration and initialization of array
clrscr();

//traversal of array
for(i=0;i<5;i++)
{
printf("\n%d",marks[i]);
}
getch();
}

Example

80

62

70

90

98

2-dimentional array

 In 2-dimentional elements are arranged in row and column format.

 When we are working with 2-dimentional array we require to refer 2-subscript


operator which indicates row and column sizes.

 The main memory of 2-dimentional array is rows and sub-memory is columns.


 On 2-dimentional array when we are referring one-subscript operator then if gives
row address, 2-subscript operator will gives element.

 On 2-dimentional array arrayName always gives main memory that is 1st row base
address, arrayName will gives next row base address.
Syntax

datatype arrayName[SIZE][SIZE];

Important points related to array

Always size of the array must be an unsigned integer value which is greater than '0' only. In

declaration of the array size must be required to mention, if size is not mention then compiler will

give an error.

Example

int arr[]; //error

In declaration of the array size must be assigned type which value is greater than 0. In

initialization of the array if specific number of values are not initialized it then rest of all elements

will be initialized with it '0'.

Example

int arr[5]={10,20}; // yes valid

arr[0]=10;

arr[1]=20;

arr[2], arr[3], arr[4]; // initialized with zero


In initialization of the array mentioning the size is optional, in this case how many elements are

initialize it that many variable are created.

Example

int arr[]={10,20,30,40,50}; // valid

Size=5;

Sizeof(arr)=10 byte

Important points for Array

 In implementation when we required 'n' number of variables of same data type then
go for an array.

 When we are working with arrays always memory will created in continues memory
location, so randomly we can access the data.

 In arrays all elements will share same name with unique identification value called
index.

 Always array index will start with '0' and end with 'size-1'.

 When we are working with array compile time memory management will occur that is
static memory allocation.

String

String is a collection of character or group of character, it is achieve in C language by using array

character. The string in C language is one-dimensional array of character which is terminated by

a null character '\0'. In other words string is a collection of character which is enclose between

double cotes ( " " ).

Note: Strings are always enclosed within double quotes. Whereas, character is enclosed within

single quotes in C.
Declaration of string

Strings are declared in C in similar manner as arrays. Only difference is that, strings are of char

type.

Example

char s[5];

Initializing Array string

String are initialize into various way in c language;

Example

char str[]="abcd";
OR
char str[5]="abcd";
OR
char str[5]={'a','b','c','d','\0'};
OR
char str[]={'a','b','c','d','\0'};
OR
char str[5]={'a','b','c','d','\0'};

In c language string can be initialize using pointer.

Example

char *c="abcd";
Reading String from user
Example

char str[5];
scanf("%s",&str);

Example

#include<stdio.h>
#include<conio.h>

void main()
{
char str[10];
printf("Enter name: ");
scanf("%s",name);
printf("Your name is: %s.",name);
getch();
}

Example of reading string

Enter name: Hitesh kumar


Your name is: Hitesh
Note: String variable str can only take only one word. It is because when white space is

encountered, the scanf() function terminates. to over come this problem you can use gets()

function.
Syntax

char str[5];
gets(str);

gets()

gets() are used to get input as a string from keyword, using gets() we can input more than one

word at a time.

puts()

puts() are used to print output on screen, generally puts() function are used with gets() function.

Example of String program

#include<stdio.h>
#include<conio.h>

void main()
{
char str[10];
printf("Enter any string: ");
gets(str);
printf("String are: ");
puts(str);
getch();
}

Explanation: Here gets() function are used for input string and puts() function are used to show

string on console or monitor.


Output
Enter String: hello word

String are: hello word

C Library String functions

All the library function of String is available in String.h header file.

S.N. Function Purpose

1 strcpy(s1, s2) Copies string s2 into string s1.

Concatenates string s2 onto the end of


2 strcat(s1, s2)
string s1.

3 strlen(s1) Returns the length of string s1.

Returns 0 if s1 and s2 are the same; less


4 strcmp(s1, s2)
than 0 if s1<s2; greater than 0 if s1>s2.

Returns a pointer to the first occurrence of


5 strchr(s1, ch)
character ch in string s1.

Returns a pointer to the first occurrence of


6 strstr(s1, s2)
string s2 in string s1.

Important points for Declaration of string

 In declaration of string size must be required to mention otherwise it gives an error.


Syntax

char str[]; // Invalid


char str[10]; // Valid
 In declaration of the string size must be unsigned integer value (not -ve or zero value)
which is greater than zero only.
Example

char str[]; // Invalid


char str[0]; // Invalid
char str[-1]; // Invalid
char str[10]; // Valid

Syntax

char variable_name[SIZE];

char str[5];

Important points for Initialization of the string

 In Initialization of the string if the specific number of character are not initialized it
then rest of all character will be initialized with NULL.
Example

char str[5]={'5','+','A'};
str[0]; ---> 5
str[1]; ---> +
str[2]; ---> A
str[3]; ---> NULL
str[4]; ---> NULL

 In initialization of the string we can not initialized more than size of string elements.
Example

char str[2]={'5','+','A','B'}; // Invalid


 In initialization of the string the size is optional in this case how many variable
elements are initialized it, that array element will created.
Example

char str[]={'5','+','A','B'}; // Valid


sizeof(str) --> 4byte

When we are working with character array explicitly NULL character does not occupies any

physical memory at the end of the character array.

Example

char str[]={'h','e','l','l','o'};
sizeof(str) --> 5byte

String data at the end of the string NULL character occupies physical memory.

Example

char str[]="hello";
sizeof(str) --> 6 byte

Structure in C

Structure is a user defined data type which hold or store heterogeneous data item or element in

a singe variable. It is a Combination of primitive and derived data type.


Why Use Structure in C

In C language array is also a user defined data type but array hold or store only similar type of

data, If we want to store different-different type of data in then we need to defined separate

variable for each type of data.

Example: Suppose we want to store Student record, then we need to store....

 Student Name

 Roll number

 Class

 Address

For store Student name and Address we need character data type, for Roll number and class we

need integer data type.

If we are using Array then we need to defined separate variable.

Example

char student_name[10], address[20];


int roll_no[5], class[5];

If we use Structure then we use single variable for all data.

Syntax

struct stu
{
char student_name[10];
char address[20];
int roll_no[5];
int class[5];
};

Note: Minimum size of Structure is one byte and Maximum size of Structure is sum of all

members variable size.

Note: Empty Structure is not possible in C Language.

Defining a Structure
Syntax

struct tagname

Datatype1 member1;

Datatype2 member2;

Datatype3 member3;

...........

};

At end of the structure creation (;) must be required because it indicates that an entity is

constructed.
Example

struct emp
{
int id;
char name[36];
int sal;
};
sizeof(struct emp) // --> 40 byte (2byte+36byte+2byte)

Syntax to create structure variable

struct tagname variable;

Difference Between Array and Structure

Array Structure

Structure is the collection of heterogeneous


1 Array is collection of homogeneous data.
data.

Structure elements are access using .


2 Array data are access using index.
operator.

3 Array allocates static memory. Structures allocate dynamic memory.

Array element access takes less time Structure elements takes more time than
4
than structures. Array.
Example of Structure in C

#include<stdio.h>
#include<conio.h>

struct emp
{
int id;
char name[36];
float sal;
};

void main()
{
struct emp e;
clrscr();
printf("Enter employee Id, Name, Salary: ");
scanf("%d",&e.id);
scanf("%s",&e.name);
scanf("%f",&e.sal);

printf("Id: %d",e.id);
printf("\nName: %s",e.name);
printf("\nSalary: %f",e.sal);
getch();
}

Output
Output: Enter employee Id, Name, Salary: 5 Spidy 45000 Id : 05 Name: Spidy Salary: 45000.00

Syntax to access structure members

By using following operators we can access structure members.

Syntax

. struct to member

--> pointer to member

When the variable is normal type then go for struct to member operator.

When the variable is pointer type then go for pointer to member operator.

Difference Between Structure and Pointer in C

Structure in C refer to a collection of various data types for example you create a structure named

"Student" which contains his name , roll no, DOB etc. Name is string, Roll no is int.

While pointer refer to address in C & symbol are used to point some particular place in C

memory.