Chapter-1
1. About the language- C was designed by Dennis Ritchie in early 70’s to support development
and implementation of Bell Lab’s Unix OS.
C is a general purpose programming language which features economy of expression, modern
control flow and data structures, and rich set of operators.
In 1983, the American national standards Institute (ANSI) established a committee to provide
a modern, comprehensive definition of C. The resulting definition, the ANSI standard or ANSI
C was completed late in 1988.
Important Note: these notes are base on ANSI standards. That means the contents are
applicable to VAX C and they are fully portable to any other environment (like DOS, UNIX)
where ANSI compatible C compiler is available. Any deviations have been specifically marked.
2. Program Structure- Every programm must have a function called ‘main’.
- The function ‘main’ in turn calls other functions to perform specific jobs.
- A function in C is composed of statements.
- Every statement ends with a semicolon.
- It is totally “free form” language.
- Comments begin with /* and ends with */
Example:
#include <stdio.h>
/* include information about standard library */
main()
/* define a function main that receives no arguments */
/* statements of main are enclosed in braces */
printf(“hello, everybody”);
Comments do not nest, and they do not occur within a string or character literals.
3. Variables- All variables used in a program must be declared.
- Variables can be initialized when they are declared.
- Variable names are made up of letters and digits.
- First character must be letter and cannot be a digit.
- The underscore is counted as a letter.
- Upper and lower case are different.
Prof. Sarvpal Singh
Department of IT & Computer Application
- At least first 31 characters of an internal name are significant. For external names, the
number may be less than 31, because external names may be used by assemblers and
loaders over which the language has no control. For external names, the standard
guarantees uniqueness only for 6 characters and a single case.
- The following identifiers are reserved for use as keywords, and may not be used
otherwise:
auto double int struct break else long
switch case enum register typedef char external
return union const float short unsigned
continue for signed void default goto sizeof
volatile do if static while
Examples of valid variable names include v1, v2, numDigits etc.
4. Data Types and Sizes- there are only a few basic data types in C:
char : a single byte, capable of holding one character
int : an integer
float : single-precision floating point
double : double-precision floating point
In addition, there are a number of qualifiers that can be applied to these basic types, like:
(i) Short & long provide different lengths of integers; short is often 16 bits, long 32 bits.
However, int without qualifier will have default of 16 or 32 bits depending on system.
(ii) The qualifiers signed or unsigned may be applied to char or any other integer;
unsigned numbers are always positive or zero.
(I) Integers
Keyword Size Range
char 8 bits (1 byte) -128 to 127
short 16 bits (2 bytes) -32768 to 32767 These are specific
unsigned int 32 bits (4 bytes) 0 to 4294967295 to VAX C
int, long 32 bits (4 bytes) -2147483648 to
2147483647
(II) Floating point numbers
Keyword Size Range
float 32 bits (1 byte) 6 to 7 These are specific to
double 64 bits (2 bytes) 15 to 16 VAX C
5. Constants- C has four basic types of constants:
(i) Integer constants: An integer constant is an integer valued consists of any
combinations of digits taken from the set 0 through 9.
An octal integer constant can consists of any combination of digits taken from the set
0 through 7. The octal integer must be preceded by a digit 0.
A hexadecimal integer constant must begin with either 0X or 0x. It can then be
followed by any combination of digits taken from the set 0 through 9 and ‘a’ through
‘f’.
Prof. Sarvpal Singh
Department of IT & Computer Application
An unsigned integer constant can be identified by appending the letter u or 0 to the
end of the constant.
It is possible to create a long integer constant by appending the letter L to the end of
the constant.
Example:
257 0743 0x77ff 5000u 123456789L represent int, octal int, hexadecimal int,
unsigned int, and long respectively.
(ii) Floating point constants: it is a base-10 number that or an exponent (or both).
Example:
500 827.602 315.0077 2E-8 0.006e-3
(iii) Character constants: A character constant is a single character, enclosed in
apostrophes (single quotation marks).
Example:
‘A’ ‘x’ ‘3’ ‘$’ ‘b/’
Character constants have corresponding integer values which are their ASCII values.
Example:
Constant Value
‘A’ 5
‘x’ 120
‘3’ 51
‘$’ 36
‘b/’ 32
(iv) String Constants: A string constants of any number of consecutive characters
(including none) enclosed in (double) quotation mark.
Example:
“queen” “Line” “12” “” (null string)
The compiler automatically places a null character (‘\p’) at the end of every string
constant, as the last character within the string.
Note: A character constant(‘P’) and the corresponding single-character string constant (“P”)
are not equivalent. A character constant has an equivalent integer value, where as a
single-character string constant does not have an equivalent integer value and in fact
constants of two characters, the specified character followed by the null character
(‘\0’).
Note: Character constants participate in numeric operations just as any other integers.
(v) Some escape sequences-C uses certain combinations of characters, such as \b, \n, \t,
to represent special conditions such as backspace, newline and horizontal tab. These
character combinations are known as escape sequences. Each escape sequence
represents a single character.
\a : bell, \b : backspace, \f : form feed
\n : newline , \r : carriage return
\t : tab, \v : vertical tab, \0 : null character
6 Declarations- A declaration associates a group of variables with a specific data type.
All variables must be declared before they can appear in executable statements.
A declaration consists of a data type followed by one or more variable names ending
with a semi-colon.
Example:
Int a, b, c;
Prof. Sarvpal Singh
Department of IT & Computer Application
float root;
short w;
long fact;
Initial values can be assigned to variables within a type declaration.
Examples:
int i=1;
char c=’b’;
7 Input-Output Functions- C provides a standard library of routines for I/O; all input and
output is done via functions. This library requires a corresponding header file named
stdio.h. this file has to be included in the program.
Format: #include<stdio.h>
a) The simplest input mechanism is to read one character at a time from the
standard input using the getchar function.
Getchar returns the next input character each time it is called or EOF when it
encounters end-of-file. (CTRL_Z is used as a terminator to end the input)
The symbolic constant EOF is defined in <stdio.h>
b) The function putchar prints a character each time it is called.
Putchar returns EOF if an error occurs.
Format: character-variable=getchar();
Putchar(character-variable);
Example:
#include<stdio.h>
main()
{
char c,b;
c=getchar();
putchar(c);
putchar(‘\n’);
b=’a’;
putchar(b);
putchar(‘\n’);
putchar(97); /* character with ASCII 97 */
putchar(‘\n’);
}
Input : z
Output : z
a
a
II. Formatted Input and Output
(a) printf function
The output of printf translates internal values of characters. Printf converts,
formats and prints its arguments on the standard output. It returns the
number of characters printed.
Format: printf(format string, arg1, arg2, ............ argN)
The format string contains two types of objects: ordinary characters, which
are copied to the output string and conversion specifications. Each conversion
specification begins a % sign and ends with a conversion character.
Basic printf conversion characters
d, i : decimal number
o : octal
Prof. Sarvpal Singh
Department of IT & Computer Application
u : unsigned decimal number
c : single character
s : string
f : double (default precision is 6 decimal digits)
x, X : hexadecimal
Example:
int i=5;
float j=7.655;
char c= ‘a’;
printf(“%d %f %c”, i, j, c);
Output is :5 7.655000
(b) scanf function
input data can be entered into the computer from a standard input device by
means of the C library function scanf. This function can be used to enter any
combination of numerical values, single characters and strings. The function
returns the number of data items that have been entered successfully. In
general terms, the scanf function is written as :
format: scanf(format string, arg1, arg2, .............. argN)
where format string refers to a string containing certain required format string
required formatting information, and arg1, arg2, ........... argN are arguments
that represent the individual input data items.
The format string comprises individual groups of characters, with one
character group for each input data item. Each character group must begin
with a percent sign (%). In its simplest form, a single character group will
consists of the percent sign (%), followed by a conversion character which
indicates the type of the corresponding data item.
Within the control string, multiple character groups can be contiguous, or they
can be separated by whitespace characters (i.e. blank spaces, tabs or new line
characters). If white space characters are used to separate multiple character
groups in the control string, then all consecutive whitespace characters in the
input data will be read but ignored.
Basic scanf conversion characters
c : single character
d : decimal integer
f : floating point
s : string
u : unsigned decimal integer
The arguments are written as variables or arrays, whose types match the
corresponding character groups in the control string. Each variable name
must be preceded by an ampersand (&). However, array names should not
begin with an ampersand.
Example:
#include<stdio.h>
Prof. Sarvpal Singh
Department of IT & Computer Application
main()
char item;
int p;
float c;
scanf(“%c %d %f”,&item, &p, &c);
On end-of –file EOF is returned, which means that the next input character
does not match the first specification in the format string.
Scanf stops when it exhausts its format string, or when some input fails to
match the control specification, given through format string.
Example: A program to print the ASCII value of a character accepted from the
terminal.
#include<stdio.h>
main()
char c;
c=getchar();
printf(“ASCII value of %c is %d”, c, c);
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise -1
Part A
Q1 Fill in the blanks:
(a) Basic data types in C are ______, ______, _______, and _______
(b) ________________ terminates a statement in C.
(c) The symbols ______, and _______ mark the beginning and end of a comment.
(d) Every C program must have a function called __________
(e) In a variable name the first character must be _____________
Q2 State TRUE/FALSE:
(a) All variables must be declared before their usage in a program.
(b) An integer variable will be initialized to zero automatically if not done explicitly.
(c) Comments must be restricted to one line only.
(d) Comments must begin at the start of a line only.
(e) getchar(c) accepts the value of c from the terminal.
(f) putchar function prints a string on the terminal.
Part B
Write a program which inputs 2 character using getchar() and swaps them.
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter-II
Operators
1 Arithmetic operators
- Binary operators are + - * / and %
- % is the modulus operator which returns the remainder of an integer division. Integer
division truncates the fractional part of the quotient. The % operator cannot be applied
to or double variables.
Example:
To accept a 2-digit number character by character and find the sum of its digits
#include<stdio.h>
main()
{
int res;
char digit1, digit2;
digit1=getchar();
digit2=getchar();
res=0;
res=res+digit1-‘0’;
res=res+10+digit2-‘0’;
printf(“Result= %d”, res);
}
2. Type conversions
Conversion rules:
These rules apply to arithmetic operations between two operators with dissimilar data
types. There may be some variation from one version of c to another.
a) If one of the operands is double, the other will be converted to double and the result will
be double.
b) Otherwise, if one of the operands is float, the other will be converted to float and the
result will be float.
c) Otherwise, convert char and short to int.
d) Then, if one of the operands is long, the other will be converted to long and the result
will be long.
3. Cast operator
The value of an expression can be converted to a different data type, if desired. To do so,
the expression must be preceded by the name of the desired data type, enclosed in
parentheses, i.e. (data type) expression. This type of construction is known as cast.
The dat type associated with the expression itself is not changed by a cast. Rather, it is
the value of the expression that undergoes type conversion wherever the cast appears.
Examples:
float i, j, k;
i=12.65;
j=5.35
k=i+j
printf(“\n %f “,k);
k=(int) i + (int) j;
printf(“\n %f “,k);
Output is :
18.000000
17.000000
Prof. Sarvpal Singh
Department of IT & Computer Application
4. Sizeof operator
Another unary operator available is the sizeof operator. This operator returns the size of
its operand, in bytes. This operator always precedes its operand.
Sizeof(object) yields an integer value corresponding to the size of the specified object in
bytes. The object can be a variable, an array or any basic data type.
Example:
#include<stdio.h>
main()
{
int i;
printf(“%d\n”,sizeof(int));
printf(“%d\n”,sizeof(i));
}
Output:
4 | This output may be changed under
4 | environments other than VAX C
5. Relational operator
There are 4 relational operators in C, namely
< less than
<= less than or equal to
> greater than
>= greater than or equal to
The relational operators have lower precedence than arithmetic operators.
Closely associated with the relational operators are the two equality operators:
== equal to
!= not equal to
These six operators are used to form logical expressions representing conditions that are
either TRUE or FALSE. The resulting expressions will be of type integer, since TRUE is
represented by the integer value 1 and false is represented by the value 0.
6. Logical operator
In addition to the relational and equality operators, C contains two logical operators.
These are :
&& and
|| or
These operators are referred to as logical and and logical or respectively.
C also includes the operator ‘|’ that negates the value of an expression and is known as
the logical not operator.
7. Unary operator
Unary operators usually precede their single operators though some unary operators are
written after their operands.
Two commonly used unary operators are the increment operator, ++ and the decrement
operator, --. The increment operator causes its operand to be increased by one, where
as the decrement operator causes its operand to be decreased by one. The operand used
with each of these operators must be a single variable.
Format: variable++ (post increment)
++variable(pre increment)
Variable-- (post decrement)
-- Variable (pre decrement)
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
(i) a++ ➔ a=a+1
(ii) a-- ➔ a=a-1
(iii) a=b++ ➔ a=b b=b+1
(iv) a=++b ➔ b=b+1 a=b
Example:
main()
{
int i;
i=1;
printf(“i=%d\n”,i);
printf(“i=%d\n”,++i);
printf(“i=%d\n”,i);
}
Output is :
i= 1
i=2
i=2
8. Assignment operators
The most commonly used assignment is ‘=’. Assignment expressions that make use of
this operator are written in the form.
Identifier=expression;
Where identifier generally represents a variable and expression represents a constant,
a variable or a more complex expression.
Note: The assignment operator = and the equality operator == are distinctly different. The
assignment operator is used to assign a value to an identifier, where as the equality
operator is used to determine if two expressions have the same value.
If two operands in an assignment expression are of different data types, then the value
of the expression on the right will automatically be converted to the type of the
identifier on the left. Under some circumstances, this automatic type conversion can
result in an alteration of the data being assigned.
- A floating point value may be truncated if assigned to an integer identifier.
- A double-precision value may be rounded if assigned to a floating point identifier.
- An integer quantity may be altered if assigned to a shorter integer identifier or to a
character identifier.
C contains the following additional assignment operator: +=, -=, *=, /=, and %=
The assignment expression
expr1 += expr2
is equivalent to
expr1=expr1+expr2
and similarly for the other operators.
Assignment rules
If the two operands in an assignment expression are of different data types, then the
value of the right hand operand will automatically be converted to the type of the
operand on the left. The entire assignment expression will then be of this same data
type. Moreover,
a) A floating-point value may be truncated if assigned to an integer identifier.
b) A double-precision value may be rounded if assigned to a floating-point (single-
precision) identifier.
Prof. Sarvpal Singh
Department of IT & Computer Application
c) An identifier quantity may be altered if assigned to a shorter identifier or to a character
identifier (some high-order bits may be lost).
Example:
int i, j;
float f, g;
i=5;
j=7;
f=5.5;
g=-3.25;
Expression Value
i+=5 10
f-=g 8.75
j*= j-3 14
j /=3; 1.833333
i %=j-2; 0
9. Precedence
The operators within C are grouped hierarchically according to their precedence.
Operations with a high precedence are carried out before operations having a lower
precedence. The natural order of evaluation can be altered, however, through the use
of parentheses.
Another important consideration is the order in which the consecutive operations within
the same precedence group are carried out. This is known as associtivity.
Operator Precedence Groups
Category Operators Associativity
Function, array, structure member, () [] . -> L --->R
pointer to structure member
Unary operators - * & - ++ -- ! R --->L
sizeof(type)
Arithmetic operators * / % L --->R
Arithmetic operators - + L --->R
Bitwise shift operators << >> L --->R
Relational operators < <= > >= L --->R
Equality operators == != L --->R
Bitwise and & L --->R
Bitwise exclusive or ˆ L --->R
Bitwise or | L --->R
Logical and && L --->R
Logical or || L --->R
Conditional operator ?: R --->L
Assignment operator = += -= *= /= %= R --->L
Comma , L --->R
Prof. Sarvpal Singh
Department of IT & Computer Application
10 Bitwise operators
C provides six operators for bit manipulation; these may only be applied to internal
operands, i.e. char, short, int and long, whether signed or unsigned.
& bitwise and
| bitwise inclusive or
ˆ bitwise exclusive or
<< left shift
>> right shift
~ one’s complement
These operators are discussed in detail in chapter XIII.
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise -2
Part A
Q1 Fill in the blanks :
a) ____________ operator is used to forcibly convert a data type into another.
b) The symbols for logical AND and OR are _______________ and ________
c) _________ operator negates the truth value of the expression following it.
d) The _____________ binary operator is used for multiplication.
Q2 What will be displayed in each of the following:
a) a=7;
b=a++;
printf(“%d”, b);
b) a=7;
b=++a;
printf(“%d”,b);
c) a=5;
while(a)
{
printf(“Hello”);
a--;
}
e) a=5;
while(a--)
printf(“Hello”);
Part B
Q1 Differentiate between:
a) = and ==
b) “/” and “%” operator
Q2 Write a program to calculate the area of a circle after accepting the radius of the circle
from the standard input.
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter III
Control Statements
There three different kinds of statements in C:
(i) Expression statements
(ii) Compound statements
(iii) Control statements
An expression statement consists of an expression followed by a semicolon. A
compound statement or a block of a sequence of two or more consecutive statements
enclosed in braces; the statements within the braces may be expression statements,
other compound statements or control statements. There is no semicolon after the right
brace that ends a block.
1 If-else- statement
The if- else statement is used to express decisions. Formally, the syntax is
if(expr)
st1
[else
St2]
Where the else part is optional. The expression is evaluated; if it is TRUE (i.e. if
expression has a non-zero value), statement 1 is executed. If it is FALSE (expression is
zero) and if there is an else part, statement 2 is executed instead.
(i) Nested if-else
It is possible to nest if-else statements within one another.
if(expr 1)
st 1
else if(expr 2)
st 2
else if(expr 3)
st 3
else if(expr 4)
st 4
else
st 5
Consider the following construction
if(expr1)
if(expr2)
st 1
else
st2
In this case, it should be noted that the expression 2 is associated with the else clause.
This is also clear from the indentation. But the same construction is written as follows
if(expr 1)
if(expr 2)
st 1
else
st 2
is the same as the above case, although the indentation is not correct.
The rule in such cases is that the else clause is always associated with the closest
preceding unmatched (i.e., else-less) if.
Prof. Sarvpal Singh
Department of IT & Computer Application
It is equivalent to
if(expr 1)
{
if(expr 2)
st 1
else
st 2
}
If we want to associate the else clause with expr 1 rather than expr 2, we can do as
follows
if(expr 1)
{
if(expr 2)
st 1
}
else
st 2
2 The conditional operator
The simple conditional operations can be carried out with the conditional operator (? :)
A conditional expression is written in the form
expression1 ? expression2 : expression3
When evaluating a conditional expression, expression1 is evaluated first. If expression1
is true (i.e. if uts value is non-zero), then expression2 is evaluated and this becomes the
value of the conditional expression. However, if expression1 is false (i.e. if its value is
zero) then expression3 is evaluated and this becomes the value of the conditional
expression.
The conditional expression is basically interpreted as
if(expression1)
expression2;
else
expression3;
Example:
(i) To find the greatest among two numbers a, b and store it in c.
int a, b, c;
c=(a > b)? a : b;
(ii) int i, j, k, p;
j=5;
k=7;
p=2;
i=(0) ? ((j > k) ? 0 : 5) : ((p > j) ? 7 : 1);
in this case, i will get the value 1.
3 The while loop
The while loop statement is used to carry out looping operations. The general form is :
While(expression)
statement
The expression is evaluated. If it is non-zero, the statement is executed and the
expression is re-evaluated.
Prof. Sarvpal Singh
Department of IT & Computer Application
This execution resumes after the statement. The statement can be simple or compound
though it is typically a compound statement. It must include some feature which
eventually alters the value of expression, thus providing a stopping condition for the
loop.
Example:
/* To print the digits 0 to 9 */
#include <stdio.h>
main()
{
int i;
i=0;
while( i< 10)
{
printf(“%c\n”, i);
i++;
}
}
Example:
/* Program to accept characters until EOF and display them */
#include <stdio.h>
main()
{
char c;
while((c= getchar())!=EOF)
putchar(c);
}
4 The for loop
The for loop statement is perhaps the most commonly used looping statement in C. This
statement includes an expression that specifies an initial value for an index, another
expression that determines whether or not the loop is continued and a third expression
that allows the index to be modified at the end of each pass.
The general form is:
for( expr 1; expr 2; expr 3)
statement
Typically, expr1 is an assignment, expr2 is a logical expression and expr3 is a unary
expression or an assignment expression.
The for statement is equivalent to
expr 1;
while (expr 2)
{
statement
expr 3;
}
The looping action will continue as long as the value of expr 2 is not zero ; i.e. as long as
the logical condition represented by expr 2 is true.
Any of the three expressions can be omitted, although the semicolons must remain.
If expr 1 or expr3 is omitted, it is simply dropped from the expansion. If the expression
2 is not present, it is taken as permanently TRUE, so
for(; ;)
;
Is an infinite loop, presumably to be taken by other means, such as a break or return.
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
/* display the numbers 0 through 9 */
#include <stdio.h>
main()
{
int d;
for ( d=0; d<=9; ++d)
printf(“%2d”,d);
}
5 The comma operator
This operator is used primarily in conjunction with the for statement. This operator
pertains two different expressions to appear in situations where only one expression
would ordinarily be used. e.g., it is possible to write:
for(expr 1a, expr 1b; expr2; expr 3a, expr 3b)
statement
Note that the comma operator accepts two distinct expressions as operands. These
expressions will be evaluated from left to right.
Example:
for(i =10, j=0; j<10; ++j, --j)
printf(“%d %d\n”, i, j);
6 The do while statement
When a loop is constructed using the while statement, the test for continuation of the
loop is carried out at the beginning of each pass. Sometimes, however, it is desirable to
have a loop with the test for continuation at the end of each pass. This can be
accompanied by means of the do-while statement.
The general form of the do-while statement is
do
statement
while(expression);
The statement will be executed repeatedly, as long as the value of expression is not
zero. Note that “statement” will always be executed at least once, since the test for
repetition does not occur until the end of the first pass through the loop.
Example:
#include <stdio.h>
main()
{
i=5;
do
{
printf(“%d\n”, i);
i+=5;
}while(i < 20 );
Example:
#include <stdio.h>
main()
{
char c;
Prof. Sarvpal Singh
Department of IT & Computer Application
do
{
printf(“\n Menu “);
printf(“\n1. Date Entry “);
printf(“\n2. File maintenance “);
printf(“\n3 Report Generation “);
printf(“\n4 Quit “);
printf(“\n “);
printf(“\n Choice: “);
c=getchar();
}
while(c< ‘1’ || c> ‘4’);
printf(“ Your Choice is : %c “, c);
}
This program will display the menu and accept a choice until a valid choice is entered.
The menu is displayed at once.
7 The break statement
The break statement is used to terminate loops or to exit from a switch. It can be used
within a while, a do-while, a for or a switch statement. The break statement is written
simply as
break ;
without any embedded expressions or statements.
A break causes the innermost enclosing loop or switch to be exited immediately.
Example:
for (c= 0; c <= n; ++c)
{
-
-
while((a = getchar())!=’\n’)
{
if(a== ‘*’ || a==’?’)
break;
-
-
}
putchar(a);
}
8 The continue statement
The continue statement is used to bypass the remainder of the current pass through a
loop. The loop does not terminate when a continue statement is encountered. Rather,
the remaining loop statements are skipped and the computation proceeds directly to
the next pass through the loop.
The continue statement can be included within a while, a do-while or for statement, it
is written simply as
continue;
without any embedded statements or expressions.
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
for(i=1; i<=3; i++)
{
printf(“%d\n”, i)
if(i==3)
break;
printf(“bottom of loop\n”);
when this particular segment is executed, the output is
1
bottom of loop
2
bottom of loop
3
out of loop
Example:
for(i=1; i <= 3; i++)
{
printf(“%d\n”,i);
if(i==2)
continue;
printf(“bottom of loop \n”);
}
printf(“out of loop”);
The output in this case is
1
bottom of loop
2
3
bottom of loop
Example:
/* programme to compute the average of nos. Inputted */
#include<stdio.h>
main()
{
float n, sum;
int count;
. sum=0.0
Count=0;
while(scanf(“%f”, &n) !=EOF)
{
if(n<= 0.0)
continue; /*skip –ve input */
sum+=n;
count++;
}
If(count >0)
Printf(“\n avg.=%f \n”, sum / count);
else
printf(“\n no +ve no. Entered \n”);
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
/* This program prints all the prime integers less than or equal to the user supplied value
n */
#include <stdio.h>
main()
{
int i, n, isPrime;
printf(“\n This program lists all primes <= n\n”);
printf(“Enter n:”);
scanf(“%d”, &n);
for (i=2; i<=n; i++)
{
isPrime =1;
/* try to find a divisor of i */
for(j=2; j<=i / 2; j++)
{
if(i % j ==0)
{
isPrime=0;
break;
}
}
If(isPrime)
printf(“%d\n”, i);
}
}
9. The goto statement
The goto statement is used to alter the normal sequence of program execution by
transferring control to some other part of the program. In this general form, the goto
statement is written as
goto Label;
where Label is an identifier used to Label the target statements to which control will be
transferred.
Control may be transferred to any other statement within the current function. The
target statement must be labelled and the label must be followed by a colon. Thus, the
target statement will appear as
Label : statement
Each labelled statement within the function must have a unique label, i.e. no two
statements can have the same label.
10 The switch statement
The switch statement is a multi-way decision that tests whether an expression matches
one of a number of constant integer values and branches accordingly.
switch (expression)
{
case <const-expr1>:
statement(s)
case <const-expr2>:
statement(s)
default:
statement(s)
Prof. Sarvpal Singh
Department of IT & Computer Application
Each case is labelled by one or more integer- valued constants or constant expressions.
If a case matches the value, execution starts at that case. All case expressions must be
different. The case Labelled default is executed if none of the other cases are satisfied.
A default is optional; if it isn’t there and if none of the cases match, no action takes place
at all. Cases and the default clause can occur in any order.
Note: The (expression) should result in an integer value. The expression may also be of
type char, since individual characters have equivalent integer values.
Const-expr represents a constant integer-valued expression.
The control always “falls through”. Thus an appropriate break statement should be used.
No two case labels can specify the same value. The case and default can occur in any
order.
Example:
/* programs to check the input for vowels */
#include <stdio.h>
#include<ctype.h>
main()
{
char c;
c=getchar();
/* convert c to LowerCase /*
c=(c >= ‘A’ && c<= ‘Z’)? (c+32) : c;
switch(c)
{
case ‘a’ : case ‘e’: case ‘i’: case ‘o’: case ‘u’:
printf(“%c is a vowel”, c);
break;
default:
printf (“not a vowel\n”);
break;
}
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise-3
Part A
Q1 Fil in the blanks :
a) The label is followed by a ____________
b) A string in C is terminated by _______________
c) ____________ statement is used to terminate an immediately enclosing for, while or
switch loop.
d) Only __________ may be used as case label in a switch statement.
e) Absence of break statement in “switch-case” leads to ____________
Part B
Q1 Differentiate between “break” and “continue” giving examples.
Q2 Find the sum of all odd no’s between 1 and 100. Try to use different looping techniques.
Q3 Write a programme to count the number of blanks, tabs and newlines in the input.
Q4 Find the greatest of three numbers using the conditional operator.
Q5 Write a program to calculate the average of the non negative numbers in a list of n
numbers.
Q6 Write a program to accept the integer and check if it can be divided by 3, 6 and 9.
Q7 Write a program that prints the number of occurrences of the character ! in the
standard input.
Q8 Write a program that test whether there are the same number of left brackets, [, as the
right brackets, ], in the standard input.
Q9 Write a program that takes an integer keyed in form the terminal and extracts and
displays each digit of the integer in English.
Q10 Write a program that converts each lower case character in the standard input to
uppercase and each uppercase character to lowercase. Pass all other characters
unchanged.
Q11 Write a program that reads nos. From the standard input and prints the largest value
entered, the smallest value, the sum of all values read and the mean of all values
inputted.
Q12 Using a for loop, write a program that computes and prints the sum of the series:
2 + 4 + ......................................+ 100
Q13 Write a program that replaces two or more consecutive blanks by a single blank.
i.e. if the input is Let’s go for a walk, the output should be
Let’s go for a walk
Prof. Sarvpal Singh
Department of IT & Computer Application
Q14 What will be the output?
I=0;
While(i < 5)
{
If(i < 3)
{
i+=2;
printf(“%d\n”, i);
continue;
}
else
{
printf(“%d\n”, ++i);
Break;
}
printf(“bottom of loop\n”);
}
Q15 Write a program to accept 25 characters and to display whether each character is a
digit, or a lowercase alphabet or an uppercase alphabet.
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter-4
Arrays
1. Introduction
Many applications require the processing of multiple data items that have common
characteristics. In such situations it is often convenient to place the data items into an
array, where they will all share the same name. The individual data items can be
characters, integers, floating point numbers, and so on. They must all, be of the same
type and the same storage class.
Each array element can be individually referred to by specifying the array name
followed by one or more subscripts, with each subscript enclosed in square brackets.
Each subscript must be expressed as a non-negative integer. Thus, in the n element
array x, the array elements are x[0], x[2]............ x[n-1]. The value of each subscript can
be expressed as an integer constant, an integer variable or a more complex integer
expression.
2 Defining an array
Arrays are defined in much the same manner as ordinary variables, except that each
array name must be accompanied by a size specification. In general terms, a one-
dimensional array may be expressed as
Storage-class data-type array [expression];
The storage class is optional; default types are automatic for arrays defined within a
function or a block, and external for arrays defined outside of a function.
Example:
/* program to generate the first 20 Fibonacci numbers */
#include <stdio.h>
main()
{
int fb[20], i;
fb[0]=0; /* by definition */
fb[1]=1; /* by definition */
/* store fib. Number in array */
for (i = 2; j < 20; ++i)
fb[i] = fb[i – 1] + fb[1 – 2];
/* print the array */
For(i = 0; i < 20; ++i)
Printf(“%d\n”, fb[i]);
}
3 Initializing Array Elements
Array definitions can include the assignment of initial values if desired. The initial values
must appear in the order in which they will be assigned to the individual array elements,
enclosed in braces and separated by commas. The general form is
Storage-class data-type array[expression]= (value 1, value 2, .................. value n)
Where value 1 refers to the value of the first array element, value 2 refers to the
value of the second array element and so on. The appearance of the expression, which
indicates the number of array elements, is optional when initial values are present.
Example:
Char color [5] = {‘w’, ‘h’, ‘i’, ‘t’, ‘e’};
int num[10 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
The array size need not be specified explicitly when initial values are included as part of
an array definition. The array size will automatically be set equal to the number of initial
values included within the definition.
Prof. Sarvpal Singh
Department of IT & Computer Application
In particular, when a string constant is assigned to a character array as a part of the
array definition, the array size specification is normally omitted. The proper array size
will be assigned automatically. This will include a provision for the null character ‘\0’,
which is automatically added at the end of every string.
Example:
Consider the following two character array definitions:
char color[6] = “white”;
or
char color[] = “white”;
The assignments are:
color[0] = ‘w’ color[1] = ‘h’ color[2] = ‘i’ color[3] = ‘t’ color[4] = ‘e’ color[5]=’\0’
Note: character strings will be treated as character arrays.
3 String Input / Output
(i) gets()
Gets a string from standard input.
Syntax : sets(s);
gets() collects a string of characters terminated by a new line from the standard
input and stores it into the array S. The new line is replaced by a null character (‘\0’) in
S. gets() allows input strings to contain certain whitespace characters(spaces, tabs).
gets returns when it encounters a new line; everything up to the new line is copied into
S.
It reurns NULL on end of file or error.
Example:
#include <stdio.h>
main()
{
Char s[80];
printf(“Enter a String:”);
gets(s);
printf(“\n The String is : %s”, s);
}
ii puts()
Outputs a string to standard output.
Syntax: puts(s);
Puts copies the null-terminated string S to the standard output and appends a
newline character.
Example:
#include <stdio.h>
main()
{
char s[] = “This is a string”;
puts(s);
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise-4
Part A
Q1 Fill in the blanks:
a) The minimum subscript for an array in C is ___________
b) In C, character strings are treated as _______________
c) The conversion character for setting in “printf” is ______________
d) The number of elements required in a character array to store the string “abc\nd” is
_____________
Part B
Q1 Write a program to find the length of a string.
Q2 Write a program to display the reverse a string.
Q3 Write a program to concatenate a string to the end of another string.
Q4 Write a program to convert a string from lower case to uppercase leaving upper case
characters unchanged.
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter-5
Functions
1 Introduction
The use of programmer defined functions allows a large program to be broken down
into a number of smaller self-continued components, each of which has some unique,
identifiable purpose. Thus, a C program can be modularized through the intelligent use
of such functions.
A function is a self contained program segment that carries out some specific, well-
defined task. Every C program consists of one or more functions. One of these functions
must be called main. Program execution will always begin by carrying out the
instructions in main.
If a program contains multiple functions their definitions may appear in any order
though they must be independent of one another, i.e., one function definition cannot
be embedded within one another.
Generally a function will process information passed to it from one calling portion
of the program and return a single value. Information will be passed to the program and
return a single value. Information will be passed to the function via special identifiers
called arguments and returned via the “return” statement. Some functions however,
accept information but do not return anything where as other functions return multiple
values.
2. Defining a function
Each function definition has the form:
Return-type function-name(arguments declarations)
{
Declarations and statements
}
Various parts may be absent; a minimal function is :
dummy()
{
}
Which does nothing and returns nothing. A do-nothing function like this is sometimes
useful as a place holder during program development. If return type is omitted, int is
assumed.
A program is just a set of definitions of variables and functions communications
between the functions is by arguments and values returned by the functions, and
through external variables (external variables will be discussed at a later stage). The
functions can occur in any order in the source file, and the source program can be split
into multiple files, so long as no function is split.
The return statement is the mechanism for returning a value from the called function
to its caller. Any expression can follow return:
Return expression;
The expression will be converted to the return type of the function if necessary.
Parentheses are often used around the expression, but they are optional.
The calling function is free to ignore the returned value. Furthermore, there need
be no expression after return; in that case, no value is returned to the caller. Control
also returns to the caller with no value when execution “falls off the end” of the function
by reaching the closing right brace. If a function fails to return a value, its “value” is
certain to be garbage.
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
/* Lower-case to Upper case conversion */
toUpper(char c1)
{
char c2;
c2= (c1 >= ‘a’ && c1 <= ‘z’ )? (c1 - 32) : c1;
return c2;
}
3 Accessing a Function
A function can be accessed (called) by specifying its name, followed by a list of
arguments enclosed in parentheses and separated by commas. If the function call does
not require any arguments, an empty pair of parentheses must follow the function
name. The function call may appear by itself, or it may be one of the operands within a
more complex expression..
The arguments appearing in a function called the referred to as actual arguments in
contrast to the final arguments that appear in the first line of the function definition.
Each actual argument must be of same data type as its corresponding formal argument.
If a function returns a non integer quantity and the portion of the program
containing the function call precedes the function definition, then there must be a
function declaration in the calling portion of the program. The function declaration
effectively informs the compiler that a function call will be accessed before it is defined.
A function declaration can be written as
return- type function-name(arguments declarations);
where data-type refers to the data type of the quantity returned by the function, and
name refers to the function name. It is called a “function prototype”. So that the
compiler can validate function calls.
4. Functions returning non-integers
Example:
long factorial(int n)
{
int i;
long prod=1;
if (n > 1)
for( i = 2; i <= n; ++i)
prod *= i;
return prod;
}
The keyword void can appear as return type specifier when defining a function that
does not return anything.
Example:
void max (int x, int y)
{
int z;
z= (x >=y)? X:y;
printf(“\n maximum value = %d ”, z);
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
int func (int , int ) /* function prototype */
main()
{
int a, b, c, d, i, j; /* variable declarations */
....
i= func (a, b);
....
j= func(c, d);
}
Example:
#include<stdio.h>
long fact(int);
main()
{
int n;
printf(“n: ”);
scanf(“%d”, &n);
printf(“n! = %ld”,fact(n));
}
long fact(int n)
{
int i;
long prod=1;
if(n >1)
for(i = 2; i<=n; ++i)
prod*=i;
return prod;
}
Example:
/* Function to convert a string to an integer */
int strToInt(char s[])
{
int i, val, res = 0;
for (i = 0; s[i] >= ‘0’ && s[i] <= ‘9’; ++i)
{
val = s[i] – ‘0’;
res= res * 10 + val;
}
return res;
}
main()
{
printf(“%d\n”,strToInt(“245”));
}
If the function definition precedes all function calls, then it is not necessary to include a
function proto type. It is, however, good programming practice to include proto type,
whether or not it is actually required.
Prof. Sarvpal Singh
Department of IT & Computer Application
5. Passing Arguments to a Function
When a single value is passed to a function via an actual argument, the value of the
actual arguments is copied into the function. Therefore, the value of the corresponding
formal argument within the calling routine will not change. This procedure for passing
the value of an argument to a function is known as passing by value.
Example:
#include<stdio.h>
void modify(int);
main()
{
int a =2;
printf(“a = %d\n”, a);
modify(a);
printf(“a= %d\n”,a);
}
void modify(int a)
{
a *=3;
printf(“a = %d\n”, a);
}
Output:
a =2
a=6
a=2
Arrays are passed differently than single-valued entities. If an array name is specified
as an actual argument, the individual array elements are not copied to the function.
Instead, the location of the array is passed to the function. If an element of the array is
accessed within the function, the access will refer to the location of that array element
relative to the location of the first element. Thus, any alteration made to any array
element within the function will carry over to the calling routine. Such a call can be
referred to as a call by reference.
6 Passing Array to a Function
An array name can be passed as an argument to a function, thus allowing the entire
array to be passed to the function. To pass an array to a function, the array name must
appear by itself, without brackets or superscripts as an actual argument within the
function call. The corresponding formal argument is written in the same manner,
though it must be declared as an array within the formal argument declarations. When
declaring a one dimensional array as a formal argument, the array name is written with
a pair of empty square brackets. The size of the array is not specified within the formal
argument declaration.
Example:
void func(char b[]);
main()
{
char a [10];
func(a);
................
}
Prof. Sarvpal Singh
Department of IT & Computer Application
void func(char b[])
{
.............
.............
}
Example:
/* To sort an array of integers into ascending order */
void sort (int a[], int n)
{
int i, j, temp;
for(i=0; i<n-1; ++i)
for(j=i+1; j<n; ++j)
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
main()
{
int i;
int n[10]={44, -10, 0, 16, 7, 2, 1, 57, -33, 101};
printf(“The array begore sort:\n”);
for (i = 0; i < 10; ++i)
printf(“%d”,n[i]);
sort(n,10);
printf(“The array after sort:\n”);
for (i = 0; i < 10; ++i)
printf(“%d”,n[i]);
printf(“\n”);
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise-5
Part A
Q1 State True/False giving reasons for the false ones:
a) The type returned by a function must be declared.
b) Functions in C always return a value which has to be accepted by the calling function.
c) Arguments in C are always passed by value.
d) For functions returning non integers a function prototype is a must.
e) In a call by value the address of the variable is passed.
Part A
Q1 Write a function int power(int x, int n) to return xn.
Q2 Write a function int sum(int x, int n) which returns the sum of the following series:
2x + 4x + 6x + -------------------- n trems.
Q3 Write a function to return the factorial of a number.
Q4 Write a function, int sum(int x, int n) to return the sum of the following series:
x + x2 / 2! + x3 /3! + ------------------ n terms.
Q5 Write a function int isPrime(int n) that returns 1 if its argument is a prime number, else
return 0.
Q6 Write a function int arrSum(int arr[], int num) that takes two arguments: an integer
array and the number of elements in the array. Hence the function returns as its result,
the sum of elements in the array.
Q7 What is the output:
void f(int x[], int y);
main()
{
int a[5], b, i;
for(i=0; i < 5; i++)
a[i] = 2 * i;
b = 15;
f(a, b);
for( i = 0; i < 5; i++ )
printf(“%d\n”,a[i]);
printf(“%d”, b);
}
void f(int x[], int y)
{
int i;
for(i = 0; i < 5; i++)
x[i]+= 2;
y +=2;
}
Q8 Write a function, void strCat(char strTo[], char strFrom[]) that concatenates two strings
and puts the result into the first argument.
Q9 Write a function void strCopy(char strTo[], char strFrom[]) that copies the string in the
second argument into the first argument.
Prof. Sarvpal Singh
Department of IT & Computer Application
Q10 Write a programme that prompts the user for a string, tests whether it is a palindrome,
and prints an appropriate message. The test should be done in a separate function.
Q11 Write a function int check (char str[], char c) with two parameters ‘str’ & ‘c’ . the
parameter str is a char array, and the parameter c is a character. The function check will
return 1 if c is in ‘str’ & 0 otherwise. Write a main function that calls check.
Q12 Write a function called int find (char source [], char substr[]) to determine if a character
string exists inside another string. If the function finds the specified string, then have it
return the location (offset) in the source string where the string was found. If the
function does not find the string, then have it return -1.
e.g. find(“catastrophe”, “str”);
should return the value 4.
Q13 Write a function int len(char s[]) to return the length of a string s.
Q14 Write a function void reverse (char s[]) to reverse a string.
Q15 Write a function to remove trailing blanks and tabs from a string.
Q16 Write a function void sub(char source[], int start, int count, char res[]) to extract a
portion of a character string where source is the character string from which we are
extracting the substring, start is an index number into source indicating the first
character of the substring, count is the number of characters to be extracted from the
source string, and result is an array of characters that contains the extracted substring.
e.g. sub(“character”, 4, 3, arr);
will extract “act” from the source string and place the result in arr.
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter- 6
Storage Class
There are two different ways to characterize variables: by data type, and by storage
class. Data refers to the type of information represented by variables. Storage class
refers to the performance of a variable and its scope within the program, i.e., the
portion of the program over which the variable is recognized.
There are four different storage class specifications in C:
I) automatic
II) external
III) static
IV) register
They are identified by the keywords auto, extern, static and register respectively.
Example:
auto int i, j, k;
static int w;
extern float root;
1. Automatic variable
a) Automatic variable are always declared within a function and are local to the function
in which they are declared, i.e. their scope is confined to that function. Automatic
variables defined in different functions will therefore be independent of one another,
even though they may have the same name.
b) Automatic variables can be assigned initial values. Such values will be reassigned each
time the function is re entered. If an automatic variable is not initialized in same
manner, however, its initial value will be unpredictable.
c) An automatic variable doesn’t retain its value once control is transferred out of its
defining function. Therefore, any value assigned to an automatic variable within a
function will be lost once the function is exited.
Example:
/* program to calculate the factorial */
#include<stdio.h>
long factorial(int n)
main()
{
int n; /* auto variable */
printf(“integer:”);
scanf(“%d”, &n);
printf(“%d! = %ld”, n, factorial(n));
}
long factorial(int n)
{
int i; /* auto variable */
long int prod = 1; /* auto variable */
if (n > 1)
for (i=2; i <=n; ++i)
prod*=i;
return prod;
}
Note:
Prof. Sarvpal Singh
Department of IT & Computer Application
The scope of an automatic variable can be smaller than an entire function, if they are
declared within a single compound statement.
2 Static variables
a) Static variables are defined within individual functions and therefore have the same
scope as automatic variables, i.e. they are local to the functions in which they are
defined. Unlike automatic variables, however, static variables retain their values
throughout the life of the program. As a result, if a function is exited and re entered
later, the static variables defined within that function will retain their former values.
b) The variable declaration must begin with the static storage class declaration. Static
variables, however, can’t be accessed outside of their defining function.
Note:
We can define automatic variables or static variables having the same name as external
variables. In such situations the local variables will take precedence over the external
variables, though the values of the external variables will be unaffected by any
manipulation of the local variables. Thus, the external variables maintain their
independence with locally defined automatic and static variables. The same is true of
local variables within one function that have same name as local variables within
another function.
c) Initial values can be included in static variable declarations. The initial values are
assigned to their respective variables at the beginning of program execution. The
variables retain these values throughout the life of the program, unless different values
are assigned during the course of computation.
d) Zeros will be assigned to all static variables whose declarations do not include explicit
initial values. Hence static variables will always have assigned values.
Example:
/* illustration of static and automatic variables */
void ast(void)
{
int av =1;
static int sv =1;
printf(“auto=%d static = %d\n”, av, sv);
++av;
++sv;
}
main()
{
int d;
for(d=0; d<5; ++d)
ast();
}
Output is :
auto = 1 Static = 1
auto = 1 Static = 2
auto = 1 Static = 3
auto = 1 Static = 4
auto = 1 Static = 5
Prof. Sarvpal Singh
Department of IT & Computer Application
3 External Variables
a) External variables, in contrast to automatic variables, are not confined to single
functions. Their scope extends from the point of definition through the remainder of
the program.
b) The use of external variables provides a convenient mechanism for transferring
information back and forth between functions. In particular, we can transfer
information into a function without using arguments.
c) An external variable definition is written outside of, and usually before, the functions
that access the external variables.
d) Any alteration to the value of an external variable within a function will be recognized
within the entire scope of the external variable.
e) If the function definition precedes the external variable definition, then the function
must include a declaration for that external variable.
f) An external variable declaration must begin with the storage class specifier extern.
External variables can be assigned initial values as part of the variable definition. These
initial values will be assigned only once, at the beginning of the program.the external
variables will then retain these initial values unless they are later altered during the
execution of the program. If an initial value is not included in the definition of an
external variable, the variable will automatically be assigned a value of zero.
g) Within a multi file program, external variable can be defined in one file and accessed in
another. An external variable definition can appear in only one file. Its location within
the file must be external to any function definition. In order to access an external
variable in another file, the variable must first be declared within that file. This
declaration may appear anywhere within the file. The declared must begin with the
storage class specifier extern. Initial values cannot be included in external variable
declaration.
h) The value assigned to an external variable may be altered within any file in which the
variable is recognized. Such changes will be recognized in all other files that fall within
the scope of the variable.
i) Within a file, external variable can be defined to be static. To do so, the storage class
specifier static is placed at the beginning of the definition. The scope of a ststic external
variable will be the remainder of the file in which it is defined. Other external variables
having the same names can be defined in the remaining files.
Example:
int i; /* external variable declarations */
void fn(void);
main()
{
i=5;
}
void fn(void)
{
i=1 + 1;
printf(“%d”, i);
}
Output is :
i=6
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
multifile programs
first file:
#include<stdio.h>
void outp(void);
main()
{
outp();
}
secondfile:
void outp(void)
{
printf(“function called”);
return;
}
4 Register variables
a) Registers are special storage areas within a computer’s CPU. The actual arithmetic and
logical operations that comprise a program are carried out within these registers.
Normally these operations are carried out by transferring information from the
computer’s memory to these registers, carrying out the indicated operations, and then
transferring the results back to the computer’s memory. This general procedure is
repeated many times during the course of a program’s execution.
b) For many program, the execution time can be reduced considerably if certain values
can be stored within these registers rather than in the computer’s memory, since fewer
data transfers will be required.
c) In C, the values of register variable are stored within the CPU’s registers. A variable can
be assigned this storage class simply by preceding the type of declaration with the
keyword register. Register variables are local to the function in which they are declared.
The address operator (&) cannot be applied to register variables.
VAX C computer does not complain if you apply & on
a register variable. But this is not a standard feature.
Do not rely on it
Note:
Declaring certain variable to be register variable does not guarantee that they will
actually be treated as register variables. The declaration will be valid only if the
requested register space is available. If a register declaration cannot be honoured, the
variables will be treated as having the storage class automatic.
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise-6
PART A
Q1 State true or False
a) If a local variable is declared as static, it exist in the whole program.
b) A static external variable can be accessed by a function in any file.
c) By default, automatic variables are initialized to zero.
d) We can take the address of a register variable.
e) Automatic variables retain their value after the function call is over.
f) External/static variables, if not initialized, contain garbage value..
g) Automatic variables are initialized at complete time.
h) If a variable is declared before the main(), it is implicitly an external variable whose
storage class is external.
PART B
Q1 Differentiate between external and local static variables.
Q2 Explain the utility of requirement of declaring a variable as external.
Q3 What is the output of each of the following:
a) #include<stdio.h>
main()
{
int i=3;
{
int i=5;
printf(“%d\n”,i);
}
printf(“%d\n”, i);
}
b) #include<stdio.h>
void fact(int, int);
main()
{
int i, j;
i=5;
j=1;
fact(i, j);
printf(“factorial of %d = %d”,i , j);
}
void fact(int num, int res)
{
int k;
res=1;
for(k=num; k>1; k--)
res *=k;
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Q4 What is the output of each of the following:
a) void val(void)
int i =0;
main()
{
printf(“i= %d\n”, i++);
val();
printf(“i= %d\n”, i);
val();
void val(void)
{
int i=100;
printf(“i= %d\n”, i++);
}
b) int f(int);
main()
{
int i
for (i=1; i<5; i++)
printf(“%d\n”,f(i));
}
int f(int)
{
static int x=1;
int y=3;
x=n;
return x +n +y;
}
c) float f(float);
float x=4.5;
main()
{
float y;
x *=2.0;
y= f(x);
printf(“%f %f”, x, y);
}
float f(float a)
{
a +=1.5;
x -=2.5;
return a+x;
}
d) int f(int), g(int);
main()
{
Int a, x, y, z = 2;
Prof. Sarvpal Singh
Department of IT & Computer Application
z *=3;
y = f(z);
a= g(z);
printf(“%d %d %d”, z , y, a);)
}
int t=8;
int f(int p)
{
p += -5;
t =-=4;
return p+t;
}
int g (int p)
{
p=1;
t +=p;
return p+t;
}
Q5 What is the output of following program:
main()
{
static int numbers[10] = {1, 0, 0, 0, 0, 0, 0, 0, 0, };
int i,j;
for (j=0; j<10; ++j)
for(i =0; i < j; ++i)
numbers[j] = numbers[j] + numbers[i];
for (j=0; j<10; ++j)
printf(“%d\n”,numbers[j]);
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter – 7
The C Preprocessor
1 Introduction
C provides certain language facilities by means of a pre-processor, which is conceptually
first step in compilation. The two most frequently used features are :
I) #Include, to include the contents of a file during compilation.
ii) #define to replace a token by an arbitrary sequence of characters.
2 Macro substitution
One of the primary uses of the #define statement is for assigning symbolic constants to
program constants.
A define has the form
#define name replacement-text
All subsequent occurrences of name will be replaced by replacement text. Normally,
the replacement text is the rest of the line, but a long definition may be continued onto
several lines by placing a ‘\’ at the end of each line to be continued. The scope of a name
defined with #define is from its point of definition to the end of the source file.
Example:
# define TRUE 1
# define FALSE 0
# define AREA len*wid
# define square(x) x*x
# define max(a, b) ((a > b) ? a : b)
The pre-processor statement #define TRUE 1
Defines the name TRUE and makes it equivalent to the value 1. The name TRUE can
subsequently be used anywhere in the program where the constant 1 could be used.
A defined bane is not a variable. Therefore, we can’t assign a value to it. The define
statements can appear anywhere in the program, either inside a function or outside a
function, it can subsequently be used anywhere in the program.
Example: #define PI 3.14
Note: the constant NULL, EOF are defined in the file stdio.h
Example:
#define isLeap(y) ((y%4==0 && y%100!=0) || y%4==0)
With the above definition, we can write a statement such as if(isLeap(year)) to test if
the value of a variable year was a leap year or not.
Example: #define isLowerCase(c) (c>=’a’ && c<=’z’)
We can use this macro in a subsequent macro definition to convert a character from
lower case to uppercase, leaving any non lower case character unchanged:
#define toUpper(c) (isLowerCase ? c- ‘a’ + ‘A’ : c)
Example:
#include<stdio.h>
#define loop(n) {for (lines=1; lines <= n; lines++)\
{for (count = 1; count <=n – lines; count++)\
putchar(‘ ‘);\
for(count=1; count<=2*lines-1; count++)\
putchar(‘*’);\
printf(“\n);\
}
}
Prof. Sarvpal Singh
Department of IT & Computer Application
main()
{
int count, lines, n;
printf(“number of lines: ”);
scanf(“%d”, &n),
loop(n);
}
When this program is executed it displays a triangle of asterisk, whose size in terms
of the number of lines, is determined by a user supplied value.
Input:
Number of lines =6
Output: *
***
*****
*******
*********
***********
Macros are sometimes used in place of functions within a program. The use of a macro
place of a function eliminates the times delays associated with the function calls.
Note: do not terminate a mcro definition with a semicolon. Also data types does not effect a
Macro.
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise - 7
Q1 Discuss the advantages and disadvantages of using a MACRO?
Q2 Define a macro, cls(), which clears the screen.
Hint: Print the escape sequence “^[[2J” on the screen
^[ is escape character, ASCII value 27
Q3 Write a macro isUpper(c) that gives a non-zero value if a character is an uppercase
letter.
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter – 8
Recursion
C function may be used recursively, i.e. a function may call itself.
Example:
/* To print the factorial of a number */
int fact(int);
main()
{
int n;
printf(“enter a positive number:);
scanf(“%d”, &n);
printf(“The factorial of %d is %d \n”,n, fact(n));
}
int fact(int n)
{
if(n>1)
return n* fact(n-1);
else
return 1;
Example: /* to calculate xy */
int pow(int x, int y)
{
if(y == 0)
return 1;
if(y==1)
return x;
return x * pow (x, y - 1)
Example:
/* To read a line of text and write it backwards */
void reverse(void)
{
int c;
if((c = getchar()) !=’’\n’;)
reverse();
putchar(c);
}
When a recursive program is executed, the recursive function calls are not executed
immediately. Rather, they are placed on a stack until the condition that terminates the
recursion is encountered. The function calls are then executed in reverse order, as they
are “popped” of the stack. This reversal in the order of execution is a characteristic of
all functions executed recursively.
Examples: /*To find the sum of the digits of a number */
Int sumDigits(int n)
{
if(!(n/10))
return n;
else
return (n%10) + sumDigits(n/10);
}
Prof. Sarvpal Singh
Department of IT & Computer Application
Example:
/* To find the product of 2 nos. */
int prod(int a, int b)
{
if(a==0 || b==0)
return 0;
if(b > 1)
return a+ prod(a, b-1));
else
return a;
}
Example:
/* To find a / b, where a and b are +ve */
int div(int a, int b)
{
If(a==0 || a<b)
return 0;
If(b==1)
return a;
else
return 1 + div(a - b, b)
Prof. Sarvpal Singh
Department of IT & Computer Application
Exercise- 8
Q1 What is the advantage of using a recursive technique ?
Q2 What will be the output of the following:
#include<stdio.h>
main()
{
printf(“hello”);
main();
}
Q3 Write a recursive function, int sum(int n), that returns:
2 + 4 + 6 + .................... +2n
Q4 Write a recursive function to print the binary equivalent of an integer.
Prof. Sarvpal Singh
Department of IT & Computer Application
Chapter- 9
Library functions
The C language is accompanied by a number of library functions that carry out various
commonly used operations or calculations.
In order to use a library function it may be necessary to include certain specific
information within the main portion of the program. This is accomplished with the pre-
processor statement
#include <filename>
Where filename represents the name of the header file in which the particular library
function is defined.
1 Character Functions
All these functions have the return type int.
These functions are declared in the file <ctype.h>
i) isdigit(c) - to check wether a character is a digit or not.
ii) isxdigit(c) - to check wether a character is a hexadecimal digit.
iii) isalpha(c) - to check wether a character is an alphabet.
iv) isalnum(c) - to check if a character is alphabetic or numeric.
v) islower(c) - to check if it is lower case alphabet.
vi) isspace(c) - checks all white space characters.
vii) isupper(c) - to check for upper case alphabet.
viii) tolower(c) - to convert an uppercase character to lowercase.
ix) toupper(c) - to convert a lower case character to uppercase character.
x) isprint(c) - to check wether a character is a printing character including space.
2 String functions
These functions are declared in the file <string.h>
i) strcpy(s1, s2) – copies s2 to s1
ii) strncpy(s1, s2, n) – copies s2 to s1 until either NULL character is reached or n character
have been copied whichever occurs first.
Example:
char a[10], b[10] = “hello”;
strcpy(a,b);
puts(a);
will display hello
Example:
char a[20], b[20] = “student”;
strncpy(a, b, 3);
now a[10], a[1], and a[2] will store ‘s’, ‘t’, and ‘u’ respectively. (Note that there is no
NULL terminator in a)
iii) int strcmp(char s1[], char s2[])
- compare s1 and s2
- returns 0 if strings are equal
- returns >0 if s1> s2
- returns <0 if s1<s2
Example:
If(strcmp(a,b)==0)
Implies that if a & b are equal
Prof. Sarvpal Singh
Department of IT & Computer Application
iv) int strncmp(char s1[], char s2[], int n)
- compares n characters
- returns the same value as strcmp
Example:
strncmp(s1, s2, 4)
Will compare the first 4 bytes of s1 and s2
v) int strlen(char s[])
- returns length of the string (excluding null)
vi) strcat(s1, s2)
- concatenates s2 to the end of s1 and places a null at the end of the final
string.
Example:
strcat(a, b)
puts(a);
will display the concatenated string.
Prof. Sarvpal Singh
Department of IT & Computer Application