Nothing Special   »   [go: up one dir, main page]

Sabyasachi Moitra

Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

C

Sabyasachi Moitra
moitrasabyasachi@hotmail.com
2

Introduction
• C is a general-purpose, high-level programming language.
• C programming language was developed in 1972 by Dennis
Ritchie at Bell Laboratories of AT&T (American Telephone &
Telegraph), located in U.S.A.
• Portable
- Can be executed in many machines with little bit or no change.
• Procedure-oriented programming language
- Specifies a series of steps or procedures for the program to
solve the problem.
• Structured programming language
- Breaks a program into parts or blocks.
3

History of C
4

First C Program
Source Code
Output
(first.c)
#include<stdio.h> HELLO WORLD!!!
#include<conio.h>

void main()
{
clrscr();

printf("HELLO WORLD!!!");

getch();
}
5

Parameter Description
#include<stdio.h> • Includes the standard input output
library functions.
• The printf() function is defined in
stdio.h file.
#include<conio.h> • Includes the console input output
library functions.
• The getch() function is defined in
conio.h file.
void main() • The main() function is the entry
point of every program in C
language.
• The void keyword specifies that it
returns no value.
clrscr() Used to clear the output screen.
printf() Used to print data on the console.
getch() Asks for a single character, blocks the
screen until any key is pressed.
6

Flow of C Program
CONSTANTS, VARIABLES
& DATA TYPES
8

Tokens
Smallest individual units in a program are known as tokens.

Keywords

Identifiers
TOKENS
Constants

Strings

Special
Symbols

Operators
9

Keywords
• Reserved identifiers.
• Cannot be used as names for the program variables or
other user-defined program elements.
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct …..
10

Identifiers
• Identifiers refer to the names of variables, functions,
arrays, etc., created by the programmers.
• An identifier starts with a letter A to Z, a to z, or an
underscore '_' followed by zero or more letters,
underscores, and digits (0 to 9).
• Punctuation characters such as @, $, and % are not
allowed within identifiers.
• Case-sensitive, i.e., account & ACCOUNT are two
different identifiers.
11

Constants
Constants refer to fixed values that do not change during
the execution of a program.
Integer
Constants 5
Numeric
Constants
Real
Constants 5.5

CONSTANTS Single
Character 'A'
Constants

Character String
Constants Constants "ABC"

Backslash
Character '\n'
Constants
12

Variables
• Identifier.
• Data name.
• Used to store a data value which can be changed during
program execution.
• E.g. sum, avg, etc.
13

Data Types

DATA TYPES

Primary or
Derived User-defined
Fundamental

int, float, array, pointer,


typedef, enum
char, void structure, union
14

User-defined Data Type


Data Type Description Example
Allow users to define an typedef int units;
identifier that would units
represent an existing data batch1,batch2;
typedef type.
Syntax
typedef type identifier;
enum identifier enum day
{value1,…,valuen}; {Mon,Tue,...,Sun};
The identifier is a user- enum day
defined enumerated data week_st,week_end;
type which can be used to
declare variables that can
enum have one of the values
enclosed within the braces.
After this definition, we can
declare variables of this
new type,
enum identifier v1,…,vn;
15

Storage Class
Storage class provides information about the location and
visibility of variables within a program.
Storage Class Meaning
Local variable, known only
auto to the function in which it is
defined.
Local variable, initialized
only once & exists till the
static end of the program. Retains
its value between multiple
function calls.
Global variable, known to all
extern
functions in the file.
Local variable, stored in the
register
register.
16

Type Qualifiers
The keywords which are used to modify the properties of a
variable are called type qualifiers.
Qualifier Description Example
Tells the size of basic long int a;
Size Qualifier
data type.
Tells the sign of the unsigned int a;
Sign Qualifier
variable.
A variable declared as const int a;
constant cannot be
Constant Qualifier
modified during program
execution.
A variable declared as volatile int a;
volatile can be changed
Volatile Qualifier at any time by some
external sources during
program execution.
OPERATORS &
EXPRESSIONS
18

Operators
• An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
• Operators are used in programs to manipulate data &
variables.
• They usually form a part of the mathematical or logical
expressions.
19

Types of Operator
Type Operators
Arithmetic Operators +, -, *, /, %
Relational Operators ==, !=, >, <, >=, <=
Logical Operators &&, ||, !
Increment & Decrement ++, --
Operators
Conditional Operator ?:
Bitwise Operators &, |, ~, ^, <<, >>
=, +=, -=, *=, /=, %=, &=, |=, ^=,
Assignment Operators
<<=, >>=
Special Operators &, *, ,, sizeof()
20

Example
21

Output
22

Type Cast Operator


C permits explicit type conversion of variables or
expressions using the type cast operator.

Syntax
(type-name)expression;

Example
avg = sum/(float)i;
DECISION MAKING &
BRANCHING
24

Simple if Statement
• An if statement consists of a Boolean expression followed
by one or more statements.
• If the Boolean expression evaluates to true, then the block
of code inside the if statement will be executed. If the
Boolean expression evaluates to false, then the first set of
code after the end of the if statement will be executed.
25

Example
26

if…else Statement
• An if statement can be followed by an optional else
statement, which executes when the Boolean expression
is false.
• If the Boolean expression evaluates to true, then the if
block will be executed, otherwise, the else block will be
executed.
27

Example
28

Nested if or if…else Statements


Use of one if or if…else statement inside another if or
if…else statement(s).
29

Example
30

if…else if Ladder Statement


The if…else if statement is used to execute one code from
multiple conditions.
31

Example
32

switch Statement
A switch statement allows a variable to be tested for
equality against a list of values known as case.
33

Example
34

goto Statement
• A goto statement in C programming provides an
unconditional jump from the goto to a labeled statement in
the same function.
• A goto statement makes difficult to trace the control flow
of a program, making the program hard to understand and
modify.
35

Example
DECISION MAKING &
LOOPING
37

What is loop?
• A loop in C language is used to execute a block of code or
a part of the program for several times.
• It saves code.
38

Types of Loops

LOOPS

while do while for


39

while Loop
• Iterates the code until the condition is false.
• Condition is given before the code. So the code may be
executed 0 or more times.
40

Example
Source Code Output
#include <stdio.h> 1
#include <conio.h>
2
void main() 3
{ 4
int i=1;
5
clrscr(); 6
7
while(i<=10) 8
{
printf("%d \n",i); 9
i++; 10
}

getch();
}
41

do while Loop
• Iterates the code until the condition is false.
• Condition is given after the code. So at least once the
code is executed whether the condition is true or false.
42

Example
Source Code Output
#include <stdio.h> 1
#include <conio.h>
2
void main() 3
{ 4
int i=1;
5
clrscr(); 6
7
do 8
{
printf("%d \n",i); 9
i++; 10
}while(i<=10);

getch();
}
43

for Loop
• Iterates the code until the condition is false.
• Initialization, condition and increment/decrement is given
before the code. So the code may be executed 0 or more
times.
44

Example
Source Code Output
#include <stdio.h> 1
#include <conio.h>
2
void main() 3
{ 4
int i=1;
5
clrscr(); 6
7
for(i=1;i<=10;i++) 8
{
printf("%d \n",i); 9
} 10
getch();
}
45

break VS continue
break continue
• Can appear in both • Can appear only in
switch and loop loop statements.
statements. • When encountered,
• When encountered, gets the control to the
terminates the block next iteration of the
and gets the control loop.
out of the switch or
loop.
46

Example
break continue
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>

void main() void main()


{ {
int i=1; int i=1;

clrscr(); clrscr();

for(i=1;i<=10;i++) for(i=1;i<=10;i++)
{ {
if(i==5) if(i==5)
break; continue;

printf("%d ",i); printf("%d ",i);


} }

getch(); getch();
} }

1234 1 2 3 4 6 7 8 9 10
ARRAYS
48

What is an Array?
• Collection of homogeneous (similar) elements (data) in a
contiguous memory location.
• Linear Data Structure
- A data structure (data organization and storage format
that enables efficient access and modification) is said to
be linear if the elements form a sequence.
49

Example (1D Array)


50

Example (2D Array)


CHARACTER ARRAYS &
STRINGS
52

C Strings
Strings are actually one-dimensional array of characters
terminated by a null character '\0'.

Declaration Syntax
char ch[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
char ch[6] = "Hello";
53

Example
Source Code Output
#include<stdio.h> Char Array Value is: Hello
#include<conio.h>
String Literal Value is: Hello
void main ()
{
char ch[6]={‘H', ‘e', ‘l', ‘l', 'o',
'\0'};
char ch2[6]=“Hello";
clrscr();
printf("Char Array Value is: %s\n",
ch);
printf("String Literal Value is:
%s\n", ch2);
getch();
}
54

gets() VS puts()
gets() puts()
The gets() function reads string from The puts() function prints the string
user (similar to scanf() function). (similar to printf() function).

Example Output

#include<stdio.h> Enter your name: Bob Dylan


#include<conio.h> Your name is: Bob Dylan
void main()
{
char name[50];
clrscr();
printf("Enter your name: ");
gets(name);
printf("Your name is: ");
puts(name);
getch();
}
55

Some String Handling Functions


Function Description
strlen() Finds the length of a string.
strcpy() Copies one string over another.
strcat() Concatenates two strings.
strcmp() Compares two strings.
…..
56

Example
USER-DEFINED
FUNCTIONS
58

What is Function?
• A function is a group of statements that together perform a
task.
• It can be called many times.
• It provides code reusability and code optimization.
59

Types of Functions

Function
created by
printf(), programmer
scanf()

Library User-defined
Function Function
60

Example
61

Passing Array to Function


62

What is Recursion?
• When function is called within the same function, it is
known as recursion.
• The function which calls the same function, is known as
recursive function.
63

Example
64

Some Terminologies
Term Description
Parameters that appear in function
Actual Parameters calls.
s=add(10,20);
Parameters that appear in function
Formal Parameters declarations.
int add(int a,int b){…}
The point at which the function is
being invoked or called is known as
Calling Function the calling function.
s=add(10,20);

The function which is being executed


due to the function call is known as the
Called Function called function.
int add(int a,int b){…}
STRUCTURES & UNIONS
66

What is a Structure?
• User defined datatype.
• Allows us to hold different type of elements.
• Each element of a structure is called a member.
• Widely used to store student information, employee
information, product information, book information etc.
• Similar to class in C++ and Java.
67

Example
68

Array of Structures
• Used to store many information of different data types.
• Also known as collection of structures.
69

Example
70

What is a Union?
• Like Structure, Union is also a user defined datatype that
is used to hold different type of elements.
• Unlike Structure, Union occupies the memory of the
largest member only, i.e., it shares the memory of the
largest member.
71

Example
72

Structure VS Union
Structure Union
A structure is defined with struct A union is defined with union keyword.
keyword.
The size of a structure variable is The size of a union variable is equal to
equal to the sum of the individual sizes the size of its largest member.
of its members.
Structure members are allocated Union members share common
distinct memory. memory space.
POINTERS
74

What are Pointers?


• Derived data type, i.e., built from one of the fundamental
data types available in C.
• Contains memory address of another variable as its
value.
75

Example
76

Pointer to Pointer
A pointer referring to the address of another pointer, i.e., a
pointer can point to the address of another pointer which
points to the address of a value.
77

Example
78

Pointers & Arrays


79

Array of Pointers
• An indexed set of variables in which the variables are
pointers, i.e., a reference to a location in memory.
• Consider the following array of strings:
char name[3][25];
Here, name is a table containing three names, each with a
maximum length of 25 characters (including null character).
Thus, the total storage requirement for the name table is 75
bytes,
80

Therefore, instead of making each row a fixed number of


characters, we can make it a pointer to a string of varying
length,
char *name[3]={
"New Zealand",
"Australia",
"India“
};
Here, name is an array of three pointers to characters, each
pointer pointing to a particular name,
name[0] New Zealand
name[1] Australia
name[2] India
81

Thus, allocating only 28 bytes of memory,


N e w Z e a l a n d \0
A u t r a l i a \0
I n d i a \0
82

Example
83

Call by Value VS Call by Reference


Call by Value Call by Reference
A copy of the value is passed to the An address of the value is passed to
function. the function.
Changes made inside the function is Changes made inside the function is
not reflected on other functions. reflected outside the function also.
Actual and formal arguments will be Actual and formal arguments will be
created in different memory locations. created in same memory location.
Original value is not modified. Original value is modified.
84

Example (Call by Value)


85

Example (Call by Reference)


86

Static Memory Allocation VS Dynamic


Memory Allocation
Static Memory Allocation Dynamic Memory Allocation
Memory allocated at compile time. Memory allocated at run time.
Memory can’t be increased during Memory can be increased during
execution . execution .
87

Dynamic Memory Allocation Functions


• malloc()
- Allocates single block of requested memory.
- Doesn't initialize memory at execution time, so it has
garbage value initially.
ptr=(cast-type*)malloc(byte-size)

• calloc()
- Allocates multiple blocks of requested memory, each of
same size.
- Initially initialize all bytes to zero.
ptr=(cast-type*)calloc(number,byte-size)
88

Dynamic Memory Allocation Functions (2)


• realloc()
- Reallocates the memory occupied by malloc() or calloc()
functions.
ptr=realloc(ptr, new-size)

• free()
- Frees the dynamically allocated memory.
free()
89

Example (malloc())
90

Example (calloc())
91

Example (realloc())
FILE MANAGEMENT IN C
93

What is File?
• A file is a collection of related data stored in a particular
area on the disk.
• Until now we have been using the scanf() & printf()
functions for reading from standard input (keyboard) and
writing to standard output (screen) respectively.
- It becomes cumbersome & time consuming to handle
large volumes of data through terminal.
- The entire data is lost when either the program is
terminated or the computer is turned off.
• To overcome the discussed problems the concept of files
is employed in C programming.
94

Writing to a File
95

Reading from a File


96

Some File Opening Modes


Mode Description
• Opens a text file in read mode.
r • Returns NULL if the file doesn’t
exist.
• Opens a text file in write mode.
• Creates a new file if the file doesn’t
w exist.
• Removes the content if the file exist
& writes new records into it.
• Opens a text file in append mode.
• Creates a new file if the file doesn’t
a exist.
• Append records to the end of the
file if it exist.

97

Some File Handling Functions


Function Description
• Creates a new file for use.
fopen()
• Opens an existing file for use.
Closes the file which has been opened
fclose()
for use.
fputc() Writes a character to a file.
fgetc() Reads a character from a file.
fputs() Writes a line of characters into a file.
fgets() Reads a line of characters from a file.

98

References
• E Balagurusamy, Programming in ANSI C, 4th Edition,
McGrawHill, 2007
• Courtesy of JavaTPoint – C Programming Language
Tutorial. URL: http://www.javatpoint.com/c-programming-
language-tutorial
• Courtesy of TutorialsPoint – C Tutorial. URL:
http://www.tutorialspoint.com/cprogramming

You might also like