0% found this document useful (0 votes)
1 views94 pages

C Notes

The document provides an overview of the C programming language, detailing its history, features, and basic components such as data types, variables, constants, and operators. It explains the structure of a C program, including the importance of syntax, comments, and the character set. Additionally, it covers storage classes and the rules for naming variables and constants, along with examples to illustrate these concepts.

Uploaded by

Ajay Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views94 pages

C Notes

The document provides an overview of the C programming language, detailing its history, features, and basic components such as data types, variables, constants, and operators. It explains the structure of a C program, including the importance of syntax, comments, and the character set. Additionally, it covers storage classes and the rules for naming variables and constants, along with examples to illustrate these concepts.

Uploaded by

Ajay Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

1

C LANGUAGE

Chapter 1
1) C-PROGRAMMING
1.1) Basics of c-programming

Simple Portability Syntax based

Case sensitive
Powerful

Fast and Features of C Structure oriented


efficient
Modular Middlelevel
Use pointers
Compiler based Platform
dependent
Fig. 1.1 Features of C

Introduction:
y C is a programming language designed and written by Dennis Ritchie.
y It was designed and developed at AT & T Bell Laboratories, USA, in 1972.
y In the late 70’s, C began to replace more familiar languages such as
ALGOL, PL/I etc. It gradually gained popularity.
y Major portions of operating systems such as Windows, Linux are written
in C mainly due to its speed of execution.
y Device drivers and embedded systems are majority written in C.
y Like any other language, C-programming language is composed of
alphabets, digits and special symbols which are used to form constants,
variables, keywords to write instructions further. These combinations of
instructions form a C-program.

Alphabets
Constants
Digits Program
Variables Instructions
Special
Keywords
Symbols

Fig. 1.2
C-character set:
y A character set denotes any alphabets, digits or special symbol used to
represent information.
y The following table shows the C-character set:

Alphabets A – Z, a – z

Digits 0–9
C LANGUAGE

Special symbol ~ ' ! @ # % ^ & * () _ - + = | \ { } [ ] : ; “ ' < > , . ? /

1
Chapter 1

Token:
Smallest individual unit (Keywords, identifiers, constants, strings, special
symbols, operators).

Table 1.1 Keywords in C


Identifiers:
� It is a name used to identify a variable, constant or a function.
y An identifier is a combination of letters, numbers and special symbol
(only _ underscore)

Example:
Var123
Valid
Variable_10
Identifers
Demo_1

Invalid Var@123
idenfiers V$demo
Hell#

Fig. 1.3
� C does not allow punctuation characters and special symbols such as
?,-, @, #, $, % within identifiers.
C LANGUAGE

2
Chapter 1
Whitespace:
y Whitespace in C programming language are blank lines, tabs or new
lines, and blank spaces.
y These whitespace helps the compiler in understanding, and identifying
when one element in the statement ends, and next element starts.

Example: int age;


A single whitespace or blankspace between int, and age enables the
compiler to identify int datatypes, and age as the variable of int datatype.
whereas: int age = age1 + age2;
the space between age, = age1, + and age2 is not necessary, but for
readability purposes, it is always preferred to add them.

Comments:
y They are ignored by the compiler.
y Comments are like helping texts in a C-program.
y Mostly added to increase the readability of a program.
Single line comments: //
Multi-line comments: /* _________
_________
_________ */
Instruction:
y It is a combination of keyword, variable, and constants.

Example: int a = 10;

Program
y It is a collection of instructions.

Example:

header file
#include <stdio.h>
function
void main() C-program structure:
{ int a = 1; int b = 2; variable y Preprocessor commands
int c = a + b; y Functions
operation
y Variables
printf("sum%d", c);
y Statements and expressions
} y Comments
print statement
C LANGUAGE

3
Chapter 1

Semicolon:
y A semicolon “;” is a statement terminator in C.
y Every statement must be ended with a semicolon.
y It indicates the end of a logical entry.

Constants and variables:


y Alphabets, numbers and special symbols, when properly combined
form constants & variables.
y Constant is an entity that does not change during the execution of the
program.
y Variable is an entity that may change during the execution of the program.

Rules to name variables and constants:


1) The variables or constant name is a combination of 1 to 31 characters,
i.e. length can be maximum 30.
2) These characters can be alphabets, digits, underscores.
3) The first character in the variable or constant name must be an alphabet
or underscore.
4) No comma, whitespaces are allowed within the variable or constant
name.
5) No special symbol other than underscore and no keyword can be used
as constant or variable name.

Example:

Table 1.2
C LANGUAGE

4
Chapter 1
Constants:
y Value that cannot be changed during the execution of the program

Fig. 1.4 Types of Constants


1) Numeric constant:
� numeric digits (may or may not have decimal point).
should have at least one digit, no commas or space, either positive
� 
or negative sign.
� by default sign is positive.

Fig. 1.5 Types of Numeric Constants


2) Character constants:
� Single character enclosed within single quotes.
C LANGUAGE

� A character constant is a single alphabet, a single digit or a single


special symbol enclosed within single quotes.
Example: ‘a’, ‘B’, ‘8’, ‘=’

5
Chapter 1

Example:

Table 1.3

Note:

Table 1.4
3) String constants:
� It has zero, one or more than one character.
� enclosed within double quotes “”
� at the end of string \0 is automatically placed by compiler.
� \0 refers to as NULL string.

Example:
“Hello”
“8”
“593”
“”
“A”

4) Symbolic constants:
� using the keyword: define
� when one constant is to be used several times.
C LANGUAGE

� A symbolic constant is a tag used to replace a number, e.g. pi can be


used to replace 3.14.

6
Chapter 1
� These sequences of characters may be numeric constant, character
constant or string constant.
� Generally defined at the beginning of the program with header files.
Syntax: #define name value

Example: Defining a constant pi whose value is 3.14159625


#define pi 3.14159625

Some more examples:


#define max 100
#define CH ‘a’
#define Name “Somesh”

1.2 TYPES OF VARIABLES


Datatypes in C:
y An attribute given to every data used in the program is known as data
type for the data. A variable is declared with a data type so that it holds
a value of that type.
y The type of variable specifies how much space it requires in storage
and how it is stored in memory.

E C LANGUAGE

Fig. 1.6 Data-Types in C

7
Chapter 1

1) Primary datatypes:

Integer Real Character

Table 1.5

1)
2)
3)
4)
5)
6)
7)
8)
9)
10)
11)
Table 1.6
C LANGUAGE

8
Chapter 1
Fig. 1.7
The variable of integer data type in C Programming can be signed or unsigned
number. Three different declarations of type integer are short, int, and long.
All of them in size, e.g. “short” has a lower range than “int” and “long” has
a larger range than “int”. Though the actual size in bytes depends on the
architecture on which program is being written.

2) Secondary datatype:
   � These data types are divided or defined using primitive datatypes

Secondary Datatype

structure enumeration union

Fig. 1.8 Types of Secondary Datatypes

1.2.2 Scope and lifetime variables:


Storage classes:
y In addition to datatypes, each variable has one or more attribute known
as the storage class.
C LANGUAGE

9
Chapter 1

Scope

Default value
Lifetime

Storage
Place of storage
Class

Fig.Fig.
: Features that storage
1.9 Features classClasses
of Storage decides
y about a variable
The use of storage class makes the programs more efficient and swift.
y The syntax of declaring the storage class of a variable is:
Syntax: Storage_class_name datatype variable_name;
Example: Storage_class_name int a;
y There are four types of storage classes, namely automatic, external,
static and register.

Types of storage class

Class: Automatic Static External Register


Keywords: (auto) (static) (extern) (register)

Fig. 1.10
A storage class decides about the following aspects of a variable:
1) Lifetime: It is the time between creation & destruction of a variable.
2) Scope: The progress range/location where the variable is available for use.
3) Default Value: The default value which is taken by uninitialized variable.
4) Place of storage: The place in memory which is allocated to the variable.
C LANGUAGE

10
Chapter 1
Types of storage class:

Table 1.7 All about Storage Classes


y To make global static variables, declare the static variable outside of
all functions.
y Static variables can only be initialized by constants or constant
expressions.
y An static variable is initialized once, and it retains its value during the
recursive function calls.

Example 1:
Consider the given C-program statements:
int x = 12
static int y = 15;
func()
{ static int x;
x = x + 2;
printf(“inside func(): x = %d, y = %d\n”, x, y);
}
main()
{ int x = 13;
func();
func();
printf(“inside main ():x = %d, y = %d\n”, x, y);
}
Output: Inside func():x = 2, y = 15
Inside func():x = 4, y = 15
Inside main():x = 13, y = 15
In func(), x is initialized to 0 and x = 0 is used, since it is a static variable,
C LANGUAGE

hence its value is retained between function calls. Since y has been
initialized outside main and func(), it is accessible to both the functions.

11
Chapter 1

Example 2:
Consider the given C-program statements:
func1()
{ extern int x;
x++;
printf(“func1:%d\n”, x);
}
int x = 189;
func2()
{ x++;
printf(“func2:%d\n”, x);
}
main()
{ func1();
func2();
}
Output: func1:190
func2:191

Previous Years’ Questions

(GATE-2000)
C LANGUAGE

12
Chapter 1
a) b) c) d)
Sol: c) ( )

i)
ii)
iii)
iv)

a) b)
c) d)
Sol: d) ( )
C LANGUAGE

13
C LANGUAGE Chapter 1

c)
a)
..

14
b)

d)
a) b)

Chapter 1
c) d)

Sol: d) ( )

1.3 OPERATORS IN C
y An operator specifies an operation to be performed that yields a value.
y An operand is a data item on which an operator acts upon.

Other Size of
Bitwise
operators operator
operator
Comma
Arithmetic
operators
operator
Assignment
Conditional Operators
operator
Operator

Logical Increment
Operator & Decrement
operator
Relational
Operator

Fig. 1.11 Types of Operators in C


y Operators can be of two types primarily:
1) unary operator 2) binary operators
C LANGUAGE

15
Chapter 1

Operators types

Unary Binary

Operates Operates
on only one on two
operand operands

Fig. 1.12

Bitwise operator:
y Manipulation at bit level can be performed using bitwise operators.
y These operators perform operation on individual bits.

Operator Meaning

Table 1.8 Bitwise Operators


C LANGUAGE

16
Chapter 1
Bitwise AND (&):
y Binary operator represented as &

Table 1.9
Syntax: operand 1 & operand 2
Bitwise inclusive OR (|):
y Binary operator represented by |.

Table 1.10
Syntax: operand 1 | operand 2
Bitwise XOR (^):
y produces output 1 for only those input combinations that have odd
number of 1’s.
y Binary operator represented by ^.

Table 1.11
Syntax: operand 1 ^ operand 2
Compliment (~):
y One’s compliment operator represented by ~.
y unary operator
C LANGUAGE

Table 1.12

17
Chapter 1

Syntax: ~ operand.
Bitwise left shift (<<):
y Binary operator represented by <<.
Syntax:
Operand 1 Operand 2

Operand No. of bits


whose to be shifted
bits are
to be
shifted left

y Shifting bits results in equal no. of bits being vacated on the other side,
these vacated spaces are filled with 0 bits.

Example:
Let x = 0001 0011 0000 0100, then x<<4 means left shift x by 4 bits, then:

0001
 0011 0000 0100 0001

Lost bits Filled bits
∴ After left shifting: 0011 0000 0100 0000
Bitwise right shift (>>):
y Binary operator represented by >>.
y Similar to left shift except it shifts bit in the opposite direction as of
left shift i.e. shift bit to the right side.
y Similar to left shift, here the bits are shifted to right & bits are vacated
in the left and right shifting on unsigned quantity always fill with zero in
the vacated positions. In right shifting on signed quantity, then will fill
with sign bits (“arithmetic shift”) on the vacated positions.

Example:
Let unsigned int x= 0001 0011 0000 0100, then x>>4 means right shift x by
4 bits, then:

0000
 0001 0011 0000 0100

Filled bits Lost bits
After right shifting: 0000 0001 0011 0000
C LANGUAGE

18
Chapter 1
Arithmetic operator:
y On the basis of no. of operands:

Arithmetic Operator

unary operator binary operator


+, – +, –, *, /, %

Fig. 1.13
y On the basis of value of operands:

Fig. 1.14
Binary arithmetic operator:

Operator Meaning

Table 1.13

Relational operator:
y These operators are used to compare values of two expressions
C LANGUAGE

depending on their relations.


y Relational expression is an expression with relational operators.

19
Chapter 1

Operator Meaning

g
g
Table 1.14

Logical operators:
y They are also known as Boolean operators.
y Used for combining expressions.
y They return 0 for false and 1 for true.

Operator Meaning

Table 1.15
C LANGUAGE

Non − zero value → True


Zero value → False

20
Chapter 1
AND operator (&&):
y Binary operator represented as &&.

Table 1.16 Truth table for AND


Syntax: (condition 1) && (condition 2)
OR operator (||):
y Binary operator represented as ||.

Table 1.17 Truth table for OR


Syntax: (condition 1) || (condition 2)
NOT operator (!):
y unary operator represented by !.
y negates the value of the condition.

Table 1.18 Truth table for NOT


Syntax: ! (Condition)
Assignment operator:
y used to assign values to variables, denoted by symbol ‘=’.
Syntax:
Operand 1 = Operand 2

Should be a Can be a variable,


variable expression or
C LANGUAGE

a constant

21
Chapter 1

Compound assignment operator:


y Combination of arithmetic operator with assignment operator.

Compound assignment operator Alternate


x+=5 x=x+5
x–=5 x=x– 5

x/=5 x = x/5
x% = 5 x = x%5
x*=5 x = x*5
Table 1.19
Increment and decrement operator:
y Unary operator
y Increment operator represented by ++.
y Decrement operator represented by ––.

Table 1.20
y ++ increment by 1
y -- decrement by 1.
y The increment and decrement operator can be either: (1) prefix; (2)
postfix;

Types

Fig. 1.15
Prefix increment/decrement:
C LANGUAGE

y The value of the variable is incremented or decremented, then the value


is used in the operation.

22
Chapter 1
Syntax: ++x or Operator variable;
––x

Example:
Let x =5, then y=++x means increment the value of x by 1 and then use the
value to be assigned to y. ∴ y = 6
Similarly, y=––x means decrement the value of y by 1 and then use the
value to be assigned to y. ∴ y = 1

Postfix increment/decrement:
y First the value of variable is used, then it is incremented or decremented.
Syntax: x++ or Variable operator;
x––

Example:
Let x =5, then y = x++ means assign y = 5, then increment the value of x by
1 i.e. after execution y = 5 & x = 6.
Similarly, y = x–– means assign y = 5, then decrement the value of x by 1 i.e.
after execution y = 5 & x = 4.

Conditional operator:
y It is a ternary operator which requires three expressions as operands.
y Represented by ? and : space
y Syntax: Text expression ? expression 1: expression 2

Fig. 1.16
Example:
max = a > b ? a: b

This translates to that if (a > b) True, then max = a


C LANGUAGE

False, then max = b

23
Chapter 1

y printf statements can also be used.

Example: a > b ? printf (“a is larger”): printf (“b is larger”);

Rack Your Brain

Which of the following is not a unary operator?


1) ++ 2) – 3) sizeof 4) ?:

Comma operator:
y Represented by ‘,’
y It is used to allow different expressions to appear in places where exactly one expression
would be used.
y Also commonly used as a separator.

Example:

Table 1.21
Example:
Sum = (a = 10, b = 7, c = 3, a + b + c);
Here sum would be a + b + c i.e. sum = 20.

Sizeof operator:
y unary operator
y returns the size of operand in bytes.
y The parameter passed can be a variable, constant or any datatype (int, float, character).
Syntax: sizeof(parameter);

Variable\ constant\ Datatype

Example:
sizeof(int); would return the bytes occupied by integer datatype.
C LANGUAGE

24
Chapter 1
Rack Your Brain

Consider the given C-program:


#include <stdio.h>
int main()
{printf(“%u%u%u%u”, sizeof(schar), sizeof(int), sizeof(float)
sizeof(double));
return 0;
}
1) 1 4 4 8 2) 1 2 4 8 3) 1 4 8 16 4) Machine dependent

Previous Years’ Question

Sol: 0) ( )
C LANGUAGE

25
Chapter 1

a) b) c) d)

Sol: c)

a) b) c) d)

Sol: d)
C LANGUAGE

26
Chapter 1
1.4 TYPE CONVERSION
y It includes converting data type of one operand into
data type of another operand to perform operations.

Type Conversion

Implicit Type Explicit type


Conversion conversion

by compiler user defined

Automatic type Type conversions


Conversions in assignments

Automatic Automatic
unary binary
conversion conversions

Fig. 1.17
Implicit type conversion:
y Done by the C compiler based on some predefined C-language rules.

Implicit type Conversion

Automatic type Type conversion in


conversion assignment : If operands
are of different types,
then the RHS operands
are converted into the
Automatic unary type conversion: Automatic binary type of LHS operand.
All operands of type char & short are type conversion
converted to int before operation.
C LANGUAGE

Fig. 1.18

27
Chapter 1

Rules for automatic binary type conversion:


1) With a binary operator, if both the operands have dissimilar data types
then the operand with lower rank gets converted into the data type of
higher rank operand. It is known as data type promotion.
2) In case of unsigned datatypes:
i) One operand is unsigned long int, others are converted to unsigned
long int as well as the result is stored as unsigned long int.
ii) One operand is unsigned int and other is long int, then:
Case I If long int can represent all values of unsigned int, then
unsigned is converted to long int and the result is also stored
in long int etc.
Case II Both are converted to unsigned long int along with the result.
iii) One operand is unsigned int, then others along with the result are
converted and stored as unsigned int.
Consequences of these promotions and demotions
1) Few higher order bits get dropped when higher order rank data type is
converted to a lower order rank data type. E.g. when int is converted to
short.
2) During the conversion of the float data type into int, the fractional part
gets removed.
3) Digits are rounded off while conversion of double type to float type.
4) The sign may be dropped in case of conversion of signed type to unsigned
types.
5) There is no increased accuracy or precision when an int is converted to
float or float to double.
C LANGUAGE

28
Chapter 1
Highest Rank

long double

double

float

unsigned long int


long int

unsigned int

int

char, short int

Lowest Rank

Fig. 1.19 Rank of Datatypes in C


Explicit type conversion (Type casting):
Some cases such as:

float z ; 

int
= x 20, =y 3;      …(i)
z = x / y; 

The value of z would be 6.0 and not 6.666666
y These cases require the implementation of explicit type conversion.
y This allows user to specify our own/user defined conversion.
y Also known as Type casting or Coercions.
y Type casting is implemented using the cast operator.
y The cast operator is a unary operator which converts an expression to a particular
datatype temporarily.
Syntax : (Datatype) expression;
  
Cast Operator

y Using the cast operator (float) in (i).


z = (float) x/y;
then the value of z would be 6.666667

Lower Higher
Datatype Datatype
C LANGUAGE

Fig. 1.20

29
Chapter 1

Precedence and associativity of operators:


y For an expression having more than one operator, there exists certain
precedence and associativity rules for its evaluation.

Example:
Given an expression: 2 + 3 * 5
It contain 2 operations: + and *, if + performed before *, then result would
be 25 and if * performed before +, then result would be 17.
∴ To remove this ambiguity of which operation to perform first the
C-languages specifies the order of precedence & associativity of operators.
y Operator precedence: Determines which operator is performed first in
an expression.
y Operator associativity: It is used when two operators of same
precedence appear in an expression.
Associativity can be: Left to right
or
Right to left
C LANGUAGE

30
Chapter 1
Table 1.22 Operator Precedence and Associativity Table

Example: 5 + 16 / 2 * 4
y Since / and * have higher precedence than +
∴ they are evaluated first.
y / and * have same precedence, so which would be evaluated first amongst the two is
determined by the associativity rules. Since, /and * are left to right associative.
∴ / is performed before *.
The given expression can be considered as:
5 + (16/2) * 4
Solving: 5 + (8 * 4)
⇒ 5 + 32
C LANGUAGE

⇒ 37

31
Chapter 1

Role of parentheses:
y Parenthesis are used to change the order of precedence of any operation.
y All the operations enclosed in parenthesis are performed first.

Example:
I. Without parenthesis II. With parenthesis
36/6+3 36/(6+3)

(1) (1)
(2)
6 9

(2)
9               4

y Sometimes to increase the readability of the code and expression


parenthesis are used.
Example: x = a!=b & c * d >= m%n
Better: x = (a!= b) & ((c*d)>=(m%n))

Modify the order of


expression evaluation
Change Role of ( )
Order of Simplify complex
precedence expressions

Increase the
readability of
code

Fig. 1.21

1.5 FLOW CONTROL IN C


y Control statements enable us to specify the order in which the various
instructions in the program are to be executed.
y It determines the flow of control in C.

Control Statements

Selection Iteration Jump


Statements Statement Statement

if if else switch for while do while break continue goto return


C LANGUAGE

Fig. 1.22 Types of Control Statements

32
Chapter 1
y Compound statements or a block are a group of statements which are
enclosed within a pair of curly braces { }.
A compound statement is syntactically equivalent to a single statement.

If else statements:
y Bi-directional conditional control statement.
y The statement tests one or more conditions and executes the block
based on the outcome of the test.
y Any non-zero value is regarded as true, whereas 0 is regarded as false.

If...........else

Single if Nested
If.....else else if ladder
statement if else
Syntax : Syntax : Syntax :
if (condition) if (condition) if (condition1)
statement1; statement1; {if (condition2)
or else statement1;
if (condition) statement2; else statement2;
{statement; or }
if (condition) else
{statement; {if (condition 3)
} statement 3;
else
} statement4;
True
Condition else }
False {statement;
Statement1
Statement1

}
Next
Statement True False
Condition

Statement1 Statement2

Next Statement

Fig. 1.23 Types of If-else Statements


Loops:
y Used when one wants to execute a part of a program or a block of
statements several times.
y With the help of loops, one can execute a part of program repeatedly
C LANGUAGE

till some condition is true.

33
Chapter 1

Fig. 1.24 Types of Loop Statements


While loop:
y First the condition is evaluated, if it is true, then the body of loop is
executed.
Syntax: While (condition) OR While (condition)
Statement; { Statement;
Statement;


}

Note: While loops are used when the number of iterations are not known
in advance.

False
While (Condition)

True

Body of loop
Next statement
out of the loop

Fig. 1.25 Flow Chart for While Loop


y Each execution of loop body is called an iteration.
Example: #include <stdio.h>
C LANGUAGE

main()

34
Chapter 1
{ int i = 1;
while(i <=5)
{ printf(“%d\t”, i);
i++;
}
}
Output: 1 2 3 4 5
This C-program prints the numbers from 1 to 5. The variable i is initialized
to 1 and then the condition is checked whether (i < = 5) if true, then the
printf statement is executed. The value of i is incremented by 1 each time
the loop is executed.

Sol: ( )

Do-while loop:
y Similar to while loop just that in do while loop first the statements are
executed, then the condition is checked.
y This results in the execution of the statements at least once even if
the condition is false for the first iteration.
C LANGUAGE

35
Chapter 1
C LANGUAGE

y The body of for loop can have single statement or a block of statements.

36
Chapter 1
y In for loop:
Expression 1: Initialization expression, executed only once, and is generally an assignment
expression.
Expression 2: Test expression or condition, tested before each iteration, generally uses
relational or logical operators.
Expression 3: Update expression or updation, executed each time for body of loop is
executed.
y Firstly, the initialization expression is executed, and the loop variables are initialized,
then the condition is checked.
y If the condition expression is true, then the body of the loop is executed, and the
updation expression is executed.
y This continues till the condition expression is true, and once the condition expression
becomes false, the loop terminates and control is transferred to the statement following
the for loop.
Initialization
expression

False
Condition

True

Body of loop

Update expression

Out of loop
Next Statements

Fig. 1.26 Flow Chart of “for” Loop


y For loops are used when the number of iterations are known in advance.
Example:
# include <stdio.h>
main()
{ int i;
   for(int i = 1; i < = 5; i++)
  printf(“%d\t”,i);
C LANGUAGE

}
Output: 1 2 3 4 5

37
Chapter 1

Some loops that are valid:


y for(; n > 0; n/=10)//initialization of n should be mentioned before loop.
y for(i = 0, j = 10; i < =j; i++, j--)//multiple expression separated by comma
& semi-colon.
y for(; ; )//infinite loop.

Example:
C LANGUAGE

38
Chapter 1
a) b) c) d)
Sol: b)
Hint ( )

Nesting of loops:
y Loop within a loop
y Any type of loop can be nested inside any other type of loop.

Infinite loops:
y Loops that go on executing infinitely.
y The loops that do not terminate are called infinite loops.

Example:

while(1) for (; ;) do
{...................... {...................... {......................
..................... ..................... .....................
} } } while (1);

Infinite while loop Infinite for loop Infinite do while loop

y To come out of such loops break or goto statements are used.


C LANGUAGE

39
Chapter 1

1.6 BREAK, CONTINUE AND GOTO STATEMENTS

Fig. 1.27 Types of Control Statements


y These loop control statements enable the control of programs/loop to
be transferred.

Break statement:
y Used when it becomes necessary to come out of the loop even before
the loop condition becomes false.
y Break statement causes the immediate exit from the loop.

Syntax: break;
y Popularly used in switch statements.

While loop:
C LANGUAGE

40
Chapter 1
Do-While Loop

For Loop

Continue statement:
y Used when one wants to skip some statements and execute the next
iteration.
Syntax: continue;
y Generally used with condition statements, when a condition statement
is encountered and is true, then the statements after the keyword
continue are skipped & the loops condition is checked for next iteration.

Example:
While Loop
C LANGUAGE

41
Chapter 1

Do-while Loop:

For Loop

Goto statement:
y Unconditional control statement
y Transfers the flow of control to another part of the program.
Syntax: goto label;
 Statement;
 Statement;
………………..
………………..
………………..

label:
 Statement;
 Statement;
………………..
C LANGUAGE

………………..

42
Chapter 1
y The label can be placed anywhere:

Fig. 1.28 Types of Goto Statements

Forward goto Backward goto

goto label; label:


Statement; Statement;
Statement; Statement;
Statement; Statement;
Skipped executed
__________ __________
__________ __________
__________ __________

label : goto label ;


Statement; Statement;
Statement; Statement;
__________ executed __________ Skipped
__________ __________
__________ __________

Fig. 1.29
C LANGUAGE

43
Chapter 1

Often leads to spaghetti code (Ambiguous & not understandable)

Complex Poor
control flow programming

Difficulty
in maintenance Why not goto Difficult
of code to debug

Ambiguity in Spaghetti
program control Code

Fig. 1.30
Although there might be situation such as complex nested loops or deeply
nested loops where goto or jump statements can improve the readability
of code.

Example:
C LANGUAGE

44
Chapter 1
Return statement:
y ends the execution of function and returns the control of execution to the calling
function.
y does not mandatorily need any conditional statements.
y Depending on the type of function it may or may not return values.

Fig. 1.31 Types of Functions


Syntax: return expression;

Example:
Void Function Non-void Function
void func() return_datatype func()
{ { return value;
} }

1.7 SWITCH CASE


y Multi-directional conditional control statement.
y Popularly used for menu driven programs.
y Uses three keywords: switch, case, break, default.
Syntax: switch(expression)
{ case constant 1: Statement;
break;
case constant 2: statement;
break;
____________
____________
____________
default: Statements;
}
y Expression: can be anything:
1) An expression yielding an integer value.
2) Value of any integer
C LANGUAGE

3) Character variable
4) Function call returning a value.

45
Chapter 1

y Constants:
1) Should be integer or character type.
2) can be constants or constant expressions.

Fig. 1.32

-
C LANGUAGE

46
Chapter 1
Previous Years’ Question

a)
b)
c)
d)

Sol: c) ( )

1.8 FUNCTIONS AND PROGRAM STRUCTURES


1.8.1 Basics of functions:
y Self-contained sub-program with a well-defined task.
y Although function calls are overhead but are still used.

Understandable
Modular & Compact
Easy to
representation
modify and
(Divide and Conquer)
debug
Why functions?

Easily multiple
calling of code
Avoid rewriting
Code Reuse of
(Repetition) Code
(reusability)
C LANGUAGE

Fig. 1.33

47
Chapter 1

Types of functions:

B
F
F
F

include

Fig. 1.33 Types of Functions

1) M

2) C

3) C
C LANGUAGE

Table 1.22
48
Chapter 1
Syntax:
return_type function_name (arguments)
{
Statement;
_________
_________
_________
}

Function

Example: Program to find sum of two numbers:


#include <stdio.h>
int sum (int x, int y); //function declaration
main () Calling function ?
{ int a, b, s; → main()
printf(“enter the value of a & b:”); Called function?
scanf(“%d%d”, &a, &b); → sum()
s = sum(a, b); //function
printf(“sum=%d”,b);
}
int sum (int x, int y) //function definition
{
int s;
s = x + y;
return s;
}
C LANGUAGE

49
Chapter 1

Types of functions
(on basis of return type & Arguments)

With Without
Arguments Arguments

With Without With Without


return type return type return type return type

int func(int a) void func(int a) int func(void) void fun(void)

Fig. 1.34 Types of Functions Basis of Return Type and Arguments


Function arguments:
y The calling function sends some values to the called function, these
values are known as arguments or parameters.

Fig. 1.35 Types of Function Arguments

Example: Program showing formal and actual arguments:


#include <stdio.h>
mul(int p, int q)//formal arguments
{ int prod;
prod = p*q;
return prod;
C LANGUAGE

}
sum (int p, int q)//formal arguments

50
Chapter 1
{ int s;
s = p + q;
return s;
}
main()
{int a = 2, b = 3;
printf(“%d\t”, mul(a, b));//actual arguments
printf(“%d\t”, mul(5, 4));//actual arguments
printf(“%d\t”, mul(a+b, b–a));//actual arguments
printf(“%d\t”, sum(a, b));
printf(“%d\t”, sum(mul(a, b), b));
}
Output: 6 20 5 5 9

1)

2)

3)
4)

:
C LANGUAGE

5)
51
4)

Chapter 1

5)

6)

1)
2)
3)

M E

and
C LANGUAGE

7)

8)
52
M E

Chapter 1
and

7)

8)

String library functions:


� There are several library functions to manipulate strings, all present in
the header file strings.

Fig. 1.36 String Library Functions


Example: Consider the given C-program
#include < stdio.h>
#include < string.h>
main ()
{ char S1 = “Banglore”;
char str S3[10];
char S2 = “Manglore”;
int length1=strlen (S1);
int length2=strlen (S2);
C LANGUAGE

printf (“length S1: %d\n”,length1);


printf(“length S2:%d\n”,length2);
if ((strcmp(S1, S2)) == 0)
53
Chapter 1

printf(“strings are same\n”);


else
printf(“strings are different\n”);
strcpy (S3, S1);
printf (“S3 string: %s\n”, S3);
strcpy (S1, S2);
printf (“new string: %s\n”, S1);
}
Output:
length S1: 8
length S2: 8
Strings different
S3 string: Banglore
New string: Banglore, Manglore

Local, global and static variables:


C LANGUAGE

Fig. 1.37 Types of Variables

54
Chapter 1
Recursion:
y It is the process when a function calls itself.
y Powerful technique whose complicated algorithms are solved by the
divide and conquer approach.
y The sub-problems are defined in terms of the problem itself.
A function should have the capability of calling itself.

The function that calls itself, again and again, is called a recursive function.

Example:

C LANGUAGE

55
Chapter 1

Point to remember:
y One should be able to define the solution of the problem in terms of a
similar type of smaller problem.
y There should be a termination condition; otherwise, the recursive call
would never terminate.

Popular Problems

Factorial Power Fibonacci Tower of


Hanoi
Fig. 1.38

Advantages of Recursion

Code is compact Elegant and Divide and conquer Some inherent data
(modular) understandable approach simplifies structures are
the concept recursive

Fig. 1.39

Disadvantages of Recursion

Less Greater time Memory


efficient requirement requirements

Fig. 1.40
Factorial:
Factorial of a positive integer n can be represented as a product of all
integers from 1 to n.
n! = 1 * 2 * 3 * …………….. *n
It can be written as:
n! = n * (n – 1)!
 1 ;n = 0
Here: n! = 
C LANGUAGE

n * (n − 1) ! ;n > 0

56
Chapter 1
Program to find the factorial:
#include <stdio.h>
long fact (int n);
main()
{ int num;
printf(“enter the number”);
scanf(“%d” & num);
printf(“factorial: %Id”, fact(num));
}
long fact(int n)
{ if (n = = 0)
 return(1);
else
  return (n*fact(n–1));
}

C LANGUAGE

57
Chapter 1

Rack Your Brain

1) GCD of two numbers.


2) Finding second maximum of three distinct numbers.
Hint. 1) GCD of two numbers:
f(a, b)
{ if(a == 0)
   return b;
if(b = = 0)
   return a;
if(a == b)
   return a;
else
   if(a > b)
   return f(a – b, b);
else
   return f(a, b – a)
}
3) Second maximum of three distinct numbers:
int func(int a, int b, int c)
{ if((a >= b) && (c < b))
   return b;
else
if(a > = b)
  return func(a, c, b);
else
return func(b, a, c); }

Value passing in functions:

1)

2)

3)

4)

5)

6)

7)
C LANGUAGE

8)

Table 1.23

58
Chapter 1
!

Fig. 1.41 Types of Value Passing Techniques

C LANGUAGE

59
C LANGUAGE Chapter 1

60
Chapter 1
1)

2)

3)

4)

5)

C LANGUAGE

6)

Table 1.24 Call by Value vs Call by Reference vs Call by Address

61
Chapter 1

during the
a) b) c) d)

Sol: d) ( )
:
C LANGUAGE

62
Chapter 1
a)
b)
c)
d)

Sol: d) ( )

a) b) c) d)

Sol: b) (
C LANGUAGE

63
Chapter 1

Sol:

1.9 POINTERS AND ARRAYS


1.9.1 Pointers and addresses:
y A pointer is a variable which stores the memory address of another
variable in the memory.
y Real power of C lies in pointers.
y The memory of the computer is made up of bytes arranged in a
sequential.
y Each byte has an index number called the address of that byte.
y If there are n bytes, the address would vary from 0 to (n – 1) bytes.

Example: 64 MB RAM
then, 64 MB
⇒ 64 × 2 bytes
20

⇒ 67108864 bytes
Then: the address of these bytes would be: 0 to 67108863.
C LANGUAGE

64
Chapter 1
Implementing Returning more than
data structures one value from a function
such as linked
list, trees, graphs.
Accessing dynamically
Use of allocated memory

Efficient pointers
code

Compact Easy to access


and array elements
modular
Fig. 1.42
Address operator:
y denoted by ‘&’ (Ampersand) and read as ‘address of’.
y returns the address of a variable when placed before it.

Example: &a: address of a


y Popularly used in scanf() function.
Program to print address of variable.
#include <stdio.h>
main ()
{ int var = 10;
float demo = 11.1;
printf(“value of var = %d, address of var = %u\n”, var, &var);
printf(“value of demo= %f, address of demo = %u\n”,
demo, & demo);
}
Output: Value of var = 10, address of var = 65524
Value of demo = 11.100000, address of demo = 65520

V
C LANGUAGE

65
Chapter 1

Pointer variables:
y Stores the memory address.
y Like all variables, it has a name, is declared and occupies space in
memory.
y Pointer: Because it points to a memory location.
Syntax: data_type *pointer_name;
int *ptr
y * (asterik) often read as “value at”.

Example: int *ptr, age = 50;


int *sal, salary = 10000;
ptr = &age;
sal = &salary;
age salary
ptr 50 sal 10000

y *ptr means value at variable ptr, since ptr stores the address of age.
∴ *ptr = * (&age) which is value at address of age.
This returns the value of variable age = 50
y Similarly: as sal = &salary
∴ *sal= * (&salary), which means the value at the address of salary.
y One can access the variable ‘age’ by using (*ptr) since ptr is storing the
location of age, hence (*ptr), can be used in place of the variable name.
This is called dereferencing pointer variables.

Example: int a = 10;


int b = 21;
int *ptr1=&a;
int *ptr2=&b;
Now:

Statement Equivalent to

Table 1.25
y Often referred to as indirection operation translating to “value at the
C LANGUAGE

address.”

66
Chapter 1
Example: #include <stdio.h>
main()
{ int a = 67;
float b = 45.6;
int*ptr1=&a;
float *ptr2 = &b;
printf(“Value of ptr1 = Address of a = %u\n”, ptr1);
printf(“Value of ptr2 = Address of b = %u\n”, ptr2);
printf(“Address of ptr1 = %u\n”, &ptr1);
printf(“Address of ptr2 = %u\n”, &ptr2);
printf(“Value of a = %d%d%d\n”, a, *ptr1, *(&a));
printf(“Value of b = %f%f%f\n”, b, *ptr2, *(&b));
}

Output:
Value of ptr1 = Address of a = 65524
Value of ptr2 = Address of b = 65520
Address of ptr1 = 65518
Address of ptr2 = 65516
Value of a = 67 67 67
Value of b = 45.600000 45.600000 45.600000
C LANGUAGE

67
Chapter 1

Pointer arithmetic:
y All types of operations are not possible with pointers.

Valid operations

Addition Subtraction of Increment subtraction of


of integer an integer from and same type
to a pointer a pointer decrement pointers.
C LANGUAGE

Fig. 1.43 Types of Value Passing Techniques


y Pointer arithmetic is different since it is performed relative to the size
of the base type of pointer.

68
Chapter 1
Example: int *pi;
if: pi = 1000, let int size be 2 bytes, then (pi)++; is 1002 and not 1001.
This is because the data type int occupies 2 bytes considering 16-bit
computer.

1000 1001 1002 1003 1004 1005 1006


5000 5001
pi 1000
p1

5000 5001
1) pi++; pi 1002

5000 5001
2) pi+=2; pi 1004

pi = (pi + 2) = 1000 + 2*(size of int)


pi = (pi + 2) = 1000 + 2*2
pi = (pi + 3) = 1004

S.No. Pointer Expression Meaning


1)

2)

3)

4)
C LANGUAGE

Table 1.26

69
Chapter 1

Pointer to pointer:
y When the address of a pointer variable is stored in another variable, it
is called pointer to a pointer variable.
y Similarly, one can have a pointer to pointer to a pointer variable, and
this can be extended to any limit.
Syntax: data_type **ptr;
here: ptr is a pointer to pointer

Example: int a = 15;


int *ptra = &a;
int **pptra = &ptra;
4000 3000 2000

3000 2000 15

pptra ptra a

Table 1.27
C LANGUAGE

Sol: (

70
Chapter 1
Pointers and arrays:
y Elements of an array are stored in contiguous memory location.
int a[5] = {10, 11, 12, 13, 14};
Let int occupy 2 bytes.
Then:

1000 1002 1004 1006 1008


10 11 12 13 14
a[0] a[1] a[2] a[3] a[4]

base address (1000)

y There is a close-knit relationship between a pointer and an array. Array


name is a pointer that only refers to the initial address of the array
known as the base address of the array.
y Compiler accesses the array elements by converting subscript notation
to pointer notation.
y Since the name of the array is a constant pointer that points to the
first element of the array, therefore by pointer arithmetic when pointer
variable is incremented, it points to fix the location of its base type,
thereby making it possible to access all the elements of the array.

Example:
int a[5] = {10, 11, 12, 13, 14};

Representation Equivalent to Value

C LANGUAGE

Table 1.28

71
Chapter 1

Pointer to an array:
y Useful in multidimensional Arrays
Syntax:
data_type pointer[array size];
int *ptr[10];//ptr is a pointer to an array of size 10.

Example:
Program to differentiate between pointer to integer and pointer to an array
of integer.
#include <stdio.h>
main() {
int *p;
int(*ptr)[5];
int a[5] = {1, 2, 3, 4,};
p = a; // points to the first element of array a
ptr = a; // points to the whole array a.
printf(“ p = %u , ptr = %u \n”, p, ptr);
p++; ptr++;
printf(“ p = %u, ptr = %u \n”, p, ptr);
}
Output:
//(let int occupy 2 byte)
p = 1000, ptr = 1000
p = 1002, ptr = 1010
C LANGUAGE

Fig. 1.44

72
Chapter 1
Also, sizeof(p) = 2 sizeof(*p) = 2
sizeof(ptr) = 2 sizeof(*ptr) = 10

Pointers and 2D arrays:


y In 2-D arrays, the first subscript represents rows and the second
subscript represents column.

Example: int a[3][4] = {{10, 11, 12, 13}, {20, 21, 22, 23}, {30, 31, 32, 33}};

y 2D arrays are stored in Row major order, i.e. rows are placed next to
each other.

Fig. 1.45
a: points to 0th 1-D array →address(100)
(a+1): points to 1st 1-D array →address(108)
(a+2): points to 2nd 1-D array →address(106)
Hence: (a+i) points to ith element of a or points to ith 1-D array of a
Now: *(a+i) gives the base address of ith 1-D array.
Both(a+i) and *(a+i) are pointers but their base types are different, here:
(a+i) is an array of 4 integers
*(a+i) is equivalent to a[i] which is integer value here.
C LANGUAGE

73
Chapter 1

Table 1.29
Considering the above Example:

Fig. 1.46
Pointers and 3-D arrays:
y Elements are accessed using 3 sub-scripts
int a[2][3][2] = {{{1, 10}, {2, 11}, {3, 12}},
{{4, 13}, {5, 14}, {6, 15}}};
y A 3-D array is considered to be an array of 2-D arrays, where each
elements is a 2-D array.
C LANGUAGE

74
Chapter 1
Representation Meaning

Table 1.30

!
C LANGUAGE

75
Chapter 1

Rack Your Brain

Let int a[3][2][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};


(Assume int of 2 bytes and array start from 100), then fill the table:

Representation Meaning

Table 1.31
C LANGUAGE

Sol: ( )

76
Chapter 1
Sol: ( )

Pointers and functions:


y Arguments to the functions can be passed in two ways:
1) Call by value.
2) Call by reference.
y function can return pointers too.
Syntax:
type *func(type1, type2 ….);
float *func(int, char); // function returns pointer to float.

Example:
int *fun()
{int x = 5;
int *p = &x;
return p;
}
main()
{int *ptr;
ptr = fun();
–––––
–––––
–––––
}
C LANGUAGE

Let x be stored at 1000 address, then p = 1000.

77
Chapter 1

Character pointer and functions:


• Character pointers are used to initialize string constant.

Example: char *ptr = “Demo”;


Here ptr is a character pointer which points to the first character
of the string constant “Demo”, i.e, the base address of this string
constant.

Table 1.32 String as Arrays vs String as Pointers


C LANGUAGE

78
79
C LANGUAGE Chapter 1
Chapter 1

:
a) b)
c) d)

Sol: a) ( )
C LANGUAGE

80
Sol:

Sol:

81
C LANGUAGE Chapter 1
Chapter 1

1.10 Structures:
Basics of structures:
y A structure is a group of items in which each item is identified by its
own identifier, each of which is known as a member of the structure.
y Used to store related fields of different data types.
y Capable of storing heterogeneous data.

Student

Name Roll No. Mark


(String) (int) (float)

Fig. 1.47
Syntax: struct student{
char name[20];
int roll no;
float marks;
};

Fig. 1.48
Both declaration creates three variable which enables access individual
structure members as:

stu1.name, stu1.rollno, stu1.marks;


Let char occupy 1 byte, int 2 bytes and float 4 bytes then the entire structure
student would reserve (1×20+2+4) = 26 bytes.

Structure initialization:
C LANGUAGE

y The number, order, and type of values must be same as the structure
template/ definition.

82
Chapter 1
y The initializing values can only be constant expressions.
struct student {
char name[20];
int roll no;
float marks;
} stu1 = {“Ravi”, 13, 98};
struct student stu2 = {“Ravi”, 24, 86};

Size of structure

Size of size of (stu1)


(struct student)
size of (stu2)

Fig. 1.49
1.10.2 Array of structures:
y each element of an array is a structure type.

Example: struct student stu[10];


Here stu is an array of 10 elements where each element is a structure
having three members name, roll no &marks.

Example:
Program to sort by roll no.(bubble sort)
#include <stdio.h>
struct stud
{int roll;
char code[25];
float marks;
C LANGUAGE

};

83
Chapter 1

main()
{struct stud class[100], t;
int j, k, n; scanf (“Enter the number of students”, & n);
for (k=0; k<n; k++)
scanf(\”Enter roll no., dept code and marks”
%d %s %f”, &class[k].roll, &class[k].code, &class[k].marks);
for(j=0; j<n-1; j++)
for(k=j+1; k<n; k++)
{if(class[j].roll > class[k].roll}
{t=class[j];
class[j]=class[k];
class[k]=t;
}
}
for(k=0; k<n; k++){
printf(“roll no %d code %s marks%f\n”, class[k].roll, class[k].code,
class[k].marks);
}
Arrays within structure:
y C allows the use of arrays as structure members.

Example:
struct student {
char name[20];
int rollno;
int submarks[4];
};
The array submarks represent subject marks. Each student has Four
subject and each subject mark is denoted by submarks[0], submarks[1],
submarks[2], submarks[3].

, .
C LANGUAGE

84
Chapter 1
Pointers to structures:
y A pointer to a structure stores the start address of a structure variable.
Example:
struct student {
char name[20];
int roll no;
int marks;
};
struct student stu, *ptr;
y ptr is a pointer that can point to the variable of type struct student.
ptr = &stu;
Accessing members through structure pointer

*
(*ptr).name; (*ptr).name;
(*ptr).rollno; (*ptr).rollno;
(*ptr).marks: (*ptr).marks:
() parenthesis are necessary arrow operator formed by
since precedence, is greater combination of hypen (-)
than *operator and greater than (>) symbol.
C LANGUAGE

has the same precedence as


operator and associativity from
left to right.
      Fig. 1.50

85
Chapter 1

Structures and functions:


y structures can be passed as arguments to functions. A function can
have a return value as a structure.

1) 1)
2) 2)

3) 3)

Table 1.33

Example:
Program to add two complex numbers.
#include <stdio.h>
struct complex {float re; //real part
float in; //imaginary part
}
struct complex x, y;
struct complex add(x,y)
{struct complex t;
t.re=x.re+y.re;
t.im=x.im+y.im;
return(t);}
main()
{struct complex a, b, c; // variables a, b, c
C LANGUAGE

printf(“enter two complex numbers”);


scanf(“%f %f\n”, &a.re, &a.im);

86
Chapter 1
scanf(“%f %f\n”, &b.re, &b.im);
c=add(a,b);
printf(“The addition of real no. a and b are %f %f \n”, c.re, c.im);
}

Here the complex no. a has two parts real represented as a.re and imaginary
represented as a.im. Similarly, for complex no. b and the result of the
addition of complex no. c.

Example:
Program to add complex no. using pointers.
#include <stdio.h>
struct complex{
float re;
float im;
} struct complex *x, *y, *t;
void add(x, y, t)
{ t → re = x → re + y → re;
t → im = x → im + y → im;
}
main()
{ struct complex a, b, c;
printf(“enter two complex no.”);
scanf(“%f %f\n” &a.re, &a.im);
scanf(“%f %f”, &b.re, &b.im);
add(&a, &b, &c);
printf(“the addition of a and b are %f %f”, c.re, c.im);
}
Self-referential structures:
y Structure that contains pointers to structures of its own type
Syntax:
struct tag {
datatype member1;
datatype member2;
–––––––––
–––––––––
–––––––––
struct tag *ptr1;
struct tag *ptr2;
C LANGUAGE

87
Chapter 1

Here struct tag is a self-referential structure as it contains Two pointers


ptr1 and ptr2 of type struct tag.
Linked lists are the most popular application of self-referential data
structures.
A linked list has two parts, a data and a pointer, which together form a
node.

Pointer address of next node.


Data

Node

Information
part

Syntax: struct node {int info;


struct node *link;
}
Union:
y It is also a collection of heterogeneous data types.
y The only difference between struct and union is the way memory is
allocated to its members.
y In structure: each member has its own memory location
y In union: members share the same memory location.
y When a or the union is declared, the compiler allocates sufficient
memory to hold the largest member in the union.
Note: Union is used for saving memory
Syntax: union name
{
datatype member1;
datatype member2;
––––
––––
};
Similar to structures, unions can have union variables to access the
members
C LANGUAGE

88
Chapter 1
Arrays of union can be Function can take and
declared return union variables
Union can be
as argument
nested

Features of union

Pointer to union
possible
Union can be
self referential

Fig. 1.51

a) b) c) d)

Sol: a) ( ) C LANGUAGE

89
Chapter 1

declaration

a)
b)
c)
d)

Sol: a) ( )

Typedef:
y allows you to define a new name for an existing datatype.
Syntax: typedef datatype_name new_name;

Example: typedef int marks;


y now marks is a synonym for integer i.e marks sub1, sub2;
C LANGUAGE

90
91
C LANGUAGE Chapter 1
Chapter 1

Chapter Summary

y C-programming given by Dennis Ritchie in 1972.


y Some of its features are portability, syntax based, case-sensitive, middle level,
simple yet powerful, fast and efficient.
y The character set includes alphabets, digits and symbols. C has a total of 32
keywords.
y Components of basic C-program;

y C has integer, float, double and character as primary data types and structure,
union, and enumeration as secondary or user-defined data types.
int will normally be the natural size for a particular machine. short is often 16 bits
long, and int is of 16 or 32 bits. Each compiler allocates storage to each data type
based on the hardware, subject only to the the restriction that shorts and ints are
at least 16 bits, longs are at least 32 bits, and short is no longer than int which is
no longer than long.
y Datatype size is machine-dependent.
y C has four storage classes, namely automatic, static, external and register, that
C LANGUAGE

specify the lifetime, scope, initial value & place of storage of a variable.

92
Chapter 1
y C has Arithmetic, Assignment, increment decrement, relational, logical, conditional,
comma, sizeof, and bitwise operators to perform various operations.
y Operators are either unary(one operand) or binary(two operands)
y The conditional operator is a ternary operator(?:)
y C supports both implicit and explicit type conversion.
y Precedence and associativity play a vital role in expression evaluation.

y C has three control statement categories namely: 1. selection statements: if, if-
else, switch, 2. iteration statements: for, while, do while, 3. jump statements:
break, continue, goto, return.
y C has two type of function: user-defined and library functions.

y The library functions are in the header files; hence to use these functions in a
program one, needs to include the header files.
y Functions that are defined by the programmer are called user-defined functions.
y Functions aim at making the code modular, compact, understandable, easy to
modify, reusability and altogether avoid repetition of code.
y Function can be called with some argument; these are actual and formal arguments/
parameters.
y Actual arguments / parameters are the ones in the function calls.
y Formal arguments / parameters are the ones in the function definition.
Return Function
type name

Function call
C LANGUAGE

93
Chapter 1

y Recursion is a major application of function but is not preferred as a good


programming practice due to the memory and time requirement overhead.
y Pass by value/call be value and pass by reference/ Call by reference are two major
value passing techniques in C.
y In pass by value, a copy of actual arguments is stored in formal arguments. The
changes in formal argument not reflected back to the actual arguments.
y In pass by reference, the address of actual arguments is passed, and changes in
formal arguments are reflected in actual arguments.
y A pointer is a variable which stores the memory address of another variable.
Pointers are what make C-programming language really powerful.
y Pointers help in implementing various data structures such a linked lists, trees,
and graphs, helps in returning one or more values from functions, provide easy
access to array elements, and play major role in dynamic memory allocations. Also
makes the code compact, modular and efficient.
y Some of the valid operations on pointer include the addition of integer to a pointer,
subtraction of an integer from a pointer, increment and decrement of pointers,
subtraction of same type pointers.
y Pointers are used in function in the call by reference function calling.
y Structure and unions are user-defined structures which are heterogeneous. Both
can store multiple data types.
y The only difference is that structures reserve memory locations for each
datatype, whereas unions reserve memory location for only the largest number of
union(members share the memory location).
y Self-referential structures are used to implement data structures such as linked
lists.
C LANGUAGE

94

You might also like