C Programming Language Tutorial

C language Tutorial with programming approach for beginners and professionals, helps you to understand the C language tutorial easily. Our C tutorial explains each topic with programs.

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 following ways:

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

1) C as a mother language

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

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

2) C as a system programming language

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

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

3) C as a procedural language

A procedure is known as function, method, routine, subroutine etc. A procedural language 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

Dennis Ritchie - founder 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.


Where we use C Language

C Language is mainly used for;

  • Design Operating system
  • Design Language Compiler
  • Design Database
  • Language Interpreters
  • Utilities
  • Network Drivers
  • Assemblers

Features of C Language

C features

C is the 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 structured approach (to break the problem into parts), rich set of library functions, data types etc.

2) Machine Independent or Portable

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

3) Mid-level prorgramming language

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

4) Structured prorgramming language

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

5) Rich Library

C provides a lot of inbuilt functions that makes the development fast.

6) Memory Management

It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory at any time by calling the free() function.

7) Speed

The compilation and execution time of C language is fast.

8) 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.

Applications of C

Mainly C Language is used for Develop Desktop application and system software. Some application of C language are given below.

  • C programming language can be used to design the system software like operating system and Compiler.
  • To develop application software like database and spread sheets.
  • For Develop Graphical related application like computer and mobile games.
  • To evaluate any kind of mathematical equation use c language.
  • C programming language can be used to design the compilers.
  • UNIX Kernal is completely developed in C Language.
  • For Creating Compilers of different Languages which can take input from other language and convert it into lower level machine dependent language.
  • C programming language can be used to design Operating System.
  • C programming language can be used to design Network Devices.

How to install C

There are many compilers available for c and c++. You need to download any one. Here, we are going to use Turbo C++. It will work for both C and C++. To install the Turbo C software, you need to follow following steps.

  1. Download Turbo C++
  2. Create turboc directory inside c drive and extract the tc3.zip inside c:\turboc
  3. Double click on install.exe file
  4. Click on the tc application file located inside c:\TC\BIN to write the c program

1) Download Turbo C++ software

You can download turbo c++ from many sites. download Turbo c++

2) Create turboc directory in c drive and extract the tc3.zip

Now, you need to create a new directory turboc inside the c: drive. Now extract the tc3.zip file in c:\truboc directory.

3) Double click on the install.exe file and follow steps

Now, click on the install icon located inside the c:\turboc

install turbo c++

It will ask you to install c or not, press enter to install.

how to install turbo c++

Change your drive to c, press c.

how to install turbo c

Press enter, it will look inside the c:\turboc directory for the required files.

how to install turbo c++

Select Start installation by the down arrow key then press enter.

how to install turbo c

Now C is installed, press enter to read documentation or close the software. how to install turbo c

4) Click on the tc application located inside c:\TC\BIN

Now double click on the tc icon located in c:\TC\BIN directory to write the c program.

tc

In windows 7 or window 8, it will show a dialog block to ignore and close the application because fullscreen mode is not supported. Click on Ignore button.

Now it will showing following console.

install tc

TC Editor

TC Editor is very simple and easy to use; here i will give you all tips related to TC Editor and some shortcut keys related to TC Editor which is very useful at the time of coding. Turbo C is a most common C language compiler. Below i will discuss all about its Interfaces.

TC Editor

TC Editor

The interface of Turbo C is very simple. When IDE screen appears, the menu bar is activated. It contains various menus such as;

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

Shortcut keys Related to TC Editor

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

Source Code Vs Object Code

Difference between source code and object code.

Source Code

  • Source code is in the form of Text form.
  • Source code is Human Readable Code.
  • Source code is Generated by Human or Programmer.
  • Source code is receive Compiler as a Input.

Object Code

  • Object Code is in the form of Binary Numbers.
  • Object Code is in Machine Readable formats.
  • Object Code is Generated by Compiler.
  • Object Code is Generated by Compiler as a Output.

Compiler in C

A compiler is system software which converts programming language code into binary format in single steps. In other words Compiler is a system software which can take input from other any programming language and convert it into lower level machine dependent language.

C Compiling

Interpreter

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

Assembler

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

Compiler Vs Interpreter


Structure of C Program

Every C program can be written with the following syntax.

Syntax

#include<headerfilename.h>  --> include section
Returntype function_name(list of parameters or no parameter)  --> user defined function
{
Set of statements
.........
}
Returntype main()  --> main block or main function
{
.........
.........
}

Include section

# include is a pre-processor directive can be used to include all the predefined functions of given header files into current C program before compilation.

Syntax

#include<headerfile.h>

C library is collection of header files, header files is a container which is collection of related predefined functions.

User defined function section

If any function is defined by the user is known as user defined function. Function is collection of statement used to perform a specific Operation.

Syntax

Return_type function_Name()
{
.......    // called function
.......
}

In the above syntax function name can be any user defined name, return type represents which type of value it can return to its calling function.

Syntax

functionName();    // calling function

Note: User defined function are Optional in a C program.

Main function

This is starting executable block of any program (it is always executed by processor and OS ). One C program can have maximum one main() the entire statements of given program can be executed through main(). Without main() function no C program will be executed.

Syntax

Returntype main()
{
......
.....
}

If return type is void that function can not return any value to the operating system. So that void can be treated as no return type.

Example

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

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

Output

Hello main

IO statements in C language

IO represents input output statements and input statement can be used to read the input value from the standard input device (keyboard), output statement can be used to display the output in standard output device (Monitor) respectively. In C language IO statement can be achieve by using scanf() and printf().


main() function in C

main() function is the entry point of any C program. It is the point at which execution of program is started. When a C program is executed, the execution control goes directly to the main() function. Every C program have a main() function.

Syntax

 void main()
 {
  .........
  .........
 }

In above syntax;

  • void: is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value.
  • In place of void we can also use int return type of main() function, at that time main() return integer type value.
  • main: is a name of function which is predefined function in C library.

Simple example of main()

Example

#include<stdio.h>

void main()
{
printf("This is main function");
}

Output

This is main function



First C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.

To write the first c program, open the C console and write the following code:

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

#include <stdio.h> includes the standard input output library functions. The printf() function is defined in stdio.h .

#include <conio.h> includes the console input output library functions. The getch() function is defined in conio.h file.

void main() The main() function is the entry point of every program in c language. The void keyword specifies that it returns no value.

printf() The printf() function is used to print data on the console.

getch() The getch() function asks for a single character. Until you press any key, it blocks the screen.

c program

How to compile and run the c program

There are 2 ways to compile and run the c program, by menu and by shortcut.

By menu

Now click on the compile menu then compile sub menu to compile the c program.

Then click on the run menu then run sub menu to run the c program.

By shortcut

Or, press ctrl+f9 keys compile and run the program directly.

You will see the following output on user screen.

c program output

You can view the user screen any time by pressing the alt+f5 keys.

Now press Esc to return to the turbo c++ console.

Clrscr() and Getch() in C

clrscr() and getch() both are predefined function in "conio.h" (console input output header file).

Clrscr()

It is a predefined function in "conio.h" (console input output header file) used to clear the console screen. It is a predefined function, by using this function we can clear the data from console (Monitor). Using of clrscr() is always optional but it should be place after variable or function declaration only.

Example of clrscr()

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

void main()
{
int a=10, b=20;
int sum=0;
clrscr();  // use clrscr() after variable declaration
sum=a+b;
printf("Sum: %d",s);
getch();
}

Output

Sum: 30

Getch()

It is a predefined function in "conio.h" (console input output header file) will tell to the console wait for some time until a key is hit given after running of program.

By using this function we can read a character directly from the keyboard. Generally getch() are placing at end of the program after printing the output on screen.

Example of getch()

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

void main()
{
int a=10, b=20;
int sum=0;
clrscr();
sum=a+b;
printf("Sum: %d",s);
getch();  // use getch() befor end of main()
}

Output

Sum: 30

images




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 above program by the figure given below.

C program flow

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

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

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

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

5) The executable code is sent to loader which loads it into memory and then it is executed. After execution, output is sent to console.












Comments in C

Generally Comments are used to provide the description about the Logic written in program. Comments are not display on output screen.

When we are used the comments, then that specific part will be ignored by compiler.

In 'C' language two types of comments are possible

  • Single line comments
  • Multiple line comments

Single line comments

Single line comments can be provided by using / /....................

Multiple line comments

Multiple line comments can be provided by using /*......................*/

Note: When we are working with the multiple line comments then nested comments are not possible.

comment in c

Rules for Writing Comments

1. Program contains any number of comments at any place.

Example

// header files
#include<stdio.h>
#include<conio.h>

void main()
{
// variable declaration
int a,b,c;
a=10;
b=20;
c=a+b;
printf("Sum= %d",c);
getch();
}

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

Example

void main()
{
/*
/*      comments   */
*/
}

3. Comments can be splits over more than one line.

Example

void main()
{
/* main   
   function
   body part
*/
}

4. Comments are not case sensitive.

Example

void main()
{

/*  MAIN Function BODY   */

}

5. Single line comments start with "//"

Example

void main()
{

// Single line comment

}

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:

breakcharcontinuedo
else externforif
longreturnsignedstatic
switchunionvoidwhile

Constant in C

Types of Constant in C

It is an identifier whose value can not be changed at the execution time of program. In general constant can be used to represent as fixed values in a C program. Constants are classified into following types.

constant in c

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

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

Declare constant

const keyword are used for declare a constant.

Syntax

const int height = 100;

Example

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

void main()
{
const int a=10;
printf("%d",a);
a=20; // gives error you can't modify const
getch();
}

constant example


Variable

Variable is an identifier which holds data or another one variable. It is an identifier whose value can be changed at the execution time of program. It is used to identify input data in a program.

Syntax:

variable images

Syntax

Variable_name = value;

Rules to declare a Variable

To Declare any variable in C language you need to follow rules and regulation of C Language, which is given below;

  • Every variable name should start with alphabets or underscore (_).
  • No spaces are allowed in variable declaration.
  • Except underscore (_) no other special symbol are allowed in the middle of the variable declaration (not allowed -> roll-no, allowed -> roll_no).
  • Maximum length of variable is 8 characters depend on compiler and operation system.
  • Every variable name always should exist in the left hand side of assignment operator (invalid -> 10=a; valid -> a=10;).
  • No keyword should access variable name (int for <- invalid because for is keyword).

Note: In a c program variable name always can be used to identify the input or output data.

Variable declarations

This is the process of allocating sufficient memory space for the data in term of variable.

Syntax

Datatype variable_name;
int a;

variable declaration

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

Garbage value

Garbage value can be any value given by system and that is no way related to correct programs. This is a disadvantage of C programming language and in C programming it can overcome using variable initialization.

Variable initialization

It is the process of allocating sufficient memory space with user defined values.

Syntax

Datatype nariable_name=value;

Example

int  b = 30;

variable initilization

Variable assignment

It is a process of assigning a value to a variable.

Syntax

Variable_Name = value

Example

int  a= 20;
int b;

variable Assignement

Example

b = 25; // --> direct assigned variable
b = a;  // --> assigned value in term of variable
b = a+15;  // --> assigned value as term of expression

variable Assignement

Scope of variable

Difference between Local variable and Global variable

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

Global variable

Global variables are defined outside of all the functions, generally on top of the program. The global variables will hold their value throughout the life-time of your program.

Local variable

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

Example of Global and Local variable

Example

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

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

Output

Value of a: 10
Value of b: 20

DataType in C Language

Data type is a keyword used to identify type of data. Data types are used for storing the input of the program into the main memory (RAM) of the computer by allocating sufficient amount of memory space in the main memory of the computer.

In other words data types are used for representing the input of the user in the main memory (RAM) of the computer.

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

  • Fundamental or primitive data types
  • Derived data types
  • User defined data types

datatype images

Primitive data types

These are the data types whose variable can hold maximum one value at a time, in C language it can be achieve by int, float, double, char.

Example

int a;  //  valid
a = 10,20,30;  //  invalid

Derived data types

These data type are derived from fundamental data type. Variables of derived data type allow us to store multiple values of same type in one variable but never allows to store multiple values of different types. These are the data type whose variable can hold more than one value of similar type. In C language it can be achieve by array.

Example

int  a[] = {10,20,30};  // valid
int b[] = {100, 'A', "ABC"};   //  invalid

User defined data types

User defined data types related variables allows us to store multiple values either of same type or different type or both. This is a data type whose variable can hold more than one value of dissimilar type, in C language it is achieved by structure.

Syntax

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

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

Data type modifiers in C

In c language Data Type Modifiers are keywords used to change the properties of current properties of data type. Data type modifiers are classified into following types.

  • long
  • short
  • unsigned
  • signed

Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of storage space allocated to a variable.

For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the range by using long int which is 8 byte. We can decrease the range by using short int which is 2 byte.

long:

This can be used to increased size of the current data type to 2 more bytes, which can be applied on int or double data types. For example int occupy 2 byte of memory if we use long with integer variable then it occupy 4 byte of memory.

datatype Modifiers images

Syntax

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

short

In general int data type occupies different memory spaces for a different operating system; to allocate fixed memory space short keyword can be used.

Syntax

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

unsigned

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

Syntax

unsigned int a =100;    // right
unsigned int a=-100;    // wrong

Signed

This keyword accepts both negative or positive value and this is default properties or data type modifiers for every data type.

Example

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

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

Operators

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

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Ternary or Conditional Operators

operators

Arithmetic Operators

Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A hold 8 and B hold 3.


Relational Operators

Which can be used to check the Condition, it always return true or false. Lets suppose variable A hold 8 and B hold 3.

Logical Operator

Which can be used to combine more than one Condition?. Suppose you want to combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is Logical Operator.

Assignment operators

Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.





Increment and Decrement Operator in C

Increment Operators are used to increased the value of the variable by one and Decrement Operators are used to decrease the value of the variable by one in C programs.

Both increment and decrement operator are used on a single operand or variable, so it is called as a unary operator. Unary operators are having higher priority than the other operators it means unary operators are executed before other operators.

Syntax

 ++  // increment operator
 --   // decrement operator

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

Example

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

Type of Increment Operator

  • pre-increment
  • post-increment

pre-increment (++ variable)

In pre-increment first increment the value of variable and then used inside the expression (initialize into another variable).

Syntax

++ variable;

Example pre-increment

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

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

Output

x: 11
i: 11

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

post-increment (variable ++)

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

Syntax

variable ++;

Example post-increment

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

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

Output

x: 10
i: 11

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

Type of Decrement Operator

  • pre-decrement
  • post-decrement

Pre-decrement (-- variable)

In pre-decrement first decrement the value of variable and then used inside the expression (initialize into another variable).

Syntax

-- variable;

Example pre-decrement

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

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

Output

x: 9
i: 9

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

post-decrement (variable --)

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

Syntax

variable --;

Example post-decrement

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

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

Output

x: 10
i: 9

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

Example of increment and decrement operator

increment and decrement operator

Example

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

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

Output

x: 0

Ternary Operator in C

If any operator is used on three operands or variable is known as Ternary Operator. It can be represented with ? : . It is also called as conditional operator

Ternary Operator in C

Advantage of Ternary Operator

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

Syntax

expression-1 ? expression-2 : expression-3

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either value or variable or statement or any mathematical expression. If condition will be true expression-2 will be execute otherwise expression-3 will be executed.

Syntax

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

Flow Diagram

Ternary Operator

Find largest number among 3 numbers using ternary operator

Example

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

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

Output

Enter any three number: 5 7 2
Largest number is 7



sizeof operator

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

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

Syntax

sizeof(variable)

Example

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

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

Output

Size of Integer: 2
Size of float: 4
Size of double: 8
Size of character: 1

Expression evaluation

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

Priority

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

Associativity

It represents which operator should be evaluated first if an expression is containing more than one operator with same priority.

Example 1:

images

Example 2:

images

Error in C

Error is a abnormal condition whenever it occurs execution of the program is stopped these are mainly classified into following types.

  • Compile time error
  • Run time error

Compile time error

If any error is generated at the time of compilation is known as compile time error, in general these are raised while break down the rules and regulation of programming language.

Example:

Missing semicolon, writing keyword in upper case, writing variable declaration, initialization after calling clrscr() function.

Compile time errors also known as syntax errors.

Compile time error
Compile time error

Run time error

If any error is generated at run time is known as runtime error, in general these are raised because of writing wrong logics in the program.

Example

Calling function without existence, divide by zero.
Int a=10,b;
B=a/0; --> infinite
Here out of range of int data type.

In general it is very difficult to identify logical error in C language, to overcome this problem exception handling was introduced in object oriented programming language.

error in c

Warning

Warning is also an abnormal condition but whenever it occurred execution of program will never be stopped.

Note: In C language warning can be neglected but error can not be neglected.

Warning in c
Warning in c


Printf and Scanf

Printf()

Printf is a predefined function in "stdio.h" header file, by using this function, we can print the data or user defined message on console or monitor. While working with printf(), it can take any number of arguments but first argument must be within the double cotes (" ") and every argument should separated with comma ( , ) Within the double cotes, whatever we pass, it prints same, if any format specifies are there, then that copy the type of value. The scientific name of the monitor is called console.

Syntax

printf("user defined message");

Syntax

prinf("Format specifers",value1,value2,..);

Example of printf function

int a=10;
double d=13.4;
printf("%f%d",d,a);

scanf()

scanf() is a predefined function in "stdio.h" header file. It can be used to read the input value from the keyword.

Syntax

scanf("format specifiers",&value1,&value2,.....);

Example of scanf function

int a;
float b;
scanf("%d%f",&a,&b);

In the above syntax format specifier is a special character in the C language used to specify the data type of value.

The address list represents the address of variables in which the value will be stored.

Example

int a;
float b;
scanf("%d%f",&a,&b);

In the above example scanf() is able to read two input values (both int and float value) and those are stored in a and b variable respectively.

Syntax

double d=17.8;
char c;
long int l;
scanf("%c%lf%ld",&c&d&l);

images

Example of printf() and scanf()

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

void main();
{
int a;
float b;
clrscr();
printf("Enter any two numbers: ");
scanf("%d %f",&a,&b);
printf("%d %f",a,b);
getch();
}

Output

Enter any two numbers:
10
3.5


Storage Class in C

Storage class specifiers in C language tells to the compiler where to store a variable (Storage area of variable), how to store the variable, Scope of variable, Default value of a variable (if it is not initialized it), what is the initial value of the variable and life time of the variable.

Storage classes of C will provides following information to compiler.

  • Storage area of variable
  • Scope of variable that is in which block the variable is visible.
  • Life time of a variable that is how long the variable will be there in active mode.
  • Default value of a variable if it is not initialized it.

Type of Storage Class

Storage classes in mainly divided into four types,

  • auto
  • extern
  • static
  • register

auto Storage Class

The auto storage class is the default storage class for all local variables. The scope auto variable is within the function. It is equivalent to local variable.

Syntax

{
   int roll;
   auto int roll;
}

In above example define two variable with same storage class auto and their scope is within the function.

Example of auto storage class

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

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

Output

Output:
0 0 0 0

static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the life-time of the program instead of creating and destroying it each time it comes into and goes out of scope.

Example of static storage class

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

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

Output

Output:
0 1 2 3

extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. It is equivalent to global variable.

Example of extern storage class

Example

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

int x = 20 ;
void main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
getch();
}
int y=30;

Output

The value of x is 20
The value of y is 30

Register Storage Class

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

Advantages: The register variables are faster than remaining variables, because register variable are stored in register memory not in main memory..

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

  • In TC-3.0 we can't access the address of register variables.
  • Pointer are ptr related concepts are can't applied to register variable.

Example

void main()
{
register int a=10;
++a;
printf("\n value of a: %d",a);
printf("Enter a value:");
scanf("%d",&a);
--a;
printf("\n value of a: %d",a);
getch();
}

Output

Input data is 50.
Error, must take address of a memory location.

Explanation

  • In scanf() function if address is provided for the register variable then it will give error, if addition is not provided it normally work.
  • Register storage class specifier just recommended to the compiler to hold the variable in CPU register if the memory is available or else stored in stack area of data segment.

Difference between all storage classes





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

C if else Statement

The if statement in C language is used to perform operation on the basis of condition. By using 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 condition is true. The syntax of if statement is given below:

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

Flowchart of if statement in C

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

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

if-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 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!


Switch Statement

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

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

Syntax

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

Flow chart

Switch Case

Rules for apply switch

  • The switch expression must be of integer or character type.
  • With switch statement use only byte, short, int, char data type.
  • With switch statement not use float data type.
  • You can use any number of case statements within a switch.
  • The case value can be used only inside the switch statement.
  • Value for a case must be same as the variable in switch.

Valid statement for switch

Example

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

Limitations of switch

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

Example

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

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

case 4.2:  // Invalid 

Syntax

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

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

Rulse table of switch

Invalid SwitchInvalid Case
switch(2.3)case 2.5;
switch(a+2.5)case x;
case x+2;
case 1,2,3;

Example of switch case

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

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

Output

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

Note: In switch statement default is optional but when we use this in switch default is executed at last whenever all cases are not satisfied the condition.

Example of Switch without break

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

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

Output

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

Note: In switch statement when you not use break keyword after any statement then all the case after matching case will be execute. In above code case 4 is match and after case 4 all case are execute from case-4 to case-7.

C Program for calculator

Example

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

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

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

Example

Enter First number: 6
Enter operator : +
Enter Second number: 10
Sum: 16

Explanation: In above code choice=getch(); is used for scan or get one value by using getch() function from keyboard, and store is choice.


Looping statement

Looping statement are the statements execute one or more statement repeatedly several number of times. In C programming language there are three types of loops; while, for and do-while.

Why use loop ?

When you need to execute a block of code several number of times then you need to use looping concept in C language.

Advantage with looping statement

  • Reduce length of Code
  • Take less memory space.
  • Burden on the developer is reducing.
  • Time consuming process to execute the program is reduced.

loop

Types of Loops.

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

  • while loop
  • for loop
  • do..while

Difference between conditional and looping statement

Conditional statement executes only once in the program where as looping statements executes repeatedly several number of time.

While loop

In while loop First check the condition if condition is true then control goes inside the loop body other wise goes outside the body. while loop will be repeats in clock wise direction.

Syntax

Assignment;
while(condition)
{
statements;
............
Increment or Decrements (++ or --);
}

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

When while loop is use ?

When we do not know about how many times loops are perform or iteration of loop is unknown.

Flow Diagram

While Loop

Example of while Loop

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

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

Output

Output:
1
2
3
4

Execution process of while loop is slower than for loop.

For loop

When you need to execute a block of code several number of times then you need to use looping concept in C language. In C Programming Language for loop is a statement which allows code to be repeatedly executed. It contains 3 parts.

  • Initialization
  • Condition
  • Increment or Decrements

Syntax

for ( initialization; condition; increment )
{
 statement(s);
}

For Loop

  • Initialization: This step is execute first and this is execute only once when we are entering into the loop first time. This step is allow to declare and initialize any loop control variables.
  • Condition: This is next step after initialization step, if it is true, the body of the loop is executed, if it is false then the body of the loop does not execute and flow of control goes outside of the for loop.
  • Increment or Decrements: After completion of Initialization and Condition steps loop body code is executed and then Increment or Decrements steps is execute. This statement allows to update any loop control variables.

Note: In for loop everything is optional but mandatory to place 2 semicolons (; ;)

Example

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

Flow Diagram

For Loop

Control flow of for loop

control flow

  • First initialize the variable, It execute only once when we are entering into the loop first time.
  • In second step check condition
  • In third step control goes inside loop body and execute.
  • At last increase the value of variable
  • Same process is repeat until condition not false.

For Loop

See in Detail

Example of for loop

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

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

Output

1
2
3
4

Important Points

  • In for loop if condition part is not given then it will repeats infinite times, because condition part will replace it non-zero. So it is always true like. for( ; 1; )
  • For loop is repeats in anti lock wise direction.
  • In for loop also rechecking process will be occurred that is before execution of the statement block, condition part will evaluated.

Example

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

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

Do-While loop


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

A do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given condition at the end of the block (in while).

Syntax

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

Flow Diagram

Do While Loop

When use do..while loop

when we need to repeat the statement block at least one time then use do-while loop. In do-while loop post-checking process will be occur, that is after execution of the statement block condition part will be executed.

In below example you can see in this program i=20 and we check condition i is less than 10, that means condition is false but do..while loop execute once and print Hello world ! at one time.

Example of do..while loop

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

void main()
{
int i=20;
do
{
printf("Hello world !");
i++;
}
while(i<10);
getch();
}

Output

Hello world !

Example of do..while loop

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

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

Output

1
2
3
4

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

c language break statement flowchart

Example of C break statement with switch case

  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


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.


Function

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

function

Why use function ?

Function are used for divide a large code into module, due to this we can easily debug and maintain the code. For example if we write a calculator programs at that time we can write every logic in a separate function (For addition sum(), for subtraction sub()). Any function can be called many times.

Advantage of Function

  • Code Re-usability
  • Develop an application in module format.
  • Easily to debug the program.
  • Code optimization: No need to write lot of code.

Type of Function

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

  • Library function or pre-define function.
  • User defined function.

function

Library function

Library functions are those which are predefined in C compiler. The implementation part of pre-defined functions is available in library files that are .lib/.obj files. .lib or .obj files are contained pre-compiled code. printf(), scanf(), clrscr(), pow() etc. are pre-defined functions.

Limitations of Library function

  • All predefined function are contained limited task only that is for what purpose function is designed for same purpose it should be used.
  • As a programmer we do not having any controls on predefined function implementation part is there in machine readable format.
  • In implementation whenever a predefined function is not supporting user requirement then go for user defined function.

User defined function

These functions are created by programmer according to their requirement for example suppose you want to create a function for add two number then you create a function with name sum() this type of function is called user defined function.

Defining a function.

Defining of function is nothing but give body of function that means write logic inside function body.

Syntax

    
return_type  function_name(parameter)
{
function body;
}
  • Return type: A function may return a value. The return_type is the data type of the value the function returns.Return type parameters and returns statement are optional.
  • Function name: Function name is the name of function it is decided by programmer or you.
  • Parameters: This is a value which is pass in function at the time of calling of function A parameter is like a placeholder. It is optional.
  • Function body: Function body is the collection of statements.

Function Declarations

A function declaration is the process of tells the compiler about a function name. The actual body of the function can be defined separately.

Syntax

return_type  function_name(parameter);

Note: At the time of function declaration function must be terminated with ;.

calling a function.

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

Syntax

function_name(); 
    or  
variable=function_name(argument);  

Note: At the time of function calling function must be terminated with ';'.

Example of Function

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

void sum(); // declaring a function
clrsct();
int a=10,b=20, c;

void sum()  // defining function
{
c=a+b;
printf("Sum: %d", c);
}
void main()
{
sum();  // calling function
}

Output

    
Sum: 30


Function Arguments in C

Call by Value and Call by Reference in C

On the basis of arguments there are two types of function are available in C language, they are;

function arguments

  • With argument
  • Without argument

If a function take any arguments, it must declare variables that accept the values as a arguments. These variables are called the formal parameters of the function. There are two ways to pass value or data to function in C language which is given below;

  • call by value
  • call by reference

call by value

Call by value

In call by value, original value can not be changed or modified. In call by value, when you passed value to the function it 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 but it not change the value of variable inside the caller method such as main().

Call by value

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

void swap(int a, int b)
{
 int temp;
 temp=a;
 a=b;
 b=temp;
}

void main() 
{  
 int a=100, b=200;  
 clrscr();  
 swap(a, b);  // passing value to function
 printf("\nValue of a: %d",a);
 printf("\nValue of b: %d",b);
 getch();  
}  

Output

    
Value of a: 200
Value of b: 100

Call by reference

In call by reference, original value is changed or 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, any value changed inside the function, is reflected inside as well as outside the function.

Example Call by reference

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

void swap(int *a, int *b)
{
 int temp;
 temp=*a;
 *a=*b;
 *b=temp;
}

void main() 
{  
 int a=100, b=200;  
 clrscr();  
 swap(&a, &b);  // passing value to function
 printf("\nValue of a: %d",a);
 printf("\nValue of b: %d",b);
 getch();  
}  

Output

    
Value of a: 200
Value of b: 100

Difference between call by value and call by reference.

Note: By default, C uses call by value to pass arguments.

Important points related to Function

  • The basic purpose of the function is code reuse.
  • From any function we can invoke (call) any another functions.
  • Always compilation will be take place from top to bottom.
  • Always execution process will starts from main() and ends with main() only.
  • In implementation when we are calling a function which is define later for avoiding the compilation error we need to for forward declaration that is prototype is required.
  • In function definition first line is called function declaration or function header.
  • Always function declaration should be match with function declaratory.
  • In implementation whenever a function does not returns any values back to the calling place then specify the return type.
  • Void means nothing that is no return value.
  • In implementation whenever a function returns other than void then specify the return type as return value type that is on e type of return value it is returning same type of return statement should be mentioned.
  • Default return type of any function is an int.
  • Default parameter type of any function is void.

Recursive Function in C

When Function is call within same function is called Recursion. The function which call same function is called recursive function. In other word when a function call itself then that function is called Recursive function.

Recursive function are very useful to solve many mathematical problems like to calculate factorial of a number, generating Fibonacci series, etc.

Advantage of Recursion

  • Function calling related information will be maintained by recursion.
  • Stack evaluation will be take place by using recursion.
  • In fix prefix, post-fix notation will be evaluated by using recursion.

Disadvantage of Recursion

  • It is a very slow process due to stack overlapping.
  • Recursive programs can create stack overflow.
  • Recursive functions can create as loops.

Find the Factorial of any number using recursion

Example

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

void main()
{
int fact(int);
int i,f,num;
clrscr();
printf("Enter any number: ");
scanf("%d",&num);
f=fact(num);
printf("Factorial: %d",f);
getch();
}

int fact(int n)
{
if(a<0)
return(-1);
if(a==0)
return(1);
else
{
return(n*fact(n-1));
}
}

Output

Enter any number: 5
Factorial: 120

Recursive Function in C

Find the Table of any number using recursion

Example

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

void main()
{
int table(int,int);
int n,i;      // local variable
clrscr();
printf("Enter any num : ");
scanf("%d",&n);
for(i=1;i< =10;i++)
{
printf(" %d*%d= %d\n",n,i,table(n,i));
}
getch();
}
int table(n,i)
{
int t;
if(i==1)
{
return(n);
}
else
{
t=(table(n,i-1)+n);
return(t);
//return(table(n,i-1)+n);
}
}

Output

Enter any number: 5
5*1= 5
5*2= 10
5*3= 15
5*4= 20
5*5= 25
5*6= 30
5*7= 35
5*8= 40
5*9= 45
5*10= 50


C Array

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.

array in c



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;  

initialization of array in c language

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 arrays or 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


C Pointers

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

c pointers

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

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.

pointer example

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).

Pointer Program to swap 2 numbers without using 3rd variable

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int a=10,b=20,*p1=&a,*p2=&b;  
  5. clrscr();  
  6.   
  7. printf("Before swap: *p1=%d *p2=%d",*p1,*p2);  
  8. *p1=*p1+*p2;  
  9. *p2=*p1-*p2;  
  10. *p1=*p1-*p2;  
  11. printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);  
  12.   
  13. getch();  
  14. }  

Output

Before swap: *p1=10 *p2=20
After swap: *p1=20 *p2=10


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:

pointer to pointer in c

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.

C pointer to pointer example

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 in C

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.

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.

  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*)malloc(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

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) 

String

String is a collection of character or group of character, it is achieve in C language by using array character. The string in C language is one-dimensional array of character which is terminated by a null character '\0'. In other words string is a collection of character which is enclose between double cotes ( " " ).

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

Declaration of string

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

Example

    
char s[5];

String in C

Initializing Array string

String are initialize into various way in c language;

Example

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

In c language string can be initialize using pointer.

Example

char *c="abcd";

String in C

Reading String from user

Example

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

Example

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

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

Example of reading string

    
Enter name: Hitesh kumar
Your name is: Hitesh

Note: String variable str can only take only one word. It is because when white space is encountered, the scanf() function terminates. to over come this problem you can use gets() function.

Syntax

    
char str[5];
gets(str);

gets()

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

puts()

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

Example of String program

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

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

Explanation: Here gets() function are used for input string and puts() function are used to show string on console or monitor.

Output

Enter String: hello word
String are: hello word

C Library String functions

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


Important points for Declaration of string

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

Syntax

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

Example

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

Syntax

    
char variable_name[SIZE];
    
char str[5];

Important points for Initialization of the string

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

Example

char str[5]={'5','+','A'};
    str[0];  ---> 5
    str[1];  ---> +
    str[2];  ---> A
    str[3];  ---> NULL
    str[4];  ---> NULL
  • In initialization of the string we can not initialized more than size of string elements.

Example

    
char str[2]={'5','+','A','B'};  // Invalid
  • In initialization of the string the size is optional in this case how many variable elements are initialized it, that array element will created.

Example

    
char str[]={'5','+','A','B'};  // Valid
sizeof(str)  --> 4byte

When we are working with character array explicitly NULL character does not occupies any physical memory at the end of the character array.

Example

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

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

Example

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


C Math

C Programming allows us to perform mathematical operations through the functions defined in <math.h> header file. The <math.h> header file contains various methods for performing mathematical operations such as sqrt(), pow(), ceil(), floor() etc.

C Math Functions

There are various methods in math.h header file. The commonly used functions of math.h header file are given below.

C Math Example

Let's see a simple example of math functions found in math.h header file.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. #include<math.h>  
  4. void main(){  
  5. clrscr();  
  6.   
  7. printf("\n%f",ceil(3.6));  
  8. printf("\n%f",ceil(3.3));  
  9. printf("\n%f",floor(3.6));  
  10. printf("\n%f",floor(3.2));  
  11. printf("\n%f",sqrt(16));  
  12. printf("\n%f",sqrt(7));  
  13. printf("\n%f",pow(2,4));  
  14. printf("\n%f",pow(3,3));  
  15. printf("\n%d",abs(-12));  
  16. getch();  
  17. }  

Output:

4.000000
4.000000
3.000000
3.000000
4.000000
2.645751
16.000000
27.000000
12


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; id, name and salary are the members or fields of the structure. Let's understand it by the diagram given below:

c structure

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 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 : 101
employee 1 name : Sonoo Jaiswal

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 Jaiswal");//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 Jaiswal
employee 1 salary : 56000.000000
employee 2 id : 102
employee 2 name : James Bond
employee 2 salary : 126000.000000


Array of Structures in C

There can be array of structures in C programming to store many information of different data types. The array of structures is also known as collection of structures.

Let's see an example of structure with array that stores information of 5 students and prints it.

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. #include<string.h>  
  4. struct student{  
  5. int rollno;  
  6. char name[10];  
  7. };  
  8. void main(){  
  9. int i;  
  10. struct student st[5];  
  11. clrscr();  
  12. printf("Enter Records of 5 students");  
  13.   
  14. for(i=0;i<5;i++){  
  15. printf("\nEnter Rollno:");  
  16. scanf("%d",&st[i].rollno);  
  17. printf("\nEnter Name:");  
  18. scanf("%s",&st[i].name);  
  19. }  
  20.   
  21. printf("\nStudent Information List:");  
  22. for(i=0;i<5;i++){  
  23. printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);  
  24. }  
  25.   
  26. getch();  
  27. }  

Output:

Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz


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 Jaiswal");//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 Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014


C Union

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

But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares memory of largest member.

difference between structure and union

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:

Opening File: fopen()

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.

Closing File: fclose()

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

  1. int fclose( FILE *fp );  

C fprintf() and fscanf()

Writing File : fprintf() function

The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.

Syntax:

  1. int fprintf(FILE *stream, const char *format [, argument, ...])  

Example:

  1. #include <stdio.h>  
  2. main(){  
  3.    FILE *fp;  
  4.    fp = fopen("file.txt", "w");//opening file  
  5.    fprintf(fp, "Hello file by fprintf...\n");//writing data into file  
  6.    fclose(fp);//closing file  
  7. }  

Reading File : fscanf() function

The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file.

Syntax:

  1. int fscanf(FILE *stream, const char *format [, argument, ...])  

Example:

  1. #include <stdio.h>  
  2. main(){  
  3.    FILE *fp;  
  4.    char buff[255];//creating char array to store data of file  
  5.    fp = fopen("file.txt", "r");  
  6.    while(fscanf(fp, "%s", buff)!=EOF){  
  7.    printf("%s ", buff );  
  8.    }  
  9.    fclose(fp);  
  10. }  

Output:

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>  
  2. void main()  
  3. {  
  4.     FILE *fptr;  
  5.     int id;  
  6.     char name[30];  
  7.     float salary;  
  8.     fptr = fopen("emp.txt", "w+");/*  open for writing */  
  9.     if (fptr == NULL)  
  10.     {  
  11.         printf("File does not exists \n");  
  12.         return;  
  13.     }  
  14.     printf("Enter the id\n");  
  15.     scanf("%d", &id);  
  16.     fprintf(fptr, "Id= %d\n", id);  
  17.     printf("Enter the name \n");  
  18.     scanf("%s", name);  
  19.     fprintf(fptr, "Name= %s\n", name);  
  20.     printf("Enter the salary\n");  
  21.     scanf("%f", &salary);  
  22.     fprintf(fptr, "Salary= %.2f\n", salary);  
  23.     fclose(fptr);  
  24. }  

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 

C fputc() and fgetc()

Writing File : fputc() function

The fputc() function is used to write a single character into file. It outputs a character to a stream.

Syntax:

  1. int fputc(int c, FILE *stream)  

Example:

  1. #include <stdio.h>  
  2. main(){  
  3.    FILE *fp;  
  4.    fp = fopen("file1.txt", "w");//opening file  
  5.    fputc('a',fp);//writing single character into file  
  6.    fclose(fp);//closing file  
  7. }  

file1.txt

a

Reading File : fgetc() function

The fgetc() function returns a single character from the file. It gets a character from the stream. It returns EOF at the end of file.

Syntax:

  1. int fgetc(FILE *stream)  

Example:

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. FILE *fp;  
  5. char c;  
  6. clrscr();  
  7. fp=fopen("myfile.txt","r");  
  8.   
  9. while((c=fgetc(fp))!=EOF){  
  10. printf("%c",c);  
  11. }  
  12. fclose(fp);  
  13. getch();  
  14. }  

myfile.txt

this is simple text message

C fputs() and fgets()

The fputs() and fgets() in C programming are used to write and read string from stream. Let's see examples of writing and reading file using fgets() and fgets() functions.

Writing File : fputs() function

The fputs() function writes a line of characters into file. It outputs string to a stream.

Syntax:

  1. int fputs(const char *s, FILE *stream)  

Example:

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. FILE *fp;  
  5. clrscr();  
  6.   
  7. fp=fopen("myfile2.txt","w");  
  8. fputs("hello c programming",fp);  
  9.   
  10. fclose(fp);  
  11. getch();  
  12. }  

myfile2.txt

hello c programming

Reading File : fgets() function

The fgets() function reads a line of characters from file. It gets string from a stream.

Syntax:

  1. char* fgets(char *s, int n, FILE *stream)  

Example:

  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. FILE *fp;  
  5. char text[300];  
  6. clrscr();  
  7.   
  8. fp=fopen("myfile2.txt","r");  
  9. printf("%s",fgets(text,200,fp));  
  10.   
  11. fclose(fp);  
  12. getch();  
  13. }  

Output:

hello c programming

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.

C preprocessor

All preprocessor directives starts with hash # symbol.

Let's see a list of preprocessor directives.

  • #include
  • #define








  • 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 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.