You are on page 1of 24

C Notes

The Int Types


An int was originally intended to be the "natural" word size of the processor. Many
modern processors can handle different word sizes with equal ease.

It is int which causes the greatest confusion. Some people are certain that an int has 16
bits and sizeof(int) is 2. Others are equally sure that an int has 32 bits and sizeof(int) is 4.

Who is right? On any given compiler, one or the other could be right. On some compilers,
both would be wrong. I know of one compiler for a 24 bit DSP where an int has 24 bits.

The actual range of values which the signed and unsigned int types can hold are:

A signed int can hold all the values between INT_MIN and INT_MAX inclusive.
INT_MIN is required to be -32767 or less, INT_MAX must be at least 32767. Again,
many 2's complement implementations will define INT_MIN to be -32768 but this is
not required.

An unsigned int can hold all the values between 0 and UINT_MAX inclusive.
UINT_MAX must be at least 65535. The int types must contain at least 16 bits to hold
the required range of values.

NOTE: The required ranges for signed and unsigned int are identical to those for signed and unsigned
short. On compilers for 8 and 16 bit processors (including Intel x86 processors executing in 16 bit mode,
such as under MS-DOS), an int is usually 16 bits and has exactly the same representation as a short. On
compilers for 32 bit and larger processors (including Intel x86 processors executing in 32 bit mode, such as
Win32 or Linux) an int is usually 32 bits long and has exactly the same representation as a long.

The Short Int Types


There are two types of short int, signed and unsigned. If neither is specified the short is
signed. The "int" in the declaration is optional. All 6 of the following declarations are
correct:
short x; x is a signed short int
short int x; x is a signed short int
signed short x; x is a signed short int
signed short int x; x is a signed short int
unsigned short x; x is an unsigned short int
unsigned short int x; x is an unsigned short int

The range of the short int types:

1 Sphoorthy Engineering College


C Notes

A signed short can hold all the values between SHRT_MIN and SHRT_MAX inclusive.
SHRT_MIN is required to be -32767 or less, SHRT_MAX must be at least 32767.
Again, many 2's complement implementations will define SHRT_MIN to be -32768 but
this is not required.

An unsigned short can hold all the values between 0 and USHRT_MAX inclusive.
USHRT_MAX must be at least 65535.

The short types must contain at least 16 bits to hold the required range of values.

On many (but not all) C implementations, a short is smaller than an int. Programs which
need to have very large arrays of integer values in memory, or store very large numbers
of integers in files might save memory or storage space by using short in place of int if
both of the conditions below are met:
1. Short is truly smaller than int on the implementation.
2. All of the required values can fit into a short.

NOTE: On some processor architectures code to manipulate shorts can be larger and
slower than corresponding code which deals with ints. This is particularly true on the
Intel x86 processors executing 32 bit code, as in programs for Windows (NT/95/98),
Linux, and other UNIX derivatives. Every instruction which references a short in such
code is one byte larger and usually takes extra processor time to execute.

The Long Int Types


There are two types of long int, signed and unsigned. If neither is specified the long is
signed. The "int" in the declaration is optional. All 6 of the following declarations are
correct:
long x; x is a signed long int
long int x; x is a signed long int
signed long x; x is a signed long int
signed long int x; x is a signed long int
unsigned long x; x is an unsigned long int
unsigned long int x; x is an unsigned long int

The range of the long int types:

A signed long can hold all the values between LONG_MIN and LONG_MAX inclusive.
LONG_MIN is required to be -2147483647 or less, LONG_MAX must be at least
2147483647. Again, many 2's complement implementations will define LONG_MIN to
be -2147483648 but this is not required.

2 Sphoorthy Engineering College


C Notes

An unsigned long can hold all the values between 0 and ULONG_MAX inclusive.
ULONG_MAX must be at least 4294967295. The long types must contain at least 32
bits to hold the required range of values.

The Long Long Int Types (C Only)


64 bit processors have been readily available in workstations for several years, and they
will be coming to desktop computers soon. These processors can address enough memory
to have arrays with more elements than a 32 bit long can specify. Inexpensive disk drives
in use today can hold a file which contains more bytes than a 32 bit offset can reach. The
requirement for an integer type required to hold more than 32 bits is obvious.

The 1999 update to the ANSI/ISO C language standard has added a new integer type to
C, one that is required to be at contain at least 64 bits.

Included in this update are the new variable types signed and unsigned long long . The
selected name comes from gcc and several other compilers which already provide this
type as an extension. On 32 bit Windows compilers from Microsoft, Borland (and maybe
others) this same extension has the name __int64.

While the C++ standard is quite new and most likely will not change for several years, it
is almost certain that C++ compilers will add support for these types as well. The C++
compilers which come with the implementations mentioned above do.

There are two types of long long int, signed and unsigned. If neither is specified the long
long is signed. The "int" in the declaration is optional. All 6 of the following declarations
are correct:

long long x; x is a signed long long int


long long int x; x is a signed long long int
signed long long x; x is a signed long long int
signed long long int x; x is a signed long long int
unsigned long long x; x is an unsigned long long int
unsigned long long int x; x is an unsigned long long int

The range of the long long int types:

A signed long long can hold all the values between LLONG_MIN and LLONG_MAX
inclusive. LLONG_MIN is required to be -9223372036854775807 or less,
LLONG_MAX must be at least 9223372036854775807. Again, many 2's complement
implementations will define LLONG_MIN to be -9223372036854775808 but this is not
required.

3 Sphoorthy Engineering College


C Notes

An unsigned long long can hold all the values between 0 and ULLONG_MAX inclusive.
ULLONG_MAX must be at least 18446744073709551615. The long types must contain
at least 64 bits to hold the required range of values.

Values In <limits.h>
The standard header <limits.h> contains macros which expand to values which allow a
program to determine information about the ranges of values each integer type can hold
at run time. Each of these types (except for "plain" char, that is char without a signed or
unsigned in front of it) must be able to contain a minimum range of values.

Type <limits.h> Constant Minimum Value

SCHAR_MIN -127
signed char
SCHAR_MAX 127

0
unsigned char
UCHAR_MAX 255

CHAR_MIN
"plain" char (note 1)
CHAR_MAX

SHRT_MIN -32767
signed short
SHRT_MAX 32767

0
unsigned short
USHRT_MAX 65535

INT_MIN -32767
signed int
INT_MAX 32767

0
unsigned int
UINT_MAX 65535

LONG_MIN -2147483647
signed long
LONG_MAX 2147483647

0
unsigned long
ULONG_MAX 4294967295

LLONG_MIN -9223372036854775807
signed long long
LLONG_MAX 9223372036854775807

4 Sphoorthy Engineering College


C Notes

0
unsigned long long
ULLONG_MAX 18446744073709551615

Note 1: On implementations where default " plain" is signed, CHAR_MIN is equal to


SCHAR_MIN and CHAR_MAX is equal to SCHAR_MAX. If "plain" char is unsigned,
CHAR_MIN is 0 and CHAR_MAX is equal to UCHAR_MAX.

OPERATORS:

C includes a large number of operators which fall into different categories. These are
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators
 Unary Operators
 Conditional Operators
 Bit-Wise Operators

Arithmetic Operators:

To solve most programming problems we need to perform arithmetic operations by


writing arithmetic expressions. The following table shows all arithmetic operators
provided by C.
Arithmetic Meaning Declarations: int a=5, b=16
Operators Double c=3.0, d=7.5
Integer Examples Floating Point
Examples
+ Addition a + b is 21 c + d is 10.5

_ Subtraction a – b is -11 c - d is -4.5


b – a is 11 d – c is 4.5
* Multiplication b * a is 80 c * d is 22.5

/ Division a / b is 5 c / d is 0.4
b / a is 3 d / c is 2.5
% Remainder a % b is 5
(Modulo b % a is 1 Not Possible
Division)

Each operator manipulates two operands, which may be constants, variables, or other
arithmetic expression. The arithmetic operators may be used with int or double data type

5 Sphoorthy Engineering College


C Notes

operands. On the other hand, the remainder operator also known as modulus operator can
be used with integer operands to find the remainder of the division.

 When both operands in an arithmetic expression are integers, the expression is


called as integer expression, and the operation is called integer arithmetic.
 When both operands in an arithmetic expression are floating point numbers, the
expression is called floating point expression or real expression, and the operation
is called floating point arithmetic or real arithmetic.
 The result of an integer arithmetic always have integer value.
 The remainder operator (%) requires that both operands be integers and the
second operand be non zero.
 The division operator requires the second operand be nonzero.
 The result of integer division results in a truncated quotient (i.e. the decimal
portion of the quotient will be dropped).
 If a division operation is carried out with two floating point numbers or with one
floating point number and one integer, the result will be a floating point quotient.
For example 7.5/5=1.5.
 If one of both operands are negative then the addition, subtraction, multiplication,
and division operations will result in values whose signs are determined by the
usual rules of algebra.
 The result of the remainder operation always gets the sign of first operand. For
examples

If a=14 and b=5 then a % b=4


If a=-14 and b=5 then a % b = -4
If a = -14 and b = 5 then a % b = -4
If a= -14 and b = -5 then a % b = 4
 Operands the differ in type may undergo type conversion before the expression
takes on its final value. In general, the final result will be expressed in the highest
precision possible, consistent with the data type of the operands.

For example

Operand 1 Operand 2 Result

Short Int Int

Int Float Float

Double Float Double

Double Int Double

Int Long Long

6 Sphoorthy Engineering College


C Notes

Relational Operators:

Relational Operators are used in C to compare values, typically in conditional control


statements. The four relational operators in c are <,<=,>,>=. There are two equality
operators = = and !=. They are closely associated with the relational operators.

Relational Operator Meaning


< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Equality Operators Meaning
== Equal to
!= Not equal to

The double equal sign ‘= =’ used to compare equality is different from the single equal to
‘=’ sign which is used as an assignment operator.
These six operators are used to form logical expressions, which represent conditions that
are either true or false. The result of the expressions is of type integer, since true is
represented by the integer value 1 and false is represented by the value 0.

Declarations: int i=3, j=7;


flaot f=5.5,g=4.5
Expression Interpretation Value
i< 4 True 1
(i + j <= 10 True 1
f >g True 1
f <= g False 0
j/i != 2 False 0

Among the relational and equality operators each operator is a complement of another
operator in group.

Using complement operators we can simplify the expressions as

7 Sphoorthy Engineering College


C Notes

Original Expression Simplified Expression


!(a<b) a>=b
!(a>b) a<=b
!(a!=b) a= =b
!(a<=b) a>b
!(a>=b) a<b
!(a= =b) a!=b

Logical Operators:

In addition to arithmetic and relational operators, C has 3 logical operators for combining
logical values and creating new logical values. These operators are
Logical Operator Meaning
! NOT
&& Logical AND
|| Logical OR
NOT:
The NOT operator (!) is a unary operator (Operator that acts upon single operand). It
changes a true value (1) to false (zero) and a false value to true.

AND:
The AND operator (&&) is a binary operator. Its result is true only when both operands
are true; otherwise it is false.

OR:
The OR operator (| |) is a binary operator. Its result is false only when both the operands
are false; otherwise true.

Declarations: int i=3, j=7;


double f=5.5 , g=4.5
char ch=’T’
Expression Interpretation Value
(i<= 5) && (ch = = ‘T’) True 1
(j < 8) || (ch = = ‘L’) True 1
(f + g) = = 10.0 | | I < 2 True 1
F >= 6 | | (i*j)<15 False 0
!(f>5.0) False 0

Assignment Operator:

Assignment operator assigns the value of expression on the right side of it to the variable
on the left of it. The assignment expression evaluates the operand on the right side of the
operator (=) and places its value in the variable on the left. Assignment expressions that
make use of assignment operator have the form:

8 Sphoorthy Engineering College


C Notes

Identifier = expression;

Where identifier represents a variable and expression represents a constant, a variable or


a more complex expression.

Ex: a = 2;
Area = length * width;

Note:

 If the two operands in an assignment expression are of different data types, then
the value of the expression on the right side of assignment operator will
automatically be converted to the type of the identifier on the left of assignment
operator.

For example
 A floating value may be truncated if it is assigned to an integer identifier.
 A double value may be rounded if it is assigned to a floating point identifier.
 An integer value may be changed if it is assigned to a short integer identifier or to
a character identifier.

Unary Operators:

The operators that act upon a single operand to produce a new value are known as unary
operators. C supports the following unary operators.

Operators:

Minus operator –
Increment operator ++
Decrement operator - -
Size operator
(type) operator

Minus operator –

The most common unary operation is a unary minus, where a numerical constant,
variable or expression is preceded by a minus sign. It is important to note that the unary
minus operation is distinctly different from the arithmetic operator which denotes
subtraction (-). The subtraction operator requires two separate operands.

Ex: -123, -qty, -4E-8

Increment and Decrement Operator

9 Sphoorthy Engineering College


C Notes

The increment operator (++) adds 1 to the operand, whereas the decrement operator (--)
subtract 1 from the operand. The increment and decrement operators can each be used in
two different ways, depending on whether the operator is written before or after the
operand. For example
a++; /* operator is written after the operand */
++a; /* operator is written before the operand */

If the operator precedes the operand (e.g., ++a), then it is called pre-increment operator
and the operand will be changed in value before it is used for its intended purpose within
the program. On the other hand, if the operator follows the operand (i.e a++), then it is
called post-increment operator and the value of the operand will be changed after it is
used.

sizeof Operator:

In C, an operator sizeof is used to calculate size of various datatypes. These can be basic
or primitive datatypes present in the language, as well as the ones, created by
programmer. The sizeof opearator looks like a function, but it is actually an operator that
returns the length, in bytes. It is used to get size of space any data-element/datatype
occupies in memory. If type name is used, it always needs to be enclosed in parentheses,
whereas variable name can be specified with or without parentheses.

Ex:

int i;

sizeof i;
sizeof(int);

Type Conversion (Cast Operator)

Rather than let the compiler implicitly convert data, we can convert data from one type to another
by using cast operator. To cast data from one type to another it is necessary to specify type in
parentheses before the value we want to be converted. For example to convert integer variable
count, to a float we code the expression as

(float) count;

Since cast operator is an unary operator, we must put binary expression to be casted in
parentheses to get the correct conversion. For example

(float) (a+b)

One use of the cast is to ensure that the result of a division is a floating point number. In case of
division, proper casting is necessary.

Conditional Expressions

10 Sphoorthy Engineering College


C Notes

Simple conditional operations can be carried out with the conditional operator (? :). The
conditional operator (? :) is a ternary operator since it takes three operands. The general form of
conditional expression is

Test expression ? expression 1 : expression 2;

Conditional operator works as follows:

 The test expression is implicitly converted to Boolean expression. It is evaluated.


 If the result of test expression is true(1), the expression 1 is evaluated and the conditional
expression takes on value of expression 1.
 If the result of test expression is false (0), the expression 2 is evaluated and the
conditional expression takes on value of expression 2.

Therefore the result of the conditional operator is the result of whichever expression is evaluated
– the first or the second. Only on of the last 2 expressions is evaluated in a conditional
expression.

Bitwise operators

The bitwise operators are the bit manipulation operators. They can manipulate individual
bits within the piece of data. These operators can operate on integers and characters but
not on floating point numbers or numbers having double data type.

Operator Description Example

The bitwise complement operator is an Operand = 1111 0000 1111 0000


unary operator. It complements each bit ~ operand
~
of the operand. Resulted
Operand = 0000 1111 0000 1111
The bitwise AND operator compares Operand 1 = 1111 1111 1111 0000
each bit of its first operand to the Operand 2 = 1111 0000 1111 0000
corresponding bit of its second operand.
&
If both bits are 1, the corresponding X= operand 1 & operand 2
result bit is set to 1. Otherwise the Then
corresponding bit is set to 0. X= 1111 0000 1111 0000
The bitwise inclusive OR operator Operand 1= 0000 1111 0011 0000
compares each bit of its first operand to Operand 2= 1111 1111 0000 1111
the corresponding bit of its second
| operand. If either of bits is 1 the X=operand 1 | operand 2
corresponding result bit is set to 1, Then
otherwise the corresponding bit is set to X= 1111 1111 0011 1111
0.
^ The bitwise exclusive OR operator Operand 1= 1111 0000 1100 0011
compares each bit of its first operand to Operand 2= 1111 1111 0011 0011
the corresponding bit of its second

11 Sphoorthy Engineering College


C Notes

operand. If one bit is 0 and the other bit X= operand 1 ^ operand 2


is 1 the corresponding result bit is set to Then
1 otherwise result bit is set to 0. X= 0000 1111 1111 0000
The bitwise shift left operator is a binary Operand 1 = 1111 0000 1111 0001
operator. The first operand is the value Operand 2 = 1
<<
to be shifted and the second operand X=operand 1 << operand 2
specifies the number of bits to shifted. X= 1110 0001 1110 0010
The bitwise right shift operator is a Operand 1 = 1111 0000 1111 0000
binary operator. The first operand is the Operand 2 = 2
>> value to be shifted and the second X = operand 1 >> operand 2
operand specifies the number of bits to X=00 1111 0000 1111 00
be shifted.

Operator Precedence and Associativity

Operator precedence describes the order in which c evaluates different operators in a


complex expression. For example, in the expression a = 4+b*2, which happens first, the
addition or the multiplication? The operator precedence will tell us which operation
should perform first. The operator which is having highest precedence will evaluate first
and the operator which is having lowest precedence evaluate last. If two operators are on
the same level of precedence then the order they will be evaluated in is going to be
considered. This is knows as Associativity property of an operator.

Operator Operator Description Associativity Precedence


Type Level
Parentheses, () Parentheses
Left to right 1
Braces [] Brackets
++ -- Unary pre increment / pre
decrement
+ - Unary plus / minus

! ~ Unary Logical negation /


Unary bitwise complement Right to left 2
(type) Unary cast

& Address

Size of Determine Size in bytes


Binary Multiplication / Division/
* / % Left to right 3
Modules
Addition / Subtraction
+ - Left to right 4
<< >> Bitwise shift left, bitwise Left to right 5
shift right

12 Sphoorthy Engineering College


C Notes

Relational less than / less


< <=
than or equal to
Left to right 6
Relational greater than /
> >=
greater than or equal to
Relational is equal to / is
= = != Left to right 7
not equal to
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
Logical AND
&& Left to right 11
Logical OR
|| Left to right 12

Ternary (Conditional)
Ternary ? : Right to left 13

Assignment
=
Addition/Subtraction
+= -=
Assignment
Multiplication/Division
*= /=
Assignment
Assignment Right to left 14
Modulus/bitwise AND
%= &=
assignment
Bitwise exclusive/inclusive
^= !=
OR assignment
Bitwise Shift left/right
<<= >>=
assignment
Comma (separate
Comma , Expression) Left to right 15

INPUT & OUTPUT STATEMENTS

Reading data, processing it and writing the processed data known as information or a
result of a program are the essential functions of a program. The C is a functional
language. It provides a number of macros and functions to enable the programmer to
effectively carry out these input and output operations. Some of the input/output
functions / macros in C are
1. getchar() 2. putchar()
3. scanf() 4. printf()
5. gets() 6. puts()

13 Sphoorthy Engineering College


C Notes

The data entered by the user through the standard input device and processed data is
displayed on the standard output device.

I/O Functions:

I / O functions are grouped into two categories.

 Unformatted I/O functions


 Formatted I/O function.

The Formatted I/O functions allows programmers to specify the type of data and the way
in which it should be read in or written out. On the other hand, unformatted I/O functions
do not specify the type of data and the way is should be read or written. Amongst the
above specified I/O functions scanf() and printf() are formatted I/O functions.
Function Formatted Unformatted
Input scanf() getchar(),gets()

Output printf() putchar(),puts()

Formatted Output – The printf function

C provides the printf function to display the data on the monitor. This function can be
used to display any combination of numerical values, single characters and strings. The
general form of printf statement
Function name

Function arguments

printf(“my roll number is %d. \n”, rollno)

control string print list


The %d is known as a placeholder or conversion character or format code or format
specifier. At the time of display the value of the specified variable is substituted at the
place of placeholder. In out example, value of rollno is substituted in place of %d. The
printf uses different placeholders to display different type of data items.

Placeholder Type of Data Item displayed

%c Single character

%d Signed decimal integer

%e Floating point number with an exponent

%f Floating point number without an exponent

14 Sphoorthy Engineering College


C Notes

%g Floating point number either with exponent or without exponent


depending on value. Trailing zeros and trailing decimal point
will not be displayed.
%i Singed decimal number
%o Octal number, without leading zero
%s String
%u Unsigned decimal integer
%x Hexadecimal number, without leading zero

There are certain letters which may be used as prefix for certain placeholders. These are

h: the h letter can be applied to d,i,o,u and x placeholders. The h letter tells printf() to
display short integers. As an example, %hu indicates that the data is of type short
unsigned integer.

l: the l letter can be applied to d,i,o,u and x placeholder. The l letter tells printf() to
display long integers. As an example, %ld indicates that the data is of type long integer.
When it is applied to f, it indicates double data type.

L: the L letter, when applied to f indicates long double data type.

Some important points to remember

 Control string must be enclosed within the double quotes.


 For every data item to be displayed there must be a placeholder corresponding to
its data type.
 Multiple placeholders are allowed in the control string. In such a case they may be
contiguous or separated by blank spaces or commas.
 The data items must be included in the print list and they must be separated by
commas.
 Print list is not enclosed within double quotes.
 The comma must be used to separate the format string and the print list.
Formatting integer output

We have seen that how integer numbers can be displayed on the monitor using %d
placeholder. In case of integer numbers, the placeholder can accept modifiers to
specify the minimum field width and left justification by default, all output is right
justified. We can force the information to be left justified by putting a minus sign
directly after the %. For example
printf statement Output (assume x=1234)

15 Sphoorthy Engineering College


C Notes

1 2 3 4
printf(“%d”,x);

1 2 3 4
printf(“%6d”,x);

Right justified

1 2 3 4
printf(“%-6d”,x);

Left justified

As shown in the above examples, if the number width in digits is less than the minimum
field width the empty places are filled with spaces. However if the number width is
greater than the minimum field width, the number is printed in the full, overriding the
minimum field width specification. This is illustrated in the following list.

It is also possible to pad the empty places with zeros. If we want to pad with zeros, we
have to place a zero before the minimum field width specifier.

printf statement Output (assume x=1234)

1 2 3 4
printf(“%3d”,x);
Overriding the minimum field width
0 0 1 2 3 4
printf(“%06d”,x);
Padding with zeros

As shown in the above examples, if the number width in digits is less than the minimum
field width the empty places are filled with spaces. However if the number width is
greater than the minimum field width, the number is printed in the full, overriding the
minimum field width specification. This is illustrated in the following list.

It is also possible to pad the empty places with zeros. If we want to pad with zeros, we
have to place a zero before the minimum field width specifier.

printf statement Output (assume x=1234)


printf(“%3d”,x);
1 2 3 4

16 Sphoorthy Engineering College


C Notes

Overriding the minimum field width

0 0 1 2 3 4
printf(“%06d”,x);
Padding with zeros
Formatting floating point output

In case of floating point numbers placeholder can accept modifiers that specify the
minimum field width, precision and left justification. To add a modifier we have to place
a decimal point follower by the precision after the field width specifier. For e and f
formats, the precision modifier determines the number of decimal places to be displayed.
For example %8.4f will display a number at least 8 characters wide including decimal
point with four decimal places.

printf statement Output (assume x=3456.12065)

3 4 5 6 . 1 2 0 6 5 0
printf(“%f”,x);
Default precision is 6

3 4 5 6 . 1 2
printf(“%7.2f”,x);

Total 7 characters wide out of 2 are decimal point

3 4 5 6 . 1 2
printf(“%9.2f”,x);

Right justified

3 4 5 6 . 1 2
printf(“%-9.2f”,x);

left justified

3 . 4 5 6 E + 0 3
printf(“%9.3e”,x);

3 decimal places and total 9 characters wide

Formatting String Output

17 Sphoorthy Engineering College


C Notes

When the precision is applied to strings, the number preceding period specifies the
minimum field width and the number following the period specifies the number of
characters of the string to be displayed. For examples %16.9s will display a string that
will be at least sixteen characters long; however only first nine characters from the string
are displayed with remaining blank characters. Let us see the important points related to
formatted string display.

 When minimum field width is specified without negative sign, display is right
justified.
 When only minimum field width is specified and it is less than the actual string
length, the minimum field width is overridden and complete string is displayed.
 We can insert negative sign before minimum field width to get left justified
display.

printf Output (assume str: “THIS IS A TEST STRING”


statement containing 21 characters including blanks.)

T H I S I S A T E S T S T R I N G
printf(“%s”,str);

T HI S I S A T ES T S T R I NG
printf(“%24s”,
str);

T H I S I S A T ES T
printf(“%24.14s
”,str);

Escape Sequences to enhance the readability of output

The backslash symbol( \ ) is known as escape character. Since the newline character and
the tab character begin with backslash they are called escape sequences. They are

Escape Function
Sequences
Newline : Displays the message or variable values following it on
\n
the next line.
Tab: Moves cursor to the next tab
\t

18 Sphoorthy Engineering College


C Notes

Backspace: Moves cursor one position to the left of its current


\b
position.
Form feed: Advances the computer stationary attached to the
\f
printer to the top of next page.
Single Quote: Displays single quote
\’
Backslash: Displays backslash
\\
Double Quote: Displays double quote
\”
Carriage Return : Takes the cursor to the beginning of the line in
\r
which it is currently placed.
Alert: Alerts the user by sounding the speaker inside the computer.
\a

Functions

In structural programming, the program is divided into small independent tasks. These
tasks are small enough to be understood easily without having to understand the entire
program at once. Each task is designed to perform specific functionality on its own.
When these tasks are performed, their outcomes are combined together to solve the
problem. Such a structural programming can be implemented using modular
programming. In modular programming, the program is divided into separate small
programs called modules. Each module is designed to perform specific function. Modules
make out actual program shorter, hence easier to read and understand. A defined function
or set of similar functions is coded in a separate module or sub module, which means that
code can be loaded into memory more efficiently and that modules can be reused in other
programs. After a module has been tested individually, it is then integrated with other
modules into the overall program structure.

Each module can be subdivided according to software engineering principles. The


following structural chart shows the relation between each module and its sub module.
Such a design approach is called top-down design.

Main
Module

Module Module Module


1 2 3

19 Sphoorthy Engineering College


Module Module Module Module Module Module Module
1A 1B 1C 2A 2B 3A 3B
C Notes

The main module is known as a calling module because it has submodule. Each of the
sub module is known as called modules. However, modules 1, 2 and 3 also have sub
modules therefore they are also calling modules. The communication between modules
in a structure chart is allowed only through a calling module. If module 1 need to send
data to module 2, the data must be passed through the calling module, main module. No
communication can take place directly between modules that do not have a clling-called
relationship. This means that in a structural chart, a module can be called by one and only
one higher module.

There are several advantages of modular / structural programming, some of them are

Reusability: Many programs require that a particular group of instructions accessed


repeatedly, from several different places within the program. The repeated instructions
can be placed within a single function, which can then be accessed wherever it is needed.
This avoids rewriting of group of instructions on every access.

Easy Debugging: Since each function is smaller and has a logical clarity, it is easy to
locate and correct errors in it.

Build Library: The use of functions allows a programmer to build a customized


library of frequently used routines or system-dependent features. Each routine can
programmed as a separate function and stored within a special library file. Building
libraries reduce the time and space complexity and promote the portability.

Basics of Functions

A function by definition, is a procedure or routine. In other words, it’s a self-contained


block of code that executes a certain task. Although some languages do distinguish
between procedure and function, whereas a function returns a value of some kind and a
procedure does not, C combines both functionalities into its definition. In order to use
function in the program we need to establish 3 elements that are related to the function.

20 Sphoorthy Engineering College


C Notes

 Function Declaration: All identifiers in C need to be declared before they are


used. This is true for functions as well as variables. For functions the declarations
needs to be before the first call of the function.
 Function Definition: It is actual code for the function to perform the specific
task.
 Function Call: In order to use function in the program we use function call to
access the function. The program or function that calls the function is referred to
as calling program or calling function.

Ex:

#include <stdio.h>

print_msg(); /* The function Declaration */

void main() /* the main function */


{
print_msg(); /* The function call */
}

print_msg() /* the function definition */


{

printf(“this is a module called print_msg \n”);

So a function is a self contained independent program segment that performs a specific


task and optionally returns a value to the calling function.

 A function is defined by a function name followed by a pair of parentheses.


A function is defined as follows:

<return-type> <function name> (list of arguments)


{
Declarations
Statements
[return expression]
}

Ex:
The following is function that computes the xn for given values of x and n.

float power(float x,int n)


{
float p=1.0; int k;

21 Sphoorthy Engineering College


C Notes

for(k=1;k<=n;k++)
p=p*x;
return p;
}

 The function is called from another function. For example, we can call the above
function form main(). This function returns the value of xn.
power(x,n);

 Depending upon whether arguments are passed or not, and whether a value from the
function is returned or not, can be classified into the following four categories.

i. Functions with no arguments and no return value


ii. Functions with no arguments and return value
iii. Functions with arguments and no return value
iv. Functions with arguments and return value.

 A function is declared in the calling function, as stated below:

<return-type> <function-name> (<argument types>);

For example, the function is declared as function prototype:

float power(float,int);

 The arguments passing from the calling function are known as actual parameters; the
parameters in the called function are named as formal parameters. The following is an
example:

If we call power(x,n) from the main(), then the actual arguments are x and n. In the called
function, float power(float p, int q), p and q are formal argument or parameters. After
execution of this function, the function returns a float-point value to the calling function.

Actual & Formal Arguments or Parameters


Actual Arguments Formal Arguments

22 Sphoorthy Engineering College


C Notes

When a function is called, the data is A function definition starts with the type
passed from a calling function as of the function. The function name is
arguments. These arguments are known followed by a list of argument declaration
as actual arguments. Following is an within parentheses. The arguments act as
example of calling function. placeholders for values that are passed
when function is called. These are called
main() formal arguments. A function example:
{
float func(float,int); float func(float y, int m)
…… {
func(x,n); ……..
…… return …..;
} }

Actual arguments: x,n Formal arguments: y,m

The names of the formal arguments The actual and formal arguments must
need not be the same as the names of the match in number, type and order.
actual arguments.

Actual arguments must be assigned The values of the actual arguments are
values before a function call is made. assigned to the formal variables on a one-
to-one basis.
When a function call is made, only a
copy of the values of actual arguments is The formal arguments y and m are local to
passed to the called function. The the function.
processing inside the called function
does not have any effect on the variables
used in the actual argument list.

Global & Local Variables

Global Variables Local Variables

23 Sphoorthy Engineering College


C Notes

The global variables are declared The variables declared within a function
outside a function. These variables are are called local variables. Their scope and
available to all the functions of a life-time exists as long as the execution of
program. Example the function. Local variables vanish when
function is terminated.
int a,b,c; /* global variable */
main() int func1()
{ {
….. flaot x,y; /* local variables */
Func1(); ........
Func2(); x=a+b ;
} y=b*c+10 ;
.........
When we declare variables as global, }
they are automatically initialized to zero
in case of numeric variables, and null in Local variables contain garbage values if
case of character variables. they are not initialized.

Call by Value & Call by Reference

Pass by value OR Call by Value Pass By Reference OR Call by


Reference
By default, all values of the actual To change the values of variables in the
arguments of a function are passed by calling function, the address of the
“pass by value”. When a function is variables are passed as arguments to the
called from a function (calling function), called function. If the variables are
the values are stored temporarily in modified in the called function, then this
formal arguments of the “called effect will be reflected in the calling
function”. A called function cannot function. This phenomenon is known as
access the actual memory locations of “pass by reference”.
the actual arguments, and therefore, For a function to effect “call by
cannot change the contents of actual reference” pointers are used in the
arguments of the calling function. The argument list in the function definition.
called function does not affect values of Then, when the function is called,
the calling function. addresses of variables are passed as
arguments.

24 Sphoorthy Engineering College