C Notes
C Notes
C LANGUAGE
Chapter 1
1) C-PROGRAMMING
1.1) Basics of c-programming
Case sensitive
Powerful
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
1
Chapter 1
Token:
Smallest individual unit (Keywords, identifiers, constants, strings, special
symbols, operators).
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.
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.
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.
Example:
Table 1.2
C LANGUAGE
4
Chapter 1
Constants:
y Value that cannot be changed during the execution of the program
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
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
E C LANGUAGE
7
Chapter 1
1) Primary datatypes:
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
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.
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:
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
(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
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
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
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
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
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
20
Chapter 1
AND operator (&&):
y Binary operator represented as &&.
a constant
21
Chapter 1
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
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
23
Chapter 1
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);
Example:
sizeof(int); would return the bytes occupied by integer datatype.
C LANGUAGE
24
Chapter 1
Rack Your Brain
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
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.
Fig. 1.18
27
Chapter 1
28
Chapter 1
Highest Rank
long double
double
float
unsigned int
int
Lowest Rank
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
Lower Higher
Datatype Datatype
C LANGUAGE
Fig. 1.20
29
Chapter 1
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
Increase the
readability of
code
Fig. 1.21
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
33
Chapter 1
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
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
}
Output: 1 2 3 4 5
37
Chapter 1
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);
39
Chapter 1
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.29
C LANGUAGE
43
Chapter 1
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.
Example:
Void Function Non-void Function
void func() return_datatype func()
{ { return value;
} }
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) ( )
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
1) M
2) C
3) C
C LANGUAGE
Table 1.22
48
Chapter 1
Syntax:
return_type function_name (arguments)
{
Statement;
_________
_________
_________
}
Function
49
Chapter 1
Types of functions
(on basis of return type & Arguments)
With Without
Arguments Arguments
}
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)
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
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
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
1)
2)
3)
4)
5)
6)
7)
C LANGUAGE
8)
Table 1.23
58
Chapter 1
!
C LANGUAGE
59
C LANGUAGE Chapter 1
60
Chapter 1
1)
2)
3)
4)
5)
C LANGUAGE
6)
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:
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
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”.
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.
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
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.
5000 5001
1) pi++; pi 1002
5000 5001
2) pi+=2; pi 1004
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
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:
Example:
int a[5] = {10, 11, 12, 13, 14};
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
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
Representation Meaning
Table 1.31
C LANGUAGE
Sol: ( )
76
Chapter 1
Sol: ( )
Example:
int *fun()
{int x = 5;
int *p = &x;
return p;
}
main()
{int *ptr;
ptr = fun();
–––––
–––––
–––––
}
C LANGUAGE
77
Chapter 1
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
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:
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
Fig. 1.49
1.10.2 Array of structures:
y each element of an array is a structure type.
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
85
Chapter 1
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
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
Node
Information
part
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;
90
91
C LANGUAGE Chapter 1
Chapter 1
Chapter Summary
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
94