C Material

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 102

C Language

The C Language is developed by Dennis Ritchie for creating system applications that
directly interact with the hardware devices such as drivers, kernels, etc.

C programming is considered as the base for other programming languages, that is why
it is known as mother language.

Features of C Language

C is the widely used language. It provides many 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

1) Simple
C is a simple language in the sense that it provides a structured approach (to break the
problem into parts), the rich set of library functions, data types, etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed on different machines with
some machine specific changes. Therefore, C is a machine independent language.

3) Mid-level programming language


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

4) Structured programming language


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

5) Rich Library
C provides a lot of inbuilt functions that make the development fast.

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

7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt
functions and hence the lesser overhead.
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. Recursion enables us to use the approach of backtracking.

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.

This is official website

Download Turbo C++ for Windows 10 & 7(32-64 bit) Latest Version - 2021

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:

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

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


function is defined in stdio.h .

int main() The main() function is the entry point of every program in c language.

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

return 0 The return 0 statement, returns execution status to the OS. The 0 value is used
for successful execution and 1 for unsuccessful execution.

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.

Compilation process in c
What is a compilation?
The compilation is a process of converting the source code into object code. It is done
with the help of the compiler. The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it generates the object code.
The c compilation process converts the source code taken as input into the object code
or machine code. The compilation process can be divided into four steps, i.e., Pre-
processing, Compiling, Assembling, and Linking.

The preprocessor takes the source code as an input, and it removes all the comments
from the source code. The preprocessor takes the preprocessor directive and interprets
it. For example, if <stdio.h>, the directive is available in the program, then the
preprocessor interprets the directive and replace this directive with the content of
the 'stdio.h' file.

The following are the phases through which our program passes before being
transformed into an executable form:

23K

o Preprocessor
o Compiler
o Assembler
o Linker
Preprocessor
The source code is the code which is written in a text editor and the source code file is
given an extension ".c". This source code is first passed to the preprocessor, and then
the preprocessor expands this code. After expanding the code, the expanded code is
passed to the compiler.

Compiler
The code which is expanded by the preprocessor is passed to the compiler. The
compiler converts this code into assembly code. Or we can say that the C compiler
converts the pre-processed code into assembly code.

Assembler
The assembly code is converted into object code by using an assembler. The name of
the object file generated by the assembler is the same as the source file. The extension
of the object file in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the
source file is 'hello.c', then the name of the object file would be 'hello.obj'.

Linker
Mainly, all the programs written in C use library functions. These library functions are
pre-compiled, and the object code of these library files is stored with '.lib' (or '.a')
extension. The main working of the linker is to combine the object code of library files
with the object code of our program. Sometimes the situation arises when our program
refers to the functions defined in other files; then linker plays a very important role in
this. It links the object code of these files to our program. Therefore, we conclude that
the job of the linker is to link the object code of our program with the object code of
the library files and other files. The output of the linker is the executable file. The name
of the executable file is the same as the source file but differs only in their extensions. In
DOS, the extension of the executable file is '.exe', and in UNIX, the executable file can be
named as 'a.out'. For example, if we are using printf() function in a program, then the
linker adds its associated code in an output file.

printf() and scanf() in C


The printf() and scanf() functions are used for input and output in C language. Both
functions are inbuilt library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

1. printf("format string",argument_list);  

The format string can be %d (integer), %c (character), %s (string), %f (float) et

scanf() function
The scanf() function is used for input. It reads the input data from the console.

1. scanf("format string",argument_list);  

Program to print cube of given number


Example of c language that gets input from the user and prints the cube of the given
number.
#include<stdio.h>    
int main(){    
int number;    
printf("enter a number:");    
scanf("%d",&number);    
printf("cube of number is:%d ",number*number*number);    
return 0;  
}    

The scanf("%d",&number) statement reads integer number from the console and


stores the given value in number variable.

The printf("cube of number is:%d ",number*number*number) statement prints the


cube of number on the console.

Program to print sum of 2 numbers


Example of input and output in C language that prints addition of 2 numbers.
#include<stdio.h>    
int main(){    
int x=0,y=0,result=0;  
  
printf("enter first number:");  
scanf("%d",&x);  
printf("enter second number:");  
scanf("%d",&y);  
  
result=x+y;  
printf("sum of 2 numbers:%d ",result);  
1.   
return 0;  
}    

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

There are the following data types in C language.

Types Data Types


Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types


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

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

Data types and its size is given according to 32-bit architecture.

Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

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

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

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

unsigned int 2 byte 0 to 65,535

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


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

unsigned short int 2 byte 0 to 65,535

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

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

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

float 4 byte

double 8 byte

long double 10 byte

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

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


identified.

Syntax to declare a variable:

1. type variable_list;  

The example of declaring the variable is given below:

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

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

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

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

Rules for defining variables


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

Valid datatypes:

o int a;  
o int _ab;  
o int a30;  

Types of Variables in C
There are many types of variables in c:

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

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

It must be declared at the start of the block.


void function1(){  
int x=10;//local variable  
}  

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

It must be declared at the start of the block.

int value=20;//global variable  
void function1(){  
int x=10;//local variable  
}  

Static Variable
A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

void function1(){  
int x=10;//local variable  
static int y=10;//static variable  
x=x+1;  
y=y+1;  
printf("%d,%d",x,y);  
}  

Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default.
We can explicitly declare an automatic variable using auto keyword.

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

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

extern int x=10;//external variable (also global)  
program1.c
#include "myfile.h"  
#include <stdio.h>  
void printValue(){  
    printf("Global variable: %d", global_variable);  
}  

C Identifiers
C identifiers represent the name in the C program, for example, variables, functions,
arrays, structures, unions, labels, etc. An identifier can be composed of letters such as
uppercase, lowercase letters, underscore, digits, but the starting letter should be either
an alphabet or an underscore. If the identifier is not used in the external linkage, then it
is called as an internal identifier. If the identifier is used in the external linkage, then it is
called as an external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins


either with an alphabetical character or an underscore, which are used to represent
various programming elements such as variables, functions, arrays, structures, unions,
labels, etc. There are 52 alphabetical characters (uppercase and lowercase), underscore
character, and ten numerical digits (0-9) that represent the identifiers. There is a total of
63 alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers


o The first character of an identifier should be either an alphabet or an underscore, and
then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifiers

1. total, sum, average, _m _, sum_1, etc.  

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

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


language.

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Ternary or Conditional Operators
o Assignment Operator

Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next.
The associativity specifies the operator direction to be evaluated; it may be left to right
or right to left.

int value=10+20*10;  
The value variable will contain 210 because * (multiplicative operator) is evaluated
before + (additive operator).

The precedence and associativity of C operators is given below:

Category Operator Associativity

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

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

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

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

Comma , Left to right

Comments in C
Comments in C language are used to provide information about lines of code. It is
widely used for documenting code.

There are 2 types of comments in the C language.

1. Single Line Comments


2. Multi-Line Comments

Single Line Comments


Single line comments are represented by double slash \\. Let's see an example of a
single line comment in C.

#include<stdio.h>    
int main(){    
    //printing information    
    printf("Hello C");    
return 0;  
}      

Mult Line Comments


Multi-Line comments are represented by slash asterisk \* ... *\. It can occupy many lines
of code, but it can't be nested. Syntax:

/*  
code 
to be commented 
*/  

Example of a multi-Line comment in C.

#include<stdio.h>    
int main(){    
    /*printing information   
      Multi-Line Comment*/  
    printf("Hello C");    
return 0;  
}       

C Format Specifier
The Format specifier is a string used in the formatted input and output functions.
The format string determines the format of the input and output. The format
string always starts with a '%' character.

The commonly used format specifiers in printf() function are:

Format Description
specifier

%d or %i It is used to print the signed integer value where signed integer means that
the variable can hold both positive and negative values.

%u It is used to print the unsigned integer value where the unsigned integer
means that the variable can hold only positive value.

%o It is used to print the octal unsigned integer where octal integer value
always starts with a 0 value.

%x It is used to print the hexadecimal unsigned integer where the hexadecimal


integer value always starts with a 0x value. In this, alphabetical characters
are printed in small letters such as a, b, c, etc.

%X It is used to print the hexadecimal unsigned integer, but %X prints the


alphabetical characters in uppercase such as A, B, C, etc.

%f It is used for printing the decimal floating-point values. By default, it prints


the 6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.

%g It is used to print the decimal floating-point values, and it uses the fixed
precision, i.e., the value after the decimal in input would be exactly the same
as the value in the output.

%p It is used to print the address in a hexadecimal form.

%c It is used to print the unsigned character.

%s It is used to print the strings.

%ld It is used to print the long-signed integer value.

int main()  
{  
  int b=6;  
  int c=8;  
  printf("Value of b is:%d", b);  
  printf("\nValue of c is:%d",c);  
  
    return 0;  
}  

Control Statements
C if else Statement

The if-else statement in C is used to perform the operations based on some specific
condition. The operations specified in if block are executed if and only if the given
condition is true.
There are the following variants of if statement in C language.

o If statement
o If-else statement
o If else-if ladder
o Nested if

If Statement
The if statement is used to check some given condition and perform some operations
depending upon the correctness of that condition. It is mostly used in the scenario
where we need to perform the different operations for the different conditions. The
syntax of the if statement is given below.

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

#include<stdio.h>    
int main(){    
int number=0;    
printf("Enter a number:");    
scanf("%d",&number);    
if(number%2==0){    
printf("%d is even number",number);    
}    
return 0;  
}    

Program to find the largest number of the three.


#include <stdio.h>  
int main()  
{  
    int a, b, c;   
     printf("Enter three numbers?");  
    scanf("%d %d %d",&a,&b,&c);  
    if(a>b && a>c)  
    {  
        printf("%d is largest",a);  
    }  
    if(b>a  && b > c)  
    {  
        printf("%d is largest",b);  
    }  
    if(c>a && c>b)  
    {  
        printf("%d is largest",c);  
    }  
    if(a == b && a == c)   
    {  
        printf("All are equal");   
    }  
}  

Output

If-else Statement
The if-else statement is used to perform two operations for a single condition. The if-
else statement is an extension to the if statement using which, we can perform two
different operations, i.e., one is for the correctness of that condition, and the other is for
the incorrectness of the condition. Here, we must notice that if and else block cannot be
executed simiulteneously. Using if-else statement is always preferable since it always
invokes an otherwise case with every if condition. The syntax of the if-else statement is
given below.

if(expression){  
//code to be executed if condition is true  
}else{  
//code to be executed if condition is false  
}  

Program to check whether a person is eligible to vote or not.


#include <stdio.h>  
int main()  
{  
    int age;   
    printf("Enter your age?");   
    scanf("%d",&age);  
    if(age>=18)  
    {  
        printf("You are eligible to vote...");   
    }  
    else   
    {  
        printf("Sorry ... you can't vote");   
    }  
}  

if else-if ladder Statement


The if-else-if ladder statement is an extension to the if-else statement. It is used in the
scenario where there are multiple cases to be performed for different conditions. In if-
else-if ladder statement, if a condition is true then the statements defined in the if block
will be executed, otherwise if some other condition is true then the statements defined
in the else-if block will be executed, at the last if none of the condition is true then the
statements defined in the else block will be executed. There are multiple else-if blocks
possible. It is similar to the switch case statement where the default is executed instead
of else block if none of the cases is matched.

if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}  

Program to calculate the grade of the student according to the


specified marks.
#include <stdio.h>  
int main()  
{  
    int marks;   
    printf("Enter your marks?");  
    scanf("%d",&marks);   
    if(marks > 85 && marks <= 100)  
    {  
        printf("Congrats ! you scored grade A ...");   
    }  
    else if (marks > 60 && marks <= 85)   
    {  
        printf("You scored grade B + ...");  
    }  
    else if (marks > 40 && marks <= 60)   
    {  
        printf("You scored grade B ...");  
    }  
    else if (marks > 30 && marks <= 40)   
    {  
        printf("You scored grade C ...");   
    }  
    else   
    {  
        printf("Sorry you are fail ...");   
    }  
}  

C Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable. Here, We can define various statements in the multiple cases for the
different values of a single variable.

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

switch(expression){    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
......    
    
default:     
 code to be executed if all cases are not matched;    
}    

Rules for switch statement in C language


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

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


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

4) The break statement in switch case is not must. It is optional. If there is no break


statement found in the case, all the cases will be executed present after the matched
case. It is known as fall through the state of C switch statement.

Examples.

We are assuming that there are following variables.

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

valid Switch Invalid Switch Valid Case Invalid Case

switch(x) switch(f) case 3; case 2.5;

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

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

switch(func(x,y)) case 'x'>'y'; case 1,2,3;

Example of c language switch statement.

#include<stdio.h>  
int main(){    
int number=0;     
printf("enter a number:");    
scanf("%d",&number);    
switch(number){    
case 10:    
printf("number is equals to 10");    
break;    
case 50:    
printf("number is equal to 50");    
break;    
case 100:    
printf("number is equal to 100");    
break;    
default:    
printf("number is not equal to 10, 50 or 100");    
}    
return 0;  
}    

C Loops
The looping can be defined as repeating the same process multiple times until a specific
condition satisfies. There are three types of loops used in the C language. In this part of
the tutorial, we are going to learn all the aspects of C loops.

Why use loops in C language?


The looping simplifies the complex problems into the easy ones. It enables us to alter
the flow of the program so that instead of writing the same code again and again, we
can repeat the same code for a finite number of times. For example, if we need to print
the first 10 natural numbers then, instead of using the printf statement 10 times, we can
print inside a loop which runs up to 10 iterations.

Advantage of loops in C
1) It provides code reusability.

2) Using loops, we do not need to write the same code again and again.

2.1M

54

OOPs Concepts in Java


3) Using loops, we can traverse over the elements of data structures (array or linked
lists).

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

1. do while
2. while
3. for

do-while loop in C
The do-while loop continues until a given condition satisfies. It is also called post tested
loop. It is used when it is necessary to execute the loop at least once (mostly menu
driven programs).

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

do{  
//code to be executed  
}while(condition);  

while loop in C
The while loop in c is to be used in the scenario where we don't know the number of
iterations in advance. The block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also called a pre-tested loop.

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

while(condition){  
//code to be executed  
}  
for loop in C
The for loop is used in the case where we need to execute some part of the code until
the given condition is satisfied. The for loop is also called as a per-tested loop. It is
better to use for loop if the number of iteration is known in advance.

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

for(initialization;condition;incr/decr){  
//code to be executed  
}  
Flow Chart for For:
do while loop in C
The do while loop is a post tested loop. Using the do-while loop, we can repeat the
execution of several parts of the statements. The do-while loop is mainly used in the
case where we need to execute the loop at least once. The do-while loop is mostly used
in menu-driven programs where the termination condition depends upon the end user.
do while loop syntax

The syntax of the C language do-while loop is given below:

do{  
//code to be executed  
}while(condition);  

Example 
#include<stdio.h>  
#include<stdlib.h>  
void main ()  
{  
    char c;  
    int choice,dummy;    
    do{  
    printf("\n1. Print Hello\n2. Print java\n3. Exit\n");  
    scanf("%d",&choice);  
    switch(choice)  
    {  
        case 1 :   
        printf("Hello");   
        break;  
        case 2:    
        printf("Javatpoint");  
        break;  
        case 3:  
        exit(0);   
      

  break;  
        default:   
        printf("please enter valid choice");      
    }  
    printf("do you want to enter more?");   
    scanf("%d",&dummy);  
    scanf("%c",&c);  
    }while(c=='y');  
}  
Flowchart of do while loop
while loop in C
While loop is also known as a pre-tested loop. In general, a while loop allows a part of
the code to be executed multiple times depending upon a given boolean condition. It
can be viewed as a repeating if statement. The while loop is mostly used in the case
where the number of iterations is not known in advance.

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

while(condition){  
//code to be executed  
}

Example of the while loop in C language


Program of while loop that prints table of 1.

#include<stdio.h>  
int main(){    
int i=1;      
while(i<=10){      
printf("%d \n",i);      
i++;      
}  
return 0;  
}    

Program to print table for the given number using while


loop in C
#include<stdio.h>  
int main(){    
int i=1,number=0,b=9;    
printf("Enter a number: ");    
scanf("%d",&number);    
while(i<=10){    
printf("%d \n",(number*i));    
i++;    
}    
return 0;  
}   

for loop in C
The for loop in C language is used to iterate the statements or a part of the program
several times. It is frequently used to traverse the data structures like the array and
linked list.

Syntax of for loop in C


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

for(Expression 1; Expression 2; Expression 3){  
//code
}

#include<stdio.h>  
int main(){  
int i=0;        
for(i=1;i<=10;i++){      
printf("%d \n",i);      
}     
return 0;  
}     
C Program: Print table for the given number using C for loop

#include<stdio.h>  
int main(){  
int i=1,number=0;      
printf("Enter a number: ");    
scanf("%d",&number);    
for(i=1;i<=10;i++){      
printf("%d \n",(number*i));    
}    
return 0;  
}    

C Array
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a
student in 6 subjects, then we don't need to define different variables for the marks in the different
subject. Instead of that, we can define an array which can store the marks in each subject at the
contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to access the
elements of the array.

Properties of Array

The array contains the following properties.

o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored
at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each
element of the array with the given base address and the size of the data element.

Advantage of C Array

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

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the 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 the 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 the array.

1. int marks[5];  

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

Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize each
element of the array by using the index.

Consider the following example.

1. marks[0]=80;//initialization of array  
2. marks[1]=60;  
3. marks[2]=70;  
4. marks[3]=85;  
5. marks[4]=75;  
#include<stdio.h>  
int main(){      
int i=0;    
int marks[5];//declaration of array       
marks[0]=80;//initialization of array    
marks[1]=60;    
marks[2]=70;    
marks[3]=85;    
marks[4]=75;    
//traversal of array    
for(i=0;i<5;i++){      
printf("%d \n",marks[i]);    
}//end of for loop     
return 0;  
}

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};  

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

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

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

#include<stdio.h>  
int main(){      
int i=0;    
int marks[5]={20,30,40,50,60};//declaration and initialization of array    
 //traversal of array    
for(i=0;i<5;i++){      
printf("%d \n",marks[i]);    
}    
return 0;  
}    
   

C Array Example: Sorting an array


In the following program, we are using bubble sort method to sort the array in ascending order.

#include<stdio.h>    
void main ()    
{    
    int i, j,temp;     
    int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};     
    for(i = 0; i<10; i++)    
    {    
        for(j = i+1; j<10; j++)    
        {    
            if(a[j] > a[i])    
            {    
                temp = a[i];    
                a[i] = a[j];    
                a[j] = temp;     
            }     
        }     
    }     
    printf("Printing Sorted Element List ...\n");    
    for(i = 0; i<10; i++)    
    {    
        printf("%d\n",a[i]);    
    }    
1. }     

Program to print the largest and second largest element of the array.
#include<stdio.h>  
void main ()  
{  
    int arr[100],i,n,largest,sec_largest;  
    printf("Enter the size of the array?");  
    scanf("%d",&n);  
    printf("Enter the elements of the array?");  
    for(i = 0; i<n; i++)  
    {  
        scanf("%d",&a[i]);  
    }  
    largest = a[0];  
    sec_largest = a[1];  
    for(i=0;i<n;i++)  
    {  
        if(a[i]>largest)  
        {  
            sec_largest = largest;  
            largest = a[i];  
        }  
        else if (a[i]>sec_largest && a[i]!=largest)  
        {  
            sec_largest=a[i];  
        }  
    }  
    printf("largest = %d, second largest = %d",largest,sec_largest);  
      
}  

Two Dimensional Array in C


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns. However, 2D arrays are created to
implement a relational database lookalike data structure. It provides ease of holding the bulk of data at
once which can be passed to any number of functions wherever required.

Declaration of two dimensional Array in C


The syntax to declare the 2D array is given below.

1. data_type array_name[rows][columns];  

Consider the following example.


1. int twodimen[4][3];  

Here, 4 is the number of rows, and 3 is the number of columns

Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being
done simultaneously. However, this will not work with 2D arrays. We will have to define at least the
second dimension of the array. The two-dimensional array can be declared and defined in the following
way.

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

Two-dimensional array example in C


#include<stdio.h>  
int main(){      
int i=0,j=0;    
int a[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};     
//traversing 2D array    
for(i=0;i<4;i++){    
 for(j=0;j<3;j++){    
   printf("a[%d] [%d] = %d \n",i,j,a[i][j]);    
 }//end of j    
}//end of i    
return 0;  
}    

C 2D array example: Storing elements in a matrix and printing it.


#include <stdio.h>    
void main ()    
{    
    int a[3][3],i,j;     
    for (i=0;i<3;i++)    
    {    
        for (j=0;j<3;j++)    
        {    
            printf("Enter a[%d][%d]: ",i,j);                
            scanf("%d",&a[i][j]);    
        }    
    }    
    printf("\n printing the elements ....\n");     
    for(i=0;i<3;i++)    
    {    
        printf("\n");    
        for (j=0;j<3;j++)    
        {    
            printf("%d\t",a[i][j]);    
        }    
    }    
}    

Return an Array in C
What is an Array?
An array is a type of data structure that stores a fixed-size of a homogeneous collection of data. In short,
we can say that array is a collection of variables of the same type.

For example, if we want to declare 'n' number of variables, n1, n2...n., if we create all these variables
individually, then it becomes a very tedious task. In such a case, we create an array of variables having the
same type. Each element of an array can be accessed using an index of the element.

Pass a single-dimensional array to a function.

Passing array to a function

#include <stdio.h>  
void getarray(int a[])  
{  
    printf("Elements of array are : ");  
    for(int i=0;i<5;i++)  
    {  
        printf("%d ", a[i]);  
    }  
}  
int main()  
{  
   int arr[5]={45,67,34,78,90};  
   getarray(arr);  
   return 0;  
}  

Passing array to a function as a pointer


#include <stdio.h>  
void printarray(char *a)  
{  
    printf("Elements of array are : ");  
    for(int i=0;i<5;i++)  
    {  
        printf("%c ", a[i]);  
    }  
}  
int main()  
{  
  char arr[5]={'A','B','C','D','E'};  
  printarray(a);  
  return 0;  
}  

C Strings
The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The
character array or the string is used to manipulate text such as word or sentences. Each character in the
array occupies one byte of memory, and the last character must always be 0. The termination character
('\0') is important in a string since it is the only way to identify where the string ends. When we define a
string as char s[10], the character s[10] is implicitly initialized with the null in the memory.

There are two ways to declare a string in c language.

1. By char array
2. By string literal

Example of declaring string by char array in C language.

1. char ch[10]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};  

As we know, array index starts from 0, so it will be represented as in the figure given below.

We can also define the string by the string literal in C language. For example:

1. char ch[]="welcome";  
In such case, '\0' will be appended at the end of the string by the compiler.

Difference between char array and string literal

There are two main differences between char array and literal.

o We need to add the null character '\0' at the end of the array by ourself whereas, it is appended
internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can reassign the
characters of the array.

String Example in C
Example where a string is declared and being printed. The '%s' is used as a format specifier for the string
in c language.

#include<stdio.h>  
#include <string.h>    
int main(){    
  char ch[11]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0''};    
   char ch2[11]="javadotnet";    
    
   printf("Char Array Value is: %s\n", ch);    
   printf("String Literal Value is: %s\n", ch2);    
 return 0;    
}    

Traversing String
Traversing the string is one of the most important aspects in any of the programming languages. We may
need to manipulate a very large text which can be done by traversing the text. Traversing string is
somewhat different from the traversing an integer array. We need to know the length of the array to
traverse an integer array, whereas we may use the null character in the case of string to identify the end
the string and terminate the loop.

Hence, there are two ways to traverse a string.

o By using the length of string


o By using the null character.
Using the length of string

Example of counting the number of vowels in a string.

#include<stdio.h>  
void main ()  
{  
    char s[11] = "welcome";  
    int i = 0;   
    int count = 0;  
    while(i<11)  
    {  
        if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')  
        {  
            count ++;  
        }  
        i++;  
    }  
    printf("The number of vowels %d",count);  
}  

using the null character

Example of counting the number of vowels by using the null character.

#include<stdio.h>  
void main ()  
{  
    char s[11] = "welcome";  
    int i = 0;   
    int count = 0;  
    while(s[i] != NULL)  
    {  
        if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')  
        {  
            count ++;  
        }  
        i++;  
    }  
    printf("The number of vowels %d",count);  
}  

Accepting string as the input


Till now, we have used scanf to accept the input from the user. However, it can also be used in the case of
strings but with a different scenario. Consider the below code which stores the string while space is
encountered.

#include<stdio.h>  
void main ()  
{  
    char s[20];  
    printf("Enter the string?");  
    scanf("%s",s);  
    printf("You entered %s",s);  
}  

C gets() and puts() functions


The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the
input/output operations of the strings.

C gets() function
The gets() function enables the user to enter some characters followed by the enter key. All the characters
entered by the user get stored in a character array. The null character is added to the array to make it a
string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the
user.

Declaration

1. char[] gets(char[]);  

Reading string using gets()


#include<stdio.h>  
void main ()  
{  
    char s[30];  
    printf("Enter the string? ");  
    gets(s);  
    printf("You entered %s",s);  
}  

C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to print the string
on the console which is previously read by using gets() or scanf() function. The puts() function returns an
integer value representing the number of characters being printed on the console. Since, it prints an
additional newline character with the string, which moves the cursor to the new line on the console, the
integer value returned by puts() will always be equal to the number of characters present in the string plus
1.

Declaration

1. int puts(char[])  

 Example to read a string using gets() and print it on the console using puts().

#include<stdio.h>  
#include <string.h>    
int main(){    
char name[50];    
printf("Enter your name: ");    
gets(name); //reads string from user    
printf("Your name is: ");    
puts(name);  //displays string    
return 0;    
}    

C String Functions
There are many important string functions defined in "string.h" library.

No Function Description
.

1) strlen(string_name) returns the length of string name.

2) strcpy(destination, source) copies the contents of source string to destination string.

3) strcat(first_string, concats or joins first string with second string. The result of the
second_string) string is stored in first string.

4) strcmp(first_string, compares the first string with second string. If both strings are
second_string) same, it returns 0.

5) strrev(string) returns reverse string.

6) strlwr(string) returns string characters in lowercase.

7) strupr(string) returns string characters in uppercase.

C String Length: strlen() function


The strlen() function returns the length of the given string. It doesn't count null character '\0'.

#include<stdio.h>  
#include <string.h>    
int main(){    
char ch[20]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};    
   printf("Length of string is: %d",strlen(ch));    
 return 0;    

C Copy String: strcpy()


The strcpy(destination, source) function copies the source string in destination.

#include<stdio.h>  
#include <string.h>    
int main(){    
 char ch[20]={ 'w', 'e', 'l', 'c', 'o', 'm', 'e', '\0'};    
   char ch2[20];    
   strcpy(ch2,ch);    
   printf("Value of second string is: %s",ch2);    
 return 0;    
}    

C String Concatenation: strcat()


The strcat(first_string, second_string) function concatenates two strings and result is returned to
first_string.

#include<stdio.h>  
#include <string.h>    
int main(){    
  char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};    
   char ch2[10]={'c', '\0'};    
   strcat(ch,ch2);    
   printf("Value of first string is: %s",ch);    
 return 0;    
}    

C Compare String: strcmp()


The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are
equal.

Here, we are using gets() function which reads string from the console.

#include<stdio.h>  
#include <string.h>    
int main(){    
  char str1[20],str2[20];    
  printf("Enter 1st string: ");    
  gets(str1);//reads string from console    
  printf("Enter 2nd string: ");    
  gets(str2);    
  if(strcmp(str1,str2)==0)    
      printf("Strings are equal");    
  else    
      printf("Strings are not equal");    
 return 0;    
}    

C Reverse String: strrev()


The strrev(string) function returns reverse of the given string. Let's see a simple example of strrev()
function.

#include<stdio.h>  
#include <string.h>    
int main(){    
  char str[20];    
  printf("Enter string: ");    
  gets(str);//reads string from console    
  printf("String is: %s",str);    
  printf("\nReverse String is: %s",strrev(str));    
 return 0;    
}    

C String Lowercase: strlwr()


The strlwr(string) function returns string characters in lowercase. Let's see a simple example of strlwr()
function.

#include<stdio.h>  

#include <string.h>    
int main(){    
  char str[20];    
  printf("Enter string: ");    
  gets(str);//reads string from console    
  printf("String is: %s",str);    
  printf("\nLower String is: %s",strlwr(str));  
return 0;

   C String Uppercase: strupr()


The strupr(string) function returns string characters in uppercase. Let's see a simple example of strupr()
function.

#include<stdio.h>  
#include <string.h>    
int main(){    
  char str[20];    
  printf("Enter string: ");    
  gets(str);//reads string from console    
  printf("String is: %s",str);    
  printf("\nUpper String is: %s",strupr(str));    
 return 0;    
}    

  C Functions
In c, we can divide a large program into the basic building blocks known as function. The function
contains the set of programming statements enclosed by {}. A function can be called multiple times to
provide reusability and modularity to the C program. In other words, we can say that the collection of
functions creates a program. The function is also known as procedureor subroutinein other programming
languages.

Advantage of functions in C
There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a program.
o We can call C functions any number of times in a program and from any place in a program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Function Aspects
There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the compiler
about the function name, function parameters, and return type.

o Function call Function can be called from anywhere in the program. The parameter list must not
differ in function calling and function declaration. We must pass the same number of functions as
it is declared in the function declaration.

o Function definition It contains the actual statements which are to be executed. It is the most
important aspect to which the control comes when the function is called. Here, we must notice
that only one value can be returned from the function.

SN C function aspects Syntax

1 Function declaration return_type function_name (argument list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list) {function body;}


Syntax:

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

Types of Functions
There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so that
he/she can use it many times. It reduces the complexity of a big program and optimizes the code.

Return Value
A C function may or may not return a value from the function. If you don't have to return any value from
the function, use void for the return type.

Example of C function that doesn't return any value from the function.

Example without return value:

void hello(){  
printf("hello c");  
}  

Next If you want to return any value from the function, you need to use any data type such as int, long,
char, etc. The return type depends on the value to be returned from the function.

Example of C function that returns int value from the function.

Example with return value:

int get(){  
return 10;  
}  

float get(){  
return 10.2;  
}  

Different aspects of function calling


A function may or may not accept any argument. It may or may not return any value. Based on these facts,
There are four different aspects of function calls.

o function without arguments and without return value


o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

Example for Function without argument and without return value

#include<stdio.h>  
void printName();  
void main ()  
{  
    printf("Hello ");  
    printName();  
}  
void printName()  
{  
    printf("welcome");  
}  
Example 2

#include<stdio.h>  
void sum();  
void main()  
{  
    printf("\nGoing to calculate the sum of two numbers:");  
    sum();  
}  
void sum()  
{  
    int a,b;   
    printf("\nEnter two numbers");  
    scanf("%d %d",&a,&b);   
    printf("The sum is %d",a+b);  
}  

Example for Function without argument and with return value

#include<stdio.h>  
int sum();  
void main()  
{  
    int result;   
    printf("\nGoing to calculate the sum of two numbers:");  
    result = sum();  
    printf("%d",result);  
}  
int sum()  
{  
    int a,b;   
    printf("\nEnter two numbers");  
    scanf("%d %d",&a,&b);  
    return a+b;   
}  
program to calculate the area of the square

#include<stdio.h>  
int sum();  
void main()  
{  
    printf("Going to calculate the area of the square\n");  
    float area = square();  
    printf("The area of the square: %f\n",area);  
}  
int square()  
{  
    float side;  
    printf("Enter the length of the side in meters: ");  
    scanf("%f",&side);  
    return side * side;  
}  

Example for Function with argument and without return value

#include<stdio.h>  
void sum(int, int);  
void main()  
{  
    int a,b,result;   
    printf("\nGoing to calculate the sum of two numbers:");  
    printf("\nEnter two numbers:");  
    scanf("%d %d",&a,&b);  
    sum(a,b);  
}  
void sum(int a, int b)  
{  
    printf("\nThe sum is %d",a+b);      
}  

Example 2: program to calculate the average of five numbers.

#include<stdio.h>  
void average(int, int, int, int, int);  
void main()  
{  
    int a,b,c,d,e;   
    printf("\nGoing to calculate the average of five numbers:");  
    printf("\nEnter five numbers:");  
    scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);  
    average(a,b,c,d,e);  
}  
void average(int a, int b, int c, int d, int e)  
{  
    float avg;   
    avg = (a+b+c+d+e)/5;   
    printf("The average of given five numbers : %f",avg);  
}  

Example for Function with argument and with return value

#include<stdio.h>  
int sum(int, int);  
void main()  
{  
    int a,b,result;   
    printf("\nGoing to calculate the sum of two numbers:");  
    printf("\nEnter two numbers:");  
    scanf("%d %d",&a,&b);  
    result = sum(a,b);  
    printf("\nThe sum is : %d",result);  
}  
int sum(int a, int b)  
{  
    return a+b;  
}  

Example 2: Program to check whether a number is even or odd

#include<stdio.h>  
int even_odd(int);  
void main()  
{  
 int n,flag=0;  
 printf("\nGoing to check whether a number is even or odd");  
 printf("\nEnter the number: ");  
 scanf("%d",&n);  
 flag = even_odd(n);  
 if(flag == 0)  
 {  
    printf("\nThe number is odd");  
 }  
 else   
 {  
    printf("\nThe number is even");  
 }  
}  
int even_odd(int n)  
{  
    if(n%2 == 0)  
    {  
        return 1;  
    }  
    else   
    {  
        return 0;  
    }  
}  

What is Structure
Structure in c is a user-defined data type that enables us to store the collection of different data types.
Each element of a structure is called a member. Structures ca; simulate the use of classes and templates as
it can store various information

The ,struct keyword is used to define the structure.

Syntax to define the structure in c.


struct structure_name   
{  
    data_type member1;  
    data_type member2;  
    .  
    .  
    data_type memeberN;  
};  

Define a structure for an entity employee in c.


struct employee  
{   
int id;  
    char name[20];  
    float salary;  
};  

The following image shows the memory allocation of the structure employee that is defined in the above
example.
Here, struct is the keyword; employee is the name of the structure; id, name, and salary are the
members or fields of the structure. Let's understand it by the diagram given below:

Declaring structure variable


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

1. By struct keyword within main() function


2. By declaring a variable at the time of defining the structure.

1st way:

Example to declare the structure variable by struct keyword. It should be declared within the main
function.
struct employee  
{   int id;  
    char name[50];  
    float salary;  
};

Now write given code inside the main() function.

1. struct employee e1, e2;  

The variables e1 and e2 can be used to access the values stored in the structure.

Here, e1 and e2 can be treated in the same way as the objects in C++ and Java.

2nd way:

Declare variable at the time of defining the structure.

struct employee  
{   int id;  
    char name[50];  
    float salary;  
}e1,e2; 

Which approach is good

If number of variables are not fixed, use the 1st approach. It provides you the flexibility to declare the
structure variable many times.

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

Accessing members of the structure


There are two ways to access structure members:

1. By . (member or dot operator)


2. By -> (structure pointer operator)

To access the id member of p1 variable by. (member) operator.

1. p1.id  
C Structure example

include<stdio.h>  
#include <string.h>    
struct employee      
{   int id;      
    char name[50];      
}e1;  //declaring e1 variable for structure    
int main( )    
{    
   //store first employee information    
   e1.id=101;    
   strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array    
   //printing first employee information    
   printf( "employee 1 id : %d\n", e1.id);    
   printf( "employee 1 name : %s\n", e1.name);    

return 0;  
}    

Example 2

#include<stdio.h>  
#include <string.h>    
struct employee      
{   int id;      
    char name[50];      
    float salary;      
}e1,e2;  //declaring e1 and e2 variables for structure    
int main( )    
{    
   //store first employee information    
   e1.id=101;    
   strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array    
   e1.salary=56000;    
    
  //store second employee information    
   e2.id=102;    
   strcpy(e2.name, "James Bond");    
   e2.salary=126000;    
     
   //printing first employee information    
   printf( "employee 1 id : %d\n", e1.id);    
   printf( "employee 1 name : %s\n", e1.name);    
   printf( "employee 1 salary : %f\n", e1.salary);    
    
   //printing second employee information    
   printf( "employee 2 id : %d\n", e2.id);    
   printf( "employee 2 name : %s\n", e2.name);    
   printf( "employee 2 salary : %f\n", e2.salary);    
   return 0;    
}    

C Array of Structures

Why use an array of structures?


Consider a case, where we need to store the data of 3 students. We can store it by using the structure as
given below.

#include<stdio.h>  
struct student  
{  
    char name[20];  
    int id;  
    float marks;  
};  
void main()  
{  
    struct student s1,s2,s3;  
    printf("Enter the name, id, and marks of student 1 ");  
    scanf("%s %d %f",s1.name,&s1.id,&s1.marks);  

    printf("Enter the name, id, and marks of student 2 ");  
    scanf("%s %d %f",s2.name,&s2.id,&s2.marks);  
    
    printf("Enter the name, id, and marks of student 3 ");  
    scanf("%s %d %f",s3.name,&s3.id,&s3.marks);  

    printf("Printing the details....\n");  
    printf("%s %d %f\n",s1.name,s1.id,s1.marks);  
    printf("%s %d %f\n",s2.name,s2.id,s2.marks);  
    printf("%s %d %f\n",s3.name,s3.id,s3.marks);  
}  

Union in C
Union can be defined as a user-defined data type which is a collection
of different variables of different data types in the same memory
location. The union can also be defined as many members, but only
one member can contain a value at a particular point in time.

Union is a user-defined data type, but unlike structures, they share the
same memory location.

struct abc  
{  
   int a;  
   char b;   
}   

The above code is the user-defined structure that consists of two


members, i.e., 'a' of type int and 'b' of type character. When we check
the addresses of 'a' and 'b', we found that their addresses are
different. Therefore, we conclude that the members in the structure do
not share the same memory location.

When we define the union, then we found that union is defined in


the same way as the structure is defined but the difference is that
union keyword is used for defining the union data type, whereas
the struct keyword is used for defining the structure. The union
contains the data members, i.e., 'a' and 'b', when we check the
addresses of both the variables then we found that both have the
same addresses. It means that the union members share the same
memory location.

In union, members will share the memory location. If we try to make


changes in any of the member then it will be reflected to the other
member as well

union abc  
{  
   int a;  
char b;   
}var;  
int main()  
{  
  var.a = 66;  
  printf("\n a = %d", var.a);  
  printf("\n b = %d", var.b);  
}   
n the above code, union has two members, i.e., 'a' and 'b'. The 'var' is a
variable of union abc type. In the main() method, we assign the 66 to
'a' variable, so var.a will print 66 on the screen. Since both 'a' and 'b'
share the memory location, var.b will print 'B' (ascii code of 66).

Deciding the size of the union


The size of the union is based on the size of the largest member of the
union.

union abc{  
int a;  
char b;  
float c;  
double d;  
};  
int main()  
{  
  printf("Size of union abc is %d", sizeof(union abc));  
  return 0;  
}  

As we know, the size of int is 4 bytes, size of char is 1 byte, size of


float is 4 bytes, and the size of double is 8 bytes. Since the double
variable occupies the largest memory among all the four
variables, so total 8 bytes will be allocated in the memory.
Therefore, the output of the above program would be 8 bytes.

Accessing members of union using pointers

We can access the members of the union through pointers by


using the (->) arrow operator.

Example.

#include <stdio.h>  
union abc  
{  
    int a;  
    char b;  
};  
int main()  
{  
    union abc *ptr; // pointer variable declaration  
    union abc var;  
    var.a= 90;  
    ptr = &var;  
    printf("The value of a is : %d", ptr->a);  
    return 0;  
}  

C Pointers
The pointer in C language is a variable which stores the address of
another variable. This variable can be of type int, char, array, function,
or any other pointer. The size of the pointer depends on the
architecture. However, in 32-bit architecture the size of a pointer is 2
byte.

Consider the following example to define a pointer which stores the


address of an integer.

int n = 10;   
int* p = &n; // Variable p of type pointer is pointing to the address 
of the variable n of type integer.   

Declaring a pointer

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


symbol). It is also known as indirection pointer used to
dereference a pointer.

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

Pointer Example
An example of using pointers to print the address and value is given
below.
As you can see in the above figure, pointer variable stores the address
of number variable, i.e., fff4. The value of number variable is 50. But
the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of


pointer variable p.

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.

Pointer example as explained for the above figure.

#include<stdio.h>  
int main(){  
int number=50;    
int *p;      
p=&number;//stores the address of number variable    
printf("Address of p variable is %x \n",p); // p contains the address of the 
number therefore printing p gives the address of number.     
printf("Value of p variable is %d \n",*p); // As we know that * is used to d
ereference a pointer therefore if we print *p, we will get the value stored 
at the address contained by p.    
return 0;  
}    

Pointer to array
int arr[10];  
int *p[10]=&arr; // Variable p of type pointer is pointing to the address o
f an integer array arr.  

Pointer to a function
void show (int);  
void(*p)(int) = &display; // Pointer p is pointing to the address of a funct
ion  

Pointer to structure
struct st {  
    int i;  
    float f;  
}ref;  
struct st *p = &ref;  
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 a function using the pointer.

3) It makes you able to access any memory location in the


computer's memory.

Usage of pointer
There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and


calloc() functions where the 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.

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.

#include<stdio.h>  
int main(){  
int number=50;   
printf("value of number is %d, address of number is %u",number,&numb
er);    
return 0;  

Pointer Program to swap two numbers


without using the 3rd variable.
#include<stdio.h>  
int main(){  
int a=10,b=20,*p1=&a,*p2=&b;  
  
printf("Before swap: *p1=%d *p2=%d",*p1,*p2);  
*p1=*p1+*p2;  
*p2=*p1-*p2;  
*p1=*p1-*p2;  
printf("\nAfter swap: *p1=%d *p2=%d",*p1,*p2);  
  
return 0;  
}  
Pointers to functions

Pointers give greatly possibilities to 'C' functions which we are


limited to return one value. With pointer parameters, our
functions now can process actual data rather than a copy of
data.
In order to modify the actual values of variables, the calling
statement passes addresses to pointer parameters in a
function.
#include,stdio.h>
void swap (int *a, int *b);
int main() {
int m = 25;
int n = 100;
printf("m is %d, n is %d\n", m, n);
swap(&m, &n);
printf("m is %d, n is %d\n", m, n);
return 0;}
void swap (int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;}
}

Pointers to Arrays
#include <stdio.h>

int main () {

/* an array with 5 elements */


double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;

p = balance;
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}

printf( "Array values using balance as address\n");


for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance +
i) );
}
return 0;
}

Pointers to strings
#include<stdio.h>
Void main()
{
Char s[20],t[20];
Printf(“\n Enter a string”);
gets(s);
sc(t,c);
printf(“\n source=%s \t Target=%s’,s,t);
}
Void sc(char *t1,char *s1)
{
While (*s1!=’\0’’)
{
*t1=*s1;
*t1++;
*s1++;
}
*t1=0;
}
Pointers to structures

#include <stdio.h>
struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1;

printf("Enter age: ");


scanf("%d", &personPtr->age);

printf("Enter weight: ");


scanf("%f", &personPtr->weight);

printf("Displaying:\n");
printf("Age: %d\n", personPtr->age);
printf("weight: %f", personPtr->weight);

return 0;
}

File Handling in C
In programming, we may require some specific input data to be
generated several numbers of times. Sometimes, it is not enough to
only display the data on the console. The data to be displayed may be
very large, and only a limited amount of data can be displayed on the
console, and since the memory is volatile, it is impossible to recover
the programmatically generated data again and again. However, if we
need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file
handling in C.
File handling in C enables us to create, update, read, and delete the
files stored on the local file system through our C program.

The following operations can be performed on a file.

o Creation of the new file


o Opening an existing file
o Reading from the file
o Writing to the file
o Deleting the file

Functions for file handling


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

No. Function Description

1 fopen() opens new or existing file

2 fprintf() write data into the file

3 fscanf() reads data from the file

4 fputc() writes a character into the file

5 fgetc() reads a character from file

6 fclose() closes the file

7 fseek() sets the file pointer to given position


8 fputw() writes an integer to file

9 fgetw() reads an integer from file

10 ftell() returns current position

11 rewind() sets the file pointer to the beginning of the file

Opening File: fopen()


We must open a file before it can be read, write, or update. The
fopen() function is used to open a file.

The syntax of the fopen() is given below.

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

The fopen() function accepts two parameters:

o The file name (string). If the file is stored at some specific


location, then we must mention the path at which the file is
stored. For example, a file name can be
like "c://some_folder/some_file.ext".
o The mode in which the file is to be opened. It is a string.

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

Mode Description
r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

The fopen function works in the following way.

o Firstly, It searches the file to be opened.


o Then, it loads the file from the disk and place it into the buffer.
The buffer is used to provide efficiency for the read operations.
o It sets up a character pointer which points to the first character
of the file.
Example which opens a file in write mode.

#include<stdio.h>  
void main( )  
{  
FILE *fp ;  
char ch ;  
fp = fopen("file_handle.c","r") ;  
while ( 1 )  
{  
ch = fgetc ( fp ) ;  
if ( ch == EOF )  
break ;  
printf("%c",ch) ;  
}  
fclose (fp ) ;  
}  

Closing File: fclose()


The fclose() function is used to close a file. The file must be closed
after performing all the operations on it.

The syntax of fclose() function is given below:

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:

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

Example:

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

Reading File : fscanf() function


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

Syntax:

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

Example:

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

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.

#include <stdio.h>  
void main()  
{  
    FILE *fptr;  
    int id;  
    char name[30];  
    float salary;  
    fptr = fopen("emp.txt", "w+");/*  open for writing */  
    if (fptr == NULL)  
    {  
        printf("File does not exists \n");  
        return;  
    }  
    printf("Enter the id\n");  
    scanf("%d", &id);  
    fprintf(fptr, "Id= %d\n", id);  
    printf("Enter the name \n");  
    scanf("%s", name);  
    fprintf(fptr, "Name= %s\n", name);  
    printf("Enter the salary\n");  
    scanf("%f", &salary);  
    fprintf(fptr, "Salary= %.2f\n", salary);  
    fclose(fptr);  
}  

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:

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

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:

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
char c;  
clrscr();  
fp=fopen("myfile.txt","r");  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
fclose(fp);  
getch();  
}  

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:

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
clrscr();  
  
fp=fopen("myfile2.txt","w");  
fputs("hello c programming",fp);  
  
fclose(fp);  
getch();  
}

Reading File : fgets() function


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

Syntax:

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

Example:

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
char text[300];  
clrscr();  
  
fp=fopen("myfile2.txt","r");  
printf("%s",fgets(text,200,fp));  
  
fclose(fp);  
getch();  
}  
C fseek() function
The fseek() function is used to set the file pointer to the specified
offset. It is used to write data into file at desired location.

Syntax:

int fseek(FILE *stream, long int offset, int whence)  

There are 3 constants used in the fseek() function for whence:


SEEK_SET, SEEK_CUR and SEEK_END.

Example:

#include <stdio.h>  
void main(){  
   FILE *fp;  
  
   fp = fopen("myfile.txt","w+");  
   fputs("This is javatpoint", fp);  
    
   fseek( fp, 7, SEEK_SET );  
   fputs("sonoo jaiswal", fp);  
   fclose(fp);  
}

C rewind() function
The rewind() function sets the file pointer at the beginning of the
stream. It is useful if you have to use stream many times.
Syntax:

void rewind(FILE *stream)  

#include<stdio.h>  
#include<conio.h>  
void main(){  
FILE *fp;  
char c;  
clrscr();  
fp=fopen("file.txt","r");  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
  
rewind(fp);//moves the file pointer at beginning of the file  
  
while((c=fgetc(fp))!=EOF){  
printf("%c",c);  
}  
  
fclose(fp);    
getch();    
}    

C ftell() function
The ftell() function returns the current file position of the specified
stream. We can use ftell() function to get the total size of a file after
moving file pointer at the end of file. We can use SEEK_END constant
to move the file pointer at the end of file.

Syntax:

long int ftell(FILE *stream)  

Example:

#include <stdio.h>  
#include <conio.h>  
void main (){  
   FILE *fp;  
   int length;  
   clrscr();  
   fp = fopen("file.txt", "r");  
   fseek(fp, 0, SEEK_END);  
  
   length = ftell(fp);  
  
   fclose(fp);  
   printf("Size of file: %d bytes", length);  
   getch();  
}  

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

The difference between static memory allocation and dynamic


memory allocation.

static memory allocation dynamic memory allocation

memory is allocated at compile time. memory is allocated at run tim

memory can't be increased while executing memory can be increased


program program.

used in array. used in linked list.

The methods used for dynamic memory allocation.

malloc() allocates single block of requested memory.

calloc() allocates multiple block of requested memory.

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

free() frees the dynamically allocated memory.


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

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


initially.

It returns NULL if memory is not sufficient.

The syntax of malloc() function is given below:

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

Example of malloc() function

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
  int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)malloc(n*sizeof(int));  //memory allocated using malloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);     
return 0;  
}    

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:

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

Example of calloc() function.

#include<stdio.h>  
#include<stdlib.h>  
int main(){  
 int n,i,*ptr,sum=0;    
    printf("Enter number of elements: ");    
    scanf("%d",&n);    
    ptr=(int*)calloc(n,sizeof(int));  //memory allocated using calloc    
    if(ptr==NULL)                         
    {    
        printf("Sorry! unable to allocate memory");    
        exit(0);    
    }    
    printf("Enter elements of array: ");    
    for(i=0;i<n;++i)    
    {    
        scanf("%d",ptr+i);    
        sum+=*(ptr+i);    
    }    
    printf("Sum=%d",sum);    
    free(ptr);    
return 0;  
}    

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.

Syntax of realloc() function.

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.

Syntax of free() function.

free(ptr)  

Command Line Arguments in C


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

To support command line argument, you need to change the structure


of main() function as given below.

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

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


the first argument.

The argv[] contains the total number of arguments. The first argument


is the file name always.

Example
Let's see the example of command line arguments where we are
passing one argument with file name.
#include <stdio.h>  
void main(int argc, char *argv[] )  {  
  
   printf("Program name is: %s\n", argv[0]);  
   
   if(argc < 2){  
      printf("No argument passed through command line.\n");  
   }  
   else{  
      printf("First argument is: %s\n", argv[1]);  
   }  

Run this program as follows in Linux:

1. ./program hello  

Run this program as follows in Windows from command line:

1. program.exe hello  

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.

No Function Description
.

1) ceil(number) rounds up the given number. It returns the integer v


than or equal to given number.

2) floor(number) rounds down the given number. It returns the integ


than or equal to given number.

3) sqrt(number) returns the square root of given number.

4) pow(base, returns the power of given number.


exponent)

5) abs(number) returns the absolute value of given number.

C Math Example

Example of math functions found in math.h header file

#include<stdio.h>  
#include <math.h>    
int main(){    
printf("\n%f",ceil(3.6));    
printf("\n%f",ceil(3.3));    
printf("\n%f",floor(3.6));    
printf("\n%f",floor(3.2));    
printf("\n%f",sqrt(16));    
printf("\n%f",sqrt(7));    
printf("\n%f",pow(2,4));    
printf("\n%f",pow(3,3));    
printf("\n%d",abs(-12));     
 return 0;    
}    

Enum in C
The enum in C is also known as the enumerated type. It is a user-
defined data type that consists of integer values, and it provides
meaningful names to these values. The use of enum in C makes the
program easy to understand and maintain.

The enum is defined by using the enum keyword.

The following is the way to define the enum in C:

enum flag

{integer_const1, integer_const2,.....integter_constN};  
In the above declaration, we define the enum named as flag
containing 'N' integer constants. The default value of
integer_const1 is 0, integer_const2 is 1, and so on. We can also
change the default value of the integer constants at the time of
the declaration.

For example:

enum fruits{mango, apple, strawberry, papaya};  

enum fruits{  
mango=2,  
apple=1,  
strawberry=5,  
papaya=7,  
}; 

Enumerated type declaration


As we know that in C language, we need to declare the variable of a pre-
defined type such as int, float, char, etc. Similarly, we can declare the
variable of a user-defined data type, such as enum. Let's see how we can
declare the variable of an enum type.

Suppose we create the enum of type status as shown below:

1. enum status{false,true};  

Now, we create the variable of status type:

1. enum status s; // creating a variable of the status type.  
In the above statement, we have declared the 's' variable of type status.

To create a variable, the above two statements can be written as:

1. enum status{false,true} s;  

In this case, the default value of false will be equal to 0, and the value of
true will be equal to 1.

Program of enum.

#include <stdio.h>  
 enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Fri
day, Saturday};  
 int main()  
{  
 enum weekdays w; // variable declaration of weekdays type  
 w=Monday; // assigning value of Monday to w.  
 printf("The value of w is %d",w);  
    return 0;  
}  
Example to understand the enum more clearly.

#include <stdio.h>  
 enum months{jan=1, feb, march, april, may, june, july, august, septembe
r, october, november, december};  
int main()  
{  
// printing the values of months  
 for(int i=jan;i<=december;i++)  
 {  
 printf("%d, ",i);  
 }  
    return 0;  
}  

What is getch() in C?
The getch() is a predefined non-standard function that is defined
in conio.h header file. It is mostly used by the Dev C/C++, MS- DOS's
compilers like Turbo C to hold the screen until the user passes a single
value to exit from the console screen. It can also be used to read a
single byte character or string from the keyboard and then print. It
does not hold any parameters. It has no buffer area to store the input
character in a program.

Why we use a getch() function?


We use a getch() function in a C/ C++ program to hold the output
screen for some time until the user passes a key from the keyboard to
exit the console screen. Using getch() function, we can hide the input
character provided by the users in the ATM PIN, password, etc.

Syntax:

int getch(void);  

Parameters: The getch() function does not accept any parameter from
the user.

Return value: It returns the ASCII value of the key pressed by the user
as an input.

Write a simple program to display the character entered by the user


using the getch() function in C.

Program.c

#include <stdio.h>   
#include <conio.h>   
int main()  
{  
       printf(" Passed value by the User is: %c", getch()); // print a character 
entered by the user  
    return 0;  
}  

Factorial Program using loop


#include<stdio.h>  
int main()    
{    
 int i,fact=1,number;    
 printf("Enter a number: ");    
  scanf("%d",&number);    
    for(i=1;i<=number;i++){    
      fact=fact*i;    
  }    
  printf("Factorial of %d is: %d",number,fact);    
return 0;  
}   

Factorial Program using recursion in C


#include<stdio.h>  
  
long factorial(int n)  
{  
  if (n == 0)  
    return 1;  
  else  
    return(n * factorial(n-1));  
}  
   
void main()  
{  
  int number;  
  long fact;  
  printf("Enter a number: ");  
  scanf("%d", &number);   
     fact = factorial(number);  
  printf("Factorial of %d is %ld\n", number, fact);  
  return 0;  
}  

Prime Number program in C


Prime number in C: Prime number is a number that is greater than 1
and divided by 1 or itself. In other words, prime numbers can't be
divided by other numbers than itself or 1. For example 2, 3, 5, 7, 11, 13,
17, 19, 23.... are the prime numbers.

#include<stdio.h>  
int main(){    
int n,i,m=0,flag=0;    
printf("Enter the number to check prime:");    
scanf("%d",&n);    
m=n/2;    
for(i=2;i<=m;i++)    
{    
if(n%i==0)    
{    
printf("Number is not prime");    
flag=1;    
break;    
}    
}    
if(flag==0)    
printf("Number is prime");     
return 0;  
 }    

Armstrong Number in C
Before going to write the c program to check whether the number is
Armstrong or not, let's understand what is Armstrong number.

Armstrong number is a number that is equal to the sum of cubes of its


digits. For example 0, 1, 153, 370, 371 and 407 are the Armstrong
numbers.

c program to check Armstrong Number in C.

#include<stdio.h>  
 int main()    
{    
int n,r,sum=0,temp;    
printf("enter the number=");    
scanf("%d",&n);    
temp=n;    
while(n>0)    
{    
r=n%10;    
sum=sum+(r*r*r);    
n=n/10;    
}    
if(temp==sum)    
printf("armstrong  number ");    
else    
printf("not armstrong number");    
return 0;  
}   

You might also like