Introduction to C

C Programing is compiled, structural, middle level programing language developed at AT & T’s Bell Laboratories of USA in 1972, designed and written by Dennis Ritchie to redeveloped UNIX operation system.  It is improved version of B language which is developed by Ken Thompson.

During the 1980s, C gradually gained popularity. It has become one of the most widely used programming languages. C programming is an excellent language to learn to program for beginners. Many popular software are written in C like Oracle, MySQL, core library of Android, almost every Device Driver. Major parts of WINDOWS, LINUX and Web Browsers are written in C. If you have to closely interact with the hardware without compromising the performance, C is going to be your choice.

Application of C Programing: C is used to development of Operating System (like Windows, Linux), Graphical User Interface, Integrated Development Environment, Browser Design, Compiler Design, Data Base Design, Graphics packages, Word Processor, spreadsheets, mobile and computer game are written in C. C is used in Embedded system, Network devices Specially, C program is used to develop Desktop Application.

History of C Language: 

  • The C Programing language is a structure oriented programing language, developed at Bell Laboratories in 1972 by Dennis Ritchie.
  • C programing language features were derived from an earlier language called “B” (Which is upgraded version of Basic Combined Programming Language “BCPL”). BCPL was developed by Martin Richards in 1966.
  • C language was invented for implementing UNIX Operating system.
  • In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C programming language” and commonly known as K&R C.
  • In 1983, The American National Standard Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C’’, was completed late 1988.

Features of C: There are lots of features or characteristics of C language due to which it is still famous enough even after around 50 years of development. It provides:

  • Simple
  • General Purpose Programming Language
  • Reliability
  • Powerful/Robust
  • Portability
  • Modular/Procedure oriented
  • Flexibility
  • Structured Programing Language Interactivity
  • Modularity
  • Efficiency And Effectiveness  

Compilation Process in C: The computer understands only machine language. So to make our software to run on a machine, we need a process which can translate this code into a language that computer can understand. This process of translation is called compilation. Or we can say- compilation is the process of translating the code you write into a language that is native to the machine you are targeting. The source code has to pass through set of sub processes.

The instruction written in the c programming language is called as C source code. When we write a C program we are going to store that in the computer memory as a computer file and the file which is containing source code is called as the source file and if the file containing the source code written in the C Programming language, that file is called as C source file. The file which is containing the C source code will be saved with “.C” extension.

The compilation process can be split into four separate stages: which are preprocessing, compilation, Assembly and Linking. The first stage of compilation is called preprocessing. Which takes the source file as input and scan it for all preprocessor directives or simply “#codes”. It generates the preprocessed file with “.i” extension and in this output file, all the macros will be resolved and comments will be taken out. The next stage is compilation which takes preprocessed file as input and converts the high level source code into assembly instruction. Which are specific to the target processor architecture. It generates a file with “.s” extension. The next stage is Assembly which converts the assembly instruction resulted from the compilation and generate object code with “.o” extension (Linuxed based platform) and “.obj” extension (Windows based platform). The O/P consists of actual instructions to be run by the target processor. Till now we have included only header file which contains function declaration. Functions like scanf and printf used in our program still have no definition. They will be define in some library files. Linking is the final stage of compilation. Which takes all the static libraries and object files and generate single executable file with “.out” extension in Linux based platform and “.exe” extension in Windows based platform.

Why to learn C Programming– 

  • C is a mother of all languages because C is the first complete language.
  • C helps you build a strong programming foundation which is ever lasting and which help you all through your life.
  • The object oriented programming methods present in C++, C# and Java provides huge advantage for programmers but the basic programming elements like looping, variable declaration, logical and arithmetic operation are almost similar in C. So learning C definitely gives you an extra edge before jumping on learning C++, C#, Java.
  • The programs written in C are very efficient. Its performance and speed of execution is unique. Even todays device drivers are also written in C.
  • C is basically a middle level language. It is an interface between assembly language and high level languages. C can interface with both of them. When you know C you can get introduced to the computer architecture, you can understand memory management, CPU cache, you can know port programming, as well as you can also have Database programming because of files in C are very strong.
  • C programs can be easily embedded in other languages which is very big asset of C.
  • Most 3D Gaming framework like DirectX are built in C programming language. Because for any Game user experience that is speed of execution is very important and C suits best for its because it’s speed reliability and performance.
  • Using C we can directly access hardware. C is easy to learn and understand.
  • C is efficient, powerful, portable and flexible. Flexible because of its memory management. Portable because it can take the same source code, compiled and execute it to get the object which is same in all machine.
  • C being a structure language. Once you learn how to use a structure programming language, it becomes a programming language which will help you lifetime. 
  • If you learn new languages like C++, Java, Python, once you know C porting to these language is so easy.

Environment Setup/Installation Process– If you want to set up your environment for C programming language, you need the following two software tools available on your computer, (a) Text Editor and (b) The C Compiler but now to start learning C programming, you can only have to install the C compiler in your system, and nowadays C and C++ both compilers come as a single integrated package, which serves the purpose of C and C++ both program development.

Installation on UNIX/Linux– 

If you are using Linux or UNIX, then check whether GCC is installed on your system by entering the following command from the command line –

$ gcc -v

If you have GNU compiler installed on your machine, then it should print a message as follows –

Using built-in specs.Target: i386-redhat-linuxConfigured with: ../configure –prefix=/usr …….Thread model: posixgcc version 4.1.2 20080704 (Red Hat 4.1.2-46)

If GCC is not installed, then you will have to install it yourself using the detailed instructions available at

This tutorial has been written based on Linux and all the given examples have been compiled on the Cent OS flavor of the Linux system.

Installation on Mac OS

If you use Mac OS X, the easiest way to obtain GCC is to download the Xcode development environment from Apple’s web site and follow the simple installation instructions. Once you have Xcode setup, you will be able to use GNU compiler for C/C++.

Xcode is currently available at

Installation on Windows

To install GCC on Windows, you need to install MinGW. To install MinGW, go to the MinGW homepage,, and follow the link to the MinGW download page. Download the latest version of the MinGW installation program, which should be named MinGW-<version>.exe.

While installing Min GW, at a minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but you may wish to install more.

Add the bin subdirectory of your MinGW installation to your PATH environment variable, so that you can specify these tools on the command line by their simple names.

After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool, and several other GNU tools from the Windows command line.

List of C Compilers for Windows OS– Since there are various compilers available into the online market, here are the lists of some of the frequently used ones:

  • CCS C Compiler
  • Turbo C
  • Minimalist GNU for Windows (MinGW)
  • Portable C Compiler
  • Clang C++
  • Digital Mars C++ Compiler
  • Intel C++
  • IBM C++
  • Visual C++ : Express Edition
  • Oracle C++

All of these above compilers for C are free to download, but there are some other paid C compilers also available, or programmers can get it for trial version:

  • Embarcadero C++
  • Edison Design Group C++
  • Green Hills C++
  • HP C++ for Unix
  • Intel C++ for Windows, Linux, and some embedded systems.
  • Microsoft C++
  • Paradigm C++

The following are IDE’s (Integrated Development Environments) that will automatically download everything you need to begin programming and running the C-Programming language.

Install Dev C++ – Install Dev C++ from Dev-C++ is a integrated development environment (IDE) for programming in C and C++. It is bundled with, the MinGW or TDM-GCC 64bit port of the GCC as its compiler.

Install Code::Blocks -Install codeblocks-17.12mingw-setup.exe . Codeblocks is a cross-platform IDE built around wxWidgets, designed to be extensible and configurable. Runs on Windows and Linux. If the link to the installation file is not working, go to and install the program.

Install Cygwin- Okay, so this method does not use an IDE like the previous methods, but it’s still another way that you can get a C-Program to run on your Windows Operating System through command prompt.

First install GNU Compiler Collection or GCC for short, on Microsoft Windows. I will show you different ways to install GCC which was originally written as the compiler for the GNU operating system (A Unix like Operating System).

Cygwin (a software interface that has the look and feel of a Unix environment, but is run within the Windows operating system was created). Cygwin allows for integration between Windows applications, Unix-like applications and data.

The install steps are:

  1. Install Cygwin, which gives us a Unix-like environment running on Windows.
  2. Install a set of Cygwin packages required for building GCC.
  3. From within Cygwin, download the GCC source code, build and install it.
  4. Test the new GCC compiler in C++14 mode using the -std=c++14 option.

C Program structure– 

Documentation Section
Link Section
Definition Section
Global declaration section
Main(){Declaration SectionExecution Section}
Function 1   ……….
UserFunction n

Documentation Section– The first section is documentation section. It consists of comments lines which are not compiled by compiler. Comments are added in a program to increase it’s readability and understandability. They are written by two reverse slashes “//” before the statements. This is use to write single line comment. A multiline comment is written by typing a reverse slash and a star “/*” followed by the comment lines which is followed by the star and reverse slash “*/”.

Comments are specify the name of program, author and other details related to the program. It is used for future reference.

Link Section – All the library file that are included in the program are mention in the section. The compiler is informed about the library files to be linked with the program. This process is called as Linking. All the statements is starts with the “#” include text belong to the link section. For example the statement “#include<stdio.h>” links library file “stdio” to the program.

Definition Section – All the symbolic constants that are to be used in the program are defined here. All statements are starts with the “#” define text belong to the definition section.

#define pi=3.14;#define true=1;#define false=0;

Global Declaration Section– All the variables which are used is more than one function are called as Global variables. And they should be declare before they are used anywhere in the program in the section. All the user defined functions are also declare here.

//Globall declaration Sectionint green;//user defined function


                                            {  green=0; }


                                               {  green=1;   }

Here “green” is global variable.

Main function definition section – Every c program must have one main function. All the statements in the main section must have must appear between the opening and closing braces. This section has two parts. First part is declaration part. As every c variable must be declare before its use. Therefore all the variable to be used in the main section are declare here in declaration section.

Main(){      //Declaration int principle, rate, time, interest;//Executionprinciple=20000;rate= 15;time=7;interest=(principle*time*rate)/100;


User defined function definition section – All the user defined functions are calling by the main function. All the section except the main section may not be present in the program if not required but every program must have one main section.

C Basic Syntax

Token in C – A program consists various tokens. Token could be Keyword, Identifier, Constant, string or any symbol.


#inclde<stdio.h>int main(){Printf(“ Hello World… \n”);}

Here every word of this program are called token.

Semicolon : This is statement terminator. Each statement must be terminate with “;”.

Comments: It is used to increase the readability of the program. This is two type 1)one line comment, 2)Multiple line comment.

//Think Green and increase Green./*Let’s move to the sky….…….to protect Earth. */

Identifier: Identifier is name used to identify the variable, functions and user defined items. Identifier is specific form of token. An identifier starts with a letter A to Z, a to z, or an “_” followed by zero or more letters, underscores and digits (0 to 9). C does not allow punctuation characters such as @,$, and % within identifiers.

C is case-sensitive programing language. Thus Manpower and manpower are two different identifiers in C.

Keyword: Keywords are one kind of token. Reserved word of language is called keyword. These keyword can’t be used as identifiers. We can use within it but not alone. There are 33 keywords in C language.

defaultIf staticWhile

Whitespace : A line containing only whitespace or comments is called blank line. C compiler totally ignore the blank line. Whitespace is the term used in C to describe blank lines, tabs, newline character and comments. Whitespace separate one element to another, in a statement so that compiler can recognize. int var_a; If whitespace required we have to give at least one.

 Syntax to write main() or a program in c:

#include<stdio.h>int main(){    //Statements…    return(0);}

Syntax of variable definition or declarations:

datatype variable-name;Example: int a;

Some Escape Sequences;

\a : bell sound\b : backspace \f : form feed\n : new line\t : tab\0 : null character\v : vertical tab

Input Output functions:

  • Character input
Variable-name=getchar();Example: b=getchar();
  • Character output

Formatted Input-Output function syntaxes:

Scanf(“format specifier”,&variable-name);Example- scanf(“%d”,&a);Printf(“format specifier”,variable-name);Example: printf(“%d”,a);

Some format Specifier:

%d,i => decimal no%o => octal%f => float%c => single character%u => unsinged decimal no%x,X => hexadecimal

Conditional statements:

  1. If statement
if(condition){       //statements…}
  1. If-else statements:
if(condition){       //statement 1}else{         //statement 2}
  1. Nested if-else:
if(condition 1){     //statement 1}else if(condition 2){        //statement 2}else//statement 3
  1. Switch case statement
Switch(choice-case-variable){Case1: //statement 1                break;Case2: //statement 2                 Break;Default: //statement 3
  1. Conditional operator/Ternary operator
Variable = (condition) ? execute if true : execute if false;Example- a = (b>c) ? b : c;

Loops Syntaxes:

  1. While loop:
while(expressions){    //statements}
  1. Do-While Loop:
do{     //statements}
  1. For Loop:
For(exp1;exp2;exp3){     //statements}

Datatypes: Datatype is a type of data which is used in the program. In other word, we can say that it is used to declare a variable. Datatype specify how we entered data in our program and what type of data we entered. There are two types of datatype: a) primary datatype, b) secondary datatype

  1. Primary or Basic Datatype- i)int, ii) char, iii)float, iv) double
  2. Secondary or Derived Datatype– i) Array, ii) Pointer, iii) Structure, iv) Union

Modifiers: Modifiers are used as a prefix to the datatype to redefined the size and range of the datatype.

Systax: modifier datatype variable-name;

There are two types of modifiers: i) size modifier (short, long, longlong), ii) sign modifier( signed, unsigned)

Short modifier– We can use short modifier only with the “int” datatype. As a explain earlier int take different memory space like 2 bytes, 4 bytes or 8 bytes; it depends on the computer architecture and compiler. If you want to allocate fixed memory space for the int then you can used short modifier. So size of the short modifier is two bytes. So, If you want to store small integer value then you can use this modifier with the int data type.

Short int a;

Long and longlong modifier: You can use these two modifiers when you want to increase the size of the current datatype you can use these long modifier with int and double. We can’t use these with character or float. The size of the long modifier is 4 bytes or 8 bytes; it depends on the computer architechture and compiler.

long int a;

long double b;

we can use longlong only with the integer. The size of longlong is 8 bytes.

Longlong int a;

Unsigned modifier : We can use this unsigned modifier with the int and character datatype. This keyword can be used for those variable which can take only value which are “0” and “positive value”, it don’t take negative value.

unsigned int a;

unsigned char b;

If we didn’t mention any 

C Data TypesData Type is used to declare or define a variable. It specifies the data storage format for the variable. In the declaration of every variable, it is mandatory to specify it’s data type. There are three types of Data Type:

  1. Primary or Primitive Data Type
  1. char
  2. int
  3. float
  4. double
  5. void
  6. User Defined Data Type
  1. typedef
  2. enumerated
  3. Derived Data Type
  1. Array
  2. structure
  3. pointer
  4. Union
Data TypeSize(Byte)Range of ValueFormat Specifier
Signed  char1-128 to 127%c
Signed int2-32768 to 32767%d, %i
float41.2E-38 to 3.4E+38%f
double82.3E-308 to 1.7E+308%lf
unsigned char10 to 255%u
unsigned int20 to 65,535 or 0 to 4,294,967,295%llu
signed short int1-128 to 127
unsigned short int10 to 255
signed long int4-2147483648 to 21471483647%ld, %li
Unsigned long int40 to 4294967295%lu
Long double103.4E-4932 to 1.1E+4932%Lf

For example, 

int greenWorld;

Here, greenWorld is a int (integer type) variable where we can store only integer value like 2,4. We can’t store here 2.6(use float data type to store it).

C Variables –  An variable is an entity that does change or vary in respect of  time. In programing we have to store results of calculations, and it is stored in the computer memory. The computer memory consisting of a lots of small memory cells. And each memory cell has it’s own address. Variable names are the names given to the memory locations. We don’t need to worry about at which location of the memory your value is stored. Our task is just to provide the name and internally it will point some memory location.


As shown in figure, 12345 is the address of the memory cell which contain a constant 9. To make the usage of memory cell easy we give the memory cell a name as greenWorld. So 9 is stored in the memory cell named greenWorld. Here 10 is constant and the name of the memory cell is called as variable name. This variable can contain other value at another time.

If you assign some value to a variable at the time of declaration, then it is called initialization.

int greenWorld = 9;

Constant: As the name suggests constant is something that never change. Or we can say, Constant is an entity that refers to fixed values and it can’t be modified. We can define constant in our code by using #define or using const keyword.

Define constant using #define: 

Syntax for #define: #define NAME(macro) value

Job of preprocessor (not compilar) to replace name with value. The preprocessor does the job of replacing the header files with their actual content as example #include<stdio.h> is going to get replaced by preprocessor. The “NAME” is also going to get replaced by this “value available over here.

#include <stdio.h>#define PI 3.14159int main(){     printf(“%.3f”, PI);      return 0;}

Here we define a “PI” with 3.14159 where “PI” is the NAME and “3.14159” is value. We are simply going to print this “PI” instead of using “3.14159” constant and printed up to 3 decimal points. The output will be “3.141”.

What should or should not we do in the time of define the constant:

  • Please don’t add semicolon at the end.
  • Choosing capital letter for NAME is good practice.
#include<stdio.h>#define value 60int main(){     int value = 51; (int value 60=51;)     printf(“%d”,value);return 0;}

Here you can see we are not use the capital letter for “NAME”. So, what is the disadvantages you may get; It is possible that we declare the variable with the same name assign to it the value 51, and if we simply print that value. We got an error out of this because our macro is also with same name. Now the preprocessors does its job and replace this value with 60 wherever it finds its out. Here also the variable value is replace with 60. This is the disadvantage.

  • Whatever inside double quotes “ “ won’t get replaced.
  • We can use macros like functions.
#include<stdio.h>#define add(x, y) x+yint main(){     printf(“addition of two numbers: %d”, add(4,3));    return 0;}

We use the add(x,y) just like a function and after that I perform some operation which is x+y. I want to perform the addition of two numbers 4 and 3. We simply call the macro, this is going to get replace with this x+y which is nothing but 4+3, this gives us the output as 7.

  • We can use multiple lines using “\”
#include<stdio.h>#define greater(x,y) if (x>y)\                                         printf(“%d is grater than %d”,x,y);                                         else\                                           printf(“%d is lesser than %d”,x,y);int main(){     greater(5,6);        return 0;}
  • First expansion then evaluation.

#include<stdio.h>#define add(x,y) x+yint main(){     printf(“result of expression a*b+c is:”, 5* add(4,3));     return 0;}

Here 5 is multiplied with macro, first the replacement is going to get done. First expansion then evaluation. Here the expansion simply means that this macro is expanded to x+y and it is getting replaced over here which is nothing  but 5*4+3 and then the whole expression is evaluated. Result of 5*4+3, according to the BODMAS rule 5*4 is evaluated first which gives us 20 then it will add with 3, the result will 23.

  • Some predefined macros like __DATE__,__TIME__ can print current date and time .
#include<stdio.h>int main(){   printf(“Date %s\n”, __DATE__);   printf(“Time %s\n”, __TIME__);   return 0;}

Define Constant using const: You would be able to use const keyword in front of a variable. For example we can define a variable like “int var” by simply putting const keyword in front of that variable, we won’t be change its value anywhere in the code. Suppose for example we want to assign a different value to a variable that we want be able to do that because when we defined it as a constant you won’t be able to changed its value. Constant simply means that this value whatever its being assigned to a variable is permanent.

Syntax:   const data_type variable_name;

#include<stdio.h>int main(){     int var=73;      var=62;      printf(“%d”,var);       return 0;}

Here we defined a variable and assigned it a value equals to 73 and we simply going to print this value with the help of “printf” function. We got 73 as the output. Now we are assign different value to this variable. Then if we print the value of “var” we will get 62. So we would be able to assign any number of time values to it as whenever we want in our code. It is not necessary that once we initialize with this value we won’t be able to assign any different value latter in our code. Now if we put “const” keyword in front of this variable then let’s see what will happen?

#include<stdio.h>int main(){   const  int var=73;      var=62;      printf(“%d”,var);       return 0;}

We will get an error (assignment of read only variable ‘var’). Because we are trying to assign a different value to it which is after the initialization step. We are already initialize it the value is equal to the 73 and now this becomes a constant. We won’t be able to change its value further in the code. And that is why this kind of error is produced. We can also declare this variable as global and no function would be able to assign the value to it. That is the functionality of the const variable.

Type of constant:

  • Primary Constant
    • Integer Constant
    • Real constant
    • Character Constant
  • Secondary Constant
    • Array
    • String
    • Pointer
    • Union
    • Structure
    • Enumerator

Storage classes: A storage class defines the scope and life time of variables and functions.

Types of storage classes:

  1. Auto
  2. Register
  3. Static
  4. Extern
Int x=5;

From this declaration statement we can easily find three characteristics or property of variable:

  • Name of the variable
  • Size of the memory block
  • Data type of the content

There are more properties of variable:

  • Default Value
  • Storage
  • Scope
  • Life

If we don’t mention storage class in declaration statement then it will consider as “auto” storage class.

Storage classKeywordDefault ValueStorageScopeLife
AutomaticautoGarbageRAMLimited to the block in which it is declaredTill the execution of the block in which it is declared
staticstaticZero(0)RAMsameTill the end of program

Operators: Operator is a symbol that used to perform mathematical or logical operation on variables and values. 

Type of operator according their priority(High to Low):

  • Unary Operators
  • Arithmetic Operators
  • Bitwise Operators
  • Relational Operators
  • Logical Operators
  • Conditional Operators

Unary Operator- To work this operator one operads is needed. There are five type of unary operator: +(positive sign), -(negative sign), ++(increment operator), –(decrement operator),sizeof() operator.

use of post increment operator:

main(){    int x=3;    clrscr();     x++;     //x=x+1    printf(“%d”,x);    getch();}
O/P is =4

Use of pre increment:

main(){    int x=3;    clrscr();    x++;    //x=x+1    ++x;     printf(“%d”,x);     getch();}O/P is =4

Sizeof() operator: It tells the size of data type or variable:

Main(){    int x;    clrscr();    x=sizeof(float);    printf(“%d”,x);    getch();}
main(){    int x;    float k;    clrscr();    x=sizeof(y);    printf(“%d”,x);    getch();}

Arithmetic Operator: *(multiply), /(devide), %(modulo) [High Priority]

                 +(addition), -(subtraction)   [Less Priority]

Here no BODMAS rule is applied. If there are more than one arithmetic operators in a expression, the priority of these are same but they are solved from left to right. So, the associativity rule of arithmetic operators is left to right.

Bitwise Operator

Bitwise AND&
Bitwise OR|
Bitwise XOR^
Bitwise NOT~
Right Shift>>
Left Shift<<

Relational Operator– <(less than), >(Greater than), <=(Less than equal to), >=(greater than equal to)

“==”, “!=”

Relational operator always yields result either 0 or 1. Every non zero value is “True” and Zero is “False”.

Main(){    int x;    clrscr();    x=3>4;    printf(“%d”,x);   getch();}
O/P is= 0

Logical Operators: ! (NOT Operator)

&& (AND Operator)

|| (OR Operator)

NOT operator is a unary operator because its required one operand to work.

main(){    Int x=5,y;    clrscr();    y=!x>4;    printf(“%d”,y);    getch();}
main(){    int x=5,y;    clrscr();    y=x>4 && x<10;    Print(“%d”,y);    getch();}

Conditional Operator: It is also called Ternary Operator.

Syntax: Condition ? statement : statement;

Main(){    int x;    clrscr();    printf(“Enter a number”);    scanf(“%d”,&x);    x>0 ? printf(“positive”) : printf(“non positive”);    getch();}

Loops: Any repeated task more than one time is called Loop. Loop is also called Iterative control Instruction.There are three type of loop:

  1. While Loop
  2. Do-While Loop
  3. For Loop
main(){    int i=1;    while(i<5)     {           print(“Green Way”);           i++;      } getch();}
main(){    int i=1;    do     {         printf(“Green Way”);    i++;    }   while(i<5);   getch();}
main(){    int i;    for(i=1; i<5;i++)     {         printf(“Green Way”);    }   while (i<5);    getch ();}

Functions: Function is basically a set of statements that takes inputs, perform some computation and produces output.

Syntax: Return_type function name (set_of_inputs);

Return_type indicates the type of output returned by the function, function_name indicates the name of the function and the set_of_input indicates inputs provided to the function. It is not necessary to provide the inputs to the function. Without inputs it can performs some computation and it can return some output as well. Return_type indicates the type of the output and the output could be integer type, it could be character type or it could be float type and so on. 

There are two important reasons of why we are using function:

  1. Reusability– Once the function is defined, it can be reused over and over again. You can reuse the function again and again in your code without define its functionality.
  2. Abstraction- If you are just using the function in your program then you don’t have to worry about how it works inside. Example: scanf function

You can reuse scanf function multiple number of times without defines its functionality again and again in your code and also it provides the level of abstraction.

#include <stdio.h>int areaOfRect ( int length, int breadth);{    int area;    area = length * breadth;    return area ;int main(){    int l=10, b=5;    int area = areaOfRect(l, b);    printf(“%d\n”, area);}

We all know that, when we declare a variable, we declare its properties to the compiler.

For example: int var;

Here var is the name of variable and int is type of the variable. Similarly, function declaration (also called function prototype) means declaring the properties of the function to the compiler.

Example:   int func (int,char);

Here name of the function is func, return type of the function is int, no of parameters is 2, type of parameter 1 is int and type of parameter 2. It is not necessary to put the name of the parameters in function prototype.

Example:  int func (int var1, char var2);

Here var1 and var2 is the name of the parameter which is not necessary to mention. It is important to mention the name of the parameter in the function definition but it is not important to mention the name of the parameters in function declaration. 

#include <stdio.h>char func();int main(){    char c = func();    printf(“character is: %c”, c);}char func(){    return ‘a’;}

It is not necessary to declare the function before using it but is preferred to declare the function before using it.

In C language, function is divided into two parts:

  1. Library Function (printf, scanf etc.)
  2. User defined Function

Calling of function is two types:

  1. Call by value
  2. Call by reference

We can write program using function of four types:

No Argument and No Return value
No Argument and a Return value
Argument and No Return value
Argument and Return value

Function Definition: Function definition consists of block of code which is capable of performing some specific task.

int add ( int a, int b ){    int sum;    sum = a+b;    return sum;}

Here is the block of code which can perform the addition between two numbers available inside these two variable a and b.

Structure in C Program- Structure is user defined data type that can be used to group elements of different types into single type or we can say it is a collection of similar or different data type.

You can store atomic value or single value by use of primitive data types like char, int, float, double etc. You can’t store multiple value into a single variable, to store multiple data into a single variable structure is needed.

Suppose we have some mobiles and there are different specifications of these mobiles like:

Mobile 1
Mobile 2

If I want to store all these information somewhere, we need to create different variables for different types to store ‘Brand’ we need string variable; to store ‘RAM’, ‘Battery’ and ‘Camera’ we need integer variable; to store ‘Display’ value we need float variable. 

But it is not good idea to store all these information in separate variable. Suppose we have 1000 mobiles, then storing all the information in different variables is time consuming as well as memory consuming. Therefore this is not good idea. Array is not also good option because Array has the capability to store more than one elements but they all must be of same types. But our requirement is to store data of different types. Structure is one stop solution. So we have a structure which is giving us the power to define our own type that can be used to group elements of different types into a single type.

Defining a structure  

Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here
  };             Void main()            {               …………             }

This is global definition of structure. That means we can use ‘mobile’ data type in anywhere within the program. Here mobile is data type. No memory is consumed for definition of structure because we don’t create the variable using these data type. We can define structure within the function or outside the function.

Void main(){        Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here

This is local definition of structure. We can use ‘date’ function within this main function.

How to declare the variable?

Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here
  };             Void main()            {            struct mobile m1;………………………………             }

Here m1 is local variable, we can access this variable within main function.

Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here
  };               struct mobile m2;             Void main()            {               …………             }

Here m2 is globall variable.

Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here
  }m3;             Void main()            {               …………             }

m3 is also global variable, here d1,d2,d3 contains memory according their initialization.

How to initialize the structure?

Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here
  };             Void main()            {             struct mobile m1={“Samsung”,8,4000,48,15.8}; …………             }

We can also initialize like this:

Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here
  };             Void main()            {                struct mobile m1;                m1.Brand=”Samsung”;               m1.RAM=8;              m1.Battery=4000;              m1.Camera=48;              m1.Display=15.8; …………             }

User Input

Struct mobile{string Brand;int  RAM,Battery,Camera;float Display; //member variable declaration here
  };             Void main()            {                struct mobile m1;               printf(“Enter mobile1 specification:”);                scanf(“%s%d%d%d%f”,&m1.Brand,&m1.RAM,&m1.Battery,&m1.Camera,&m1.Display);printf(“Mobile1 specification: %s%d%d%d%f”,m1.Brand,m1.RAM,m1.Battery,m1.Camera,m1.Display);              getch();…………             }



Please enter your comment!
Please enter your name here

five × two =