0% found this document useful (0 votes)
12 views

Computer Programming with C

C is a programming language developed in 1972, primarily for UNIX systems, known for its performance and reliability. It has evolved with standards like ANSI C and is used extensively in operating systems and device drivers. The document also covers the structure of C programs, types of programming languages, and the compilation process.

Uploaded by

ninjashadow0719
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Computer Programming with C

C is a programming language developed in 1972, primarily for UNIX systems, known for its performance and reliability. It has evolved with standards like ANSI C and is used extensively in operating systems and device drivers. The document also covers the structure of C programs, types of programming languages, and the compilation process.

Uploaded by

ninjashadow0719
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 208

Introduction to C

C is a programming language developed at AT & T’s Bell Laboratories of USA


in 1972. It was designed and written by a man named Dennis Ritchie. In the late
seventies C began to replace the more familiar languages of that time like PL/I,
ALGOL, etc

ANSI C standard emerged in the early 1980s, this book was split into two
titles: The original was still called Programming in C, and the title that covered
ANSI C was called Programming in ANSI C. This was done because it took
several years for the compiler vendors to release their ANSI C compilers and for
them to become ubiquitous. It was initially designed for programming UNIX
operating system. Now the software tool as well as the C compiler is written in C.
Major parts of popular operating systems like Windows, UNIX, Linux is still
written in C. This is because even today when it comes to performance (speed of
execution) nothing beats C. Moreover, if one is to extend the operating system to
work with new devices one needs to write device driver programs. These
programs are exclusively written in C. C seems so popular is because it is reliable,
simple and easy to use. often heard today is – “C has been already superceded
by languages like C++, C# and Java.

Program

PGH,UEMK | [Document subtitle]


There is a close analogy between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the
language, then learn to combine these alphabets to form words, which in turn are
combined to form sentences and sentences are combined to form paragraphs. Learning
C is similar and easier. Instead of straight-away learning howto write programs, we
must first know what alphabets, numbers and special symbols are used in C, then how
using them constants, variables and keywords areconstructed, and finally how are these
combined to form an instruction. A group of instructions would be combined later on
to form a program. So

a computer program is just a collection of the instructions necessary to solve a


specific problem. The basic operations of a computer system form what is known
as the computer’s instruction set. And the approach or method that is used to solve
the problem is known as an algorithm.

So for as programming language concern these are of two types.

1) Low level language

2) High level language

Low level language:

PGH,UEMK | [Document subtitle]


Low level languages are machine level and assembly level language. In
machine level language computer only understand digital numbers i.e. in the form
of 0 and 1. So, instruction given to the computer is in the form binary digit, which
is difficult to implement instruction in binary code. This type of program is not
portable, difficult to maintain and also error prone. The assembly language is on
other hand modified version of machine level language. Where instructions are
given in English like word as ADD, SUM, MOV etc. It is easy to write and
understand but not understand by the machine. So the translator used here is
assembler to translate into machine level. Although language is bit easier,
programmer has to know low level details related to low level language. In the
assembly level language the data are stored in the computer register, which varies
for different computer. Hence it is not portable.

High level language:


These languages are machine independent, means it is portable. The language in
this category is Pascal, Cobol, Fortran etc. High level languages are understood by
the machine. So it need to translate by the translator into machine level. A
translator is software which is used to translate high level language as well as low
level language in to machine level language.

Three types of translator are there:

Compiler and interpreter are used to convert the high level language into machine
level language. The program written in high level language is known as source
program and the corresponding machine level language program is called as object
program. Both compiler and interpreter perform the same task but there working is
different. Compiler read the program at-a-time and searches the error and lists
them. If the program is error free then it is converted into object program. When
program size is large then compiler is preferred. Whereas interpreter read only one
line of the source code and convert it to object code. If it check error, statement by
statement and hence of take more time.
Integrated Development Environments (IDE)
The process of editing, compiling, running, and debugging programs is often
managed by a single integrated application known as an Integrated Development
Environment, or IDE for short. An IDE is a windows-based program that allows us

PGH,UEMK | [Document subtitle]


to easily manage large software programs, edit files in windows, and compile, link,
run, and debug programs.
On Mac OS X, CodeWarrior and Xcode are two IDEs that are used by many
programmers. Under Windows, Microsoft Visual Studio is a good example of a
popular IDE. Kylix is a popular IDE for developing applications under Linux.
Most IDEs also support program development in several different programming
languages in addition to C, such as C# and C++.

PGH,UEMK | [Document subtitle]


Lecture Note: 2

Structure of C Language program


1 ) Comment line
2) Preprocessor directive
3 ) Global variable declaration
4) main function( )
{

Local variables; Statements;


}
User defined function
}
}

Comment line
It indicates the purpose of the program. It is represented as
/*……………………………..*/
Comment line is used for increasing the readability of the program. It is useful in
explaining the program and generally used for documentation. It is enclosed within
the decimeters. Comment line can be single or multiple line but should not be
nested. It can be anywhere in the program except inside string constant &
character constant.

Preprocessor Directive:

PGH,UEMK | [Document subtitle]


#include<stdio.h> tells the compiler to include information about the standard
input/output library. It is also used in symbolic constant such as #define PI
3.14(value). The stdio.h (standard input output header file) contains definition
&declaration of system defined function such as printf( ), scanf( ), pow( ) etc.
Generally printf() function used to display and scanf() function used to read value
Global Declaration:
This is the section where variable are declared globally so that it can be access by
all the functions used in the program. And it is generally declared outside the
function :

main()
It is the user defined function and every function has one main() function from
where actually program is started and it is encloses within the pair of curly braces.
The main( ) function can be anywhere in the program but in general practice it is
placed in the first position.
Syntax : main()
{
……..
……..
……..
}
The main( ) function return value when it declared by data type as int main( )
{
return 0

PGH,UEMK | [Document subtitle]


}
The main function does not return any value when void (means null/empty) as
void main(void ) or void main()
{
printf (“C language”);
}
Output: C language
The program execution start with opening braces and end with closing brace.
And in between the two braces declaration part as well as executable part is
mentioned. And at the end of each line, the semi-colon is given which indicates
statement termination.
/*First c program with return statement*/
#include <stdio.h> int main (void)
{
printf ("welcome to c Programming language.\n"); return 0;
}
Output: welcome to c programming language.

Steps for Compiling and executing the Programs


A compiler is a software program that analyzes a program developed in a
particular computer language and then translates it into a form that is suitable for
execution

PGH,UEMK | [Document subtitle]


on a particular computer system. Figure below shows the steps that are involved
in entering, compiling, and executing a
computer program developed in the C programming language and the typical
Unix commands that would be entered from the command line.
Step 1: The program that is to be compiled is first typed into a file on the
computer system. There are various conventions that are used for naming files,
typically be any name provided the last two characters are “.c” or file with
extension .c. So, the file name prog1.c might be a valid filename for a C program.
A text editor is usually used to enter the C program into a file. For example, vi is a
popular text editor used on Unix systems. The program that is entered into the file
is known as the source program because it represents the original form of the
program expressed in the C language.

Step 2: After the source program has been entered into a file, then proceed to
have it compiled. The compilation process is initiated by typing a special
command on the system. When this command is entered, the name of the file that
contains the source program must also be specified. For example, under Unix, the
command to initiate program compilation is called cc. If we are using the popular
GNU C compiler, the command we use is gcc.
Typing the line
gcc prog1.c or cc prog1.c
In the first step of the compilation process, the compiler examines each program
statement contained in the source program and checks it to ensure that it
conforms to the syntax and semantics of the language. If any mistakes are
discovered by the compiler during this phase, they are reported to the user and the
compilation process ends right there. The errors then have to be corrected in the
source program (with the use of an editor), and the compilation process must be
restarted. Typical errors reported during this phase of compilation might be due to
an expression that has unbalanced parentheses (syntactic error), or due to the use
of a variable that is not “defined” (semantic error).

PGH,UEMK | [Document subtitle]


Step 3: When all the syntactic and semantic errors have been removed from the
program, the compiler then proceeds to take each statement of the program and
translate it into a “lower” form that is equivalent to assembly language program
needed to perform the identical task.

Step 4: After the program has been translated the next step in the compilation
process is to translate the assembly language statements into actual machine
instructions. The assembler takes each assembly language statement and converts
it into a binary format known as object code, which is then written into another file
on the system. This file has the same name as the source file under Unix, with the
last letter an “o” (for object) instead of a “c”.
Step 5: After the program has been translated into object code, it is ready to be
linked. This process is once again performed automatically whenever the cc or gcc
command is issued under Unix. The purpose of the linking phase is to get the
program into a final form for execution on the computer.
If the program uses other programs that were previously processed by the
compiler, then during this phase the programs are linked together. Programs that
are used from the system’s program library are also searched and linked together
with the object program during this phase.
The process of compiling and linking a program is often called building.

The final linked file, which is in an executable object code format, is stored in
another file on the system, ready to be run or executed. Under Unix, this file is
called a.out by default. Under Windows, the executable file usually has the same
name as the source file, with the c extension replaced by an exe extension.

PGH,UEMK | [Document subtitle]


Step 6: To subsequently execute the program, the command a.out has the effect
of loading the program called a.out into the computer’s memory and initiating its
execution.
When the program is executed, each of the statements of the program is
sequentially executed in turn. If the program requests any data from the user,
known as input, the program temporarily suspends its execution so that the input
can be entered. Or, the program might simply wait for an event, such as a mouse
being clicked, to occur. Results that are displayed by the program, known as
output, appear in a window, sometimes called the console. If the program does not
produce the desired results, it is necessary to go back and reanalyze the program’s
logic. This is known as the debugging phase, during which an attempt is made to
remove all the known problems or bugs from the program. To do this, it will most

PGH,UEMK | [Document subtitle]


likely be necessary to make changes to original source program.

PGH,UEMK | [Document subtitle]


/* Simple program to add two numbers ................................ */

PGH,UEMK | [Document subtitle]


#include <stdio.h>int

main (void)

int v1, v2, sum; //v1,v2,sum are variables and int is data type declared

v1 = 150;

v2 = 25;

sum = v1 + v2;

printf ("The sum of %i and %i is= %i\n", v1, v2, sum);

return 0;

Output:

The sum of 150 and 25 is=175


Character set

A character denotes any alphabet, digit or special symbol used to represent


information. Valid alphabets, numbers and special symbols allowed in C are

The alphabets, numbers and special symbols when properly combined form
constants, variables and keywords.

PGH,UEMK | [Document subtitle]


Identifiers

Identifiers are user defined word used to name of entities like variables, arrays,
functions, structures etc. Rules for naming identifiers are:
1) name should only consists of alphabets (both upper and lower case), digits
and underscore (_) sign.
2) first characters should be alphabet or underscore
3) name should not be a keyword
4) since C is a case sensitive, the upper case and lower case considered
differently, for example code, Code, CODE etc. are different identifiers.
5) identifiers are generally given in some meaningful name such as value,
net_salary, age, data etc. An identifier name may be long, some implementation
recognizes only first eight characters, most recognize 31 characters. ANSI
standard compiler recognize 31 characters. Some invalid identifiers are 5cb, int,
res#, avg no etc.

Keyword

PGH,UEMK | [Document subtitle]


There are certain words reserved for doing specific task, these words
are known as reserved word or keywords. These words are predefined and always
written in lower case or small letter. These keywords cann’t be used as a variable
name as it assigned with fixed meaning. Some examples are int, short, signed,
unsigned, default, volatile, float, long, double, break, continue, typedef, static,
do, for, union, return, while, do, extern, register, enum, case, goto, struct,
char, auto, const etc.

data types

Data types refer to an extensive system used for declaring variables or functions of
different types before its use. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. The value of a
variable can be changed any time.

C has the following 4 types of data types

basic built-in data types: int, float, double, char

Enumeration data type: enum

Derived data type: pointer, array, structure, union

Void data type: void

A variable declared to be of type int can be used to contain integral values


only—that is, values that do not contain decimal places. A variable declared to be of
type float can be used for storing floating- point numbers (values containing decimal
places). The double type is the same as type float, only with roughly twice the precision.
The char data type can be used to store a single character, such as thelettera, the digit
character 6, or a semicolon similarly A variable declared char canonly store
character type value.

There are two types of type qualifier in c

Size qualifier: short, long

Sign qualifier: signed, unsigned

PGH,UEMK | [Document subtitle]


When the qualifier unsigned is used the number is always positive, and when
signed is used number may be positive or negative. If the sign qualifier is not
mentioned, then by default sign qualifier is assumed. The range of values for
signed data types is less than that of unsigned data type. Because in signed type,
the left most bit is used to represent sign, while in unsigned type this bit is also
used to represent the value. The size and range of the different data types on a 16
bit machine is given below:

Basic data type Data type with type Size Range


qualifier (byte)
char char or signed char 1 -128 to 127
Unsigned char 1 0 to 255
int int or signed int 2 -32768 to 32767
unsigned int 2 0 to 65535
short int or signed short int 1 -128 to 127
unsigned short int 1 0 to 255
long int or signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float float 4 -3.4E-38 to 3.4E+38
double double 8 1.7E-308 to 1.7E+308
Long double 10 3.4E-4932 to 1.1E+4932

PGH,UEMK | [Document subtitle]


Constants

Constant is a any value that cannot be changed during program execution. In C, any
number, single character, or character string is known as a constant. A constantis an
entity that doesn’t change whereas a variable is an entity that may change.For
example, the number 50 represents a constant integer value. The character string
"Programming in C is fun.\n" is an example of a constant character string. C
constants can be divided into two major categories:
These constants are further categorized as

Numeric constant Character constant String constant

Numeric constant: Numeric constant consists of digits. It required minimum size


of 2 bytes and max 4 bytes. It may be positive or negative but by default sign is
always positive. No comma or space is allowed within the numeric constant and it
must have at least 1 digit. The allowable range for integer constants is -32768 to

PGH,UEMK | [Document subtitle]


32767. Truly speaking the range of an Integer constant depends upon the compiler.
For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767.
For a 32-bit compiler the range would be even greater. Mean by a 16-bit or a 32-
bit compiler, what range of an Integer constant has to do with the type of compiler.

It is categorized a integer constant and real constant. An integer constants are


whole number which have no decimal point. Types of integer constants are:
Decimal constant: 0 ------ 9(base 10)
Octal constant: 0 ------ 7(base 8)
Hexa decimal constant: 0----9, A ----- F(base 16)

In decimal constant first digit should not be zero unlike octal constant first digit
must be zero(as 076, 0127) and in hexadecimal constant first two digit should be
0x/ 0X (such as 0x24, 0x87A). By default type of integer constant is integer but if
the value of integer constant is exceeds range then value represented by integer
type is taken to be unsigned integer or long integer. It can also be explicitly
mention integer and unsigned integer type by suffix l/L and u/U.

Real constant is also called floating point constant. To construct real constant we
must follow the rule of ,
-real constant must have at least one digit.
-It must have a decimal point.
-It could be either positive or negative.
-Default sign is positive.
-No commas or blanks are allowed within a real constant. Ex.: +325.34
426.0
-32.76

To express small/large real constant exponent(scientific) form is used where


number is written in mantissa and exponent form separated by e/E. Exponent can
be positive or negative integer but mantissa can be real/integer type, for example
3.6*105=3.6e+5. By default type of floating point constant is double, it can also be
explicitly defined it by suffix of f/F.

Character constant

PGH,UEMK | [Document subtitle]


Character constant represented as a single character enclosed within a single
quote. These can be single digit, single special symbol or white spaces such as
‘9’,’c’,’$’, ‘ ’ etc. Every character constant has a unique integer like value in
machine’s character code as if machine using ASCII (American standard code for
information interchange). Some numeric value associated with each upper and
lower case alphabets and decimal integers are as:

A ------------ Z ASCII value (65-90)

a ------------ z ASCII value (97-122)

0-------------9 ASCII value (48-59)

; ASCII value (59)

String constant

Set of characters are called string and when sequence of characters are
enclosed within a double quote (it may be combination of all kind of symbols) is a
string constant. String constant has zero, one or more than one character and at the
end of the string null character(\0) is automatically placed by compiler. Some
examples are “,sarathina” , “908”, “3”,” ”, “A” etc. In C although same characters
are enclosed within single and double quotes it represents different meaning such
as “A” and ‘A’ are different because first one is string attached with null character
at the end but second one is character constant with its corresponding ASCII value
is 65.

Symbolic constant
Symbolic constant is a name that substitute for a sequence of characters and,
characters may be numeric, character or string constant. These constant are
generally defined at the beginning of the program as

#define name value , here name generally written in


upper case for example

PGH,UEMK | [Document subtitle]


#define MAX 10

#define CH ‘b’

#define NAME “sony”

Variables

Variable is a data name which is used to store some data value or symbolic names
for storing program
computations and results. The value of the variable can be change during the
execution. The rule for naming the variables is same as the naming identifier.
Before used in the program it must be declared. Declaration of variables specify its
name, data types and range of the value that variables can store depends upon its
data types.

Syntax:

int a;

char c;

float f;

Variable initialization

When we assign any initial value to variable during the declaration, is called
initialization of variables. When variable is declared but contain undefined value
then it is called garbage value. The variable is initialized with the assignment
operator such as

Data type variable name=constant;

Example: int a=20;

Or int a;

a=20;

PGH,UEMK | [Document subtitle]


statements

Expressions
An expression is a combination of variables, constants, operators and function call.
It can be arithmetic, logical and relational for example:-

int z= x+y // arithmatic expression

a>b //relational

a==b // logical
func(a, b) // function call
Expressions consisting entirely of constant values are called constant expressions.
So, the expression
121 + 17 - 110
is a constant expression because each of the terms of the expression is a constant
value. But if i were declared to be an integer variable, the expression
180 + 2 – j
would not represent a constant expression.

Operator
This is a symbol use to perform some operation on variables, operands or with the
constant. Some operator required 2 operand to perform operation or Some
required single operation.

Several operators are there those are, arithmetic operator, assignment, increment ,
decrement, logical, conditional, comma, size of , bitwise and others.

1. Arithmatic Operator
This operator used for numeric calculation. These are of either Unary arithmetic
operator, Binary arithmetic operator. Where Unary arithmetic operator required

PGH,UEMK | [Document subtitle]


only one operand such as +,-, ++, --,!, tiled. And these operators are addition,
subtraction, multiplication, division. Binary arithmetic operator on other hand
required two operand and its operators are +(addition), -(subtraction),
*(multiplication), /(division), %(modulus). But modulus cannot applied with
floating point operand as well as there are no exponent operator in c.

Unary (+) and Unary (-) is different from addition and subtraction.

When both the operand are integer then it is called integer arithmetic and the result
is always integer. When both the operand are floating point then it is called floating
arithmetic and when operand is of integer and floating point then it is called mix
type or mixed mode arithmetic . And the result is in float type.

2.Assignment Operator

A value can be stored in a variable with the use of assignment operator. The
assignment operator(=) is used in assignment statement and assignment expression.
Operand on the left hand side should be variable and the operand on the right hand
side should be variable or constant or any expression. When variable on the left
hand side is occur on the right hand side then we can avoid by writing the
compound statement. For example,

int x= y;

int Sum=x+y+z;

3.Increment and Decrement

The Unary operator ++, --, is used as increment and decrement which acts upon
single operand. Increment operator increases the value of variable by one
.Similarly decrement operator decrease the value of the variable by one. And these
operator can only used with the variable, but cann't use with expression and
constant as ++6 or ++(x+y+z).

PGH,UEMK | [Document subtitle]


It again categories into prefix post fix . In the prefix the value of the variable is
incremented 1st, then the new value is used, where as in postfix the operator is
written after the operand(such as m++,m--).

EXAMPLE

let y=12;

z= ++y;

y= y+1;

z= y;

Similarly in the postfix increment and decrement operator is used in the operation .
And then increment and decrement is perform.

EXAMPLE

let x= 5;

y= x++;

y=x;

x= x+1;

4.Relational Operator

It is use to compared value of two expressions depending on their relation.


Expression that contain relational operator is called relational expression.

Here the value is assign according to true or false value.

a.(a>=b) || (b>20)

b.(b>a) && (e>b)

c. 0(b!=7)

5. Conditional Operator

PGH,UEMK | [Document subtitle]


It sometimes called as ternary operator. Since it required three expressions as
operand and it is represented as (? , :).

SYNTAX

exp1 ? exp2 :exp3

Here exp1 is first evaluated. It is true then value return will be exp2 . If false then
exp3.

EXAMPLE

void main()

int a=10, b=2

int s= (a>b) ? a:b;

printf(“value is:%d”);

Output:

Value is:10

6. Comma Operator

Comma operator is use to permit different expression to be appear in a situation


where only one expression would be used. All the expression are separator by
comma and are evaluated from left to right.

EXAMPLE

int i, j, k, l;

for(i=1,j=2;i<=5;j<=10;i++;j++)

PGH,UEMK | [Document subtitle]


7. Sizeof Operator

Size of operator is a Unary operator, which gives size of operand in terms of byte
that occupied in the memory. An operand may be variable, constant or data type
qualifier.

Generally it is used make portable program(program that can be run on different


machine) . It determines the length of entities, arrays and structures when their size
are not known to the programmer. It is also use to allocate size of memory
dynamically during execution of the program.

EXAMPLE

main( )

int sum;

float f;

printf( "%d%d" ,size of(f), size of (sum) );


printf("%d%d", size of(235 L), size of(A));

PGH,UEMK | [Document subtitle]


8. Bitwise Operator

Bitwise operator permit programmer to access and manipulate of data at bit level.
Various bitwise operator enlisted are

one's complement (~)

bitwise AND (&)

bitwise OR (|)

bitwise XOR (^)

left shift (<<)

right shift (>>)

These operator can operate on integer and character value but not on float and
double. In bitwise operator the function showbits( ) function is used to display the
binary representation of any integer or character value.

In one's complement all 0 changes to 1 and all 1 changes to 0. In the bitwise OR its
value would obtaining by 0 to 2 bits.

As the bitwise OR operator is used to set on a particular bit in a number. Bitwise


AND the logical AND.

It operate on 2operands and operands are compared on bit by bit basic. And hence
both the operands are of same type.

Logical or Boolean Operator

Operator used with one or more operand and return either value zero (for false) or
one (for true). The operand may be constant, variables or expressions. And the
expression that combines two or more expressions is termed as logical expression.
C has three logical operators :

PGH,UEMK | [Document subtitle]


Operator Meaning

&& AND
|| OR
! NOT
Where logical NOT is a unary operator and other two are binary
operator. Logical AND gives result true if both the conditions are
true, otherwise result is false. Andlogial OR gives result false if
both the condition false, otherwise result is true.

Precedence and associativity of operators

Operators Description Precedence level Associativity

() function call 1 left to right

[] array subscript

 arrow operator
. dot operator

+ unary plus 2 right to left


- unary minus
++ increment
-- decrement
! logical not
~ 1’s complement
* indirection
& address
(data type) type cast
sizeof size in byte
* multiplication 3 left to right
/ division
% modulus

+ addition 27
4 left to right
*
- subtraction
<< left shift 5 left to right
>> right shift

<= less than equal to 6 left to right


>= greater than equal to
< less than
> greater than

== equal to 7 left to right


!= not equal to

& bitwise AND 8 left to right

^ bitwise XOR 9 left to right

| bitwise OR 10 left to right


&& logical AND 11
|| logical OR 12
?: conditional operator 13

=, *=, /=, %= assignment operator 14 right to left


&=, ^=, <<=
>>=

, comma operator 15

28 *
Loops
Aparajita Mukherjee
Assistant Professor
UEM, Kolkata
Loops in C

C has three loop statements: the while, the for, and the
do…while. The first two are pretest loops, and the
the third is a post-test loop. We can use all of them
for event-controlled and counter-controlled loops.

Topics discussed in this section:


The while Loop
The for Loop
The do…while Loop
The Comma Expression
Aparajita Mukherjee, Assistant Professor, UEM, Kolkata
FIGURE 6-9 C Loop Constructs

Aparajita Mukherjee, Assistant Professor, UEM, Kolkata 3


FIGURE 6-10 The while Statement

Aparajita Mukherjee, Assistant Professor, UEM, Kolkata 4


FIGURE 6-11 Compound while Statement

Aparajita Mukherjee, Assistant Professor, UEM, Kolkata 5


PROGRAM 6-1 Process-control System Example

Computer Science: A Structured Programming Approach Using C 6


PROGRAM 6-2 A while Loop to Print Numbers

Computer Science: A Structured Programming Approach Using C 7


PROGRAM 6-2 A while Loop to Print Numbers

Computer Science: A Structured Programming Approach Using C 8


PROGRAM 6-3 Adding a List of Numbers

Computer Science: A Structured Programming Approach Using C 9


PROGRAM 6-3 Adding a List of Numbers

Computer Science: A Structured Programming Approach Using C 1


0
Note
A for loop is used when a loop is to be executed a known
number of times. We can do the same thing with a while
loop, but the for loop is easier to read and
more natural for counting loops.

Computer Science: A Structured Programming Approach Using C 11


FIGURE 6-14 Comparing for and while Loops

Computer Science: A Structured Programming Approach Using C 12


PROGRAM 6-4 Example of a for Loop

Computer Science: A Structured Programming Approach Using C 13


PROGRAM 6-4 Example of a for Loop

Computer Science: A Structured Programming Approach Using C 14


PROGRAM 6-5 A Simple Nested for Loop

Computer Science: A Structured Programming Approach Using C 15


PROGRAM 6-5 A Simple Nested for Loop

Computer Science: A Structured Programming Approach Using C 16


FIGURE 6-15 do…while Statement
Computer Science: A Structured Programming Approach Using C 17
PROGRAM 6-6 Two Simple Loops

Computer Science: A Structured Programming Approach Using C 18


PROGRAM 6-6 Two Simple Loops

Computer Science: A Structured Programming Approach Using C 19


FIGURE 6-16 Pre- and Post-test Loops

Computer Science: A Structured Programming Approach Using C 20


PROGRAM 6-7 Adding a List with the do…while

Computer Science: A Structured Programming Approach Using C 21


PROGRAM 6-7 Adding a List with the do…while

Computer Science: A Structured Programming Approach Using C 22


FIGURE 6-17 Nested Comma Expression

Computer Science: A Structured Programming Approach Using C 23


PROGRAM 6-8 Comparison of while and do…while

Computer Science: A Structured Programming Approach Using C 24


PROGRAM 6-8 Comparison of while and do…while

Computer Science: A Structured Programming Approach Using C 25


FUNCTION

A function is a self contained block of codes or sub programs


with a set of statements that perform some specific task or
coherent task when it is called.
It is something like to hiring a person to do some specific task
like, every six
months servicing a bike and hand over to it.
Any ‘C’ program contain at least one function i.e main().
There are basically two types of function those are
1. Library function
2. User defined function
The user defined functions defined by the user according to
its requirement
System defined function can’t be modified, it can only read
and can be used.
These function are supplied with every C compiler
Source of these library function are pre complied and only
object code get used by
the user by linking to the code by linker
Here in system defined function description:
Function definition : predefined, precompiled, stored in the
library

PGH,UEMK | [Document subtitle]


Function declaration : In header file with or function
prototype.
Function call : By the programmer
User defined function
Syntax:-
Return type name of function (type 1 arg 1, type2 arg2,
type3 arg3)
Return type function name argument list of the above syntax
So when user gets his own function three thing he has to
know, these are.
Function declaration
Function definition
Function call
These three things are represented like
int function(int, int, int); /*function declaration*/
main() /* calling function*/
{
function(arg1,arg2,arg3);
}
int function(type 1 arg 1,type2 arg2,type3, arg3) /*function
definition/*
{
Local variable declaration;

PGH,UEMK | [Document subtitle]


Statement;
Return value;
}
64 *Under revision

Function declaration:-
Function declaration is also known as function prototype. It
inform the compiler about three thing, those are name of the
function, number and type of argument received by the
function and the type of value returned by the function.
While declaring the name of the argument is optional and
the function prototype always terminated by the semicolon.
Function definition:-
Function definition consists of the whole description and
code of the function. It tells about what function is doing
what are its inputs and what are its out put It consists of two
parts function header and function body
Syntax:-
return type function(type 1 arg1, type2 arg2, type3 arg3)
/*function header*/
{
Local variable declaration;
Statement 1;
Statement 2;

PGH,UEMK | [Document subtitle]


Return value
}
The return type denotes the type of the value that function
will return and it is
optional and if it is omitted, it is assumed to be int by default.
The body of the
function is the compound statements or block which consists
of local variable
declaration statement and optional return statement.

The local variable declared inside a function is local to that


function only. It can’t be used anywhere in the program and
its existence is only within this function.
The arguments of the function definition are known as formal
arguments.
Function Call
When the function get called by the calling function then that
is called, function call. The compiler execute these functions
when the semicolon is followed by the
function name.
Example:-
function(arg1,arg2,arg3);
The argument that are used inside the function call are called
actual argument

PGH,UEMK | [Document subtitle]


Ex:-
int S=sum(a, b); //actual arguments
Actual argument
The arguments which are mentioned or used inside the
function call is knows as
actual argument and these are the original values and copy
of these are actually
sent to the called function
It can be written as constant, expression or any function call
like
Function (x);
Function (20, 30);
Function (a*b, c*d);
Function(2,3,sum(a, b));
Formal Arguments
The arguments which are mentioned in function definition
are called formal
arguments or dummy arguments.
66 *Under revision

These arguments are used to just hold the copied of the


values that are sent by the
calling function through the function call.

PGH,UEMK | [Document subtitle]


These arguments are like other local variables which are
created when the function
call starts and destroyed when the function ends.
The basic difference between the formal argument and the
actual argument are
1) The formal argument are declared inside the parenthesis
where as the
local variable declared at the beginning of the function block.
2). The formal argument are automatically initialized when
the copy of actual
arguments are passed while other local variable are assigned
values through the
statements.
Order number and type of actual arguments in the function
call should be match
with the order number and type of the formal arguments.
Return type
It is used to return value to the calling function. It can be
used in two way as
return
Or return(expression);
Ex:- return (a);
return (a*b);
return (a*b+c);

PGH,UEMK | [Document subtitle]


Here the 1st return statement used to terminate the function
without returning any
value
Ex:- /*summation of two values*/
int sum (int a1, int a2);
main()
67 *Under revision

{
int a,b;
printf(“enter two no”);
scanf(“%d%d”,&a,&b);
int S=sum(a,b);
printf(“summation is = %d”,s);
}
int sum(intx1,int y1)
{
int z=x1+y1;
Return z;
}

PGH,UEMK | [Document subtitle]


Advantage of function
By using function large and difficult program can be divided
in to sub programs
and solved. When we want to perform some task repeatedly
or some code is to be
used more than once at different place in the program, then
function avoids this
repeatition or rewritten over and over.
Due to reducing size, modular function it is easy to modify
and test

PGH,UEMK | [Document subtitle]


qwertyuiopasdfghjklzxcvbnmqwerty
uiopasdfghjklzxcvbnmqwertyuiopasd
fghjklzxcvbnmqwertyuiopasdfghjklzx
Function Recursion
cvbnmqwertyuiopasdfghjklzxcvbnmq
Aparajita Mukherjee
wertyuiopasdfghjklzxcvbnmqwertyui
Assistant Professor

UEM, Kolkata

opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyui
opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyui
opasdfghjklzxcvbnmqwertyuiopasdfg
hjklzxcvbnmrtyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmqwert
yuiopasdfghjklzxcvbnmqwertyuiopas
dfghjklzxcvbnmqwertyuiopasdfghjklz
xcvbnmqwertyuiopasdfghjklzxcvbnm
qwertyuiopasdfghjklzxcvbnmqwerty
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
How recursion works?
voidrecurse()
{
........
recurse();
........
}

intmain()
{
........
recurse();
........
}

Therecursioncontinuesuntilsomeconditionismettopreventit.
Topreventinfiniterecursion,if...elsestatement(orsimilarapproach)canbeusedwhereonebranch makes
the recursive call and other doesn't.

Example:SumofNaturalNumbersUsingRecursion
#include<stdio.h>
int sum(int n);

intmain()
{
intnumber,result;

printf("Enterapositiveinteger:"); scanf("%d",
&number);

result = sum(number);

printf("sum=%d",result);
}

intsum(intnum)
{
if (num!=0)
returnnum+sum(num-1);//sum()functioncallsitself
else
returnnum;
}

Output
Enterapositiveinteger:
3
6

Initially,thesum()iscalledfromthemain()functionwithnumberpassedasanargument. Suppose, the

value of num is 3 initially. During next function call, 2 is passed to the sum()
function.Thisprocesscontinuesuntilnumisequalto0.
Whennumisequalto0,theifconditionfailsandtheelsepartisexecutedreturningthesumof integers to the
main()function.
Example:FactorialofaNumberUsing Recursion
#include<stdio.h>
longintmultiplyNumbers(intn);

intmain()
{
int n;
printf("Enterapositiveinteger:"); scanf("%d",
&n);
printf("Factorialof%d=%ld",n,multiplyNumbers(n)); return 0;
}
longintmultiplyNumbers(intn)
{
if(n>=1)
returnn*multiplyNumbers(n-1);
else
return1;
}

Output
Enterapositiveinteger:6
Factorial of 6 = 720

Supposetheuserentered6.
Initially,themultiplyNumbers()iscalledfromthemain()functionwith6passedasan argument.

Then,5ispassedtothemultiplyNumbers()functionfromthesamefunction(recursivecall). In each
recursive call, the value of argument n is decreased by 1.
Whenthevalueofnislessthan1,thereisnorecursive call.

Example:GCDofTwoNumbersusingRecursion
#include<stdio.h>
inthcf(intn1,intn2); int
main()
{
intn1,n2;
printf("Entertwopositiveintegers:"); scanf("%d
%d", &n1, &n2);

printf("G.C.Dof%dand%dis%d.",n1,n2,hcf(n1,n2)); return 0;
}

inthcf(intn1,intn2)
{
if(n2!=0)
returnhcf(n2,n1%n2); else
returnn1;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Output
Entertwopositiveintegers:366 60
G.C.Dof366and60is6.

AdvantagesandDisadvantagesofRecursion
Recursionmakesprogramelegantandcleaner.Allalgorithmscanbedefinedrecursivelywhich makes
it easier to visualize and prove.
Ifthespeedoftheprogramisvitalthen,youshouldavoidusingrecursion.Recursionsusemore memory and
are generally slow. Instead, you can use loop.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


ARRAY
Array is the collection of similar data types or collection of similar entity stored
in
contiguous memory location. Array of character is a string. Each data item of an
array is called an element. And each element is unique and located in separated
memory location. Each of elements of an array share a variable but each
element
having different index no. known as subscript.
An array can be a single dimensional or multi-dimensional and number of
subscripts determines its dimension. And number of subscript is always starts
with
zero. One dimensional array is known as vector and two dimensional arrays are
known as matrix.
 ADVANTAGES: array variable can store more than one value at a time
where
other variable can store one value at a time.
Example:
int arr[100];
int mark[100];
 DECLARATION OF AN ARRAY :
Its syntax is :
Data type array name [size];
int arr[100];
int mark[100];
int a[5]={10,20,30,100,5}
The declaration of an array tells the compiler that, the data type, name of the
array,
size of the array and for each element it occupies memory space. Like for int
data
type, it occupies 2 bytes for each element and for float it occupies 4 byte for
each
element etc. The size of the array operates the number of elements that can be

PGH,UEMK | [Document subtitle]


stored in an array and it may be a int constant or constant int expression.
We can represent individual array as :
int ar[5];
ar[0], ar[1], ar[2], ar[3], ar[4];
Symbolic constant can also be used to specify the size of the array as:
#define SIZE 10;
 INITIALIZATION OF AN ARRAY:
After declaration element of local array has garbage value. If it is global or
static
array then it will be automatically initialize with zero. An explicitly it can be
initialize that
Data type array name [size] = {value1, value2, value3…}
Example:
in ar[5]={20,60,90, 100,120}

Array subscript always start from zero which is known as lower bound and
upper
value is known as upper bound and the last subscript value is one less than the
size
of array. Subscript can be an expression i.e. integer value. It can be any integer,
integer constant, integer variable, integer expression or return value from
functional call that yield integer value.
So if i & j are not variable then the valid subscript are
ar [i*7],ar[i*i],ar[i++],ar[3];
The array elements are standing in continuous memory locations and the
amount of storage required for hold the element depend in its size & type.
Total size in byte for 1D array is:
Total bytes=size of (data type) * size of array.

PGH,UEMK | [Document subtitle]


Example : if an array declared is:
int [20];
Total byte= 2 * 20 =40 byte.
 ACCESSING OF ARRAY ELEMENT:
/*Write a program to input values into an array and display them*/
#include<stdio.h>
int main()
{
int arr[5],i;
for(i=0;i<5;i++)
{
printf(“enter a value for arr[%d] \n”,i);
scanf(“%d”,&arr[i]);
}
printf(“the array elements are: \n”);
for (i=0;i<5;i++)
{
printf(“%d\t”,arr[i]);
}
return 0;
}
OUTPUT:
Enter a value for arr[0] = 12
Enter a value for arr[1] =45
Enter a value for arr[2] =59
Enter a value for arr[3] =98
Enter a value for arr[4] =21

PGH,UEMK | [Document subtitle]


The array elements are 12 45 59 98 21
Example: From the above example value stored in an array are and occupy its
memory addresses 2000, 2002, 2004, 2006, 2008 respectively.
a[0]=12, a[1]=45, a[2]=59, a[3]=98, a[4]=21
ar[0] ar[1] ar[2] ar[3] ar[4]
12 45 59 98 21
2000 2002 2004 2006 2008
Example 2:

/* Write a program to add 10 array elements */


#include<stdio.h>
void main()
{
int i ;
int arr [10];
int sum=o;
for (i=0; i<=9; i++)
{
printf (“enter the %d element \n”, i+1);
scanf (“%d”, &arr[i]);
}
for (i=0; i<=9; i++)
{
sum = sum + a[i];
}
printf (“the sum of 10 array elements is %d”, sum);
}

PGH,UEMK | [Document subtitle]


OUTPUT:
Enter a value for arr[0] =5
Enter a value for arr[1] =10
Enter a value for arr[2] =15
Enter a value for arr[3] =20
Enter a value for arr[4] =25
Enter a value for arr[5] =30
Enter a value for arr[6] =35
Enter a value for arr[7] =40
Enter a value for arr[8] =45
Enter a value for arr[9] =50
Sum = 275
while initializing a single dimensional array, it is optional to specify the size of
array. If the size is omitted during initialization then the compiler assumes the
size
of array equal to the number of initializers.
For example:-
int marks[]={99,78,50,45,67,89};
If during the initialization of the number the initializers is less then size of array,
then all the remaining elements of array are assigned value zero .
For example:-
int marks[5]={99,78};
Here the size of the array is 5 while there are only two initializers so After this
initialization, the value of the rest elements are automatically occupied by zeros
such as
Marks[0]=99 , Marks[1]=78 , Marks[2]=0, Marks[3]=0, Marks[4]=0
Again if we initialize an array like
int array[100]={0};

PGH,UEMK | [Document subtitle]


Then the all the element of the array will be initialized to zero. If the number of
initializers is more than the size given in brackets then the compiler will show
an
error.

For example:-
int arr[5]={1,2,3,4,5,6,7,8};//error
we cannot copy all the elements of an array to another array by simply assigning
it
to the other array like, by initializing or declaring as
int a[5] ={1,2,3,4,5};
int b[5];
b=a;//not valid
(note:-here we will have to copy all the elements of array one by one, using for
loop.)
 Single dimensional arrays and functions
/*program to pass array elements to a function*/
#include<stdio.h>
void main()
{
int arr[10],i;
printf(“enter the array elements\n”);
for(i=0;i<10;i++)
{
scanf(“%d”,&arr[i]);
check(arr[i]);
}
}

PGH,UEMK | [Document subtitle]


void check(int num)
{
if(num%2=0)
{
printf(”%d is even \n”,num);
}
else
{
printf(”%d is odd \n”,num);
}
}

Two dimensional arrays


Two dimensional array is known as matrix. The array declaration in both the
array
i.e.in single dimensional array single subscript is used and in two dimensional
array two subscripts are is used.
Its syntax is
Data-type array name[row][column];
Or we can say 2-d array is a collection of 1-D array placed one below the other.

Total no. of elements in 2-D array is calculated as row*column


Example:-
int a[2][3];
Total no of elements=row*column is 2*3 =6
It means the matrix consist of 2 rows and 3 columns
For example:-

PGH,UEMK | [Document subtitle]


20 2 7
8 3 15
Positions of 2-D array elements in an array are as below
00 01 02
10 11 12
a [0][0] a [0][0] a [0][0] a [0][0] a [0][0] a [0][0]
20 2 7 8 3 15
2000 2002 2004 2006 2008
Accessing 2-d array /processing 2-d arrays
For processing 2-d array, we use two nested for loops. The outer for loop
corresponds to the row and the inner for loop corresponds to the column.
For example
int a[4][5];
for reading value:-
53 *Under revision

for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf(“%d”,&a[i][j]);
}
}
For displaying value:-
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)

PGH,UEMK | [Document subtitle]


{
printf(“%d”,a[i][j]);
}
}
Initialization of 2-d array:
2-D array can be initialized in a way similar to that of 1-D array. for example:-
int mat[4][3]={11,12,13,14,15,16,17,18,19,20,21,22};
These values are assigned to the elements row wise, so the values of
elements after this initialization are
Mat[0][0]=11, Mat[1][0]=14, Mat[2][0]=17 Mat[3][0]=20
Mat[0][1]=12, Mat[1][1]=15, Mat[2][1]=18 Mat[3][1]=21
Mat[0][2]=13, Mat[1][2]=16, Mat[2][2]=19 Mat[3][2]=22
54 *Under revision

While initializing we can group the elements row wise using inner braces.
for example:-
int mat[4][3]={{11,12,13},{14,15,16},{17,18,19},{20,21,22}};
And while initializing , it is necessary to mention the 2nd dimension where 1st
dimension is optional.
int mat[][3];
int mat[2][3];
int mat[][];
int mat[2][]; invalid
If we initialize an array as
int mat[4][3]={{11},{12,13},{14,15,16},{17}};
Then the compiler will assume its all rest value as 0,which are not defined.
Mat[0][0]=11, Mat[1][0]=12, Mat[2][0]=14, Mat[3][0]=17

PGH,UEMK | [Document subtitle]


Mat[0][1]=0, Mat[1][1]=13, Mat[2][1]=15 Mat[3][1]=0
Mat[0][2]=0, Mat[1][2]=0, Mat[2][2]=16, Mat[3][2]=0
In memory map whether it is 1-D or 2-D, elements are stored in one
contiguous manner.
We can also give the size of the 2-D array by using symbolic constant
Such as
#define ROW 2;
55 *Under revision

#define COLUMN 3;
int mat[ROW][COLUMN];

PGH,UEMK | [Document subtitle]


Pointer
Aparajita Mukherjee
Assistant Professor
UEM, Kolkata
Recap:AnatomyofaTypicalCProgram

#preprocessordirectives

declarations
variables
functions

intmain (void){
declarations;
statements;
return value;
}
Aparajita Mukherjee Assistant Professor UEM, Kolkata
YourFirstCProgram
hello.c

/*WelcometoBBM101*/ #include

<stdio.h>

intmain(void)
{
printf(“Helloworld!\n”);
return 0;
}

Helloworld!

Aparajita Mukherjee Assistant Professor UEM, Kolkata


YourFirstCProgram
hello.c

/*WelcometoBBM101*/ #include /*comments*/

<stdio.h> global declarations


#includeexternalfiles
intmain(void)
{
printf(“Helloworld!\n”); mainfunction
return 0;
}

Helloworld!

Aparajita Mukherjee Assistant Professor UEM, Kolkata


YourFirstCProgram
hello.c Textsurroundedby/*and*/
isignoredbycomputer
/*WelcometoBBM101*/ #include /*comments*/
<stdio.h> global declarations
#includeexternalfiles
intmain(void)
{
printf(“Helloworld!\n”); mainfunction
return 0;
}

Helloworld!

Aparajita Mukherjee Assistant Professor UEM, Kolkata


YourFirstCProgram
hello.c

/*WelcometoBBM101*/ #include /*comments*/

<stdio.h> global declarations


#includeexternalfiles
intmain(void) “stdio.h”allowsstandard
{ input/outputoperations
printf(“Helloworld!\n”); mainfunction
return 0;
}

Helloworld!

Aparajita Mukherjee Assistant Professor UEM, Kolkata


YourFirstCProgram
hello.c

/*WelcometoBBM101*/ #include /*comments*/


<stdio.h> global declarations
#includeexternalfiles
intmain(void)
{
printf(“Helloworld!\n”); mainfunction
return 0; Cprogramscontainoneor
} morefunctions,exactlyone
of which must be main

Helloworld!

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Themain(void)ofhello.c
Arguments
Program
Returnvalue intmain(void)

intmain(void)
{
printf(“Helloworld!\n”);
return 0;
}

return “0” to OS:


• Noarguments. “everythingisOK”
• Returnsanintegervariable.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Slidecredit:BertHuang

Aparajita Mukherjee Assistant Professor UEM, Kolkata


TheProgrammingProcess

Create/Edit
Compile Execute
Program

“Thecycleendsoncetheprogrammerissatisfiedwiththe
program, e.g., performance and correctness-wise.”

Aparajita Mukherjee Assistant Professor UEM, Kolkata


C Statements
• One-linecommands
• Alwaysendinsemicolon;
• Examples:
– callfunction:printf(“hello”);/*fromstdio
*/
– declarevariable:intx;
– assignvariablevalue:x=123+456;

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Identifiers
• Asequenceofletters,digits,andtheunderscorecharacter‘_’
satisfying
– identifier= c{c|d}*
– withc={‘A’,…,‘Z’,‘a’,…,‘z’,‘_’},d={0,…,9},andasterisk“*”
means “0 or more”

• Case-sensitive
– e.g.,firstNameandfirstnamearetwodifferentidentifiers.

• Identifiersareusedfor
– Variablenames
– Functionnames
– Macronames

Aparajita Mukherjee Assistant Professor UEM, Kolkata


IdentifierExamples
• Valididentifiers
– X
– a1
– _xyz_33
– integer1
– Double

■• Invalididentifiers
Invalididentifiers
 –xyz.1
xyz.1
 –gx^2
gx^2
 –114West
114West
 –int
intThisisakeyword
 –pi*r*r
pi*r*r

Aparajita Mukherjee Assistant Professor UEM, Kolkata


BasicDataTypes
• Integer(int)
• Character(char)
• FloatingPoint(float)
• DoublePrecisionFloatingPoint(double)

• DataTypeModifiers
– signed/unsigned
– short/long

Aparajita Mukherjee Assistant Professor UEM, Kolkata


This week
• Pointers
– PointerVariableDeclarationsandInitialization
– PointerOperators
– Pointerstovoid
– CallingFunctionsbyReference
– Passingparametersbyreference
– sizeoffunction
– DynamicMemoryManagement
– PointerArithmetic
– PointersandArrays
– PointerstoFunctions

Aparajita Mukherjee Assistant Professor UEM, Kolkata


VariablesRevisited
• Whatactuallyhappenswhenwedeclarevariables?
char a;

• Creservesabyteinmemorytostorea.

• Whereisthatmemory?Atanaddress.

• Underthehood,Chasbeenkeepingtrackofvariables and
their addresses.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Pointers
• Wecanworkwithmemoryaddressestoo.Wecan use
variables called pointers.

• Apointerisavariablethatcontainstheaddressofa
variable.

• Pointersprovideapowerfulandflexiblemethodfor
manipulating data in your programs; but they are
difficult to master.

–Closerelationshipwitharraysandstrings
Aparajita Mukherjee Assistant Professor UEM, Kolkata
BenefitsofPointers
• Pointersallowyoutoreferencealargedatastructureina
compact way.
• Pointersfacilitatesharingdatabetweendifferentpartsof a
program.
– Call-by-Reference
• Dynamicmemoryallocation:Pointersmakeitpossibleto
reserve new memory during program execution.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerVariableDeclarationsand
Initialization
• Pointervariables
– Containmemoryaddressesastheirvalues
– Normalvariablescontainaspecificvalue(directreference)
count
7

– Pointerscontainaddressofavariablethathasaspecific
value (indirect reference)
– Indirection–referencingapointervalue
countPtr count
7

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerVariableDeclarationsand
Initialization
• Pointerdeclarations
– Thesyntaxforpointerdeclarationisasfollows:
type*identifier;
e.g.int *myPtr;

– Declaresapointertoanint(pointeroftypeint*)
– Multiplepointersrequireusinga*beforeeachvariable
declaration
int*myPtr1,*myPtr2;
– Candeclarepointerstoanydatatype
– Initializepointersto0,NULL,oranaddress
• 0orNULL–pointstonothing(NULLpreferred)

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerOperators
• &(addressoperator)
– Returnstheaddressofoperand
inty=5;
int*yPtr;
yPtr=&y; //yPtrgetsaddressofy
– yPtr“pointsto”y
y yptr y
5 500000 600000 600000 5
yPtr

Addressofy
is value of
yptr

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerOperators
• *(indirection/dereferencingoperator)
- Returnsasynonym/aliasofwhatitsoperandpointsto
- *yptrreturnsy(becauseyptrpointstoy)
- *canbeusedforassignment
• Returnsaliastoanobject
*yptr=7;//changesyto7
- Dereferencedpointer(operandof*)mustbeanlvalue
(noconstants)

• *and&areinverses
- Theycanceleachotherout

Aparajita Mukherjee Assistant Professor UEM, Kolkata


int rate;
int*p_rate;

rate = 500;
p_rate=&rate;

1000 1004 1008 1012

Memory 1008 500

p_rate rate

/*Printthevalues*/
printf(“rate = %d\n”, rate); /* direct access */
printf(“rate=%d\n”,*p_rate);/*indirectaccess*/

Aparajita Mukherjee Assistant Professor UEM, Kolkata


/*Usingthe&and*operators*/ #include

<stdio.h> Theaddressofaisthevalue of
aPtr.
intmain()
{
inta; /*aisaninteger*/
The * operator returns an
int*aPtr; /*aPtrisapointertoaninteger*/
alias to what its operand
a=7; pointsto.aPtrpointstoa, so
aPtr=&a; /*aPtrsettoaddressofa*/ *aPtr returns a.

printf("Theaddressofais%p\nThevalueofaPtris%p",&a,aPtr);

printf("\n\nThevalueofais%d\nThevalueof*aPtris%d",a,*aPtr);

Noticehow *and&
printf("\n\nShowingthat*and&areinversesof areinverses
eachother.\n&*aPtr=%p\n*&aPtr=%p\n",&*aPtr,*&aPtr);

return0;
}
ProgramOutput
The address of a is 0012FF88
ThevalueofaPtris0012FF88

Thevalueofais7
Thevalueof*aPtris7
Showing that * and & are inverses of each other.
&*aPtr = 0012FF88
*&aPtr=0012FF88

Aparajita Mukherjee Assistant Professor UEM, Kolkata


OperatorPrecedences–Revisited
Operators Associativity Type
() [] lefttoright highest
+ − ++ −− ! * & (type) righttoleft unary
* / % lefttoright multiplicative
+ − lefttoright additive
< <= > >= lefttoright relational
== != lefttoright equality
&& lefttoright logical and
|| lefttoright logical or
?: righttoleft conditional
= += −= *= /= %= righttoleft assignment
, lefttoright comma

Aparajita Mukherjee Assistant Professor UEM, Kolkata


AddressingandDereferencing
inta,b,*p; a

= b = 7;
p=&a;
printf(“*p=%d\n”,*p);

*p=3;
printf(“a=%d\n”,a);
ProgramOutput
p=&b; *p= 7
*p=2**p –a; a=3
printf(“b= %d\n”, b); b=11

Aparajita Mukherjee Assistant Professor UEM, Kolkata


AddressingandDereferencing
floatx,y,*p; x

= 5;
y=7;
p=&x;
y=*p;

Thus,
y = *p;
y=*&x; y
= x;
Allequivalent

Aparajita Mukherjee Assistant Professor UEM, Kolkata


AddressingandDereferencing

Declarationsandinitializations
int k=3, j=5, *p = &k, *q = &j, *r;
double x;
Expression EquivalentExpression Value
p == &k p == (&k) 1
p = k + 7 p = (k + 7) illegal
* * &p * ( * (&p)) 3
r = &x r = (&x) illegal
7 * * p/ *q +7 (( (7 * (*p) )) / (*q)) + 7 11
* (r = &j) *= *p ( * (r = (&j))) *= (*p) 15

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Pointerstovoid
• void *identifier;
• InC,voidrepresentstheabsenceoftype.
• voidpointersarepointersthatpointtoavaluethat has
no specific type.
• Thisallowsvoidpointerstopointtoanydatatype.
• Thedatapointedbyvoidpointerscannotbedirectly
dereferenced.
• Wehavetouseexplicittypecastingbeforedereferencing it.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Pointerstovoid
int x = 4;
void*q=&x;
int *p = q;
int i = *p;
intj=*(int*)q;

Declarations
int*p;
float*q;
void*v;
Legalassignments Illegalassignments
p = 0; p= 1;
p = (int*)1; v= 1;
p = v= q; p= q;
p = (int*)q;
Aparajita Mukherjee Assistant Professor UEM, Kolkata
CallingFunctionsbyReference
• Callbyreferencewithpointerarguments
– Passaddressofargumentusing&operator
– Allowsyoutochangeactuallocationinmemory
– Arraysarenotpassedwith&becausethearrayname is
already a pointer
• * operator
– Usedasalias/nicknameforvariableinsideoffunction
voiddouble_it(int*number)
{
*number=2*(*number);
}
– *numberusedasnicknameforthevariablepassed

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Passingparametersbyreference
voidSetToZero(intvar)
{
var=0;
}
• Youwouldmakethefollowingcall:
SetToZero(x);

• Thisfunctionhasnoeffectwhatever.Instead,passapointer:
voidSetToZero(int*ip)
{
*ip=0;
}
Youwouldmakethefollowingcall:
SetToZero(&x);

Thisisreferredtoascall-by-reference.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


/*Anexampleusingcall-by-reference*/ #include
<stdio.h>

voidchange_arg(int*y); int

main (void)
{
intx=5;

change_arg(&x);
printf(“%d\n”,x);
return 0;
}

voidchange_arg(int*y)
{
*y=*y+2;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


/* Cube a variable using call-by-reference
with a pointer argument */
Noticethatthefunctionprototypetakesa pointer
to an integer (int *).
#include<stdio.h>

Noticehow theaddressof numberis


voidcubeByReference(int*); /*prototype*/
given-cubeByReferenceexpectsa
pointer (an address of a variable).
intmain()
{
intnumber=5;

printf( "The original value of number is %d", number );


cubeByReference( &number );
printf("\nThenewvalueofnumberis%d\n",number);

InsidecubeByReference,*nPtris
return0;
used(*nPtrisnumber).
}

voidcubeByReference(int*nPtr)
{
*nPtr=*nPtr**nPtr**nPtr;/*cubenumberinmain*/
}
ProgramOutput
Theoriginalvalueofnumberis5 The
new value of number is 125
Aparajita Mukherjee Assistant Professor UEM, Kolkata
/*Cubeavariableusingcallbyvalue*/ #include
<stdio.h>

intCubeByValue(intn); int

main(void)
{
int number = 5;
printf(“Theoriginalvalueofnumberis%d\n”,number); number =
CubeByValue(number);
printf(“Thenewvalueofnumberis%d\n”,number); return
0;
}

int CubeByValue (int n)


{
return (n*n*n);
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


/*Swappingarguments(incorrectversion)*/
#include <stdio.h>

voidswap(intp, int q);


int main (void)
{
int a = 3;
intb=7;
printf(“%d %d\n”, a,b);
swap(a,b);
printf(“%d %d\n”, a, b);
return 0;
}

void swap (int p, int q)


{
int tmp;

tmp = p;
p = q;
q = tmp;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


/*Swappingarguments(correctversion)*/
#include <stdio.h>

voidswap(int*p,int*q); int
main (void) p q
{
inta=3;
int b = 7; 3 7
printf(“%d%d\n”,a,b);
swap(&a, &b);
printf(“%d%d\n”,a,b); return
0; q
p
}

void swap (int *p, int *q)


7 3
{
int tmp;

tmp = *p;
*p = *q;
*q = tmp;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


/*
* Thisfunctionseparatesanumberintothreeparts:asign(+,-,
* orblank),awholenumbermagnitudeandafractionpart.
* Preconditions:numisdefined;signp,wholepandfracpcontain
* addressesofmemorycellswhereresultsaretobe stored
*Postconditions: functionresultsarestoredincellspointed to by
* signp,wholep,andfracp
*/

voidseparate(doublenum,char*signp,int*wholep,double*fracp)
{
doublemagnitude;

if(num<0)
*signp=‘-‘; else
if (num == 0)
*signp=‘‘;
else
*signp=‘+’;

magnitude=fabs(num);
*wholep=floor(magnitude);
*fracp=magnitude-*wholep;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


ProgramOutput
Enteravaluetoanalyze:13.3 Parts
of 13.3000
sign:+
wholenumbermagnitude:13
int main() fractional part : 0.3000
{
doublevalue;
Enteravaluetoanalyze:-24.3
char sn; Parts of -24.3000
int whl; sign:-
doublefr; wholenumbermagnitude:24
fractional part : 0.3000

/* Gets data */
printf(“Enteravaluetoanalyze:”);
scanf(“%lf”, &value);

/*Separatesdatavalueinthreeparts*/
separate(value, &sn, &whl, &fr);

/* Prints results */
printf(“Partsof%.4f\nsign:%c\n”,value,sn);
printf(“whole number magnitude: %d\n”, whl);
printf(“fractional part : %.4f\n”, fr);

return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


BubbleSortUsingCall-by-reference
• Implementbubblesortusingpointers
– Swaptwoelements
– swapfunctionmustreceiveaddress(using&)ofarray
elements
• Arrayelementshavecall-by-valuedefault
– Usingpointersandthe*operator,swapcanswitcharray
elements
• Psuedocode
Initializearray
printdatainoriginalorder Call
function bubblesort
printsortedarray
Define bubblesort

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*Thisprogramputsvaluesintoanarray,sortsthevaluesinto ascending
order, and prints the resulting array. */

#include<stdio.h>#def
ine SIZE 10

void bubbleSort( int *array, const int size );


voidswap(int*element1Ptr,int*element2Ptr); int
main() {
/*initializearraya */
inta[SIZE]={2,6,4,8,10,12,89,68,45,37};
inti;
printf("Dataitemsinoriginalorder\n");

for(i=0;i<SIZE;i++)
printf("%4d",a[i]);

bubbleSort( a, SIZE ); /* sort the array */


printf("\nDataitemsinascendingorder\n");

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*loopthrougharraya*/
for(i=0;i<SIZE;i++)
printf("%4d",a[i]);
printf("\n");
return0;/*indicatessuccessfultermination*/
}/*endmain*/

/*sortanarrayofintegersusingbubblesortalgorithm*/ void
bubbleSort( int *array, const int size )
{
intpass,j;
for(pass=0;pass<size-1;pass++) for ( j = 0;
j < size - 1; j++ )
/*swapadjacentelementsiftheyareoutoforder*/ if (
array[ j ] > array[ j + 1 ] )
swap(&array[j],&array[j+1]);
}/*endfunctionbubbleSort */

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*swapvaluesatmemorylocationstowhichelement1Ptrand element2Ptr
point */
voidswap(int*element1Ptr,int*element2Ptr)
{
inthold=*element1Ptr;
*element1Ptr= *element2Ptr;
*element2Ptr= hold;
} /*endfunction swap*/

ProgramOutput
Data items in originalorder
2 6 4 810128968 45 37
Data items in ascendingorder
2 4 6 810123745 68 89

Aparajita Mukherjee Assistant Professor UEM, Kolkata


sizeoffunction
• sizeof
– Returnssizeofoperandinbytes
– Forarrays:sizeof1element*numberofelements
– ifsizeof(int)equals4bytes,then
intmyArray[10];
printf("%d",sizeof(myArray));
• willprint40
• sizeofcanbeusedwith
– Variablenames
– Typename
– Constantvalues

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*sizeofoperatorwhenusedonanarraynamereturnsthenumberof bytes in the
array. */
#include<stdio.h>
size_tgetSize(float*ptr);/*prototype*/

intmain(){
floatarray[20];/*createarray */

printf("Thenumberofbytesinthearrayis %d"
"\nThenumberofbytesreturnedbygetSizeis%d\n", sizeof(
array ), getSize( array ) );

return0;
}

size_tgetSize(float*ptr){
return sizeof( ptr );
}

ProgramOutput
The number of bytes in the array is 80
The number of bytes returned by getSize is 4
Aparajita Mukherjee Assistant Professor UEM, Kolkata
Example
/*Demonstratingthesizeofoperator*/
#include <stdio.h>

intmain()
{
charc; /*definec*/
shorts; /*defines*/
inti; /*definei*/
longl; /*definel*/
floatf; /*definef*/
double d; /* define d */
long double ld; /*defineld*/
intarray[20];/*initializearray */
int*ptr=array;/*createpointertoarray */

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
printf( " sizeof c = %d\tsizeof(char) =%d"
"\n sizeof s = %d\tsizeof(short) =%d"
"\n sizeof i = %d\tsizeof(int)= %d"
"\n sizeof l = %d\tsizeof(long)=%d"
"\n sizeof f = %d\tsizeof(float)=%d"
"\n sizeof d = %d\tsizeof(double)=%d"
"\n sizeofld = %d\tsizeof(longdouble)= %d"
"\n sizeofarray = %d"
"\n sizeofptr = %d\n",
sizeof c, sizeof( char ), sizeof s,
sizeof(short),sizeofi,sizeof(int), sizeof
l, sizeof( long ), sizeof f,
sizeof(float),sizeofd,sizeof(double), sizeof
ld, sizeof( long double ),
sizeofarray,sizeofptr);

return0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
ProgramOutput
sizeof c = 1 sizeof(char)= 1
sizeof s = 2 sizeof(short) = 2
sizeof i = 4 sizeof(int) = 4
sizeof l = 4 sizeof(long) = 4
sizeof f = 4 sizeof(float) = 4
sizeof d = 8 sizeof(double)=8
sizeof ld = 8 sizeof(longdouble)=8
sizeof array = 80
sizeofptr=4

Aparajita Mukherjee Assistant Professor UEM, Kolkata


DynamicMemoryManagement
• Staticmemoryallocation:spacefortheobjectis
provided in the binary at compile-time
• Dynamicmemoryallocation:blocksofmemoryof
arbitrary size can be requested at run-time

• Thefourdynamicmemorymanagementfunctionsare
malloc, calloc,realloc,andfree.
• Thesefunctionsareincludedintheheaderfile
<stdlib.h>.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


DynamicMemoryManagement
• void*malloc(size_tsize);

• allocatesstorageforanobjectwhosesizeisspecifiedby
size:
– Itreturnsapointertotheallocatedstorage,
– NULLifitisnotpossibletoallocatethestoragerequested.
– Theallocatedstorageisnotinitializedinanyway.

• e.g. float*fp,fa[10];
fp = (float *) malloc(sizeof(fa));
allocatesthestoragetoholdanarrayof10floating-point
elements, and assigns the pointer to this storage to fp.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


DynamicMemoryManagement
• void*calloc(size_tnobj,size_tsize);

• allocatesthestorageforanarrayofnobjobjects,eachofsize
size.
– Itreturnsapointertotheallocatedstorage,
– NULLifitisnotpossibletoallocatethestoragerequested.
– Theallocatedstorageisinitializedtozeros.

• e.g.double*dp,da[10];
dp=(double *) calloc(10,sizeof(double));
allocatesthestoragetoholdanarrayof10doublevalues, and
assigns the pointer to this storage to dp.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


DynamicMemoryManagement
• void *realloc(void *p, size_t size);

• changesthesizeoftheobjectpointedtobyptosize.
– Itreturnsapointertothenewstorage,
– NULLifitisnotpossibletoresizetheobject,inwhichcase the
object (*p) remains unchanged.
– The new size may be larger (the original contents are
preservedandtheremainingspaceisunitialized)orsmaller
(the contents are unchanged upto the new size) than the
original size.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


DynamicMemoryManagement
• e.g. char *cp;
cp=(char*)malloc(sizeof(“computer”));
strcpy(cp, “computer”);
cppointstoanarrayof9characterscontainingthenull-terminated
stringcomputer.

cp=(char*)realloc(cp,sizeof(“compute”));
discardsthetrailing‘\0’andmakescppointtoanarrayif8characterscontaining the
characters in computer

cp=(char*)realloc(cp,sizeof(“computerization”));
cp points to an array of 16 characters, the first 9 of which contain
thenull-terminatedstringcomputerandtheremaining7areuninitialized.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


DynamicMemoryManagement
• void *free(void *p);

• deallocatesthestoragepointedtobyp,wherepisapointer to
the storage previously allocated by malloc, calloc, or
realloc.

• e.g.free(fp);
free(dp);
free(cp);

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerArithmetic
• Arithmeticoperationscanbeperformedonpointers
– Increment/decrementpointer(++or--)
– Addanintegertoapointer(+or+=,-or-=)
– Pointersmaybesubtractedfromeachother
– Operationsmeaninglessunlessperformedonanarray

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerExpressionsandPointer
Arithmetic
• 5elementintarrayonmachinewith4byteints
– vPtrpointstofirstelementv[0]
• i.e.location3000(vPtr=3000)
– vPtr+=2;setsvPtrto3008
• vPtrpointsto v[2](incrementedby2),butthemachinehas 4
byte ints, so it points to address 3008
location
3000 3004 3008 3012 3016

v[0] v[1] v[2] v[3] v[4]

pointervariablevPtr

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerExpressionsandPointer
Arithmetic
• Subtractingpointers
– Returnsnumberofelementsfromonetotheother.If
vPtr=&v[0];
vPtr2=&v[2];//vPtr2=vPtr+2;
– vPtr2-vPtrwouldproduce2
• Pointercomparison(<,==,>)
– Seewhichpointerpointstothehighernumberedarray
element
– Also,seeifapointerpointsto0

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerExpressionsandPointer
Arithmetic
• Pointersofthesametypecanbeassignedtoeach
other
– Ifnotthesametype,acastoperatormustbe used
– Exception:pointertovoid(typevoid*)
• Genericpointer,representsanytype
• Nocastingneededtoconvertapointertovoid
pointer
• voidpointerscannotbedereferenced

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Pointers
300
int a=10; var.name address
int *b; a 1200
1200 8
int **c; b 1300
int d[3]={1,2,3}; c 1400 1300 1500
d 1500
b=&a; 1400 1300
*b=5; 1500 9
c=&b; 1504 2
*(*c)=8; 1508 15
b=d;
*(*c)=9;
*(*c+2)=15;

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
intSumIntegerArray(int*ip,intn)
{
int i,sum;
sum =0;
for (i=0;i<n; i++) {
sum+= *ip++;
}
returnsum;
}
Assume
intsum,list[5];
aredeclaredinthemainfunction.Wecanmakethefollowingfunctioncall:
sum=SumIntegerArray(list,5);

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
#include<stdio.h>
#include<stdlib.h>

intmain(void){ int
*array, *p;
inti,no_elements;
printf("Enternumberofelements:"); scanf("%d",&no_elements);

printf("Entertheelements:");
array=(int*)malloc(no_elements*sizeof(int));
for(p=array,i=0; i<no_elements; i++, p++)
scanf("%d",p);

printf("Elements:");
for(p=array,i=0;i<no_elements;i++,p++)
printf("%d ",*p);
printf("\n");

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
array=(int*)realloc(array,(no_elements+2)*sizeof(int));

printf("Enter two new elements: ");


for(p=array,i=0;i<no_elements;i++,p++); for(;
i<no_elements+2; i++, p++)
scanf("%d",p);

printf("Elements:");
for(p=array,i=0;i<no_elements+2;i++,p++)
printf("%d ",*p);
printf("\n");

free(array);
return 0; ProgramOutput
} Enternumberofelements:4
Entertheelements:2345
Elements:2345
Entertwonewelements:67
Elements:234567

Aparajita Mukherjee Assistant Professor UEM, Kolkata


UsingtheconstQualifierwithPointers**
• constqualifier
– Variablecannotbechanged
– Useconstiffunctiondoesnotneedtochangeavariable
– Attemptingtochangeaconstvariableproducesanerror
• constpointers
– Pointtoaconstantmemorylocation
– Mustbeinitializedwhendefined
– int*constmyPtr=&x;
• Typeint*const–constantpointertoanint
– constint*myPtr=&x;
• Regularpointertoaconstint
– constint*constPtr=&x;
• constpointertoaconstint
• xcanbechanged,butnot*Ptr

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*Convertinglowercaseletterstouppercaselettersusinganon-constant pointer to
non-constant data */

#include<stdio.h>#inc
lude<ctype.h>

voidconvertToUppercase(char*sPtr); int

main()
{
charstring[]="charactersand$32.98";/*initializechararray*/

printf("Thestringbeforeconversionis:%s",string);
convertToUppercase( string );
printf("\nThestringafterconversionis:%s\n",string); return 0;

/* indicates successful termination */

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*convertstringtouppercaseletters*/ void
convertToUppercase( char *sPtr )
{
while(*sPtr!='\0'){
if(islower(*sPtr)){ /*ifcharacterislowercase,*/
*sPtr=toupper(*sPtr);/*converttouppercase */
}
++sPtr;/*movesPtrtothenextcharacter */
}
}/*endfunctionconvertToUppercase*/

ProgramOutput
Thestringbeforeconversionis:charactersand$32.98 The
string after conversion is: CHARACTERS AND $32.98

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*Printingastringonecharacteratatimeusinganon-constantpointer to constant
data */

#include<stdio.h>

voidprintCharacters(constchar*sPtr); int

main()
{
/*initializechararray*/
charstring[]="printcharactersofastring";

printf("Thestringis:\n");
printCharacters( string );
printf( "\n" );

return0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*sPtrcannotmodifythecharactertowhichitpoints,i.e., sPtr is a
"read-only" pointer */

voidprintCharacters(constchar*sPtr)
{
/*loopthroughentirestring*/ for (
; *sPtr != '\0'; sPtr++ )
printf("%c",*sPtr);
}/*endfunctionprintCharacters */

ProgramOutput
The string is:
print characters of a string

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*Attemptingtomodifydatathroughanon-constantpointertoconstantdata.*/ #include
<stdio.h>

voidf(constint*xPtr);/*prototype */

intmain()
{
inty; /*definey*/
f( &y ); /* f attempts illegal modification */
return 0; /*indicatessuccessfultermination*/
}/*endmain*/

/*xPtrcannotbeusedtomodifythevalueofthevariabletowhichit points */
voidf(constint*xPtr)
{
*xPtr=100;/*error:cannotmodifyaconstobject */
}/*endfunctionf*/

Syntax error: l-value specifies const object

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*Attemptingtomodifyaconstantpointertonon-constantdata*/ #include
<stdio.h>

intmain()
{
intx;/*definex*/
inty;/*definey*/
Changing*ptrisallowed–xis
/*ptrisaconstantpointertoa not aconstant.
nintegerthatcanbemodifi ed
throughptr,butptralwayspointstothesamememorylocation*/ int *
const ptr = &x;
Changingptrisanerror–ptr
*ptr=7;/*allowed:*ptrisnotconst*/ isaconstantpointer.
ptr=&y;/*error:ptrisconst;cannotassignnewaddress */

return0;
}/*endmain*/

Syntax error: l-value specifies const object


Aparajita Mukherjee Assistant Professor UEM, Kolkata
Example
/*Attemptingtomodifyaconstantpointertoconstantdata.*/ #include
<stdio.h>

intmain() {
intx= 5;/*initializex*/
int y; /*definey*/

/*ptr isaconstantpointertoaconstantinteger.ptralwayspoints to
the samelocation;theintegeratthatlocationcannotbemodified */
constint*constptr=&x;
printf( "%d\n", *ptr );

*ptr= 7;/*error:*ptrisconst;cannot assignnewvalue */


ptr= &y;/*error:ptrisconst;cannot assignnewaddress*/

return0;/*indicatessuccessfultermination*/
}/*endmain*/

Syntax error: assignment of read-only location


syntaxerror:assignmentofread-onlyvariable‘ptr’

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointersandArrays
• Arraysareimplementedaspointers.
• Consider:
doublelist[3];
&list[1]:istheaddressofthesecondelement
&list[i]:theaddressof list[i]whichis
calculated by the formula
baseaddress ofthearray+i* 8

Aparajita Mukherjee Assistant Professor UEM, Kolkata


TheRelationshipbetweenPointersand
Arrays
• Arraysandpointersarecloselyrelated
– Arraynameislikeaconstantpointer
– Pointerscandoarraysubscriptingoperations
• Declareanarrayb[5]andapointerbPtr
– Tosetthemequaltooneanotheruse:
bPtr=b;
• Thearrayname(b)isactuallytheaddressoffirstelementof the
array b[5]
bPtr=&b[0]
• ExplicitlyassignsbPtrtoaddressoffirstelementofb

Aparajita Mukherjee Assistant Professor UEM, Kolkata


TheRelationshipbetweenPointersand
Arrays
– Elementb[3]
• Canbe accessedby*(bPtr+3)
– Wherenistheoffset.Calledpointer/offsetnotation
• Canbe accessed by bptr[3]
– Calledpointer/subscriptnotation
– bPtr[3]sameasb[3]
• Canbeaccessedbyperformingpointerarithmeticonthearray
itself
*(b+3)

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example(cont.)
/*Usingsubscriptingandpointernotationswitharrays*/
#include <stdio.h>
intmain(void)
{
inti,offset,b[4]={10,20,30,40}; int
*bPtr = b;

/*Arrayisprintedwitharraysubscriptnotation*/ for (i=0;

i < 4; i++)
printf(“b[%d]=%d\n”,i,b[i]);

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example(cont.)
/*Pointer/offsetnotationwherethepointeris the
array name */

for(offset=0;offset<4;offset++)
printf(“*(b+%d)=%d\n”,offset,*(b+offset));

/*Pointersubscriptnotation*/ for
(i=0; i < 4; i++)
printf(“bPtr[%d]=%d\n”,i,bPtr[i]);

/*Pointeroffsetnotation*/
for (offset = 0; offset < 4; offset++)
printf(“*(bPtr+%d)=%d\n”,offset”
“*(bPtr+offset)”);

return0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example(cont.)
b[ 0 ] = 10
b[ 1 ] = 20
b[ 2 ] = 30
b[ 3 ] = 40

*( b + 0 )= 10
*( b + 1 )= 20
*( b + 2 )= 30
*( b + 3 )= 40

bPtr[ 0 ] = 10
bPtr[ 1 ] = 20
bPtr[ 2 ] = 30
bPtr[ 3 ] = 40

*( bPtr + 0 )= 10
*( bPtr + 1 )= 20
*( bPtr + 2 )= 30
*( bPtr + 3 )= 40

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*Copyingastringusingarraynotationandpointernotation.*/ #include
<stdio.h>
voidcopy1(char*s1,constchar*s2);
voidcopy2(char*s1,constchar*s2 );

intmain()
{
charstring1[10 ]; /*createarraystring1*/
char *string2 = "Hello"; /*createapointertoastring*/ char
string3[ 10 ]; /* create array string3 */
charstring4[]="GoodBye";/*createapointertoastring */

copy1(string1,string2);
printf("string1=%s\n",string1); copy2(
string3, string4 );
printf("string3=%s\n",string3);

return0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/* copy s2 to s1 using array notation */
voidcopy1(char*s1,constchar*s2)
{
inti;
for(i=0;(s1[i]=s2[i])!='\0';i++)
;
}/*endfunctioncopy1*/

/*copys2tos1usingpointernotation*/ void
copy2( char *s1, const char *s2 )
{
/*loopthroughstrings*/
for(;(*s1=*s2)!='\0';s1++,s2++)
;
}/*endfunctioncopy2*/

ProgramOutput
string1 = Hello
string3=GoodBye
Aparajita Mukherjee Assistant Professor UEM, Kolkata
ArraysofPointers
• Arrayscancontainpointers
• Forexample:anarrayofstrings
char*suit[4]={"Hearts","Diamonds", "Clubs",
"Spades" };
– Stringsarepointerstothefirstcharacter
– char*–eachelementofsuitisapointertoachar
– Thestringsarenotactuallystoredinthearraysuit,only
pointers to the strings are stored
suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

suit[1] ’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

suit[2] ’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

suit[3] ’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

– suitarrayhasafixedsize,butstringscanbeofanysize

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerstoFunctions
• Pointertofunction
– Containsaddressoffunction
– Similartohowarraynameisaddressoffirstelement
– Functionnameisstartingaddressofcodethatdefines
function
• Functionpointerscanbe
– Passedtofunctions
– Storedinarrays
– Assignedtootherfunctionpointers

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PointerstoFunctions
• Example:bubblesort
– Functionbubbletakesafunctionpointer
• bubblecallsthishelper function
• thisdeterminesascendingordescendingsorting
– Theargumentinbubblesortforthefunctionpointer:
int(*compare)(inta,intb)
tellsbubblesorttoexpectapointertoafunctionthattakestwo
intsandreturnsanint
– Iftheparentheseswereleftout:
int*compare(inta,intb)
• Definesafunctionthatreceivestwointegersandreturnsapointer to a
int

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*Multipurposesortingprogramusingfunctionpointers*/ #include
<stdio.h>
#defineSIZE10

voidbubble(intwork[],constintsize,int(*compare)(inta,intb)); int ascending(


int a, int b );
intdescending(inta,intb);

intmain(){
int order; /*1forascendingorderor2fordescendingorder*/ int
counter; /* counter */

/*initializearraya */
inta[SIZE]={2,6,4,8,10,12,89,68,45,37};

printf( "Enter 1 to sort in ascending


order,\n""Enter2tosortindescendingorder:"
);
scanf("%d",&order);
printf("\nDataitemsinoriginalorder\n");

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*outputoriginalarray*/
for(counter=0;counter<SIZE;counter++) printf(
"%5d", a[ counter ] );
/*sortarrayinascendingorder;passfunctionascendingasanargument*/ if ( order
== 1 ) {
bubble(a,SIZE,ascending);
printf("\nDataitemsinascendingorder\n");} else { /*
pass function descending */
bubble(a,SIZE,descending);
printf("\nDataitemsindescendingorder\n");}
/*outputsortedarray */
for(counter=0;counter<SIZE;counter++) printf(
"%5d", a[ counter ] );
printf("\n");

return0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*multipurposebubblesort;parametercompareisapointerto the
comparison function that determines sorting order */
voidbubble(intwork[],constintsize,int(*compare)(inta,intb))
{
intpass;/*passcounter */
intcount;/*comparisoncounter*/

voidswap(int*element1Ptr,int*element2ptr); for (
pass = 1; pass < size; pass++ ) {
for(count=0;count<size-1;count++){
/* if adjacent elements are out of order, swap them */
if((*compare)(work[count],work[count+1])){
swap(&work[count],&work[count+1]);
}
}
}
}/*endfunctionbubble */

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
/*swapvaluesatmemorylocationstowhichelement1Ptrandelement2Ptrpoint*/ void swap(
int *element1Ptr, int *element2Ptr )
{
inthold;/*temporaryholdingvariable*/ hold =
*element1Ptr;
*element1Ptr=*element2Ptr;
*element2Ptr=hold;
}/*endfunctionswap*/

/*determinewhetherelementsareoutoforderforanascendingordersort*/ int
ascending( int a, int b ) {
returnb<a;
}/*endfunctionascending */

/*determinewhetherelements areout oforderfor adescendingordersort*/


intdescending(inta, int b){
returnb>a;/*swapifbisgreaterthana*/
}/*endfunctiondescending */

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Example
Enter 1 to sort in ascending order,
Enter2tosortindescendingorder:2

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in descending order
89 68 45 37 12 10 8 6 4 2

Enter 1 to sort in ascending order,


Enter2tosortindescendingorder:2

Data items in original order


2 6 4 8 10 12 89 68 45 37
Data items in descending order
89 68 45 37 12 10 8 6 4 2

ProgramOutput

Aparajita Mukherjee Assistant Professor UEM, Kolkata


String

PGH,UEMK
• 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.
• There are two ways to declare a string in c language.
• By char array [char ch[3]={‘U', ‘E', ‘M', '\0'}; ]
• By string literal[char ch[]={‘UEM’};

PGH,UEMK
Traversing String_By using the length of string
#include<stdio.h>
void main ()
{
char s[5] = “INDIA";
int i = 0;
int count = 0;
while(i<5)
{
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);
}

PGH,UEMK
Traversing String_Using the null character
• #include<stdio.h>
• void main ()
• {
• char s[5] = “INDIA";
• 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++;
• }

PGH,UEMK
Pointers with strings

#include<stdio.h>
void main ()
{
char s[4] = “PUJO";
char *p = s; // pointer p is pointing to string s.
printf("%s",p); // the string javatpoint is printed if we print p.
}

PGH,UEMK
gets() function
• The gets() function enables the user to enter some characters followed by
the enter key. The gets() allows the user to enter the space-separated
strings. It returns the string entered by the user.
#include<stdio.h>
void main ()
{
char s[30];
printf("Enter the string? ");
gets(s);
printf("You entered %s",s);
}

PGH,UEMK
fgets() function
• The fgets() makes sure that not more than the maximum limit of characters
are read.

#include<stdio.h>
void main()
{
char str[20];
printf("Enter the string? ");
fgets(str, 20, stdin);
printf("%s", str);
}
PGH,UEMK
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.
#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;
}

PGH,UEMK
• The strlen() function returns the length of the given string. It doesn't count
null character '\0'.
• The strcpy(destination, source) function copies the source string in
destination. [ strcpy(ch2,ch); ]
• The strcat(first_string, second_string) function concatenates two strings
and result is returned to first_string. [strcat(ch,ch2); ]
• The strcmp(first_string, second_string) function compares two string and
returns 0 if both strings are equal. [strcmp(str1,str2)==0]
• The strrev(string) function returns reverse of the given string.[strrev(str)]
• The strlwr(string) function returns string characters in lowercase. The
strupr(string) function returns string characters in uppercase.

PGH,UEMK
String strstr()

• The strstr() function returns pointer to the first occurrence of the matched string in the given string.
• char *strstr(const char *string, const char *match)
• string: It represents the full string from where substring will be searched. match: It represents the substring
to be searched in the full string.
• #include<stdio.h>
• #include <string.h>
• int main(){
• char str[100]="A is part of b part";
• char *sub;
• sub=strstr(str,"part");
• printf("\nSubstring is: %s",sub);
• return 0;
• }

PGH,UEMK
Structs,Unions and Enums
Aparajita Mukherjee
Assistant Professor
UEM,Kolkata

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Data Type Review
• We already learned...
– Primitive datatypes:
• char,int,long,float,double...

– Derived datatypes:
• pointers,arrays,functions...
• Today we will learn two new derived types
– Structs
– Unions
• And one “syntacticsugar” datatype
– Enums
Aparajita Mukherjee Assistant Professor UEM, Kolkata
Structs
• Struct: A derived type for a collection of
related variables under one name
– Much like classes in Java with no methods
– Members can be primitives or derived types
• Useful for...
– Readability of code through conceptual grouping
– FileI/Ooffixed length records into structs
– Designing recursive datastructures(e.g.linked lists,
trees, graphs) using pointers

Aparajita Mukherjee Assistant Professor UEM, Kolkata


StructExample
#include<stdio.h>str
>> ./a.out
uct Point{
pnt=(10,20)
intx;
int y;
};
void print_point(const struct Point *ppnt) {
printf("pnt=(%d,%d)\n",ppnt->x,ppnt->y);
}
intmain(intargc,char*argv[])
{
structPointpnt;
pnt.x = 10;
pnt.y = 20;
print_point(&pnt);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


StructTypeDeclaration
#include<stdio.h>
• Thisdeclaresatype“structPoint”
structPoint{
int x;
–Similartoaclassdeclarationin
Java
inty;
};
• Thestructhastwomembers“x”and
“y”
void print_point(const struct Point *ppnt) {
• Note: no new variables (storage
printf("pnt=(%d,%d)\n",ppnt->x,ppnt->y);
locations)havebeendeclaredyet
}
–“x”and“y”arenotstorage
intmain(intargc,char*argv[])
locations
{
structPointpnt;
pnt.x = 10;
pnt.y = 20;
print_point(&pnt);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


StructVariableDeclaration
#include<stdio.h>str
• Thisdeclaresavariable“pnt”of
uct Point{
type “struct Point”
intx;
int y;
};
Wecanalsocombinetypedeclaration
with variable declaration, but in this
void print_point(const struct Point *ppnt) {
casethetypedeclarationandvariable
printf("pnt=(%d,%d)\n",ppnt->x,ppnt->y);
declarationwillbeinthesamescope:
}
Example:
intmain(intargc,char*argv[])
structPoint{ int
{
structPointpnt; x;
pnt.x= 10; inty;
pnt.y = 20; }pnt,pnt2,*ppnt;
print_point(&pnt);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


OperationsonStructs
#include<stdio.h>str
• Fourvalidoperationsonstructs
uct Point{ – Thesizeofoperator
intx; – Thereference(&)operator
int y; – Accessingmembervariables
}; • “.” (dot) operator (When
accessedthroughstructvar)
void print_point(const struct Point *ppnt) {
• “->”(arrow)operator(When
printf("pnt=(%d,%d)\n",ppnt->x,ppnt->y); accessed through pointer to
} struct var)
intmain(intargc,char*argv[]) – Theassignment(=)operator
(e.g.structPointx,y;x=y;)
{ • Recall:arrayswereallowedsizeof,&,and[]
structPointpnt; operators but did not allow assign
pnt.x=10; • Passingstructstofunctions
pnt.y = 20; – Bypointer(copyjustthepointer)
print_point(&pnt); – Byvalue(copytheentirestruct)
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


StructInitialization
#include<stdio.h>str
• Goodhabittoinitializeallstructs
uct Point{
just like any variable
intx;
• Threewaystoinitialize
int y;
};
– Initializemembersonebyone
void print_point(const struct Point *ppnt) { –Throughassigningtoanother
printf("pnt=(%d,%d)\n",ppnt->x,ppnt->y); struct
} – Throughstructinitializer
intmain(intargc,char*argv[]) (e.g.structPointpnt={10,20};)
{ • Structinitializerscanonlybeusedat
structPointpnt; variable declaration time, just like
array initializers
pnt.x=10;
pnt.y = 20;
print_point(&pnt);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


RecursiveMemberDefinitions
• Canstructshavemembersoftheirowntype?
struct A {
int x;
structAy;
};
ItisIllegal!(ThinkofwhatthesizeofstructA wouldbe.)

• Canstructshavemembersofpointerstoowntype?
struct A {
intx;
structA*y;
};
Itislegal!(NowthinkofwhatthesizeofstructAwouldbe.)

Aparajita Mukherjee Assistant Professor UEM, Kolkata


RecursiveDataStructures
• LinkedList:
struct Node {
data data data
int data;
structNode*next; next next next
};
data
• BinaryTree:
struct Node { left right
int data;
struct Node *left; data data
structNode*right; left right left right
};
Aparajita Mukherjee Assistant Professor UEM, Kolkata
MysteriousSizeofStructExample
#include<stdio.h>
intmain(intargc,char*argv[]) >> ./a.out
{ sizeof(A)=16
struct {
charx;
longlong y;
}A;
printf("sizeof(A)=%d\n",sizeof(A));
return 0;
}
• Why16?Whynot9(1+8)?
• Becausetheaddressof“y”needstobealigned

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Inefficiency of Word-Spanning Accesses

• Word:(largest)unitofdatathatcanbeaccessedina
single memory operation
–Whatitmeanstobe a“32-bit” or“64-bit” system
– Usually,sizeofword==registersize
• Efficienttoload/storeregisterinasingleoperation
• Problem:whatifanaccessspansmultiplewords
(lands on the boundary between two words)?
– Wouldresultintwomemoryaccesses
• Imaginepatchingtogetheravaluefromtwoaccesses
• Imagineaccessestotwodifferentcachelines,pagesetc

Aparajita Mukherjee Assistant Professor UEM, Kolkata


AlignmentandWordAccesses
• n-bytealigned:addressisn-bytealigned
– ifitisamultipleofn
• aligned(access):accessisaligned
– ifaddressisn-bytealigned
– ifdatumisnbyteslong(wherenisapowerof2)
– then,alignedaccessesneverspanwords, if
n <= word size

Aparajita Mukherjee Assistant Professor UEM, Kolkata


AlignmentandWordAccesses
• aligned(primitivepointer):pointerpisaligned
– ifppointstoabasetypeofnbytes
– ifpalwayspointstoann-bytealignedaddress
– then,accessestopmustbeallalignedaccesses

• aligned(aggregatepointer):pointerpisaligned
– if pointer to each primitive member is aligned
(evenafterperformingpointerarithmeticonp)
– Forarray:onlyrequiresfirstelementtobealigned
– Forstruct:morecomplicated(membersdifferinsize)

Aparajita Mukherjee Assistant Professor UEM, Kolkata


PaddingtoEnforceStructAlignment
struct { struct {
charx; charx;
longlongy; charpadding[7];
}A; long long y;
} A;

struct{ struct{
longlongy; char longlongy; char
x; x;
}A; charpadding[7];
} A;
• Compilerinsertspaddingtopreventmisalignedaccesses
(Even when A is used in an array, hence 2nd case)
Aparajita Mukherjee Assistant Professor UEM, Kolkata
• Differentcompilersmayproducedifferentpadding
➔ Mustbecarefulwhenwriting/readingfileusingstruct

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Unions
• Union:Aderivedtypeforavariablethatcanstore
values of different data types
– Syntaxisexactlythesameasstructs
– Memberscanbeprimitiveorderivedtypes
– Eachmemberbeginsatthesamememorylocation
(Members share space)
– Updateofmemberoverwritessharedspace
– Onlymemberslastwrittentocanberead
• Usefulfor...
– Declaring storage space used for multiple purposes
(e.g.storingastring,int,andfloatatdifferenttimes)
– Savesstoragespace

Aparajita Mukherjee Assistant Professor UEM, Kolkata


UnionExample
#include <stdio.h> >>./a.out
#include<string.h> 5
union Number { Five
intnum; 1702259014
charstr[100];
};
intmain(intargc,char*argv[])
{
union Number number;
number.num = 5;
printf("%d\n",number.num);
strcpy(number.str, "Five");
printf("%s\n", number.str);
printf("%d\n",number.num);
Aparajita Mukherjee Assistant Professor UEM, Kolkata
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


SizeofUnion
#include<stdio.h>
>>./a.out
union Number {
sizeof(unionNumber)=100
int num;
charstr[100];
};
intmain(intargc,char*argv[])
{
printf("sizeof(unionNumber)=%d\n",sizeof(unionNumber));
return 0;
}

• Sizeofunionisatleastaslargeasthelargestmember.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Enums
• Enumeration:datatypeconsistingofasetofnamedvaluescalled
enumerators.E.g.:
– enumSuit{Spades,Diamonds,Clubs,Hearts}suit;
• InC,anenumisanaliasforanintegertype(sizedependsoncompiler)
• Enumeratorsarealiasesforintegerconstants
• Abovevariabledeclarationequivalentto:
int suit;
const int Spades = 0;
constintDiamonds=1;
const int Clubs = 2;
const int Hearts =3;
• Canassignintegervaluestoenumerators
– enumSuit{Spades=1,Diamonds,Clubs,Hearts}
– enumSuit{Spades=1,Diamonds=2,Clubs=4,Hearts=8}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


Enum Example
>>./a.out
suit=1
#include<stdio.h>
suit=2
intmain(intargc,char*argv[])
suit=3
{
suit=4
enumSuit{Spades=1,Diamonds,Clubs,Hearts}; enum
Hearts=4
Suit suit;
for(suit=Spades;suit<=Hearts;++suit){
printf("suit=%d\n", suit);
}
printf("Hearts=%d\n",Hearts);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


OperationsonEnums
• Sinceenumisreallyan
#include<stdio.h> integer,anyarithmetic
operationispermitted
intmain(intargc,char*argv[])
• However,onlycomparison
{
and increment/decrement
enumSuit{Spades=1,Diamonds,Clubs,Hearts}; enum operators make sense
Suit suit; semantically
for(suit=Spades;suit<=Hearts;++suit){
printf("suit=%d\n", suit);
}
printf("Hearts=%d\n", Hearts);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


OperationsonEnumerators
• Sinceanenumeratorisreally
a integer constant, any
arithmeticoperationor
#include<stdio.h>
assignment to integer
intmain(intargc,char*argv[]) variables
{ • However,onlymeanttobe
enumSuit{Spades=1,Diamonds,Clubs,Hearts}; enum used in relation to the
Suit suit; original enum type
for(suit=Spades;suit<=Hearts;++suit){
printf("suit=%d\n", suit);
}
printf("Hearts=%d\n", Hearts);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


OperationsonEnums
• Sinceenumisreallyan
#include<stdio.h> integer,anyarithmetic
operationispermitted
intmain(intargc,char*argv[])
• However,onlycomparison
{
and increment/decrement
enumSuit{Spades=1,Diamonds,Clubs,Hearts}; enum operators make sense
Suit suit; semantically
for(suit=Spades;suit<=Hearts;++suit){
printf("suit=%d\n", suit);
}
printf("Hearts=%d\n", Hearts);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


ReviewQuestion1
Whatiswrongwiththefollowingcode?

#include<stdio.h>
#include<string.h>
voidmodify(structemp*);
struct emp
{
charname[20];
int age;
};
intmain()
{
structempe={"John",35};
modify(&e);
printf("%s%d",e.name,e.age);
return 0;
}
voidmodify(structemp*p)
{
p->age=p->age+2;
}

The struct emp is mentioned in the prototype of the function modify()


Aparajita Mukherjee Assistant Professor UEM, Kolkata
beforedeclaringthestructure.Tosolvethisproblemdeclarestructemp
before the modify() prototype.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


ReviewQuestion2
Whatiswrongwiththefollowingcode?

#include<stdio.h>in

t main()
{
structemp
{
charn[20];
int age;
};
structempe1={"Dravid",
23};
structempe2=e1; if(e1
== e2)
printf("Thestructure
are equal");
return0;
}

Structure cannot be compared using'=='


Aparajita Mukherjee Assistant Professor UEM, Kolkata
ReviewQuestion3
Whatiswrongwiththefollowingcode?
#include<stdio.h>i

nt main()
{
structemp
{
charname[25];
intage;float
bs;
};
struct emp e;
e.name="Suresh";
e.age = 25;
printf("%s%d\n",e.name,
e.age);
return0;
}
Incompatibletypesinassignment.Wecannotassignastringtoastruct variable like
e.name = "Suresh"; in C.
Aparajita Mukherjee Assistant Professor UEM, Kolkata
Wehavetousestrcpy(e.name,"Suresh");toassignastring.

Aparajita Mukherjee Assistant Professor UEM, Kolkata


ReviewQuestion4
Wasarray“a”copiedtofunction“fun” or
was it passed by its address?

#include<stdio.h>
voidfun(inta[],intn); int
main()
{
inta[5]={1,2,3,4,5};
fun(a,5);
}
voidfun(inta[],intn)
{
int i;
for(i=0;i<=n-1;i++)
printf("value=%d\n",a[i]);
}

It was passed by it’s address.


Arrays cannot be passed by copy in C(directly).
Aparajita Mukherjee Assistant Professor UEM, Kolkata
ReviewQuestion5
Wasstructure“pnt”copiedtofunction“print_point”(includingitsfields) or
was it passed by its address?
#include<stdio.h>struct
Point{
intx;
inty;
};
voidprint_point(conststructPointppnt){
printf("pnt=(%d,%d)\n",ppnt.x,ppnt.y);
}
intmain(intargc,char*argv[])
{
structPointpnt; pnt.x
= 10;
pnt.y = 20;
print_point(pnt);
return 0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


ReviewQuestion6
Wasarray“my_array”copiedtofunction“print_point” or
was it passed by its address?

#include<stdio.h>struct
Point{
intstuff;
intmy_array[4];
};
voidprint_point(conststructPointppnt){
//...
}
intmain(intargc,char*argv[])
{
structxPoint={8,{1,2,3,4}};
print_point(pnt);
return0;
}

Aparajita Mukherjee Assistant Professor UEM, Kolkata


File Operation

 File: the file is a permanent storage medium in which we can store the data permanently.
 Types of file can be handled we can handle three type of file as (1) sequential file (2) random
access file (3) binary file
 opening a file:

Before performing any type of operation, a file must be opened and for this
fopen() function is used.

 syntax:

file-pointer=fopen(“FILE NAME ”,”Mode of open”);


example:

FILE *fp=fopen(“ar.c”,”r”);
If fopen() unable to open a file than it will return NULL to the file pointer.

File-pointer: The file pointer is a pointer variable which can be store the address

of a special file that means it is based upon the file pointer a file gets opened.
Declaration of a file pointer:-

FILE* var;

 Modes of open

The file can be open in three different ways as

Read mode ’ r’/rt

Write mode ’w’/wt

Appened Mode ’a’/at

 Reading a character from a file

getc() is used to read a character into a file

Syntax:
character_variable=getc(file_ptr);

 Writing acharacter into a file


putc() is used to write a character into a file

puts(character-var,file-ptr);

PGH,UEMK | [Document subtitle]


 ClOSING A FILE
fclose() function close a file.

fclose(file-ptr);

fcloseall () is used to close all the opened file at a time

communicate with file using A new type called file pointer.

 Operation with fopen()

File pointer=fopen(“FILE NAME”,”mode of open”);

If fopen() unable to open a file then it will return NULL to the file-pointer.

 Reading and writing a characters from/to a file

fgetc() is used for reading a character from the file


Syntax:

character variable= fgetc(file pointer);

fputc() is used to writing a character to a file

Syntax:

fputc(character,file_pointer);

/*Program to copy a file to another*/

#include<stdio.h>

void main()

FILE *fs,*fd;

char ch;

If(fs=fopen(“scr.txt”,”r”)==0)

printf(“sorry….The source file cannot be opened”);

return;

If(fd=fopen(“dest.txt”,”w”)==0)

printf(“Sorry…..The destination file cannot be opened”);

PGH,UEMK | [Document subtitle]


fclose(fs);
return;

while(ch=fgets(fs)!=EOF)

fputc(ch,fd);

fcloseall();

 Reading and writing a string from/to a file

getw() is used for reading a string from the file

Syntax:
gets(file pointer);

putw() is used to writing a character to a file


Syntax:

fputs(integer,file_pointer);
#include<stdio.h>
#include<stdlib.h>
void main()
{
FILE *fp;
int word;
/*place the word in a file*/
fp=fopen(“dgt.txt”,”wb”);
If(fp==NULL)
{
printf(“Error opening file”);
exit(1);
}
word=94;
putw(word,fp);
If(ferror(fp))
printf(“Error writing to file\n”);
else
printf(“Successful write\n”);
fclose(fp);
/*reopen the file*/

fp=fopen(“dgt.txt”,”rb”);If(fp==NULL)

PGH,UEMK | [Document subtitle]

You might also like