About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.

 

About of C


C Programming Language

 

The C Language is developed for creating system applications that direct interacts to the hardware devices such as drivers, kernals, etc.

C programming is considered as the base for other programming languages, that is why it 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 the languages follow 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 software. 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 specifies 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

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 & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language


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

 1. Simple

 2. Machine Independent or Portable

 3. Mid-level programming language

 4. Structured programming language

 5. Rich Library

 6. Memory Management

 7. Fast Speed

 8 Pointers

 9. Recursion

 10. Extensible


1) Simple

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


2) Machine Independent or Portable

Unlike assembly language, c programs can be executed in many machines with a 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 the 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

provides a lot of inbuilt functions that make 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 the C language is fast.


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.

 

 

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

  1. #include <stdio.h>  
  2. void main(){  
  3. printf("Hello C Language");  
  4. }  

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

 

 

1) C program (source code) is sent to the preprocessor first. The preprocessor is responsible to convert preprocessor directives into their respective values. The preprocessor generates expanded source code.

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

3) The assembly code is sent to the 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 the 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, the output is sent to the console.

 

Variables in C


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

It is a way to represent memory location through a symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

  1. type variable_list;  

The example of declaring a variable is given below:

  1. int a;  
  2. float b;  
  3. char c;  

Here, a, b, c are variables and int, float, char are data types.

We can also provide values while declaring the variables as given below:

  1. int a=10,b=20;  //declaring 2 variable of integer type  
  2. float f=20.8;  
  3. char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits and underscore.
  • A variable name can start with alphabet and underscore only. It can't start with digit.
  • No white space is allowed within variable name.
  • A variable name must not be any reserved word or keyword e.g. int, float etc.

Valid variable names:

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

Invalid variable names:

  1. int 2;  
  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, the local variable will print the same value for each function call e.g, 11,11,11, and so on. But the 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 are declared inside the block, are automatic variables by default. By we can explicitly declare an automatic variables using an 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. }  

 

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in C language.

A list of 32 keywords in c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

 

 

 

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. It size is given according to 32 bit OS.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 127

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 32,767

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 32,767

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 32,767

long int

4 byte

 

signed long int

4 byte

 

unsigned long int

4 byte

 

float

4 byte

 

double

8 byte

 

long double

10 byte


 

 

 

Operators in C


An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

 

There are the following types of operators to perform different types of operations in C language.

  - Arithmetic Operators

  - Relational Operators

  - Shift Operators

  - Logical Operators

  - Bitwise Operators

  - Ternary or Conditional Operators

  - Assignment Operator

  - Misc Operator


Precedence of Operators in C

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 are 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


An escape sequence in C language is a sequence of characters that doesn't represent itself when used inside string literal or character.

It is composed of two or more characters starting with backslash \. For example: \n represents new line.

List of Escape Sequences in C

Escape Sequence

Meaning

\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

\?

Question Mark

\nnn

octal number

\xhh

hexadecimal number

\0

Null

Escape Sequence Example

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("You\nare\nlearning\n\'c\' language\n\"Do you know C language\"");  
  7. getch();      
  8. }      

Output:

You

are

learning

'c' language

"Do you know C language"

 

if-else Statement in C


The if statement in C language is used to perform an operation on the basis of condition. By using the if-else statement, you can perform operation either condition is true or false.

 

There are many ways to use if statement in C language:

  - If statement

  - If-else statement

  - If else-if ladder

  - Nested if

 

If Statement

The single if statement in C language is used to execute the code if the condition is true. The syntax of if a statement is given below:

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

Let's see a simple example of c language if statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13.   
  14. getch();  
  15. }  

Output

enter a number:4

4 is even number

enter a number:5

 

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of if-else statement in C

Let's see the simple example of even and odd number using if-else statement in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number%2==0){  
  11. printf("%d is even number",number);  
  12. }  
  13. else{  
  14. printf("%d is odd number",number);  
  15. }  
  16. getch();  
  17. }  

Output

enter a number:4

4 is even number

enter a number:5

5 is odd number

 

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

The example of if-else-if statement in C language is given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. if(number==10){  
  11. printf("number is equals to 10");  
  12. }  
  13. else if(number==50){  
  14. printf("number is equal to 50");  
  15. }  
  16. else if(number==100){  
  17. printf("number is equal to 100");  
  18. }  
  19. else{  
  20. printf("number is not equal to 10, 50 or 100");  
  21. }  
  22. getch();  
  23. }  

Output

enter a number:4

number is not equal to 10, 50 or 100

enter a number:50

number is equal to 50

 

C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions. It is like if else-if ladder statement.

The syntax of switch statement in c language is given below:

  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }    

Rules for switch statement in C language

1) The switch expression must be of integer or character type.

2) The case value must be integer or character constant.

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

4) The break statement in switch case is not must. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. It is known as fall through state of C switch statement.

Let's try to understand it by the examples. We are assuming there are following variables.

  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Valid Switch

Invalid Switch

Valid Case

Invalid Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case 'a';

case x;

switch(a+b-2)

 

case 1+2;

case x+2;

switch(func(x,y))

 

case 'x'>'y';

case 1,2,3;


Flowchart of switch statement in C

Let's see a simple example of c language switch statement.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10");  
  13. break;  
  14. case 50:  
  15. printf("number is equal to 50");  
  16. break;  
  17. case 100:  
  18. printf("number is equal to 100");  
  19. break;  
  20. default:  
  21. printf("number is not equal to 10, 50 or 100");  
  22. }  
  23. getch();  
  24. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.

Let's try to understand the fall through state of switch statement by the example given below.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6.   
  7. printf("enter a number:");  
  8. scanf("%d",&number);  
  9.   
  10. switch(number){  
  11. case 10:  
  12. printf("number is equals to 10\n");  
  13. case 50:  
  14. printf("number is equal to 50\n");  
  15. case 100:  
  16. printf("number is equal to 100\n");  
  17. default:  
  18. printf("number is not equal to 10, 50 or 100");  
  19. }  
  20. getch();  
  21. }  

Output

enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

 

 

C Loops


The loops in C language are used to execute a block of code or a part of the program several times.

In other words, it iterates a code or group of code many times.

Why use loops in C language?

Suppose that you have to print table of 2, then you need to write 10 lines of code.

By using the loop statement, you can do it by 2 or 3 lines of code only.

Advantage of loops in C

1) It saves code.

2) It helps to traverse the elements of array (which is covered in next pages).


Types of C Loops

There are three types of loops in C language that is given below:

  1. do while
  2. while
  3. for

do-while loop in C

It iterates the code until condition is false. Here, condition is given after the code. So at least once, code is executed whether condition is true or false.

It is better if you have to execute the code at least once.

The syntax of do-while loop in c language is given below:

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart and Example of do-while loop


while loop in C

Like do while, it iterates the code until condition is false. Here, condition is given before the code. So code may be executed 0 or more times.

It is better if number of iteration is not known by the user.

The syntax of while loop in c language is given below:

  1. while(condition){  
  2. //code to be executed  
  3. }  

Flowchart and Example of while loop


for loop in C

Like while, it iterates the code until condition is false. Here, initialization, condition and increment/decrement is given before the code. So code may be executed 0 or more times.

It is good if number of iteration is known by the user.

The syntax of for loop in c language is given below:

  1. for(initialization;condition;incr/decr){  
  2. //code to be executed  
  3. }  

 

 

C break statement


The break statement in C language is used to break the execution of loop (while, do while and for) and switch case.

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

There can be two usage of C break keyword:

  1. With switch case
  2. With loop

Syntax:

  1. jump-statement;  
  2. break;  

The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.

Flowchart of break in c


Example of C break statement with switch case

Click here to see the example of C break with switch statement.


Example of C break statement with loop

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

Output

1
2
3
4
5

As you can see on console output, loop from 1 to 10 is not printed after i==5.


C break statement with inner loop

In such case, it breaks only inner loop, but not outer loop.

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

Output

1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3

As you can see the output on console, 2 3 is not printed because there is break statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break statement works for inner loop only.

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. #include <conio.h>    
  3. void main(){    
  4. int i=1;//initializing a local variable  
  5. clrscr();    
  6.   
  7. //starting a loop from 1 to 10  
  8. for(i=1;i<=10;i++){    
  9. if(i==5){//if value of i is equal to 5, it will continue the loop  
  10. continue;  
  11. }  
  12. printf("%d \n",i);  
  13. }//end of for loop  
  14.   
  15. getch();    
  16. }    

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.


C continue statement with inner loop

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

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

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. #include <conio.h>  
  3. void main() {  
  4.   int age;  
  5.   clrscr();  
  6.    ineligible:  
  7.    printf("You are not eligible to vote!\n");  
  8.   
  9.    printf("Enter you age:\n");  
  10.    scanf("%d", &age);  
  11.    if(age<18)  
  12.         goto ineligible;  
  13.    else  
  14.         printf("You are eligible to vote!\n");  
  15.   
  16.    getch();  
  17. }  

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. #include <conio.h>    
  3. void main(){      
  4. clrscr();      
  5.   
  6. float f= (float)9/4;  
  7. printf("f : %f\n", f );  
  8.   
  9. getch();      
  10. }      

Output:

f : 2.250000

 

 

functions in C


The function in C language is also known as procedure or subroutine in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.


Advantage of functions in C

There are many advantages of functions.

1) Code Reusability

By creating functions in C, you can call it many times. So we don't need to write the same code again and again.

2) Code optimization

It makes the code optimized, we don't need to write much code.

Suppose, you have to check 3 numbers (781, 883 and 531) whether it is prime number or not. Without using function, you need to write the prime number logic 3 times. So, there is repetition of code.

But if you use functions, you need to write the logic only once and you can reuse it several times.


Syntax to declare function in C

The syntax of creating function in c language is given below:

  1. return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

Syntax to call function in C

The syntax of calling function in c language is given below:

  1. variable=function_name(arguments...);  

1) variable: The variable is not mandatory. If function return type is void, you must not provide the variable because void functions doesn't return any value.

2) function_name: The function_name is name of the function to be called.

3) arguments: You need to provide same number of arguments as defined in the function at the time of declaration or definition.


Example of function in C

Let's see the simple program of function in c language.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. //defining function    
  4. int cube(int n){  
  5. return n*n*n;  
  6. }  
  7. void main(){      
  8. int result1=0,result2=0;    
  9. clrscr();      
  10.   
  11. result1=cube(2);//calling function  
  12. result2=cube(3);    
  13.       
  14. printf("%d \n",result1);  
  15. printf("%d \n",result2);  
  16.   
  17. getch();      
  18. }      

Output

8
27

 

Call by value and call by reference in C

There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.

 

Let's understand call by value and call by reference in c language one by one.


Call by value in C

In call by value, original value is not modified.

In call by value, value being passed to the function is locally stored by the function parameter in stack memory location. If you change the value of function parameter, it is changed for the current function only. It will not change the value of variable inside the caller method such as main().

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int num) {  
  4.     printf("Before adding value inside function num=%d \n",num);  
  5.     num=num+100;  
  6.     printf("After adding value inside function num=%d \n", num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(x);//passing value in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100

Call by reference in C

In call by reference, original value is modified because we pass reference (address).

Here, address of the value is passed in the function, so actual and formal arguments shares the same address space. Hence, value changed inside the function, is reflected inside as well as outside the function.

Note: To understand the call by reference, you must have the basic knowledge of pointers.

Let's try to understand the concept of call by reference in c language by the example given below:

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void change(int *num) {  
  4.     printf("Before adding value inside function num=%d \n",*num);  
  5.     (*num) += 100;  
  6.     printf("After adding value inside function num=%d \n", *num);  
  7. }  
  8.   
  9. int main() {  
  10.     int x=100;  
  11.     clrscr();  
  12.   
  13.     printf("Before function call x=%d \n", x);  
  14.     change(&x);//passing reference in function  
  15.     printf("After function call x=%d \n", x);  
  16.   
  17.     getch();  
  18.     return 0;  
  19. }  

Output

Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of value is passed to the function

An address of value is passed to the function

2

Changes made inside the function is not reflected on other functions

Changes made inside the function is reflected outside the function also

3

Actual and formal arguments will be created in different memory location

Actual and formal arguments will be created in same memory location

 

Recursion in C

When function is called within the same function, it is known as recursion in C. The function which calls the same function, is known as recursive function.

A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail recursion, we generally call the same function with return statement. An example of tail recursion is given below.

Let's see a simple example of recursion.

  1. recursionfunction(){  
  2.   
  3. recursionfunction();//calling self function  
  4.   
  5. }  

Example of tail recursion in C

Let's see an example to print factorial number using tail recursion in C language.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. int factorial (int n)  
  4. {  
  5.     if ( n < 0)  
  6.         return -1; /*Wrong value*/  
  7.     if (n == 0)  
  8.         return 1; /*Terminating condition*/  
  9.     return (n * factorial (n -1));  
  10. }  
  11.   
  12. void main(){  
  13. int fact=0;  
  14. clrscr();  
  15. fact=factorial(5);  
  16. printf("\n factorial of 5 is %d",fact);  
  17.   
  18. getch();  
  19. }  

Output

factorial of 5 is 120

We can understand the above program of recursive method call by the figure given below:

 

 

Storage Classes in C


Storage classes are used to define scope and life time of a variable. There are four storage classes in C programming.

  • auto
  • extern
  • static
  • register

Storage Classes

Storage Place

Default Value

Scope

Life-time

auto

RAM

Garbage Value

Local

Within function

extern

RAM

Zero

Global

Till the end of main program, May be declared anywhere in the program

static

RAM

Zero

Local

Till the end of main program, Retains value between multiple functions call

register

Register

Garbage Value

Local

Within function

1) auto

The auto keyword is applied to all local variables automatically. It is the default storage class that is why it is known as automatic variable.

  1. #include <stdio.h>  
  2. void main(){  
  3. int a=10;  
  4. auto int b=10;//same like above  
  5. printf("%d %d",a,b);  
  6. }  

Output:

10 10

2) register

The register variable allocates memory in register than RAM. Its size is same of register size. It has a faster access than other variables.

It is recommended to use register variable only for quick access such as in counter.

Note: We can't get the address of register variable.

  1. register int counter=0;  

3) static

The static variable is initialized only once and exists till the end of the program. It retains its value between multiple functions call.

The static variable has the default value 0 which is provided by compiler.

  1. #include <stdio.h>  
  2. void func() {  
  3.    static int i=0;//static variable  
  4.    int j=0;//local variable  
  5.    i++;  
  6.    j++;  
  7.    printf("i= %d and j= %d\n", i, j);  
  8. }  
  9. void main() {  
  10.   func();  
  11.   func();  
  12.   func();  
  13. }  

Output:

i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1

4) extern

The extern variable is visible to all the programs. It is used if two ore more files are sharing same variable or function.

  1. extern int counter=0;

 

 

Array in C


Array in C language is a collection or group of elements (data). All the elements of c array are homogeneous (similar). It has contiguous memory location.

C array is beneficial if you have to store similar elements. Suppose you have to store marks of 50 students, one way to do this is allotting 50 variables. So it will be typical and hard to manage. For example we can not access the value of these variables with only 1 or 2 lines of code.

Another way to do this is array. By using array, we can access the elements easily. Only few lines of code is required to access the elements of array.


Advantage of C Array

1) Code Optimization: Less code to the access the data.

2) Easy to traverse data: By using the for loop, we can retrieve the elements of an array easily.

3) Easy to sort data: To sort the elements of array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.


Disadvantage of C Array

1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.


Declaration of C Array

We can declare an array in the c language in the following way.

  1. data_type array_name[array_size];  

Now, let us see the example to declare array.

  1. int marks[5];  

Here, int is the data_type, marks is the array_name and 5 is the array_size.


Initialization of C Array

A simple way to initialize array is by index. Notice that array index starts from 0 and ends with [SIZE - 1].

  1. marks[0]=80;//initialization of array  
  2. marks[1]=60;  
  3. marks[2]=70;  
  4. marks[3]=85;  
  5. marks[4]=75;  


C array example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5];//declaration of array  
  6. clrscr();    
  7.   
  8. marks[0]=80;//initialization of array  
  9. marks[1]=60;  
  10. marks[2]=70;  
  11. marks[3]=85;  
  12. marks[4]=75;  
  13.   
  14. //traversal of array  
  15. for(i=0;i<5;i++){    
  16. printf("%d \n",marks[i]);  
  17. }//end of for loop  
  18.   
  19. getch();    
  20. }    

Output

80
60
70
85
75

C Array: Declaration with Initialization

We can initialize the c array at the time of declaration. Let's see the code.

  1. int marks[5]={20,30,40,50,60};  

In such case, there is no requirement to define size. So it can also be written as the following code.

  1. int marks[]={20,30,40,50,60};  

Let's see the full program to declare and initialize the array in C.

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0;  
  5. int marks[5]={20,30,40,50,60};//declaration and initialization of array  
  6. clrscr();    
  7.   
  8. //traversal of array  
  9. for(i=0;i<5;i++){    
  10. printf("%d \n",marks[i]);  
  11. }  
  12.   
  13. getch();    
  14. }    

Output

20
30
40
50
60

 

Two Dimensional Array in C

The two dimensional array in C language is represented in the form of rows and columns, also known as matrix. It is also known as array of arraysor list of arrays.

The two dimensional, three dimensional or other dimensional arrays are also known as multidimensional arrays.

Declaration of two dimensional Array in C

We can declare an array in the c language in the following way.

  1. data_type array_name[size1][size2];  

A simple example to declare two dimensional array is given below.

  1. int twodimen[4][3];  

Here, 4 is the row number and 3 is the column number.


Initialization of 2D Array in C

A way to initialize the two dimensional array at the time of declaration is given below.

  1. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  

Two dimensional array example in C

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. void main(){    
  4. int i=0,j=0;  
  5. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  
  6. clrscr();    
  7.   
  8. //traversing 2D array  
  9. for(i=0;i<4;i++){  
  10.  for(j=0;j<3;j++){  
  11.    printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);  
  12.  }//end of j  
  13. }//end of i  
  14.   
  15. getch();    
  16. }    

Output

arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6

 

Passing Array to Function in C

To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.

  1. functionname(arrayname);//passing array  

There are 3 ways to declare function that receives array as argument.

First way:

  1. return_type function(type arrayname[])  

Declaring blank subscript notation [] is the widely used technique.

Second way:

  1. return_type function(type arrayname[SIZE])  

Optionally, we can define size in subscript notation [].

Third way:

  1. return_type function(type *arrayname)  

You can also use the concept of pointer. In pointer chapter, we will learn about it.


C language passing array to function example

  1. #include <stdio.h>    
  2. #include <conio.h>    
  3. int minarray(int arr[],int size){  
  4. int min=arr[0];  
  5. int i=0;  
  6. for(i=1;i<size;i++){  
  7. if(min>arr[i]){  
  8. min=arr[i];  
  9. }  
  10. }//end of for  
  11. return min;  
  12. }//end of function  
  13.   
  14. void main(){    
  15. int i=0,min=0;  
  16. int numbers[]={4,5,7,3,8,9};//declaration of array  
  17. clrscr();    
  18.   
  19. min=minarray(numbers,6);//passing array with size  
  20. printf("minimum number is %d \n",min);  
  21.   
  22. getch();    
  23. }    

Output

minimum number is 3

 

 

Pointers in C


The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a value.


Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions.

2) We can return multiple values from function using pointer.

3) It makes you able to access any memory location in the computer's memory.


Usage of pointer

There are many usage of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.

2) Arrays, Functions and Structures

Pointers in c language are widely used in arrays, functions and structures. It reduces the code and improves the performance.


Symbols used in pointer

Symbol

Name

Description

& (ampersand sign)

address of operator

determines the address of a variable.

* (asterisk sign)

indirection operator

accesses the value at the address.


Address Of Operator

The address of operator '&' returns the address of a variable. But, we need to use %u to display the address of a variable.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;    
  5. clrscr();      
  6. printf("value of number is %d, address of number is %u",number,&number);  
  7. getch();      
  8. }      

Output

value of number is 50, address of number is fff4

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol).

  1. int *a;//pointer to int  
  2. char *c;//pointer to char  

Pointer example

An example of using pointers printing the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable i.e. fff4. The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for above figure.

  1. #include <stdio.h>      
  2. #include <conio.h>    
  3. void main(){      
  4. int number=50;  
  5. int *p;    
  6. clrscr();  
  7. p=&number;//stores the address of number variable  
  8.       
  9. printf("Address of number variable is %x \n",&number);  
  10. printf("Address of p variable is %x \n",p);  
  11. printf("Value of p variable is %d \n",*p);  
  12.   
  13. getch();      
  14. }      

Output

Address of number variable is fff4
Address of p variable is fff4
Value of p variable is 50

NULL Pointer

A pointer that is not assigned any value but NULL is known as NULL pointer. If you don't have any address to be specified in the pointer at the time of declaration, you can assign NULL value. It will a better approach.

int *p=NULL;

In most the libraries, the value of pointer is 0 (zero).

C Pointer to Pointer

In C pointer to pointer concept, a pointer refers to the address of another pointer.

In c language, a pointer can point to the address of another pointer which points to the address of a value. Let's understand it by the diagram given below:

Let's see the syntax of pointer to pointer.

  1. int **p2;  

C pointer to pointer example

Let's see an example where one pointer points to the address of another pointer.

As you can see in the above figure, p2 contains the address of p (fff2) and p contains the address of number variable (fff4).

  1. #include <stdio.h>        
  2. #include <conio.h>      
  3. void main(){        
  4. int number=50;    
  5. int *p;//pointer to int  
  6. int **p2;//pointer to pointer      
  7. clrscr();    
  8. p=&number;//stores the address of number variable    
  9. p2=&p;  
  10.         
  11. printf("Address of number variable is %x \n",&number);    
  12. printf("Address of p variable is %x \n",p);    
  13. printf("Value of *p variable is %d \n",*p);    
  14. printf("Address of p2 variable is %x \n",p2);    
  15. printf("Value of **p2 variable is %d \n",**p);    
  16.     
  17. getch();        
  18. }        

Output

Address of number variable is fff4
Address of p variable is fff4
Value of *p variable is 50
Address of p2 variable is fff2
Value of **p variable is 50

Pointer Arithmetic in C

In C pointer holds address of a value, so there can be arithmetic operations on the pointer variable. Following arithmetic operations are possible on pointer in C language:

  • Increment
  • Decrement
  • Addition
  • Subtraction
  • Comparison

Incrementing Pointer in C

Incrementing a pointer is used in array because it is contiguous memory location. Moreover, we know the value of next location.

Increment operation depends on the data type of the pointer variable. The formula of incrementing pointer is given below:

  1. new_address= current_address + i * size_of(data type)  

32 bit

For 32 bit int variable, it will increment to 2 byte.

64 bit

For 64 bit int variable, it will increment to 4 byte.

Let's see the example of incrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+1;     
  9. printf("After increment: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After increment: Address of p variable is 3214864304 

Decrementing Pointer in C

Like increment, we can decrement a pointer variable. The formula of decrementing pointer is given below:

  1. new_address= current_address - i * size_of(data type)  

32 bit

For 32 bit int variable, it will decrement to 2 byte.

64 bit

For 64 bit int variable, it will decrement to 4 byte.

Let's see the example of decrementing pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-1;     
  9. printf("After decrement: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After decrement: Address of p variable is 3214864296 

C Pointer Addition

We can add a value to the pointer variable. The formula of adding value to pointer is given below:

  1. new_address= current_address + (number * size_of(data type))  

32 bit

For 32 bit int variable, it will add 2 * number.

64 bit

For 64 bit int variable, it will add 4 * number.

Let's see the example of adding value to pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p+3;   //adding 3 to pointer variable  
  9. printf("After adding 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After adding 3: Address of p variable is 3214864312

As you can see, address of p is 3214864300. But after adding 3 with p variable, it is 3214864312 i.e. 4*3=12 increment. Since we are using 64 bit OS, it increments 12. But if we were using 32 bit OS, it were incrementing to 6 only i.e. 2*3=6. As integer value occupies 2 byte memory in 32 bit OS.


C Pointer Subtraction

Like pointer addition, we can subtract a value from the pointer variable. The formula of subtracting value from pointer variable is given below:

  1. new_address= current_address - (number * size_of(data type))  

32 bit

For 32 bit int variable, it will subtract 2 * number.

64 bit

For 64 bit int variable, it will subtract 4 * number.

Let's see the example of subtracting value from pointer variable on 64 bit OS.

  1. #include <stdio.h>          
  2. void main(){          
  3. int number=50;      
  4. int *p;//pointer to int    
  5. p=&number;//stores the address of number variable      
  6.           
  7. printf("Address of p variable is %u \n",p);      
  8. p=p-3; //subtracting 3 from pointer variable  
  9. printf("After subtracting 3: Address of p variable is %u \n",p);      
  10. }    

Output

Address of p variable is 3214864300 
After subtracting 3: Address of p variable is 3214864288

You can see after subtracting 3 from pointer variable, it is 12 (4*3) less than the previous address value.

 

 

Dynamic memory allocation


The concept of dynamic memory allocation in c language enables the C programmer to allocate memory at runtime. Dynamic memory allocation in c language is possible by 4 functions of stdlib.h header file.

 1. malloc()

 2. calloc()

 3. realloc()

 4. free()

Before learning above functions, let's understand the difference between static memory allocation and dynamic memory allocation.

static memory allocation

dynamic memory allocation

memory is allocated at compile time.

memory is allocated at run time.

memory can't be increased while executing program.

memory can be increased while executing program.

used in array.

used in linked list.

Now let's have a quick look at the methods used for dynamic memory allocation.

malloc()

allocates single block of requested memory.

calloc()

allocates multiple block of requested memory.

realloc()

reallocates the memory occupied by malloc() or calloc() functions.

free()

frees the dynamically allocated memory.


malloc() function in C

The malloc() function allocates single block of requested memory.

It doesn't initialize memory at execution time, so it has garbage value initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

  1. ptr=(cast-type*)malloc(byte-size)  

Let's see the example of malloc() function.

#include <stdio.h>  

#include <stdlib.h>  

void main()

{  

    int n,i,*ptr,sum=0;  

    printf("Enter number of elements: ");  

    scanf("%d",&n);  

    ptr=(int*)malloc(n*sizeof(int));  

    if(ptr==NULL)                       

    {  

        printf("Sorry! unable to allocate memory");  

        exit(0);  

    }  

    printf("Enter elements of array: ");  

    for(i=0;i<n;++i)  

    {  

        scanf("%d",ptr+i);  

        sum+=*(ptr+i);  

    }  

    printf("Sum=%d",sum);  

    free(ptr);  

}  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

calloc() function in C

The calloc() function allocates multiple block of requested memory.

It initially initialize all bytes to zero.

It returns NULL if memory is not sufficient.

The syntax of calloc() function is given below:

  1. ptr=(cast-type*)calloc(number, byte-size)  

Let's see the example of calloc() function.

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. void main(){  
  4.     int n,i,*ptr,sum=0;  
  5.     printf("Enter number of elements: ");  
  6.     scanf("%d",&n);  
  7.     ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc  
  8.     if(ptr==NULL)                       
  9.     {  
  10.         printf("Sorry! unable to allocate memory");  
  11.         exit(0);  
  12.     }  
  13.     printf("Enter elements of array: ");  
  14.     for(i=0;i<n;++i)  
  15.     {  
  16.         scanf("%d",ptr+i);  
  17.         sum+=*(ptr+i);  
  18.     }  
  19.     printf("Sum=%d",sum);  
  20.     free(ptr);  
  21. }  

Output:

Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30

realloc() function in C

If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by realloc() function. In short, it changes the memory size.

Let's see the syntax of realloc() function.

  1. ptr=realloc(ptr, new-size)  

free() function in C

The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

Let's see the syntax of free() function.

  1. free(ptr)  

 

 

Structure in C


Structure in c language is a user-defined datatype that allows you to hold different type of elements.

Each element of a structure is called a member.

It works like a template in C++ and class in Java. You can have different type of elements in it.

It is widely used to store student information, employee information, product information, book information etc.


Defining structure

The struct keyword is used to define structure. Let's see the syntax to define structure in c.

  1. struct structure_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define structure for employee in c.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Here, struct is the keyword, employee is the tag name of structure; idname and salary are the members or fields of the structure. Let's understand it by the diagram given below:


Declaring structure variable

We can declare variable for the structure, so that we can access the member of structure easily. There are two ways to declare structure variable:

  1. By struct keyword within main() function
  2. By declaring variable at the time of defining structure.

1st way:

Let's see the example to declare structure variable by struct keyword. It should be declared within the main function.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

Now write given code inside the main() function.

  1. struct employee e1, e2;  

2nd way:

Let's see another way to declare variable at the time of defining structure.

  1. struct employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. }e1,e2;  

Which approach is good

But if no. of variable are not fixed, use 1st approach. It provides you flexibility to declare the structure variable many times.

If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.


Accessing members of structure

There are two ways to access structure members:

  1. By . (member or dot operator)
  2. By -> (structure pointer operator)

Let's see the code to access the id member of p1 variable by . (member) operator.

  1. p1.id  

C Structure example

Let's see a simple example of structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for structure  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra

Let's see another example of structure in C language to store many employees information.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct employee    
  4. {   int id;    
  5.     char name[50];    
  6.     float salary;    
  7. }e1,e2;  //declaring e1 and e2 variables for structure  
  8. int main( )  
  9. {  
  10.    //store first employee information  
  11.    e1.id=101;  
  12.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  13.    e1.salary=56000;  
  14.   
  15.   //store second employee information  
  16.    e2.id=102;  
  17.    strcpy(e2.name, "James Bond");  
  18.    e2.salary=126000;  
  19.    
  20.    //printing first employee information  
  21.    printf( "employee 1 id : %d\n", e1.id);  
  22.    printf( "employee 1 name : %s\n", e1.name);  
  23.    printf( "employee 1 salary : %f\n", e1.salary);  
  24.   
  25.    //printing second employee information  
  26.    printf( "employee 2 id : %d\n", e2.id);  
  27.    printf( "employee 2 name : %s\n", e2.name);  
  28.    printf( "employee 2 salary : %f\n", e2.salary);  
  29.   
  30.    return 0;  
  31. }  

Output:

employee 1 id : 101
employee 1 name : Sonoo Mishra
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000

Nested Structure in C

Nested structure in c language can have another structure as a member. There are two ways to define nested structure in c language:

  1. By separate structure
  2. By Embedded structure

1) Separate structure

We can create 2 structures, but dependent structure should be used inside the main structure as a member. Let's see the code of nested structure.

  1. struct Date  
  2. {  
  3.    int dd;  
  4.    int mm;  
  5.    int yyyy;   
  6. };  
  7. struct Employee  
  8. {     
  9.    int id;  
  10.    char name[20];  
  11.    struct Date doj;  
  12. }emp1;  

As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.


2) Embedded structure

We can define structure within the structure also. It requires less code than previous way. But it can't be used in many structures.

  1. struct Employee  
  2. {     
  3.    int id;  
  4.    char name[20];  
  5.    struct Date  
  6.     {  
  7.       int dd;  
  8.       int mm;  
  9.       int yyyy;   
  10.     }doj;  
  11. }emp1;  

Accessing Nested Structure

We can access the member of nested structure by Outer_Structure.Nested_Structure.member as given below:

  1. e1.doj.dd  
  2. e1.doj.mm  
  3. e1.doj.yyyy  

C Nested Structure example

Let's see a simple example of nested structure in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. struct Employee  
  4. {     
  5.    int id;  
  6.    char name[20];  
  7.    struct Date  
  8.     {  
  9.       int dd;  
  10.       int mm;  
  11.       int yyyy;   
  12.     }doj;  
  13. }e1;  
  14. int main( )  
  15. {  
  16.    //storing employee information  
  17.    e1.id=101;  
  18.    strcpy(e1.name, "Sonoo Mishra");//copying string into char array  
  19.    e1.doj.dd=10;  
  20.    e1.doj.mm=11;  
  21.    e1.doj.yyyy=2014;  
  22.   
  23.    //printing first employee information  
  24.    printf( "employee id : %d\n", e1.id);  
  25.    printf( "employee name : %s\n", e1.name);  
  26.    printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);  
  27.    return 0;  
  28. }  

Output:

employee id : 101
employee name : Sonoo Mishra
employee date of joining (dd/mm/yyyy) : 10/11/2014

 

Union in C


Like structure, Union in c language is a user-defined data type that is used to hold a different types of elements.

But it doesn't occupy the sum of all member's sizes. It occupies the memory of the largest member only. It shares a memory of the largest member.

Advantage of union over structure

It occupies less memory because it occupies the memory of largest member only.

Disadvantage of union over structure

It can store data in one member only.


Defining union

The union keyword is used to define union. Let's see the syntax to define union in c.

  1. union union_name   
  2. {  
  3.     data_type member1;  
  4.     data_type member2;  
  5.     .  
  6.     .  
  7.     data_type memeberN;  
  8. };  

Let's see the example to define union for employee in c.

  1. union employee  
  2. {   int id;  
  3.     char name[50];  
  4.     float salary;  
  5. };  

C Union example

Let's see a simple example of union in C language.

  1. #include <stdio.h>  
  2. #include <string.h>  
  3. union employee    
  4. {   int id;    
  5.     char name[50];    
  6. }e1;  //declaring e1 variable for union  
  7. int main( )  
  8. {  
  9.    //store first employee information  
  10.    e1.id=101;  
  11.    strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array  
  12.    //printing first employee information  
  13.    printf( "employee 1 id : %d\n", e1.id);  
  14.    printf( "employee 1 name : %s\n", e1.name);  
  15.    return 0;  
  16. }  

Output:

employee 1 id : 1869508435
employee 1 name : Sonoo Jaiswal

As you can see, id gets garbage value because name has large memory size. So only name will have actual value

 

 

File Handling in C


File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.


Advantage of File

It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage medium.


Functions for file handling

There are many functions in C library to open, read, write, search and close file. A list of file functions are given below:

No.

Function

Description

1

fopen()

opens new or existing file

2

fprintf()

write data into file

3

fscanf()

reads data from file

4

fputc()

writes a character into file

5

fgetc()

reads a character from file

6

fclose()

closes the file

7

fseek()

sets the file pointer to given position

8

fputw()

writes an integer to file

9

fgetw()

reads an integer from file

10

ftell()

returns current position

11

rewind()

sets the file pointer to the beginning of the file


Opening File

The fopen() function is used to open a file. The syntax of fopen() function is given below:

  1. FILE *fopen( const char * filename, const char * mode );  

You can use one of the following modes in the fopen() function.

Mode

Description

R

opens a text file in read mode

W

opens a text file in write mode

A

opens a text file in append mode

r+

opens a text file in read and write mode

w+

opens a text file in read and write mode

a+

opens a text file in read and write mode

Rb

opens a binary file in read mode

Wb

opens a binary file in write mode

ab

opens a binary file in append mode

rb+

opens a binary file in read and write mode

wb+

opens a binary file in read and write mode

ab+

opens a binary file in read and write mode

 


Closing File

The fclose() function is used to close a file. The syntax of fclose() function is given below:

  1. int fclose( FILE *fp );  

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   fp = fopen("file.txt""w");//opening file  

   fprintf(fp, "Hello file by fprintf...\n");//writing data into file  

   fclose(fp);//closing file  

}  


Reading File : fscanf() function

The fscanf() function is used to read set of characters from file.

#include <stdio.h>  

main(){  

   FILE *fp;  

   char buff[255];//creating char array to store data of file  

   fp = fopen("file.txt""r");  

   fscanf(fp, "%s", buff);//reading data of file and writing into char array  

   printf("Data is : %s\n", buff );//printing data of char array  

   fclose(fp);  

}  

Output:

Data is : Hello file by fprintf...

C File Example: Storing employee information

Let's see a file handling example to store employee information as entered by user from console. We are going to store id, name and salary of the employee.

  1. #include <stdio.h>  

void main()  

{  

    FILE *fptr;  

    int id;  

    char name[30];  

    float salary;  

    fptr = fopen("emp.txt""w+");/*  open for writing */  

    if (fptr == NULL)  

    {  

        printf("File does not exists \n");  

        return;  

    }  

    printf("Enter the id\n");  

    scanf("%d", &id);  

    fprintf(fptr, "Id= %d\n", id);  

    printf("Enter the name \n");  

    scanf("%s", name);  

    fprintf(fptr, "Name= %s\n", name);  

    printf("Enter the salary\n");  

    scanf("%f", &salary);  

    fprintf(fptr, "Salary= %.2f\n", salary);  

    fclose(fptr);  

}  

Output:

Enter the id 
1
Enter the name 
sonoo
Enter the salary
120000 

Now open file from current directory. For windows operating system, go to TC\bin directory, you will see emp.txt file. It will have following information.

emp.txt

Id= 1
Name= sonoo
Salary= 120000 

 

 

Preprocessor Directives


The C preprocessor is a micro processor that is used by compiler to transform your code before compilation. It is called micro preprocessor because it allows us to add macros.

Note: Proprocessor direcives are executed before compilation.

All preprocessor directives starts with hash # symbol.

List of preprocessor directives.

  • #include
  • #define
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif
  • #endif
  • #error
  • #pragma

C Macros

A macro is a segment of code which is replaced by the value of macro. Macro is defined by #define directive. There are two types of macros:

  1. Object-like Macros
  2. Function-like Macros

Object-like Macros

The object-like macro is an identifier that is replaced by value. It is widely used to represent numeric constants. For example:

  1. #define PI 3.14  

Here, PI is the macro name which will be replaced by the value 3.14.

Function-like Macros

The function-like macro looks like function call. For example:

  1. #define MIN(a,b) ((a)<(b)?(a):(b))

Here, MIN is the macro name.

Visit #define to see the full example of object-like and function-like macros.

C Predefined Macros

ANSI C defines many predefined macros that can be used in c program.

No.

Macro

Description

1

_DATE_

represents current date in "MMM DD YYYY" format.

2

_TIME_

represents current time in "HH:MM:SS" format.

3

_FILE_

represents current file name.

4

_LINE_

represents current line number.

5

_STDC_

It is defined as 1 when compiler complies with the ANSI standard.

C predefined macros example

File: simple.c

#include <stdio.h>  

main() {  

   printf("File :%s\n", __FILE__ );  

   printf("Date :%s\n", __DATE__ );  

   printf("Time :%s\n", __TIME__ );  

   printf("Line :%d\n", __LINE__ );  

   printf("STDC :%d\n", __STDC__ );  

}  

Output:

File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1

 

C #include

The #include preprocessor directive is used to paste code of given file into current file. It is used include system-defined and user-defined header files. If included file is not found, compiler renders error.

By the use of #include directive, we provide information to the preprocessor where to look for the header files. There are two variants to use #include directive.

  1. #include <filename>
  2. #include "filename"

The #include <filename> tells the compiler to look for the directory where system header files are held. In UNIX, it is \usr\include directory.

The #include "filename" tells the compiler to look in the current directory from where program is running.

#include directive example

Let's see a simple example of #include directive. In this program, we are including stdio.h file because printf() function is defined in this file.

  1. #include <stdio.h>  
  2. main() {  
  3.    printf("Hello C");  
  4. }  

Output:

Hello C

#include notes:

Note 1: In #include directive, comments are not recognized. So in case of #include <a//b>, a//b is treated as filename.

Note 2: In #include directive, backslash is considered as normal text not escape sequence. So in case of #include <a\nb>, a\nb is treated as filename.

Note 3: You can use only comment after filename otherwise it will give error.

C #define

The #define preprocessor directive is used to define constant or micro substitution. It can use any basic data type.

Syntax:

  1. #define token value  

Let's see an example of #define to define a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. main() {  
  4.    printf("%f",PI);  
  5. }  

Output:

3.140000

Let's see an example of #define to create a macro.

  1. #include <stdio.h>  
  2. #define MIN(a,b) ((a)<(b)?(a):(b))  
  3. void main() {  
  4.    printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));    
  5. }  

Output:

Minimum between 10 and 20 is: 10

C #undef

The #undef preprocessor directive is used to undefine the constant or macro defined by #define.

Syntax:

  1. #undef token  

Let's see a simple example to define and undefine a constant.

  1. #include <stdio.h>  
  2. #define PI 3.14  
  3. #undef PI  
  4. main() {  
  5.    printf("%f",PI);  
  6. }  

Output:

Compile Time Error: 'PI' undeclared

The #undef directive is used to define the preprocessor constant to a limited scope so that you can declare constant again.

Let's see an example where we are defining and undefining number variable. But before being undefined, it was used by square variable.

  1. #include <stdio.h>  
  2. #define number 15  
  3. int square=number*number;  
  4. #undef number  
  5. main() {  
  6.    printf("%d",square);  
  7. }  

Output:

225

C #ifdef

The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifdef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifdef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

 

C #ifdef example

Let's see a simple example to use #ifdef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NOINPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifdef NOINPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Value of a: 2

But, if you don't define NOINPUT, it will ask user to enter a number.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifdef NOINPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11.   
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

C #ifndef

The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the code otherwise #else code is executed, if present.

Syntax:

  1. #ifndef MACRO  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #ifndef MACRO  
  2. //successful code  
  3. #else  
  4. //else code  
  5. #endif  

C #ifndef example

Let's see a simple example to use #ifndef preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define INPUT  
  4. void main() {  
  5. int a=0;  
  6. #ifndef INPUT  
  7. a=2;  
  8. #else  
  9. printf("Enter a:");  
  10. scanf("%d", &a);  
  11. #endif         
  12. printf("Value of a: %d\n", a);  
  13. getch();  
  14. }  

Output:

Enter a:5
Value of a: 5

But, if you don't define INPUT, it will execute the code of #ifndef.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. void main() {  
  4. int a=0;  
  5. #ifndef INPUT  
  6. a=2;  
  7. #else  
  8. printf("Enter a:");  
  9. scanf("%d", &a);  
  10. #endif         
  11. printf("Value of a: %d\n", a);  
  12. getch();  
  13. }  

Output:

Value of a: 2

 

C #if

The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes the code otherwise #elseif or #else or #endif code is executed.

Syntax:

  1. #if expression  
  2. //code  
  3. #endif  

Syntax with #else:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif and #else:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #if example

Let's see a simple example to use #if preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 0  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #endif         
  8. getch();  
  9. }  

Output:

Value of Number is: 0

C #else

The #else preprocessor directive evaluates the expression or condition if condition of #if is false. It can be used with #if, #elif, #ifdef and #ifndef directives.

Syntax:

  1. #if expression  
  2. //if code  
  3. #else  
  4. //else code  
  5. #endif  

Syntax with #elif:

  1. #if expression  
  2. //if code  
  3. #elif expression  
  4. //elif code  
  5. #else  
  6. //else code  
  7. #endif  

C #else example

Let's see a simple example to use #else preprocessor directive.

  1. #include <stdio.h>  
  2. #include <conio.h>  
  3. #define NUMBER 1  
  4. void main() {  
  5. #if NUMBER==0  
  6. printf("Value of Number is: %d",NUMBER);  
  7. #else  
  8. print("Value of Number is non-zero");  
  9. #endif         
  10. getch();  
  11. }  

Output:

Value of Number is non-zero

 

 

C #error

The #error preprocessor directive indicates error. The compiler gives fatal error if #error directive is found and skips further compilation process.

C #error example

Let's see a simple example to use #error preprocessor directive.

  1. #include<stdio.h>  
  2. #ifndef __MATH_H  
  3. #error First include then compile  
  4. #else  
  5. void main(){  
  6.     float a;  
  7.     a=sqrt(7);  
  8.     printf("%f",a);  
  9. }  
  10. #endif  

Output:

Compile Time Error: First include then compile

But, if you include math.h, it does not gives error.

  1. #include<stdio.h>  
  2. #include<math.h>  
  3. #ifndef __MATH_H  
  4. #error First include then compile  
  5. #else  
  6. void main(){  
  7.     float a;  
  8.     a=sqrt(7);  
  9.     printf("%f",a);  
  10. }  
  11. #endif  

Output:

2.645751

 

 

 

C #pragma

The #pragma preprocessor directive is used to provide additional information to the compiler. The #pragma directive is used by the compiler to offer machine or operating-system feature.

Syntax:

  1. #pragma token  

Different compilers can provide different usage of #pragma directive.

The turbo C++ compiler supports following #pragma directives.

  1. #pragma argsused  
  2. #pragma exit  
  3. #pragma hdrfile  
  4. #pragma hdrstop  
  5. #pragma inline  
  6. #pragma option  
  7. #pragma saveregs  
  8. #pragma startup  
  9. #pragma warn  

Let's see a simple example to use #pragma preprocessor directive.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3.   
  4. void func() ;  
  5.   
  6. #pragma startup func  
  7. #pragma exit func  
  8.  
  9. void main(){  
  10. printf("\nI am in main");  
  11. getch();  
  12. }  
  13.   
  14. void func(){  
  15. printf("\nI am in func");  
  16. getch();  
  17. }  

Output:

I am in func
I am in main
I am in func

 

 

Command Line Arguments


The arguments passed from the command line are called command-line arguments. These arguments are handled by main() function.

To support the command line argument, you need to change the structure of main() function as given below.

  1. int main(int argc, char *argv[] )  

Here, argc counts the number of arguments. It counts the file name as the first argument.

The argv[] contains the total number of arguments. The first argument is the file name always.

Example

Let's see the example of command line arguments where we are passing one argument with file name.

#include <stdio.h>  

void main(int argc, char *argv[] ) 

 {  

  

   printf("Program name is: %s\n", argv[0]);  

   

   if(argc < 2){  

      printf("No argument passed through command line.\n");  

   }  

   else{  

      printf("First argument is: %s\n", argv[1]);  

   }  

}  

Run this program as follows in Linux:

  1. ./program hello  

Run this program as follows in Windows from command line:

  1. program.exe hello  

Output:

Program name is: program
First argument is: hello

If you pass many arguments, it will print only one.

  1. ./program hello c how r u  

Output:

Program name is: program
First argument is: hello

But if you pass many arguments within double quote, all arguments will be treated as a single argument only.

  1. ./program "hello c how r u"  

Output:

Program name is: program
First argument is: hello c how r u

You can write your program to print all the arguments. In this program, we are printing only argv[1], that is why it is printing only one argument.