0% found this document useful (0 votes)
60 views85 pages

C Language

The document provides an overview of the C programming language, including its history, features, installation, basic programs, variables, data types, and control statements. It was developed in the 1970s by Dennis Ritchie at Bell Labs and is a procedural programming language that is still widely used. It allows direct interaction with hardware and has features like machine independence, pointers, recursion, and memory management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views85 pages

C Language

The document provides an overview of the C programming language, including its history, features, installation, basic programs, variables, data types, and control statements. It was developed in the 1970s by Dennis Ritchie at Bell Labs and is a procedural programming language that is still widely used. It allows direct interaction with hardware and has features like machine independence, pointers, recursion, and memory management.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

C Language - eBook

Fortune Cloud Technologies Group


2nd Floor, Abhinav Apartment, Beside Congress Bhavan, Shivaji Nagar, Pune - 411005
Landmark: Near Pune Municipal Corporation (Ma.na.pa) Bus Stand, Pune
Contact No: 9766439090 / 7083777567
Website: www.fortunecloudindia.com

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


C Introduction

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


History

C
Developed
by
Dennis Ritchie

Directly
Interact with the
Hardware devices
Developed
in 1972
American
Telephone &
Bell laboratories Telegraph
Of AT & T

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Features

simple
Machine Independent or Portable Mid-level Programming Language

Fast Speed Pointers

Rich Library C
C
Recursion

Structured Programming Language Extensible

Memory Management
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
C Installation

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Introduction to first program

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Standard
Console Input
Input and
and Output
Output #include<stdio.h>
#include<conio.h>

void main()
{
printf(“FortuneCloud”);
}

Main method Output

Statement

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Variables

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


 A variable is a name of the memory location.
 A variable is nothing but a name given to a storage area.
 The name of a variable can be composed of letters, digits, and the
underscore character.

Rules for defining variables

 A variable can have alphabets, digits, and underscore.


 A variable name can start with the alphabet, and underscore only.
 It can't start with a digit.
 No whitespace is allowed within the variable name.
 A variable name must not be any reserved word or keyword, e.g. int,
float, etc.
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
Valid Variable Names Invalid Variable names

int a; int 2;
int _ab; int a b;
int a30; int long;

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Types of Variables

Local Global

Static

Automatic External

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Local Variable

void display()
{
int a=10; //local variable
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Global Variable

int value=20; //global variable


 Declared outside the function
or block
void display()
{
 Any function can change the
printf(“Hi”);
value of the global variable.
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Static Variable

void display()
{ Declared with the
int a=10; //local variable static keyword
static int b=10; //static variable

a=a+1;
b=b+1;
printf("\n%d,%d",a,b);
} Output:

void main() 11,11


{ 11,12
display(); 11,13
display();
display();
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Automatic Variable

Output:
void main()
{  All variables in C that are
11,11
int a=10; //local variable (also automatic) declared inside the
11,12
block, are automatic
11,13
auto int b=20; // automatic variable variables by default.
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


External Variable

#include<stdio.h>
#include<conio.h>  Also known as
Output:global variable
extern int e=50; // external variable
 11,11
Defined outside
void main() 11,12
the function
{ 11,13
printf(“%d”,e);
}  They are
everywhere in
the program

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Datatypes

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


extensive
system used
for declaring
variables or The type
functions of of a
different variable
types determine
s how
It specifies the
much
type of data
space it
that a variable
occupies
can store such
in storage
as integer,
floating,
character, etc.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Datatypes in C

Basic Derived Enumeration Void

void
array enum
int
pointer
char
structure
float
union
double

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


2 byte 4 byte
1.175494351 E - 38
−32,768 to 32,767 to
1.2E-38 to 3.4E+38

int
char
e stands for Exponent
float
double
1 byte 8 byte
2.225073858507201
−128 to 127 4 E – 308 to
1.797693134862315
8 E + 308

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Control Statements

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


if
Decision else if
Making switch

Control
Statements

for
Loops while
do-while

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Decision Making

 one or more conditions to be


evaluated or tested by the
program

 statement or statements to be
executed if the condition is
determined to be true

 other statements to be executed


if the condition is determined to
be false
if
else if
switch

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Loops

 block of code needs to be


executed several number of
times

 statements are executed


sequentially

for
while
do-while

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Decision Making if

if(expression)
{
//code to be executed  check some given
} condition and
perform some
operations
depending upon the
if(expression) correctness of that
{ condition
//code to be executed
}
else
{
//code to be executed if condition is false
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example

Ex. Even odd number

int num=10;

if(num%2==0)
{
printf(“Even Number”);
}
else
{
printf(“Odd Number”);
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Decision Making else if

if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true Multiple
} cases to be
else if(condition3) performed
{ for different
//code to be executed if condition3 is true conditions
}
Else
{
//code to be executed if all the conditions are false
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example

Ex. Display days name

int day=1;

if(day==1)
{
printf(“Sunday”);
}
else if(day==2)
{
printf(“Monday”);
}
…….
else
{
printf(“Day not found”);
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Decision Making switch

switch(expression)
{
case value1:
//code to be executed;
break;
Alternate to if-else-if
case value2: statement which
//code to be executed; allows us to execute
break; multiple operations
......

default:
code to be executed if all cases are not matched;
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example

int choice=1;

switch(choice)
{
case 1:
printf(“Case 1 executed”);
break;

case 2:
printf(“Case 2 executed”);
break;

default:
printf(“Wrong choice”);
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Loops for

iterate the statements or


for(initialization;condition;incr/decr) a part of the program
{ several times
//code to be executed used to traverse the data
} structures like the array
and linked list.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example

Ex. Display 1 to 10 numbers

int i;

for(i=1;i<=10;i++)
{
printf(“%d”,i);
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Loops while

Mostly used
while(condition) in the case
where the
{
number of
//code to be executed iterations is
} not known in
advance.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example

Ex. Display 1 to 10 numbers

int i=1;

while(i<=10)
{
printf(“%d”,i);
i++;
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Loops do-while

 post tested loop


do  repeat the
{ execution of
//code to be executed several parts of the
} while(condition); statements
 termination
condition depends
upon the end user.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example

Ex. Display 1 to 10 numbers

int i=1;

do
{
printf(“%d”,i);
i++;
} while(i<=10);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Difference between while and do-while

 do-while loop is
executed for first time
 While loop is executed irrespective of the
only when given condition. After
condition is true. executing while loop
for first time, then
 Condition is checked first condition is checked.
then statement(s) is
executed.  Statement(s) is
executed atleast once,
 while loop is entry thereafter condition is
controlled loop. checked.

 do-while loop is exit


controlled loop.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Function

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


 we can divide a large program into the basic building blocks known as function.

 It contains the set of programming statements enclosed by {}.

Advantages

 we can avoid rewriting same logic/code again and again.

 We can call C functions any number of times in a program.

 We can track a large C program easily when it is divided into multiple functions.

 Reusability is the main achievement.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Types of Functions

Function

Library Function
User-defined
printf(), scanf(), etc. Function

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


User-defined function

Default Function Parameterized Function

void display() void addition(int a, int b)


{ {
printf(“default function”); int c;
} c=a+b;
printf(“addition=%d”,c);
void main() }
{
display(); void main()
} {
addition(10,20);
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


User-defined function

Function with return

int addition(int a, int b)


{
int c;
c=a+b;
return c;
}

void main()
{
printf(“%d”,addition(10,20));
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Call by value and Call by reference

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Call by value

void show(int num)


{
printf(“\nBefore adding=%d",num);  value of the actual
num=num+10; parameters is copied
printf(“\nAfter adding=%d", num); into the formal
} parameters

int main()  can not modify the


{ value of the actual
int a=10; parameter
printf(“\nBefore function call a=%d", a);
 different memory is
show(a); allocated for actual and
formal parameters
printf(“\nAfter function call a=%d", a);

return 0;
}
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
Call by reference

void show(int *num)


{
 the address of the
printf(“\nBefore adding=%d",*num);
variable is passed into
(*num)+=10;
the function call as the
printf(“\nAfter adding=%d", *num);
actual parameter.
}
 the memory allocation is
int main()
similar for both formal
{
parameters and actual
int a=10;
parameters.
printf(“\nBefore function call a=%d", a);
 modified value gets
show(&a);
stored at the same
address.
printf(“\nAfter function call a=%d", a);

return 0;
}
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
Arrays

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


 fixed-size sequential collection of elements of the same type.

 collection of similar type of data items stored at contiguous memory locations.

 store the primitive type of data such as int, char, double, float, etc.

 each data element can be randomly accessed by using its index number.

 All arrays consist of contiguous memory locations.

 The lowest address corresponds to the first element and the highest address to the last
element.

Code Optimization Ease of traversing


Advantages
Ease of sorting Random Access
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
Types of Array

One dimensional array Two dimensional array

Multi-dimensional array

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


One dimensional array

int num[3];

num[0]=10;//initialization of array
num[1]=20;
num[2]=30;

printf(“%d”,num[0]);
printf(“%d”,num[1]);
printf(“%d”,num[2]);

OR

int i;
for(i=0;i<3;i++)
{
printf("%d ",num[i]);
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Two dimensional array

int num[2][2]={{1,2},{3,4}};

int i,j;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",num[i][j]);
}
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Multi-dimensional array

int num[2][2][2];

int i,j,k;

for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
printf("%d ",num[i][j][k]);
}
}
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example: Find out sum of elements in a given array

int num[5];
int i,sum=0;

printf(“Enter the array elements”);

for(i=0;i<5;i++)
{
scanf(“%d”,&num[i]);
}

for(i=0;i<5;i++)
{
sum=sum+num[i];
}

printf(“Sum=%d”,sum);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Strings

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


 one-dimensional array of characters terminated by a null character '\0'.

 The character array or the string is used to manipulate text such as word or sentences.

Ways to declare a string

By char array By string literal

char ch[5]={‘h', ‘e', ‘l', ‘l', ‘o‘, '\0'}; char ch[]=“hello”;

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


gets() and puts()

char str[30]; char str[30];


Both the
functions are
printf("Enter the string"); involved in the printf("Enter the string");
scanf(“%s”,&str); input/output gets(str);
operations of
printf(“String=%s“,str); the strings printf(“String=");
puts(str);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


char ch1[10]=“hello”;
String Functions
char ch2[10]=“world”;
char ch3[10];

strlen(ch1) strrev(ch1)
strlen strrev
strcpy(ch3,ch1) strlwr(ch1)
strcpy strlwr

strcat(ch1,ch2) strcat strupr strupr(ch1)

strcmp(ch1,ch2) strcmp strstr strstr(ch1,”substring”)

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example: Count number of vowels in a string

char str[100];
int i=0, count=0;

printf(“Enter a string\n");
gets(str);

while (str[i] != '\0')


{
if (str[i] == 'a' || str[i] == 'A' || str[i] == 'e' || str[i] == '
E' || str[i] == 'i' || str[i] == 'I' || str[i] =='o' || str[i] =='O'
|| str[i] == 'u' || str[i] == 'U')
count++;
i++;
}
printf("Number of vowels in the string: %d", count);
return 0;

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Structure-Union

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


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

 struct keyword is used to define the structure.

Why use structure

 There are cases where we need to store multiple attributes of an entity.

 It can have different attributes of different data types.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Declaring Structure

By struct keyword By declaring a variable

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

struct employee e1, e2;

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example:

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

int main( )
{
e1.id=101;
strcpy(e1.name, “abc");

printf( “Id : %d", e1.id);


printf( “\nName : %s", e1.name);
return 0;
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Array of structure

struct student collection of multiple


{
structures variables
int id;
char name[10];
};

int main()
{
struct student s[5]; printf("\nStudent Information\n");
int i;
for(i=0;i<5;i++){
for(i=0;i<5;i++){ printf("\nId:%d, Name:%s",s[i].id,s[i].name);
printf("\nEnter Id:"); }
scanf("%d",&s[i].id); return 0;
printf("\nEnter Name:"); }
scanf("%s",&s[i].name);
}
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
Union

 Store different data types in the same memory location

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

union employee
{ int id;
char name[20];
}e1; id gets garbage
value because
void main() name has large
{ memory size
e1.id=101;
strcpy(e1.name, “abcd");

printf( "id : %d\n", e1.id);


printf( "name : %s\n", e1.name);
}
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
Difference Between Structure And Union

 Memory is allocated only to


 Separate memory location is
one member having largest size
allotted to each input
among all other input variables
member
 union student
 struct student
{
{
int id;
int id;
char name[20];
char name[20];
};
};
 Its size equal to the size of
 Size of Structure is equal or
largest member among all data
greater than the sum of size
members.
of all the data members.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Pointers

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


 A pointer is a variable whose value is the address of another variable, i.e., direct address
of the memory location.

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

Example

int num = 10;


Int *p = &num;

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Advantages

Pointer reduces the code and improves the performance

It makes you able to access any memory location

We can return multiple values from a function

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Address Of (&) Operator

Returns the
address of a
variable
int num=10;

printf("value of number is %d”,num);

printf(“address of number is %u",&num);

we need to use
%u to display the
address of a
variable.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


NULL Pointer

 A pointer that is not assigned any value but NULL is known as the NULL pointer.

int *ptr=NULL;

if(ptr!=NULL)
{
printf("value of ptr is : %d",*ptr);
}
else
{
printf(“Null pointer");
}

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Pointer Arithmetic

int a=10,b=20,c;
int *p,*q;

p=&a;
q=&b;

c=*p+*q;

printf(“addition: %d",c);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


sizeof() operator

int a=10;

It determines the
printf(“%d”,sizeof(a)); size of the
expression or the
//sizeof(int); data type
//sizeof(char);
//sizeof(float);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Function pointer

int (*p) (int , int); //Declaration of a function


pointer.

int add( int , int ); // Declaration of function.

p = add; // Assigning address of add to the p


pointer.
We can get the
address of
memory by using
the function
pointer.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Example

int main()
{
int a,b;

int (*p)(int,int);
int add(int a, int b)
{
int result;
int c;
printf("Enter a and b : ");
c=a+b;
scanf("%d%d",&a,&b);
return c;
}
p=add;

result=(*p)(a,b);

printf(“Addition: %d",result);

return 0;
}
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
File Handling

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


 File Handling is the storing of data in a file using a program.

 File handling in C enables us to create, update, read, and delete the files stored on the
local file system through our C program.

Operations

Create Open Read Write Delete

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Modes

r Opens an existing text file for reading purpose.

w Opens a text file for writing. If it does not exist, then a new file is created.

a
Opens a text file for writing in appending mode. If it does not exist, then a new file is
created.

r+ Opens a text file for both reading and writing.

Opens a text file for both reading and writing. It first truncates the file to zero length
W+
if it exists, otherwise creates a file if it does not exist.

Opens a text file for both reading and writing. It creates the file if it does not exist.
a+
The reading will start from the beginning but writing can only be appended.
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
fopen rewind
Functions for
fprintf ftell
file handling

fscanf fgetw

fputc fputw

fgetc fseek

fclose

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


fprintf() and fscanf()

FILE *fp;
fp = fopen("file.txt", "w");//opening file used to
write set of
fprintf(fp, "Hello file by fprintf...\n");//writing data into file characters
into file
fclose(fp);//closing file

FILE *fp;
char buff[255];//creating char array to store data of file
used to
fp = fopen("file.txt", "r");
read set of
characters while(fscanf(fp, "%s", buff)!=EOF)
from file {
printf("%s ", buff );
}
fclose(fp);
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
fputc() and fgetc()

FILE *fp;
fp = fopen("file.txt", "w");//opening file used to write
a single
fputc('a',fp);//writing single character into file character
into file
fclose(fp);//closing file

FILE *fp;
char c;
returns a
single fp=fopen("file.txt","r");
character
from the file while((c=fgetc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
©2021, FORTUNE CLOUD TECHNOLOGIES GROUP
fputs() and fgets()

FILE *fp;

fp=fopen("myfile.txt","w"); writes a line of


fputs("hello c programming",fp); characters
into file
fclose(fp);

FILE *fp;
char text[300];
reads a line of
characters fp=fopen("myfile.txt","r");
from file printf("%s",fgets(text,200,fp));

fclose(fp);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


fseek()

FILE *fp;

fp = fopen("myfile.txt","w+"); It is used to set


the file pointer
fputs(“C programming", fp);
to the specified
fseek( fp, 7, SEEK_SET ); offset. It is used
to write data
fputs(“Practical", fp); into file at
desired location.
fclose(fp);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


rewind()
FILE *fp;
char c;

fp=fopen("file.txt","r");
 sets the file
pointer at the while((c=fgetc(fp))!=EOF){
beginning of printf("%c",c);
the stream }

 It is useful if you rewind(fp);


have to use
stream many while((c=fgetc(fp))!=EOF){
times. printf("%c",c);
}

fclose(fp);

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


ftell()

FILE *fp;
int length;  returns the
current file
fp = fopen("file.txt", "r"); position of the
fseek(fp, 0, SEEK_END); specified
stream
length = ftell(fp);
 get the total
fclose(fp); size of a file
after moving
printf("Size of file: %d bytes", length); file pointer at
the end of file.

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP


Thank you !

©2021, FORTUNE CLOUD TECHNOLOGIES GROUP

You might also like