17UCA02-Programming in 'C' (T.vijayakumar)
17UCA02-Programming in 'C' (T.vijayakumar)
1
UNIT-I
1. OVERVIEW OF C
GIVE SHORT INTRODUCTION ABOUT C. (PART A)
The C is a general-purpose, procedural, imperative computer programming language developed in
1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX operating
system.
The C is the most widely used computer language, it keeps fluctuating at number one scale of
popularity along with Java programming language, which is also equally popular and most widely
used among modern software programmers.
C was initially used for system development work, in particular the programs that make up the
operating system. C was adopted as a system development language because it produces code that
runs nearly as fast as code written in assembly language. Some examples of the use of C might be:
Operating Systems
Language Compilers
Assemblers
Text Editors
Network Drivers
Modern Programs
Databases , Language Interpreters
Utilities
i.) HISTORY OF C
EXPLAIN THE HISTORY OF C (PART B)
C has often been termed as a "Pseudo high level
language" or a "Middle level language" by many
programmers. This is not because of its lack of
programming power but because of its capability
to access the system's low level functions.
In fact C was invented specifically to implement
UNIX. C instructions are compiled to assembly
code, therefore, depending on the complexity of
the code and on the compiler optimization
capabilities, C code may run as fast as assembly.
Ken Thompson created the B language in 1969
from Martin Richard's BCPL (Basic Combined
Programming Language). He used assembly language and B to produce the initial versions of the
UNIX operating system.
BCPL and B were typeless languages in which variables were simply words in memory. Dennis
Ritchie of Bell Laboratories later converted B into C by retaining most of B's syntax in 1972 and
wrote the first compiler.
in 1983, the ANSI X3J11 committee was asked to standardize the C language. The result was ANSI
C, a standard which was adopted in 1988. It is not forced upon any programmer, but since it is so
widely accepted, it would be economically unwise for any systems programmer or compiler writer
not to conform to the standard.
ii.) IMPORTANCE OF ‘C’ LANGUAGE
WRITE ABOUT IMPORTANCE OF C LANGUAGE (PART B)
It is robust language whose rich setup of built in functions and operator can be used to write any
complex program.
Program written in c are efficient due to several variety of data types and powerful operators. The c
complier combines the capabilities of an assembly language with the feature of high level language.
Therefore it is well suited for writing both system software and business package. There are only 32
keywords; several standard functions are available which can be used for developing program.
C is portable language; this means that c programs written for one computer system can be run on
another system, with little or no modification. C language is well suited for structured programming,
this requires user to think of a problems in terms of function or modules or block. A collection of
these modules make a program debugging and testing easier.
2
C language has its ability to extend itself. A c program is basically a collection of functions that are
supported by the c library. We can continuously add our own functions to the library with the
availability of the large number of functions.
The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.The constants are
treated just like regular variables except that their values cannot be modified after their definition.
iii.) FEATURES OF C LANGUAGE
WHAT ARE ALL THE FEATURES OF C LANGUAGE (PART B)
C is a procedure-based programming language. This means the program is viewed as a means to
solve a problem. Various functions modules or code blocks are thus, written to solve this problem.
C functions can accept parameters and return values and perform variety of tasks like input from the
user, displaying the information, etc.
C is simple and easy to learn and use. The main components like built-in functions, operators,
keywords are small in number.
In C, errors are checked only at compile time. The compiled code though have no safety checks for
bad type casts, bad array indices, or bad pointers.
C works best for small projects where performance is important.
C contains the capability of assembly language with the features of high level language.
iv.) BASIC STRUCTURE OF C
EXPLAIN ABOUT BASIC STRUCTURE OF C PROGRAM(PART B)
C program can be viewed as a group of building blocks called Functions.
A function is a subroutine that may include one or more statements designed to perform a specific
task. To write a C program, we first create functions
and then put them together.
A C program may contain one or more sections.
Documentation Section
This section contains a set of comment lines giving
the name of the program, author, date created, and
other details.
Link Section
This section provides instructions to compilers to link
functions from the system library.
Definition Section
This section defines all symbolic constants.
Global declaration Section
contains a variable that is used outside of all the
functions. These variables are Global variables.
Main ( ) function Section
Every C program must have one main ( ) function section. C permits different forms of main() as,
1) main ( ) 4) main (void)
2) int main ( ) 5) void main(void)
3) void main ( ) 6) int main(void)
The empty pair of parentheses indicates that the function has no arguments.
This may be explicitly indicated by using the keyword ‘void’ inside the parentheses.
We may also specify the keyword ‘int’ or ‘void’ before the word ‘main’.
Main() has two parts,
Declaration part declares all variables.
Executable part statements to be executed to get output
These two parts must appear between the opening and closing braces.
Subprogram section
This section contains all the user-defined functions that are called in the main function.
User-defined functions are generally placed immediately after the main function.
The # include Directive
3
C programs are divided into modules or functions.
Some functions are written by users and many others are stored in the C Library.
Library functions are grouped category-wise and stored in different files known as Header Files.
If we want to access the functions stored in the library, it is necessary to tell the compiler about the
files to be accessed by using the preprocessor directive, # include <filename> where filename
name of the library file. Preprocessor directives are placed at the beginning of a program.
v.) EXECUTING C PROGRAMS
1. This is First Step i.e Creating and Editing Program.
2. First Write C Program using Text Editor , such as [ Borland C/C++ 3.0 , Notpad++,Notpad ]
3. Save Program by using [.C] Extension.
4. Compiling C Program: C Source code with [.C] Extension is given as input to compiler and compiler
converts it into Equivalent Machine Instruction.
5. Program is linked with included header files.
6. If run time error occurs then “Run-time” errors are reported to user.
7. Again programmers have to review code and check for the solution.
2. CONSTANTS ,VARIABLES AND DATA TYPES
i.) CHARACTER SET
C characters are grouped into the following categories.
a) Letters, b) Digits, c) Special Characters, d) White Spaces
a) Letters
Uppercase A….Z
Lowercase a…..z
b) Digits
All decimal digits 0…..9
c) Special characters
, Comma & Ampersand ‘ Apostrophe / Slash + Plus Sign
. Period ^ Caret “ Quotation mark \ Backslash ( Left Parenthesis
; Semicolon * Asterisk ! Exclamation mark ~ Tilde ) Right Parenthesis
: Colon - Minus Sign | Vertical Bar _ Underscore [ Left Bracket
$ Dollar Sign % Percent Sign# number sign ] right Bracket { Left Brace } Right Brace
< Opening angle bracket (or Less than sign) > Closing angle bracket (or Greater than sign)
d) White Spaces
Blank Space, Horizontal tab Carriage return New Line Form Feed.
ii.) C TOKENS
In C programs, the smallest individual units are known as tokens.
C TOKENS
Main []
amount {}
iii.) KEYWORDS
Every C word is classified as either a keyword or an identifier. All keywords have fixed meanings
and these meanings cannot be changed.
4
auto else Long switch
break Enum register typedef
case extern return union
char float short unsigned
const for signed void
continue Goto sizeof volatile
default if static while
do Int struct _packed
iv.) IDENTIFIERS
DEFINE IDENTIFIER (PART A)
Identifiers refer to the names of variables, functions and arrays.
They are user-defined names and consist of a sequence of letters and digits, with a letter as a first
character. Both uppercase and lowercase letters are permitted.
The underscore character is also permitted in identifiers.
Identifiers should not be a keyword.
Should not start with Digit.
v.) CONSTANTS
DEFINE CONSTANTS (PART A)
The constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be modified after
their definition.
Constants in C refer to fixed values that do not change during the execution of a program.
CONSTANTS
6
Primary Data Types
PRIMARY DATA TYPES
Integral Type
Integer Character
signed type unsigned type signed char
int unsigned int unsigned
short int unsigned short int char
long int unsigned long int
Integer Types
Type Size (bits) Range
int or signed int 16 -32,768 to 32767
unsigned int 16 0 to 65535
short int 8 -128 to 127
unsigned short int 8 0 to 255
long int 32 -2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
Floating Point Types
Type Size (bits) Range
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932to 1.1E+4932
Character Types
Type Size (bits) Range
char 8 unsigned char
unsigned char 8 0 to 255
7
}
Here the variable m is called the global variable. It can be used in all the functions in the program.
The variables bal, sum and i are called local variables. Local variables are visible and meaningful
only inside the function in which they are declared.
There are four storage class specifiers, namely,
o auto,
o static,
o register and
o extern.
Static and extern variables are automatically initialized to zero. Auto variable contain undefined
value(garbage value) until they are initialized explicitly.
Auto : Local variables known only to the function in which it is declared.
Register : Local variables which is stored in he registers.
Static : Local variables which exist and retain its value even after the control is transferred to the calling
function.
Extern : Global variables known to all functions in the file.
ix.) ASSIGNING VALUES TO VARIABLES
Assigning Statement:
The syntax is
Variable_name=constant;
Eg: 1) a=20;
2) bal=75.84;
3) yes=’x’;
C permits multiple assignments in one line.
Example:
initial_value=0; final_value=100;
In C declaration and assignment can be done simultaneously, as follows.
The syntax is
data-type variable_name = constant;
8
2. No blank space between the sign ‘#’ and the word define is permitted
3. ‘#’ must be the first character in the line.
4. A blank space is required between #define and symbolic name and between the symbolic name and
the constant.
5. #define statements must not end with the semicolon.
6. After definition, the symbolic name should not be assigned any other value within the program by
using an assignment statement.
7. Symbolic names are NOT declared for data types. Their data types depend onthe type of constant.
8. #define statements may appear anywhere in the program but before it is referenced in the program.
xi.) DECLARING A VARIABLE AS CONSTANT
Eg: 1) const int class_size=40;
This tells the compiler that the value of the int variable class_size must not be modified by the
program.
xii.) DECLARING A VARIABLE AS VOLATILE
By declaring a variable as volatile, its value may be changed at any time by some external source.
Eg:1) volatile int date;
3. OPERATORS AND EXPRESSIONS
I. OPERATORS
INTRODUCTION TO OPERATORS
EXPLAIN ABOUT OPERATOR CONCEPT IN C (10 MARKS)
C supports a rich set of operators. Operators are used in programs to manipulate data and variables.
They usually form a part of the mathematical or logical expressions.
C operators are classified into a number of categories. They include:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment and Decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
i.) ARITHMETIC OPERATORS
The operators are
+ (Addition)
- (Subtraction)
* (Multiplication)
/ (Division)
% (Modulo division)
Eg: 1) a-b 2) a+b 3) a*b 4) p%q
The modulo division produces the remainder of an integer division.
The modulo division operator cannot be used on floating point data.
Note: C does not have any operator for exponentiation.
a.) Integer Arithmetic
When both the operands in a single arithmetic expression are integers, the expression is called an
integer expression ,and the operation is called integer arithmetic.
During modulo division the sign of the result is always the sign of the first operand.
That is -14 % 3 = -2 , -14 % -3 = -2 , 14 % -3 = 2
b.) Real Arithmetic
An arithmetic operation involving only real operands is called real arithmetic. If x and yare floats
then we will have:
1) x = 6.0 / 7.0 = 0.857143 2) y = 1.0 / 3.0 = 0.333333
The operator % cannot be used with real operands.
9
When one of the operands is real and the other is integer, the expression is called a mixed-mode
arithmetic expression and its result is always a real number.
Eg: 1) 15 / 10.0 = 1.5
ii.) RELATIONAL OPERATORS
Comparisons can be done with the help of relational operators. The expression containing a
relational operator is termed as a relational expression. The value of a relational expression is either
one or zero.
Operator Meaning Examples
< Less than a<b
<= Less than or equal to a < =b
> Greater than a >b
>= Greater than or equal to a > =b
== Equal to a = =b
!= Not equal to a!=b
# include <stdio.h>
main() Output:
{ int a,b,c;
a=70;b=50;c=30; A is Largest
if ((a>b) && (a>c))
printf("\n\ n\t\t\t A is Largest ");
else if (b>c)
printf("\n\n \t\t B is Largest ");
else
printf("\n\n \t\t C is Largest ");
getch();
} 10
iv.) ASSIGNMENT OPERATORS
The usual assignment operator is ‘=’.In addition, C has a set of ‘shorthand’ assignment operators of
the form, v op = exp;
Eg: 1.x += y+1; This is same as the statement x=x+(y+1);
Shorthand Assignment Operators
Statement with shorthand operator Statement with simple assignment operator
a + =1 a=a+1
a-=1 a=a–1
a *= n + 1 a = a * (n+1)
a /= n + 1 a = a / (n+1)
a %= b a=a%b
v.) INCREMENT AND DECREMENT OPERATORS
C has two very useful operators that are not generally found in other languages. These are the,
o increment operator : ++
o decrement operator: --
C allows two very useful operators. These are the increment and decrement operators: ++ and - - .
The operators ++ adds 1 to the operand, and - - subtracts 1.
Both are unary operators and takes the following form:
These operators are used for testing the bits, or shifting them right or left. Bitwise operators may not be
applied to float or double.
Example Assume if A = 60; and B = 13; Now in binary Operator Meaning
format they will be as follows: & Bitwise AND
A = 0011 1100
B = 0000 1101 | Bitwise OR
-------------------- ^ Bitwise exclusive
A&B = 0000 1100 OR
A|B = 0011 1101 << Shift left
A^B = 0011 0001
~A = 1100 0011 >> Shift right
viii.) SPECIAL OPERATORS
Define Sizeof operator(PART A)
C supports some special operators such as
Comma operator
Size of operator
Pointer operators(& and *) and
Member selection operators(. and ->)
The Comma Operator
The comma operator can be used to link the related expressions together. A comma linked list of
expressions are evaluated left to right and the value of right-most expression is the value of the
combined expression.
Eg: value = (x = 10, y = 5, x + y);
This statement first assigns the value 10 to x, then assigns 5 to y, and finally assigns 15 (i.e, 10+5) to
value.
The Size of Operator
The size of is a compiler time operator and, when used with an operand, it returns the number of
bytes the operand occupies.
Eg: 1) m = sizeof(sum); Example Program:
2) n = sizeof(long int) #include <stdio.h>
3) k = sizeof(235L) int main(){
int a;
float b;
Output: double c;
Size of int = 2 bytes char d;
Size of float = 4 bytes printf("Size of int=%d bytes\n",sizeof(a));
Size of double = 8 bytes printf("Size of float=%d bytes\n",sizeof(b));
Size of byte = 1 byte printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}
II.EXPRESSION
i.) ARITHMETIC EXPRESSIONS
DEFINE EXPRESSION (OR)ARITHMETIC EXPRESSION(PART A)
Expressions
The combination of operators and operands is said to be an expression. An arithmetic expression is a
combination of variables, constants, and operators arranged as per the syntax of the language.
Eg 1) a = x + y;
ii.) EVALUATION OF EXPRESSIONS
12
Expressions are evaluated using an assignment statement of the form,
variable = expression;
An arithmetic expression without parentheses will be evaluated from left to right using the rules of
precedence of operators.
The basic evaluation procedure includes ‘two’ left-to-right passes through the expression.
During the first pass, the high priority operators (if any) are applied as they are encountered.
During the second pass, the low priority operators (if any) are applied as they are encountered.
Consider the following evaluation statements that has been used in the program
x = a-b/3 + c*2-1
When a =9, b =12, and c = 3, the statement becomes Ex:- x= 12-4*6/3+2
x = 9-12/3 + 3*2-1 x= 12-4*2+2
and is evaluated as follows: Second pass x= 12-8+2
First pass : x = 9-12/3 + 3*2-1 Step3: x = 5+6-1 x= 12-10
Step1: x = 9-4+3*2-1 Step4: x = 11-1 x= 2
Step2: x = 9-4+6-1 Step5: x = 10
The order of evaluation can be changed by introducing parentheses into an expression.
Example:
main()
{
float a, b, c, y, x, z;
a = 9; b = 12; c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – (b / (3 + c) * 2) – 1;
printf(“x = %f ”,x);
printf(“y = %f ”,y);
printf(“z = %f ”,z);
}
OUTPUT
x = 10.000000 y = 7.000000 z = 4.000000
iii.) PRECEDENCE OF ARITHMETIC OPERATORS
EXPLAIN ABOUT PRECEDENCE OF ARITHMETIC OPERATORS IN C (PART B)
An arithmetic expression without parenthesis will be evaluated from left to right using the rule of
precedence of operators. There are two distinct priority levels of arithmetic operators in C.
High priority * / % Low priority + -
Consider the above program and if the a=9, b=12 and c=3, the statement becomes.
X=9-12/3+3*2-1
The above expression is evaluated as follows.
First Pass
o Step 1: x=9-4+3*2-1
o Step 2: x=9-4+6-1
Second Pass
o Step 3: x=5+6-1
o Step 4: x=11-1
o x=10
iv.) TYPE CONVERSION IN EXPRESSIONS
DEFINE AUTOMATIC TYPE CONVERSION(PART A)
If the operands are of different types, the lower type is automatically converter to the higher type
before the operation proceeds. This is called Type conversion.
There are two types of type conversions,
a) Implicit Type conversion
b) Explicit Type conversion
a.) Implicit or Automatic Type Conversion
13
C permits the mixing of constants and variables of different types in an expression. If the operands
are of different types, the lower type is automatically converted to higher type before the operation
proceeds. The result is of the higher type.
Given below are the sequence of rules that are applied while evaluating expressions. All short and
char are automatically converted to int; then
If one of the operands is long double, the other will be converted to long double and the result
will be in long double.
Else, If one of the operands is double, the other will be converted to double and the result will
be in double.
Rules while evaluating expressions
1. If the operands are of different types, the long double
‘lower’ type is automatically converted to the
‘higher’ type before the operation proceeds. double
The result is of the higher type. Conversion
float
2. All short and char are automatically converted Hierarchy
to int; then unsigned long
3. If one of the operands is long double, the other int
long int
will be converted to long double and the result
will be long double; unsigned
4. Else, if one of the operands is double, the other int
will be converted to double and the result will int
be double; short char
5. Else, if one of operands is float, the other will
be converted to float and the result will be float;
6. Else, if one operand is unsigned long int, the other will be converted to unsigned long int and the result
will be unsigned long int;
7. Else, if one of the operands is long int and the other is unsigned int, then
a .If unsigned int can be converted to long int, the unsigned int operand will be converted as such and
the result will be long int;
b. Else, both operands will be converted to unsigned long int and the result will be unsigned long int;
8. Else, if one of the operands is long int, the other will be converted to long int and the result will be long
int;
9. Else, if one of the operands is unsigned int, the other will be converted to unsigned int and the result
will be unsigned int.
The following changes are introduced during the final assignment.
1. Float to int causes truncation of the fractional part.
2. Double to float causes rounding of digits.
3. Long int to int causes dropping of the excess higher order bits.
b.) Explicit or Casting a Value
C performs type conversion automatically. However, there are instances when we want to force a
type conversion in a way that is different from the automatic conversion.
Syntax: (type_name)
EXAMPLE ACTION
x=(int)7.5 7.5 is converted to integer by truncation
a=(int)21.3/(int)4.5 Evaluated as 21/4 and the result would be 5.
b=(double)sum/n Division is done in floating point mode
y=(int)(a+b) The result of a+b is converted to integer
z=(int)a+b A is converted to integer and then added to b
p=cos((double)x) Converts x to double before using it
14
v.) OPERATORS PRECEDENCE AND ASSOCIATIVELY IN C
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
The control string specifies the field format in which the data is to be entered and the arguments
arg1,arg2...argn specifies the address of locations where the data are stored. Control strings and
arguments are separated by commas.
Control string contains field specification which direct the interpretation of input data.
It may include
Field(or format)specifications, consisting of conversion character %, a datatype character,
and an optional number, specifying the field width.
Blanks, tabs, or newlines.
Inputting integer numbers
The field specification for reading an integer number is %wd
Eg: scanf(“%2d %5d”,&num1, &num2);
An input field may be skipped by specifying * in the place of field width.
For eg, scanf(“%d %*d %d”,&a, &b);
Inputting Real numbers
The scanf reads real numbers using the simple specification %f for both the notations, namely
decimal point and exponential notation.
If the number to be read is of double type, then the specification should be %lf.
Scanf(“%f%f%f”, &x,&y,&z); OUTPUT
Enter three integer numbers
Inputing a Character String 123
Scanf(“%c%s”, name1, name2); 1 3 –3577
Program Enter two 4-digit numbers
/*Reading integer numbers*/ 6789 4321
main() 67 89
{ Enter two integer numbers
int a, ,b, c, x, y, z; 44 66
int p, q, r; 4321 44
printf(“Enter three integer numbers \n”); Enter a nine digit numbers
scanf(“%d %*d %d”,&a, &b, &c); 123456789
printf(“%d %d %d \n \n”,a, b, c); 66 1234 567
printf(“Enter two 4-digit numbers \n”); Enter two three digit numbers
123 456
17 89 123
scanf(“%2d %4d ”,&x, &y);
printf(“%d %d \n \n”,x, y);
printf(“Enter two integer numbers \n”);
scanf(“%d %d”,&a, &x);
printf(“%d %d \n \n”,a, x);
printf(“Enter a nine digit numbers \n”);
scanf(“%3d %4d %3d”,&p, &q, &r);
printf(“%d %d %d \n \n”,p, q, r);
printf(“Enter two three digit numbers \n”);
scanf(“%d %d”,&x, &y);
printf(“%d %d \n \n”,x, y);
}
Reading Mixed Data Types
It is possible to use one scanf statement to input a data line containing mixed mode data. In such
cases, it should be ensured that the input data items match the control specifications in order and
type.
Eg: scanf(“%d %c %f %s”,&count, &code, &ratio, &name);
Scanf Format Codes ( Code Meaning )
%c Read a single character %i Read a decimal, hexadecimal, or octal integer
%d Read a decimal integer %o Read an octal integer
%e Read a floating point value %s Read a string
%f Read a floating point value %u Read an unsigned decimal integer
%g Read a floating point value %x Read a hexa decimal integer
%h Read a short integer %[..] Read a string of word(s)
iv. ) FORMATTED OUTPUT
The printf statement provides certain features that can be effectively exploited to control the
alignment and spacing of print-outs on the terminals. The general form of printf statement is
printf(“control string”,arg1, arg2…argn)
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t and \b
Output of Integer Numbers
The format specification for printing an integer number is %wd Output of Real Numbers
The output of real numbers may be displayed in decimal notation using the following format
specification:
%w.p f
The integer w indicates the minimum number of positions that are to be used for the display of the
value and the integer p indicates the number of digits to be displayed after the decimal point.
We can also display real numbers in exponential notation by using the specification
%w.p e
Printing of Single Character
A single character can be displayed in a desired position using this format The character will be
displayed right-justified in the field of w columns.
We can make the display left-justified by placing a minus sign before the integer w.
The default value for w is 1.
Printing of Strings
The format specification for outputting strings is of the form
%wc %w.ps
UNIT – I COMPLETED
References: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy,
18
UNIT-II
DECISION MAKING AND BRANCHING
EXPLAIN ABOUT DECISION MAKING CONCEPTS (10 MARKS)
i.) INTRODUCTION:
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages:
i. if statement
ii. switch statement
iii. Conditional operator statement
iv. Goto statement.
i.) DECISION MAKING WITH IF STATEMENT
If statement can be implemented in many forms.
a) Simple if statement
b) IF…. ELSE statement
c) Nested IF…ELSE Statement
d) ELSE IF Ladder.
a.) Simple IF statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
if(Test_Expression)
{
/* statement(s) will execute if the boolean expression is true */
}
Example program
#include <stdio.h>
int main ()
{
int a = 10; /* local variable definition */
if( a < 20 ) /* check the boolean condition using if statement */
{
printf("a is less than 20\n" ); /* if condition is true then print the following */
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is less than 20;
value of a is : 10
b.) IF...ELSE statement
An if statement can be followed by an optional else statement, which
executes when the boolean expression is false.
Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
Example Program:
19
#include <stdio.h>
int main ()
{
int a = 100; /* local variable definition */
if( a < 20 ) /* check the boolean condition */
{
/* if condition is true then print the following */ When the above code is compiled and
printf("a is less than 20\n" ); executed, it produces the following result:
} a is not less than 20;
else value of a is : 100
{
printf("a is not less than 20\n" ); /* if condition is false then print the following */
}
printf("value of a is : %d\n", a);
return 0;
}
c.) Nesting of IF...ELSE IF...ELSE Ladder
An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
When using if , else if , else statements there are few points to keep in mind:
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax
The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
20
Example Program
#include <stdio.h>
int main ()
{
int a = 100; /* local variable definition */
if( a == 10 ) /* check the boolean condition */
{
printf("Value of a is 10\n" ); /* if condition is true then print the following */
}
else if( a == 20 )
{
printf("Value of a is 20\n" ); /* if, else if condition is true */
}
else if( a == 30 )
{
printf("Value of a is 30\n" ); /* if else if condition is true */
}
else
{
printf("None of the values is matching\n" ); /* if none of the conditions is true */
}
printf("Exact value of a is: %d\n", a );
return 0;
}
When the above code is compiled and executed, it produces the following result:
None of the values is matching
Exact value of a is: 100
23
DECISION MAKING AND LOOPING
EXPLAIN ABOUT DECISION MAKING AND LOOPING (PART C)
In looping, a sequence of statements are executed until some conditions for termination of the loop
are satisfied. A program loop therefore consists of two segments, one known as the body of the loop
and the other known as the control statements.
Eg:
main()
{
double x, y;
read:
scanf(“%f”,&x);
if(x < 0) goto read;
y = sqrt(x);
printf(“%f %f \n”,x, y);
goto read;
}
The C language provides for three loop constructs for performing loop operations. They are
i. The while statement
ii. The do statement
iii. The for statement
i.) THE WHILE STATEMENT
The basic format of the while statement is
The while is an entry–controlled loop statement. The test-condition is
evaluated and if the condition is true, then the body of the loop is
executed. After execution of the body, the test-condition is once again
evaluated and if it is true, the body is executed once again. This process of repeated execution of the
body continues until the test-condition finally becomes false and the control is transferred out of the
loop.
Eg:
sum = 0;
n = 1;
while(n <= 10)
{
sum = sum + n* n;
n = n + 1;
}
printf(“sum = %d \n”,sum);
ii.) THE DO STATEMENT
In while loop the body of the loop may not be executed at all if the condition is not satisfied at the
very first attempt. Such situations can be handled with the help of the do statement.
In the example above, the while loop will run, as long i is smaller then twenty. In the while loop
there is an if statement that states that if i equals ten the while loop must stop (break).
With “continue;” it is possible to skip the rest of the commands in the current loop and start from
the top again. (the loop variable must still be incremented). Take a look at the example below:
#include<stdio.h>
int main()
{
int i = 0;
while ( i < 20 )
{
i++;
continue;
printf("Nothing to see\n");
}
return 0;
}
In the example above, the printf function is never called because of the “continue;”.
25
ARRAYS : DEFINITION AND DECLARATION
DEFINE ARRAY (PART A)
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant greater than
zero and type can be any valid C data type. For example, to declare a 10-element array
called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.
Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of elements that we
declare for the array between square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 7.0, 50.0};
You will create exactly the same array as you did in the previous example. Following is an example
to assign a single element of the array −
balance[4] = 50.0;
th
The above statement assigns the 5 element in the array with a value of 50.0. All arrays have 0 as
the index of their first element which is also called the base index and the last index of an array will
be total size of the array minus 1. Shown below is the pictorial representation of the array we
discussed above −
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
for ( i = 0; i < 10; i++ ) /* initialize elements of array n to 0 */
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
for (j = 0; j < 10; j++ ) /* output each array element's value */
{
26
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
ONE DIMENSIONAL ARRAY
EXPLAIN IN DETAIL ABOUT ONE DIMENSIONAL ARRAY (5 marks)
i.) INTRODUCTION:
An array with a single subscript is known as one dimensional array.
Eg: 1) int number[5];
The values to array elements can be assigned as follows.
Eg: 1) number[0] = 35;
number[1] = 40;
number[2] = 20;
ii.) DECLARATION OF ARRAYS
The general form of array declaration is
type variable-name[size];
Eg: 1) float height[50];
2) int group[10];
3)char name[10];
Program
/*Program showing one-dimensional array*/
main() OUTPUT
{ Enter 10 real numbers:
int i; 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10.10
float x[10],value,total; x[1] = 1.10
printf(“Enter 10 real numbers:\n”); x[2] = 2.20
for(i =0; i < 10; i++) x[3] = 3.30
{ x[4] = 4.40
scanf(“%f”,&value); x[5] = 5.50
x[i] = value; x[6] = 6.60
} x[7] = 7.70
total = 0.0; x[8] = 8.80
for(i = 0; i < 10; i++) x[9] = 9.90
total = total + x[i] * x[i]; x[10] = 10.10
printf(“\n”); Total = 446.86
for(i = 0; i < 10; i++)
printf(“x[%2d] = %5.2f \n”,i+1,x[i]);
printf(“\nTotal = %.2f\n”,total);
}
TWO-DIMENSIONAL ARRAYS
Two-dimensional arrays are declared as follows
Eg: product[i][j] = row * column;
type array-name[row_size][column_size];
27
For example consider a two array v[4][3]
Col 0 Col 1 Col 3
Row0
Row1
Row2
Row3
Example Program:
include <stdio.h>
int main ()
{
/* an array with 5 rows and 2 columns*/
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;
/* output each array element's value */
for ( i = 0; i < 5; i++ )
{
for ( j = 0; j < 2; j++ )
{
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}
return 0;
}
MULTIDIMENSIONAL ARRAY
C allows arrays of three or more dimensions. The exact limit is determined by the compiler. The
general form of a multidimensional array is
type array_name[s1][s2][s3]…s[m];
Example Program:
include<conio.h>
void main()
{
int i, j, k;
int arr[3][3][3]=
{
{
{11, 12, 13},
28
{14, 15, 16},
{17, 18, 19}
},
{
{21, 22, 23},
{24, 25, 26},
{27, 28, 29}
},
{
{31, 32, 33},
{34, 35, 36},
{37, 38, 39}
},
};
clrscr();
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
getch();
}
DYNAMIC ARRAYS
Dynamic memory allocation allows a program to obtain more memory space, while running or to
release space when no space is required.
Although, C language inherently does not has any technique to allocated memory dynamically, there
are 4 library functions under "stdlib.h" for dynamic memory allocation.
Function Use of Function
malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory
free() dellocate the previously allocated space
malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory
of specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc() :
o ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with
size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
o ptr=(int*)malloc(100*sizeof(int));
29
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and
the pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and
calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks
of memory each of same size and sets all bytes to zero.
Syntax of calloc() :
o ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For
example:ptr=(float*)calloc(25,sizeof(float));This statement allocates contiguous space in memory for
an array of 25 elements each of size of float, i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.
o syntax of free() : free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.
Examples of calloc() and malloc()
UNIT –II COMPLETED
Reference Book: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy.
UNIT-III
CHARACTER ARRAYS AND STRINGS
i.) INTRODUCTION
A string is a array of characters. Any group of characters (except the double quote sign) defined
between double quotation marks is a constant string. Eg: “Man is obviously made to think”
If we want to include a double quote in a string, then we may use it with the back slash.
Eg: printf(“\”well done!\””);
Output : “well done!”
The operations that are performed on character strings are
Reading and writing strings.
Combining strings together.
Copying one string to another.
Comparing strings for equality.
Extracting a portion of a string.
ii.) DECLARING AND INITIALIZING STRING VARIABLES
A string variable is any valid C variable name and is always declared as an array.
The general form of declaration of a string variable is
char string_name[size];
Eg: char city[10]; char name[30];
When the compiler assigns a character string to a character array, it automatically supplies a null
character (‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number
of characters in the string plus one. C permits a character array to be initialized in either of the
following two forms
static char city[9] = “NEW YORK”;
static char city[9] = {‘N’, ‘E’, ‘W’, ‘ ‘, ‘Y’, ‘O’, ‘R’, ‘K’, ‘\0’};
iii.) READING STRING FROM TERMINAL
The familiar input function scanf can be used with %s format specification to read in a string of
characters.
Eg: char address[15];
scanf(“%s”,address);
Program
/*Reading a series of words using scanf function*/
main()
{
30
char word1[40],word2[40],word3[40],word4[40];
printf(“Enter text:\n”);
scanf(“%s %s”,word1, word2);
scanf(“%s”, word3);
scanf(“%s”,word4);
printf(“\n”);
printf(“word1 = %s \n word2 = %s \n”,word1, word2);
printf(“word3 = %s \n word4 = %s \n”,word3, word4);
}
Reading a Line of Text
It is not possible to use scanf function to read a line containing more than one word. This is because
the scanf terminates reading as soon as a space is encountered in the input. We can use the getchar
function repeatedly to read single character from the terminal, using the function getchar. Thus an
entire line of text can be read and stored in an array.
Program
/*Program to read a line of text from terminal*/
#include<stdio.h>
main()
{
char line[81],character;
int c;
c = 0;
printf(“Enter text. Press<Return>at end \n”);
do
{
character = getchar();
line[c] = character;
c++;
}
while(character != ‘\n’);
c = c-1;
line[c] = ‘\0’;
printf(“\n %s \n”,line);
}
iii.) WRITING STRINGS TO SCREEN
We have used extensively the printf function with %s format to print strings to the screen. The
format %s can be used to display an array of characters that is terminated by the null character.
For eg, the statement printf(“%s”, name); can be used to display the entire contents of the array
name.
iv.) ARITHMETIC OPERATIONS ON CHARACTERS
C allows us to manipulate characters the same way we do with numbers. Whenever a character
constant or character variable is used in an expression, it is automatically converted into integer
value by the system.
For eg, if the machine uses the ASCII representation, then,
x = ‘a’;
printf(“%d \n”,x);
will display the number 97 on the screen.
The C library supports a function that converts a string of digits into their integer values. The
function takes the form x = atoi(string)
v.) PUTTING STRINGS TOGETHER
Just as we cannot assign one string to another directly, we cannot join two strings together by the
simple arithmetic addition. That is, the statements such as
string3 = string1 + string2;
string2 = string1 + “hello”;
are not valid.
31
The characters from string1 and string2 should be copied into string3 one after the other. The process
of combining two strings together is called concatenation.
x = atoi(string)
vi.) COMPARISON OF TWO STRINGS
C does not permit the comparison of two strings directly. That is, the statements such as
if(name1 == name2)
if(name == “ABC”);
are not permitted.
It is therefore necessary to compare the two strings to be tested, character by character. The
comparison is done until there is a mismatch or one of the strings terminate into a null character,
whichever occurs first.
vii.) STRING - HANDLING FUNCTIONS
C library supports a large number of string-handling functions that can be used to carry out many of
the string manipulation activities. Following are the most commonly used string handling functions.
Function Action
a) strcat( ) Concatenates two strings
b) strcmp( ) Compares two strings
c) strcpy( ) Copies one string over another
d) strlen( ) Finds the length of the string
a) strcat( ) Function
The strcat function joins two strings together. It takes the following form
strcat( string1,string2);
Eg: strcat(part1, “GOOD”);
b) strcmp( ) Function
It is used to compare two strings identified by the arguments and has a value 0 if they are equal. It
takes the form: strcmp(string1,string2);
Eg: 1) strcmp(name1,name2);
2) strcmp(name1,”john”);
3) strcmp(“ram”, “rom”);
c) strcpy( ) Function
This function works almost like a string assignment operator. It takes the form
strcpy(string1,string2)
This assigns the content of string2 to string1.
Eg: 1) strcpy(city, “DELHI”);
2) strcpy(city1,city2);
d) strlen( ) Function
This function counts and returns the number of characters in a string.
n = strlen(string);
Example Program
/*Illustration of string-handling functions*/
#include<string.h>
main()
{
char s1[20],s2[20],s3[20];
int x, l1, l2, l3;
printf(“Enter two string constants \n”);
printf(“?”);
scanf(“%s %s”, s1, s2); OUTPUT
x = strcmp(s1, s2); Enter two string constants
if(x != 0) ? New York
printf(“Strings are not equal \n”); Strings are not equal
strcat(s1, s2); s1 = New York length = 7 characters
else s2 = York length = 4 characters
printf(“Strings are equal \n”);
strcpy(s3,s1);
32
l1 = strlen(s1);
l2 = strlen(s2);
l3 = strlen(s3);
printf(“\ns1 = %s \t length = %d characters \n”,s1, l1);
printf(“\ns2= %s \t length = %d characters \n”,s2, l2);
printf(“\ns3 = %s \t length = %d characters \n”,s3, l3);
}
viii.) OTHER STRING FUNCTIONS
Strncpy Function
In addition to the function strcpy that copies one string to another; we have another function strncpy
that copies only the left-most n characters of the source string to the target string variable.
This is a three-parameter function and is invoked as follows: strncpy(s1, s2, 5);
This statement copies the first 5 character of the source string s2 into the target string s1.
Since the 5 characters may not include the terminating null character, we have to place it explicitly in
the 6th position of s2 as: s1[6] =’\0’; Now, the string s1 contains a proper string.
Strncmp Function
A variation of the function strcmp is the function strncmp. This function also has three parameters
as: strncmp (s1, s2, n);
This compares the left-most n character of s1 to s2 and returns
1. 0 if they are equal;
2. Negative number, if s1 sub-string is less than s2; and
3. Positive number, otherwise.
Strncat Function
This is another concatenation function that takes three parameters: strncat(s1,s2,n);
This call will concatenate the left-most n characters of s2 to the end of s1.
Strstr Function
It is a two-parameter function used to locate a sub-string in a string and takes the form: strstr (s1,
s2);
Example strstr (s1, “ABC”);
The function strstr searches the string s1 to see whether the string s2 is contained in s1. If yes, the
function returns the position of the first occurrence of the sub-string. Otherwise, it returns a NULL
pointer.
We also have functions to determine the existence of a character in a string.
The function call strchr(s1, ‘m’); will locate the first occurrence of the character ‘m’
A list of names can be treated as a table of strings and a two dimensional character array can be used
to store the entire list.
Example:
printf("%d", strlen ("cord") )'; 4
printf("%s", strcpy(sl, "string")); string
printf("%s", strncpy(s2, "endomorph", 4)); endo
printf("%s", strcat(s1, s2)); stringendo
printf("%d", strcmp (s1, s2)); 1
printf("%d". strncmp(sl+6, s2, 4)); 0
printf("%s", strchr (si, 'n')); ngendo
printf ("%s". strrchr (si, 'n' ) ) ; ndo
USER-DEFINED FUNCTIONS
User-defined functions are those functions which are defined by the user at the time of writing
program. Functions are made for code reusability and for saving time and space.
i.) INTRODUCTION
Functions can be classified into two categories, namely, library functions and user defined functions.
Main is an example of user-defined functions, printf and scanf belong to the category of library
functions.
33
The main difference between these two categories is that library functions are not required to be
written by us whereas a user-defined function has to be developed by the user at the time of writing
the program.
Function declaration
General syntax of function declaration is, return-type function-name (parameter-list) ;
Function definition Syntax
General syntax of function definition is,
return-type function-name (parameter-list)
{
function-body ;
}
The first line return-type function-name(parameter) is known as function header and the
statement within curly braces is called function body.
ii.) NEED FOR USER-DEFINED FUNCTIONS
It facilitates top-down modular programming.
The length of the source program can be reduced by using functions at appropriate places.
It is easy to locate and isolate a faulty function for further investigations.
A function can be used by many other programs
iii.) A MULTIFUNCTION PROGRAM
A function is a self-contained block of code that performs a particular task. Once a function has been
designed and packed, it can be treated as a ‘black box’ that takes some data from the main program
and returns a value. Thus a program, which has been written using a number of functions, is treated
as a multi-function program.
iv.) ELEMENTS OF USER DEFINED FUNCTIONS
In order to make use of a user-defined function, we need to establish three elements that are related
to functions.
1. Function definition
2. Function call
3. Function declaration
v.) DEFINITION OF FUNCTIONS
The general form of a function definition in C programming language is as follows:
return_type function_name( parameter list )
{
body of the function
}
A function definition in C programming language consists of a function header and a function body.
Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
Function Body: The function body contains a collection of statements that define what the function
does.
vi.) RETURN VALUES AND THEIR TYPES
All C functions can be called either with arguments or without arguments in a C program.
C function with arguments (parameters) and with return value
C function with arguments (parameters) and without return value
C function without arguments (parameters) and without return value
C function without arguments (parameters) and with return value
34
S.no C function syntax
1 with arguments and with int function ( int ); // function declaration
return values function ( a ); // function call
int function( int a ) // function definition
{statements; return a;}
2 with arguments and without void function ( int ); // function declaration
return values function( a ); // function call
void function( int a ) // function definition
{statements;}
3 without arguments and without void function(); // function declaration
return values function(); // function call
void function() // function definition
{statements;}
4 without arguments and with int function ( ); // function declaration
return values function ( ); // function call
int function( ) // function definition
{statements; return a;}
vii.) FUNCTION CALLS
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task, and when its return statement is executed or when its function-
ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if
function returns a value, then you can store returned value. For example:
#include <stdio.h>
int max(int num1, int num2);
int main ()
{
int a = 100,b = 200, ret;
ret = max(a, b);
printf( "Max value is : %d\n", ret );
return 0;
}
FUNCTION DECLARATION
Function declaration is the first line of function definition. When a
function is called, control of the program is transferred to function
declaration.
Syntax of function declaration
return_type function_name(type(1) argument(1),....,type(n) argument(n))
Function body
Function declaration is followed by body of function inside braces.
Passing arguments to functions
In programming, argument(parameter) refers to data this is passed to function(function
definition) while calling function.
In above example two variable, num1 and num2 are passed to function during function call
and these arguments are accepted by arguments a and b in function definition.
CATEGORY OF FUNCTIONS
A function may belong to one of the following categories.
1) Functions with no arguments and no return values.
2) Functions with arguments and no return values.
3) Functions with arguments and return values
4) Function with no arguments return value
35
i.) FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE
#include<stdio.h>
void area(); // Prototype Declaration
void main()
{
area(); Output :
} Enter the radius : 3
void area() Area of Circle = 28.260000
{
float area_circle;
float rad;
printf("\nEnter the radius : ");
scanf("%f",&rad);
area_circle = 3.14 * rad * rad ;
printf("Area of Circle = %f",area_circle);
}
ii.) FUNCTION WITH ARGUMENTS AND NO RETURN VALUES
#include<stdio.h>
#include<conio.h>
void area(float rad); // Prototype Declaration
void main()
{
float rad;
printf("nEnter the radius : "); Output :
scanf("%f",&rad); Enter the radius : 3
area(rad); Area of Circle = 28.260000
getch();
}
void area(float rad)
{
float ar;
ar = 3.14 * rad * rad ;
printf("Area of Circle = %f",ar);
}
Syntax:
Void Main( ) Void Function1( ) Void function3( )
{ { {
Function1( ); Function2( ) Function3( )
} } }
RECURSION
i.) INTRODUCTION
A function that calls itself is known as recursive function and this technique is known as
recursion in C programming.
Output:
Example of recursion in C programming
This is example of recursion
Main( )
This is example of recursion
{
This is example of recursion
Printf(“This is example of recursion\n”);
:
Main( );
:
}
It will run indefinitely.
37
PASSING ARRAYS TO FUNCTION
Example program for passing arrays to function
#include <stdio.h>
disp( char ch)
{
printf("%c ", ch); Output:
} abcdefghij
int main()
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'I', 'j'};
for (int x=0; x<=10; x++)
{
disp (arr[x]);
}
return 0;
}
PASSING STRING TO FUNCTION
String can be passed to function in similar manner as arrays as, string is also an array
#include <stdio.h>
void Reverse();
int main()
{
printf("Enter a sentence: ");
Reverse();
return 0;
}
void Reverse()
{
char c; Output
scanf("%c",&c); Enter a sentence: margorp emosewa
if( c != '\n') awesome program
{
Reverse();
printf("%c",c);
}
}
Nested blocks
A set of statements enclosed in a set of braces is known a block or compound statement.
A block can have its own declaration and other statements.
It is also possible to have a block of such statements inside the body of a function or another block
known as nested blocks.
39
Ex: main()
{ int a =20;
int b=10;
-------- outer block The result C
{ int a=0; will be 10,
int c=a+b; inner block not 30
}
b=a;
}
UNIT –III COMPLETED
Reference Book: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy.
UNIT-IV
STRUCTURES AND UNION
i.) INTRODUCTION
C supports a constructed data type known as structures, a mechanism for packing data of different
types. A structure is a convenient tool for handling a group of logically related data items. For
example, it can be used to represent a set of attributes, such as student _ name, roll _ number and
marks. The concept of a structure is analogous to that of a ‘record’ in many other languages. More
examples of such structures are:
time : seconds, minutes, hours
data : day, month, year
book : author, title, price, year
city : name, country, population
ii.) DEFINING A STRUCTURE
Unlike arrays, structure must be defined first for their format that may be used later to declare
structure variables
We can define a structure to hold this information as follows:
struct book _bank
{
char title[20];
char author[15];
int pages;
float price;
};
The keyword struct declares a structure to hold the details of four data fields, namely title, author,
pages, and price. These fields are called structure elements or members. Each member may belong to
different type of data. book _ bank is the name of the structure and is called the structure tag. The tag
name may be used subsequently to declare variables that have the tag’s structure.
The general format of a structure definition is as follows:
struct tag _ name
{
data _ type member1;
data _ type member2;
--------- -----
--------- -----
};
iii.) DECLARING STRUCTURE VARIABLE
Let us see how to declare structure in c programming language.
struct tag
{
data_type1 member1;
data_type2 member2;
40
data_type3 member3;
};
Example
struct date
{
int date;
char month[20];
int year;
}today;
int main()
{
printf("Vehicle No of Wheels : %d",v1.wheels);
printf("Vehicle Name : %s",v1.vname);
printf("Vehicle Color : %s",v1.color);
return(0);
}
Output :
Vehicle No of Wheels : 4
Vehicle Name : Nano
Vehicle Color : Red
void main()
{
int i;
struct Employee Emp[ 3 ]; //Statement 1
for(i=0;i<3;i++)
{
printf("\nEnter details of %d Employee",i+1);
}
Output :
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date doj;
}emp1;
#include <stdio.h>
struct Employee
{
char ename[20];
int ssn;
float salary;
struct date
{
int date;
int month;
int year;
}doj;
}emp = {"Pritesh",1000,1000.50,{22,6,1990}};
return 0;
}
Output :
Employee Name : Pritesh
Employee SSN : 1000
Employee Salary : 1000.500000
Employee DOJ : 22/6/1990
44
iii.) STRUCTURE AND FUNCTIONS:
EXPLAIN ABOUT STRUCTURE AND FUNCTIONS.(PART B)
C supports the passing of structure values as arguments to functions. There are 3 arguments by which the
values of a structure can be transferred from one function to another.
1. The first method is to pass each member of the structure as an actual argument of the function call.
2. The second method involves passing of a copy of the entire structure to the called function.
3. The third approach employs a concept called pointers i.e., the address location of the structure is
passed to the called function. This method is more efficient as compared to the second one.
Syntax:
function-name (structure_variable_name);
data-typefn-name (struct_typest_name)
{
----
----
return (expression);
Description: }
1. The called function must be declared for its type, appropriate to the data type it is expected to return.
2. The structure variable used as the actual argument and the corresponding formal argument in the
called function must be of the same struct type.
3. The return statement is necessary only when the function is returning some data.
4. When a function returns a structure, it must be assigned to a structure of identical type in the calling
function.
5. The called function must be declared in the calling function for its type, if it is placed after the
calling function.
UNION
DEFINE UNION(PART A)
A union is a special data type available in C that allows to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you did while defining a
structure. The union statement defines a new data type with more than one member for your
program. The format of the union statement is as follows −
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( )
{
45
union Data data;
return 0;
}
When the above code is compiled and executed, it produces the following result −
Memory size occupied by data : 20
i.) SIZE OF STRUCTURE
WHAT ARE ALL DIFFERENT WAYS OF CALCULATING SIZE OF STRUCTURE(PART B)
Different ways of calculating size of structure
1. By observation
2. By Using sizeof Operator
3. Without using Sizeof Operator
Way 1 : Calculate by adding Individual Sizes
struct Book
{
int pages;
char name[10];
char author[10];
float price;
}b1;
Calculating Size of Structure :
Size = size of 'Pages' + size of 'Name' +
size of 'Author' + size of 'Price'
= 2 + 10 * 1 + 10 * 1 + 4
= 2 + 10 + 10 + 4
= 26
Sizeof Operator is used to Calculate size of data type,variable,expression result.Syntax of sizeof is
much like function, but sizeof is not a library function. Sizeof is C Operator.
#include<stdio.h>
typedef struct b1 {
char bname[30];
int ssn;
int pages;
}book;
book b1 = {"Let Us C","1000",90};
int main()
{
printf("\nSize of Structure : %d",sizeof(b1));
return(0);
}
Output :
Size of Structure : 26
POINTERS
i.) INTRODUCTION
DEFINE POINTER(PART A)
Pointers are variables that hold address of another variable of same data type.
Pointers are one of the most distinct and exciting features of C language. It provides power and
flexibility to the language. Although pointer may appear little confusing and complicated in the
beginning, but trust me its a powerful tool and handy to use once its mastered.
Benefit of using pointers
Pointers are more efficient in handling Array and Structure.
Pointer allows references to function and thereby helps in passing of function as arguments to other
function.
It reduces length and the program execution time.
It allows C to support dynamic memory management.
ii.) UNDERSTANDING POINTER
Whenever a variable is declared, system will allocate a
location to that variable in the memory, to hold value. This
location will have its own address number.
Let us assume that system has allocated memory location 80F
for a variable a. int a = 10 ;
We can access the value 10 by either using the variable name a or the address 80F. Since the
memory addresses are simply numbers they can be assigned to some other variable.
The variable that holds memory address are called pointer variables. A pointer variable is therefore
nothing but a variable that contains an address, which is a location of another variable. Value of
pointer variable will be stored in another memory location.
p ----------> ?
Suppose the base address of x is 1000 and assuming that each integer requires 2 bytes then the 5
elements will be stored as follows:
Elements x [0] x [0] x [0] x [0] x [0]
Value 1 2 3 4 5
Base address
The name x is defined as a constant pointer pointing to the first element, x [0] and therefore the value
of x is 1000, the location where x [0] is stored. That is,
X = & x [0] = 1000
If we declare p as an integer pointer, then we can make the pointer p to point to the array and x by
the following assignment.
p = x;
This is equivalent to p = & x [0];
49
Now, we can access every value of x using p++ to move from one element to another. It contains the
two concepts,
1. pointers and one-dimensional arrays
2. pointers and two-dimensional arrays
Pointers and one-dimensional arrays:
It includes only one subscript (or) one index value
int a[10];
*a= *(a+0)=a[0]
*(a+1)=a[1]
*(a+2)=a[2]
*(a+3)=a[3]
*(a+4)=a[4]
……………
……………
*(a+i)=a[i]
In general,(a+i) gives the address of ith element in the array a and *(a+i) is the element stored in the
ith location of the array.
x.) POINTER AND CHARACTER STRINGS
Pointer can also be used to create strings. Pointer variables of char type are treated as string.
char *str = "Hello";
This creates a string and stores its address in the pointer variable str. The pointer str now points to
the first character of the string "Hello". Another important thing to note that string created using
char pointer can be assigned a value at runtime.
char *str;
str = "hello"; //thi is Legal
The content of the string can be printed using printf() and puts().
printf("%s", str);
puts(str);
Notice that str is pointer to the string, it is also name of the string. Therefore we do not need to use
indirection operator *.
xi.) ARRAY OF POINTERS
We can also have array of pointers. Pointers are very helpful in handling character array with rows of
varying length.
char *name[3]={
"Adam",
"chris",
"Deniel"
};
//Now see same array without using pointer
char name[3][20]= {
"Adam",
"chris",
"Deniel"
};
50
xii.) POINTERS AS FUNCTION ARGUMENTS
WRITE A NOTE ON POINTERS AND FUNCTIONS.
When we pass addresses to a function, the parameters receiving the addresses should be a pointer.
The process of calling the function using pointers to pass the addresses of variable is known as call
by reference.
Example
#include<stdio.h>
void swap (int *a, int *b )
{
int temp;
temp= *a;
Output:
a=*b;
20 10 ( the values are changed)
*b=temp;
}
void main ( )
{
int a = 10,= 20
swap (&a, &b);
printf( “%d %d”,a ,b);
}
It includes
1. Passing pointers as arguments to functions.
2. Returning a pointer from a function.
3. Pointer to a function.
Example
FILE *p1,*p2;
P1=fopen(“data”,”r”);
P2=fopen(“result”,”w”);
Mode of opening Purpose
r Open for reading
w Open for writing (file need not exist)
a Open for appending (file need not exist)
r+ Open for reading and writing, start at beginning
w+ Open for reading and writing (overwrite file)
a+ Open for reading and writing (append if file exists)
Many recent compilers include additional modes of operation. They include
r+ The existing file is opened to the beginning for both reading and wring
w+ Same as w except both for reading and writing
a+ Same as a except both for reading and writing
iii.) CLOSING A FILE:
A file must be closed as soon as all operations on it have been completed.
Syntax: fclose(file_pointer);
Here file pointer indicates the pointer of the file
Example:
FILE *p1, *p2;
P1=fopen(“input”, “w”);
P2=fopen(“output”, “r”);
……
fclose(p1);
fclose(p2);
INPUT AND OUTPUT OPERATIONS ON FILES
WHAT ARE THE INPUT AND OUTPUT OPERATIONS USED IN FILES?
i.) getc( ):
53
It is used to read a character from a file associated with FILE pointer fp1. Similarly getc is used to
read the data from file that has been opened in read mode.
Syntax: c=getc(fp);
Where c represents a variable of character and fp represents a pointer to file.
Program: To count the number of lines, words, and characters in a file.
#include<stdio.h> if(ch==' ')
#include<conio.h> w++;
void main() else if(ch=='\n' || ch=='\0')
{ {
FILE *fp; l++;
char name[100],ch; w++;
int c=0,w=0,l=0; }
clrscr(); else
printf("enter line of text : \n"); c++;
fp=fopen("sample5.txt","w"); }
scanf("%[^EOF]",name); fclose(fp);
fprintf(fp,"%s",name); printf("no of character: %d\n no of words: %d \n no of lines:
fclose(fp); %d \n",c,w,l);
fp=fopen("sample5.txt","r"); getch();
while((ch=getc(fp))!=EOF) }
{
putc( ):
It is used to write a character to the file. Syntax: putc(c,fp);
Where c represents a character and fp represents a pointer to file.
The file pointer moves by one character position for every operation of getc or putc.
The getw() and putw() functions:
The getw and putw are integer oriented functions. They are used to read and write integer values.
Syntax:
1. getw(fp);
2. putw(integer, fp);
Program to separate odd and even numbers using file.
#include<stdio.h> if(temp%2==0)
#include<conio.h> putw(temp,f3);
void main() else
{ putw(temp,f2);
FILE *f1,*f2,*f3; }
inttemp,i; fclose(f1);
clrscr(); fclose(f2);
printf("enter number:\n "); fclose(f3);
f1=fopen("input.txt","w"); f2=fopen("odd.txt","r");
for(i=0;i<=50;i++) f3=fopen("even.txt","r");
{ printf("\n Odd numbers are \n");
scanf("%d",&temp); while((temp=getw(f2)) !=EOF)
if(temp == -1) break; printf("%d ",temp);
putw(temp,f1); printf("\n Even numbers are \n");
} while((temp=getw(f3)) !=EOF)
fclose(f1); printf("%d ",temp);
f1=fopen("input.txt","r"); fclose(f2);
f2=fopen("odd.txt","w"); fclose(f3);
f3=fopen("even.txt","w"); getch();
while((temp=getw(f1)) !=EOF) }
{
fscanf ():
54
fscanf allows to read multiple data items which may (or not) be of different types to a file. fscanf() is
similar to scanf().
Syntax: fscanf(fp,”control string”,arguments-list);
fprintf():
fprintf is to write multiple data items which may (or not) be of different types to a file. fprintf() is
similar to printf()
Syntax: fprintf(fp,”control string”,arguments-list);
ERROR HANDLING DURING I/O OPERATIONS
EXPLAIN ABOUTERROR HANDLING DURING I/O OPERATIONS?
It is possible that an error may occur during I/O operations on a file.
1. Trying to read beyond the end-of file mark
2. Device overflow
3. File has not been opened
4. Opening a file with an invalid file \name
They are two status-inquiry library functions: feof and ferror that can help us detect I/O errors in the
files.
Example1:
if (feof(fp))
printf(“End of data]n”);
Example2:
if(ferror(fp)!=0)
printf(“An error has occurred”);
Statement Meaning
fseek(fp,0l,0); Go to the beginning.
fseek(fp,0l,1); Stay at the current position.
fseek(fp,0l,2); Go to the end of the file, past the last character of the file.
fseek(fp,m,0); Move to (m+1)th byte in the file
fseek(fp,m,1); Go forward by m bytes
fseek(fp,-m,1); Go backward by m bytes from the current position
fseek(fp,-m,2); Go backward by m bytes from the end.
ftell():
The function ftell() returns the current position of the file pointer
Syntax:
position=ftell(fp);
Here fp is a pointer to FILE type representing a file,the current position of the file pointer of the file
is returned by the function
rewind():
55
The rewind() repositions the file pointer to the beginning of a file
Syntax:
rewind(fp);
COMMAND LINE ARGUMENTS
EXPLAIN ABOUT COMMAND LINE ARGUMENT WITH EXAMPLE.
Itis a parameter supplied to a program when the program is invoked.
This parameter may represent a filename the program should process.
Example:
C>PROGRAM X_FILE
Consider the first line of the main function, i.e., main (). These parentheses may contain special
arguments that allow parameters to be passed to main from the Operating System. Two such
arguments are argc and argv, respectively.
The first of these, argc, must be an integer variable, while the second, argv, is an array of pointer to
characters, i.e., an array of strings. Each string in this array will represent a parameter that is passed
to main.
The value of argcwill indicate the number of parameters passed. The variable argc is an argument
counter that counts thye number of arguments on the command line.
The argv is an argument vector and represents an array of character pointers that points to the
command line arguments.
argv[0]->PROGRAM
argv[1]->X_FILE
argv[2]->Y_FILE
Program:
#include<stdio.h>
#include<process.h>
void main(intargc,char *argv[]);
{
FILE *fin,*fout;
Char c;
If(argc!=3) Output:
{ C:\>copy om.dat om1.dat
printf(“Invalid number of arguments”); As a result the contents of om.dat are
exit(1); copied to om1.dat
}
fin=fopen(argv[1],”r”);
fout=fopen(argv[2],”w”);
while(!feof(fin))
{
c=getc(fin);
putc(c,fout);
}
fclose(fin);
fclose(fout);
}
Example Program:
#include <stdio.h>
main()
{ When the above code is compiled and
FILE *fp; executed, it reads the file created in previous
char buff[100]; section and produces the following result:
fp = fopen("/tmp/test.txt", "r"); 1 : This
fscanf(fp, "%s", buff); 2: is testing for fprintf...
printf("1 : %s\n", buff );
56
fgets(buff, 255, (FILE*)fp);
printf("2: %s\n", buff );
fgets(buff, 255, (FILE*)fp);
printf("3: %s\n", buff );
fclose(fp);
}
Example Program
#include <stdio.h> When the above code is compiled and executed, it waits
int main( ) for you to input some text when you enter a text and
{ press enter then program proceeds and reads the input
char str[100]; and displays it as follows:
int i;
printf( "Enter a value :"); $./a.out
scanf("%s %d", str, &i); Enter a value : seven 7
printf( "\nYou entered: %s, %d ", str, i); You entered: seven 7
return 0;
}
UNIT –V COMPLETED
Reference Book: “Programming in ANSI C”, Fifth Edition , by E.Balagurusamy.
57