C PROGRAMING
C PROGRAMING
PROGRAMMING IN ‘C’
BCA I Semester
Compiled by
Prof.Panchajanyeswari M Achar
SIMS, Mangalore
--------------
2015-16
Srinivas Institute of Management Studies BCA – I Semester
CONTENTS
UNIT I PAGE
Chapter 1 5
Overview of C
1.1 History of C
1.2 Importance of C
1.3 Basic Structure of C program
1.4 Rules for writing a C program
1.5 Execution Style of C program
Assignment
Chapter 2 10
Constants, variables and data types
2.1 Character Set
2.2 C tokens
2.3 Keywords and identifiers
2.4 Constants
2.5 Variable
2.6 Data types
2.7 Declaration of variables
2.8 Assigning values to variables
2.9 Defining symbolic constant
Assignment
Chapter 3 17
Operators and Expressions
3.1 Arithmetic Operators
3.2 Relational Operators
3.3 Logical Operators
3.4 Assignment Operators
3.5 Increment and decrement operators
3.6 Conditional Operators
3.7 Bitwise Operators
3.8 Special operators
3.9 Evaluating expressions
3.10 Precedence of operators and associativity
3.11 Type conversions
3.12 Built-in mathematical functions
Assignment
Chapter 4 25
Managing input/output operations
4.1 Reading and writing a character
4.2 Formatted input – usage of scanf function
4.3 Formatted output – usage of printf function
4.3.1 Output of integers
Compiled by
Mrs. Panchajanyeswari 1
Srinivas Institute of Management Studies BCA – I Semester
Chapter 7 48
Arrays
7.1 Declaration and initialization
7.2 Accessing one dimensional array
7.3 Accessing two dimensional array
7.4 Sample programs in Arrays
7.4.1 C program to implement linear search
7.4.2 C program to sort an array in descending order
7.4.3 C program to add two matrices
7.4.4 C program to multiply two matrices
7.4.5 C Program to find transpose of a Matrix
Assignment
UNIT III
Chapter 8 56
Handling of character strings
8.1 Declaring and initializing string variables
8.2 Reading strings from terminal
8.3 Writing strings onto screen
8.4 Arithmetic operations on characters
8.5 Putting strings together
8.6 Comparison of strings
Compiled by
Mrs. Panchajanyeswari 2
Srinivas Institute of Management Studies BCA – I Semester
UNIT IV
Chapter 10 75
Structures and Unions
10.1 Structure definitions
10.2 Giving values to members
10.3 Structure initialization
10.4 Comparison of structure variables
10.5 Array of structures
10.6 Arrays within structures
10.7 Structures within structures
10.8 Structures and functions
10.9 Unions
10.10 Size of structures
10.11 Bit fields
Assignment
Chapter 11 80
Pointers
11.1 Understanding pointers
11.2 Accessing a pointer variable
11.3 Declaring and initializing a pointer variable
11.4 Accessing a pointer variable
11.5 Pointer expressions
11.6 Pointer increments and scale factor
11.7 Pointers and arrays
11.8 Call by value
11.9 Call by reference
Assignment
Compiled by
Mrs. Panchajanyeswari 3
Srinivas Institute of Management Studies BCA – I Semester
Chapter 12 84
The preprocessor
12.1 Macro substitution
12.2 File inclusion
12.3 Compiler control directives
12.4 Command line arguments
Assignment
Chapter 13 87
File management in C
13.1 Introduction
13.2 Defining and opening a file
13.3 Closing a file
13.4 I/O operations on files
13.5 Error handling during I/O operations
Assignment
Compiled by
Mrs. Panchajanyeswari 4
Srinivas Institute of Management Studies BCA – I Semester
UNIT I
CHAPTER 1
OVERVIEW OF C LANGUAGE
1.1 History of C
1.2 Importance of C
1.3 Basic Structure of C program
1.4 Rules for writing a C program
1.5 Execution Style of C program
Assignment questions
1.1 History of C:
C is an offspring of Basic Combined Programming Language BCPL called B developed
in 1960’s at Cambridge University. B language was modified and written by Dennis Ritchie and
the language was called C. C language was developed and implemented at AT&T’s Bell
laboratory in the year 1972. Over the years C became very popular because it was reliable,
simple and easy to use.
Compiled by
Mrs. Panchajanyeswari 5
Srinivas Institute of Management Studies BCA – I Semester
• The definition section is used to define all the symbolic constants in a program
• Global declaration section declares all the global variables in the program. A global
variable is a variable that is used in more than one function in a program. These variables
are declared outside so that they can be accessed by all the functions in the application.
• Every C program must have only one main() function. It indicates that the name of the
function is main and that the program execution should begin here. The empty
parenthesis () that follow main indicate that the function has no arguments. The actual
execution of the program begins here.
• This section consists of 2 parts – declaration part and execution part. All the variables
that are used in the program are declared in the declaration part. There must be at least
one statement n the execution part. These 2 parts are enclosed between curly braces{}.
Program execution begins at the opening brace { and the closing brace } indicates the
logical end of the program. Ever statement in this ection are terminated by a semicolon(;).
• Every C program must have a main() section.
• The sub program section contains all the user defined functions that are called in the main
function.
Documentation Section
Link Section
Definition Section
Subprogram section
Function 1
……
Function n
Sample Program 1:
Compiled by
Mrs. Panchajanyeswari 7
Srinivas Institute of Management Studies BCA – I Semester
/*Documentation Section*/
/*Sample C Program to find area of a circle*/
/*Link Section*/
#include<stdio.h>
/*Definition Section*/
#define PI 3.141592
/*main function section*/
void main()
{
int rad; /*declaration part*/
float area;
clrscr();
rad=14; /*execution part*/
area=PI*rad*rad;
printf("Area:%f",area);
getch();
}
Output:
Area : 615.752014
Sample Program 2:
#include<stdio.h>
void main()
{
printf("Hi Jahnavi");
getch();
}
Output:
Hi Jahnavi
Compiled by
Mrs. Panchajanyeswari 7
Srinivas Institute of Management Studies BCA – I Semester
System Ready
Compile Source
C Compiler
Program
Syntax
Errors ?
Yes
CORRECT OUTPUT
Compiled by
Stop
Mrs. Panchajanyeswari 8
Srinivas Institute of Management Studies BCA – I Semester
Assignment
1. Explain the structure of a C program.(2006, 2007,2010,2013)
2. List the features of C (2008,2011)
3. What are the rules to write a C program?
Compiled by
Mrs. Panchajanyeswari 9
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 2
CONSTANTS, VARIABLES AND DATA TYPES
2.1 Character Set
2.2 C tokens
2.3 Keywords and identifiers
2.4 Constants
2.5 Variable
2.6 Data types
2.7 Declaration of variables
Compiled by
Mrs. Panchajanyeswari 10
Srinivas Institute of Management Studies BCA – I Semester
2.2 C Tokens:
The smallest individual units in a program are known as tokens. C supports 6 types of
tokens. They are
• Keywords
• Identifiers
• Constants
• Strings
• Special symbols
• Operators
C TOKENS
Compiled by
Mrs. Panchajanyeswari 11
Keywords Constants Strings Operators
-15.5 “ABC”
Float while +-/*
100 “year”
2.4 Constants:
A constant refers to a fixed value that does not change during the execution of a program.
Integer constants refer to a sequence of digits preceded by an optional +/- sign. E.g. +123, -567,
0. Decimal integers consist of a set of digits 0-9. An octal integer consists of combination of
digits from 0 to 7 with a leading 0. E.g. 032, 056,0435. A hexadecimal integer consists of 0-9
digits and alphabets A through F to represent numbers from 10-15. A hexadecimal integer is
preceded by 0x or 0X. E.g. 0xF2, 0X35A, 0x56
Constants
Compiled by
Mrs. Panchajanyeswari 12
Srinivas Institute of Management Studies BCA – I Semester
• The mantissa could be either a real number expressed in decimal notation or an integer.
The exponent is an integer with an optional +/- sign. E.g. 0.65e4, 1.25e-5, 56.23E-1
Constant Meaning
‘\a’ Audible alert
‘\n’ New line
‘\t’ Horizontal tab space
‘\0’ Null character
‘\’’ Single quote
2.5 Variables:
• A variable is a data name that may be used to store a data value
• A variable may take different values at different times during execution.
• The value of a variable changes during the execution of a program
Rules for naming a variable:
• Variable names should begin with a letter.
• Variable names should not be keywords.
• Blank spaces are not allowed.
• Uppercase and lowercase letters are significant because C is a case sensitive language.
• Length of a variable name should not exceed 8 characters
Integral Type
Compiled by
Mrs. Panchajanyeswari Integer Character 13
Compiled by
Mrs. Panchajanyeswari 14
Srinivas Institute of Management Studies BCA – I Semester
• Short int is used for small range of values and requires half the amount of storage as a
regular int number uses.
• Long int requires double the storage as an int value.
• In unsigned integers, all the bits in the storage are used to store the magnitude and are
always positive
units batch1,batch2;
marks m1,m2,m3;
• Another type of user defined data type is enumerated data types
Syntax: enum identifier {value1,value2,…,valuen};
Compiled by
Mrs. Panchajanyeswari 15
Srinivas Institute of Management Studies BCA – I Semester
Compiled by
Mrs. Panchajanyeswari 16
Srinivas Institute of Management Studies BCA – I Semester
Assignment
2 mark Questions:
1. Define variable.(2005,2007, 2008,2011,2012)
2. Define constant (2007,2008)
3. What are trigraph characters? Give example.
4. What is a backslash constant? Give example. (2009, 2011)
5. Define keyword. Give example. (2005,2007, 2008)
6. What is a token in C? Give example
7. List the character set in C.
8. How do you declare a variable in C? Give example (2004,2009,2010)
9. How do you assign a value to a variable? Give example.
10. How do you declare a variable as a constant? Give example (2010,2009)
11. How do you define a symbolic constant in C? Give example
12. Differentiate between keyword and identifier(2007,2009,2011)
13. What is the purpose of typedef in C?
14. What is the purpose of enum keyword in C?
5 mark Questions:
1. Explain the primary data types in C. (2008,2009)
2. Explain the various types of constants in C.(2006,2007)
3. Explain about tokens available in C.(2008)
4. How do you declare a variable in C? What are the rules to form a variable?(2008)
5. Write a note on user defined data types in C.
Compiled by
Mrs. Panchajanyeswari 17
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 3
OPERATORS AND EXPRESSIONS
3.1 Arithmetic Operators
3.2 Relational Operators
3.3 Logical Operators
3.4 Assignment Operators
3.5 Increment and decrement operators
3.6 Conditional Operators
3.7 Bitwise Operators
3.8 Special operators
3.9 Evaluating expressions
3.10 Precedence of operators and associativity
3.11 Type conversions
3.12 Built-in mathematical functions
Assignment
C supports a rich set of operators. An operator is a symbol that tells the computer
to perform an arithmetic or logical function. Operators are used in programs to manipulate data
and variables. Operators in C can be classified into a number of categories. They are
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Increment and Decrement Operators
Conditional Operators
Bitwise Operator
Special Operators
Compiled by
Mrs. Panchajanyeswari 18
Srinivas Institute of Management Studies BCA – I Semester
Operator Meaning
&& Logical And
|| Logical Or
! Logical Not
Compiled by
Mrs. Panchajanyeswari 19
Srinivas Institute of Management Studies BCA – I Semester
Compiled by
Mrs. Panchajanyeswari 20
Srinivas Institute of Management Studies BCA – I Semester
b=10;
x=(a>b)?a:b;
The output of the above example is as follows- The value of b i.e. 10 is assigned to x.
Program:
#include<stdio.h>
void main()
{
int a,b,small;
printf("Enter value for a");
scanf("%d",&a);
printf("Enter value for b");
scanf("%d",&b);
small=(a<b)?a:b;
printf("%d is small",small);
getch();
}
Operator Meaning
& Bitwise And
| Bitwise Or
^ Bitwise exclusive Or
<< Shift left
>> Shift Right
~ One’s complement
Sample Program:
#include<stdio.h>
void main()
{
float x;
printf("The size of variable x is %d bytes",sizeof(x));
getch();
Compiled by
Mrs. Panchajanyeswari 21
Srinivas Institute of Management Studies BCA – I Semester
Output:
The size of variable x is 4 bytes
If more than one operators are involved in an expression then, C language has predefined rule of
priority of operators. This rule of priority of operators is called operator precedence.
Associativity of operators
Associativity indicates in which order two operators of same precedence(priority) executes. Let
us suppose an expression:
a==b!=c
Compiled by
Mrs. Panchajanyeswari 22
Srinivas Institute of Management Studies BCA – I Semester
Here, operators == and != have same precedence. The associativity of both == and != is left to
right, i.e, the expression in left is executed first and execution take pale towards right. Thus,
a==b!=c equivalent to :
(a==b)!=c
The table below shows all the operators in C with precedence and associativity.
Note: Precedence of operators decreases from top to bottom in the given table.
Summary of C operators with precedence and associativity
Operator Meaning of operator Associativity
() Functional call
[] Array element reference
Left to right
-> Indirect member selection
. Direct member selection
! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
Right to left
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply
/ Divide Left to right
% Remainder
+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)
<< Left shift
Left to right
>> Right shift
< Less than
<= Less than or equal
Left to right
> Greater than
>= Greater than or equal
== Equal to
Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Left to right
= Simple assignment Right to left
Compiled by
Mrs. Panchajanyeswari 23
Srinivas Institute of Management Studies BCA – I Semester
Assignment:
2 mark questions
1. What is the difference between pre-increment and post-increment operators (2006)
2. If the value of a=5 then, explain a—and –a.
Compiled by
Mrs. Panchajanyeswari 24
Srinivas Institute of Management Studies BCA – I Semester
Compiled by
Mrs. Panchajanyeswari 25
Srinivas Institute of Management Studies BCA – I Semester
UNIT II
CHAPTER 4
MANAGING INPUT/OUTPUT OPERATIONS
4.1.2Writing a Character:
putchar( ) is the function used to display one character at a time on the terminal.
Syntax: putchar(var-name);
Here var-name is a valid C variable declared as a character data type.
E.g. ch= ‘n’;
putchar(ch);
The above statements display the character ‘n’ on the monitor.
Compiled by
Mrs. Panchajanyeswari 26
Srinivas Institute of Management Studies BCA – I Semester
Compiled by
Mrs. Panchajanyeswari 27
Srinivas Institute of Management Studies BCA – I Semester
by placing a minus (-) sign after %. We can also pad the leading spaces by 0 by placing a 0
before a field specifier.
Examples:
printf(“%d”,1978) ;
Output: 1 9 7 8
printf(“%6d”,1978);
Output:
1 9 7 8
printf(“%-6d”,1978);
Output:
1 9 7 8
printf(“%06d”,1978);
Output:
0 0 1 9 7 8
9 8 . 7 7
printf(“%10.2e”,y);
9 . 8 8 e + 0 1
printf(“%11.4e”,-y);
- 9 . 8 7 6 5 e + 0 1
Compiled by
Mrs. Panchajanyeswari 28
Srinivas Institute of Management Studies BCA – I Semester
printf(“%10s”,city);
C H E N N A I
printf(“%10.4s”,city);
C H E N
printf(“%-10s”,city);
C H E N N A I
Assignment
2 mark Questions:
1. What is purpose of getchar() function in C? (2006,2008,2011)
2. What is purpose of putchar() function in C?(2005,2008)
3. Give the syntax of scanf with example. (2005,2008,2011)
4. Give the syntax of printf with example.(2007)
5 mark Questions:
1. Explain how to get formatted output for real numbers in C with examples.(2011)
2. Explain how to get formatted output for strings in C with examples.(2012)
3. Explain how to get formatted output for integer numbers in C with examples.(2005)
Compiled by
Mrs. Panchajanyeswari 29
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 5
DECISION MAKING AND BRANCHING
Introduction:
The program statements are executed sequentially. But, sometimes we need to change the
order of execution of statements depending on certain conditions. C language possesses decision
making capabilities and supports statements called decision making statements. The decision
making statements supported by C are as follows:
1. if statement
2. switch statement
3. Conditional operator statement
4. goto statement
The if statement:
The if statement is a powerful decision making statement and is used to control the flow
of execution of statements. It is basically a two-way decision statement used in conjunction with
an expression. The computer evaluates the value of the expression first and depending on the
value of the expression it transfers control to a particular statement. The if statement can be
implemented in different forms depending on the complexity of the conditions to be tested. The
different forms of if statements are:
• Simple if
Compiled by
Mrs. Panchajanyeswari 30
Srinivas Institute of Management Studies BCA – I Semester
• If…else statement
• Nested if…else statement
• Elseif ladder
Example:
if(category==sports)
{
mark=mark+bonus;
}
printf(“%f “ ,mark);
Entry
Test True
expression
?
Statement – x
Compiled by
Mrs. Panchajanyeswari 31
Srinivas Institute of Management Studies BCA – I Semester
if(test-expression)
{
True-block statements;
}
else
{
False-block statements;
}
Statement x;
If the test expression is true, then the true block statements are executed otherwise the
false block statements are executed. Either of the two statements, i.e. true block or false block
statements only are executed, but not both. In both the cases, the control transfers to statement x
after executing the block.
Example 1:
if(code==1)
boy=boy+1;
else
girl=girl+1;
Example 2:
if(a>b)
printf(“a is greater than b”);
else
printf(“b is greater than a”);
Test
expression
?
Statement – x
Sample Program:
Compiled by
Mrs. Panchajanyeswari 32
Srinivas Institute of Management Studies BCA – I Semester
#include<stdio.h>
void main()
{
int n;
printf("Enter Number");
scanf("%d",&n);
if(n%2==0)
printf("Even Number");
else
printf("Odd number");
getch();
}
Output:
Enter Number 5
Odd number
Enter Number 8
Even Number
if(test condition1)
{
if (test condition2)
statement 1;
else
statement 2;
}
else
statement 3;
statement x;
False True
Test
Compiled by expression
Mrs. Panchajanyeswari 1? 33
statement – 3 Statement – 2
Statement- 1
Srinivas Institute of Management Studies BCA – I Semester
Example 1:
if(sex==”F”)
{
if(bal>50000)
bonus=0.05*bal;
else
bonus=0.02*bal;
}
else
bonus=0.01*bal;
bal=bal+bonus;
Example 2:
if (i > 2)
{
if (i < 4)
{
printf ("i is three");
}
}
Example 3:
#include<stdio.h>
void main()
{
int a,b,c;
clrscr();
printf("Enter value for a:");
scanf("%d",&a);
Compiled by
Mrs. Panchajanyeswari 34
Srinivas Institute of Management Studies BCA – I Semester
True False
Condition 1
True False
Condition 2
Statement - 1
Statement -2 False
Condition 3
Statement - 3 False
True
Condition n
Statement - n
Default
statement
Compiled by
Mrs. Panchajanyeswari 35
Statement -x
Next statement
Srinivas Institute of Management Studies BCA – I Semester
if(condition 1)
statement 1;
elseif(condition 2)
statement 2;
elseif(condition 3)
statement 3;
:
:
elseif(condition n)
statement n;
else
default statement;
statement x;
Here the conditions are evaluated from top. As soon as a true condition is encountered,
the statements associated with it are executed and the control is transferred to statement x. If all
the conditions are false, then the final else containing the default statement will be executed.
Example:
if(marks>79)
grade= “ Distinction”;
else if(marks>59)
grade= “ First”;
else if(marks>49)
grade= “ Second”;
else if(marks>39)
grade= “ Third”;
else
grade= “Fail”;
printf(“%s”,grade);
Compiled by
Mrs. Panchajanyeswari 36
Srinivas Institute of Management Studies BCA – I Semester
switch(expression)
{
case value 1:
block 1;
break;
case value 2:
block 2;
break;
:
:
case value n:
block n;
break;
default:
block x;
break;
}
Compiled by
Mrs. Panchajanyeswari 37
Srinivas Institute of Management Studies BCA – I Semester
Example:
index=marks/10;
switch(index)
{
case 10:
case 9:
case 8:
grade=’A’;
break;
case 7:
case 6:
grade=’B’;
break;
case 5:
grade=’C’;
Compiled by
Mrs. Panchajanyeswari 38
Srinivas Institute of Management Studies BCA – I Semester
break;
case 4:
grade=’D’;
break;
default:
grade=’E’;
break;
}
printf(“%c”,grade);
Program:
#include<stdio.h>
void main()
{
char ch;
printf("Enter a character in CAPITAL:");
scanf("%c",&ch);
switch(ch)
{
case 'V':printf("Color is Violet");
break;
case 'I':printf("Color is Indigo");
break;
case 'B':printf("Color is Blue");
break;
case 'G':printf("Color is Green");
break;
case 'Y':printf("Color is Yellow");
break;
case 'O':printf("Color is Orange");
break;
case 'R':printf("Color is Red");
break;
default :printf("Color not in Rainbow");
}
getch();
}
Output:
Enter a character in CAPITAL:B
Color is Blue
Enter a character in CAPITAL:E
Color not in Rainbow
Compiled by
Mrs. Panchajanyeswari 39
Srinivas Institute of Management Studies BCA – I Semester
Statement Description
An if statement consists of a boolean expression followed by
if statement
one or more statements.
An if statement can be followed by an optional else statement,
if...else statement
which executes when the boolean expression is false.
You can use one if or else if statement inside another if or else
nested if statements
if statement(s).
A switch statement allows a variable to be tested for equality
switch statement
against a list of values.
Sample Program:
#include<stdio.h>
void main()
{
int a,b,small;
clrscr();f
printf("Enter value for a");
scanf("%d",&a);
printf("Enter value for b");
scanf("%d",&b);
small=(a<b)?a:b;
printf("%d is small",small);
getch();
}
Output:
Enter value for a 5
Enter value for b 4
4 is small
Compiled by
Mrs. Panchajanyeswari 40
Srinivas Institute of Management Studies BCA – I Semester
Goto statements are used to branch unconditionally from one point to another in a
program. The goto statement requires a label in order to identify the place where the branch is to
be made. A label can be any valid user defined name and must be followed by a : . The label is
placed immediately before the statement where the control is to be transferred. The label can
appear anywhere in the program either before or after the goto label. The goto statement can be
used to transfer control outside the loop when peculiar conditions are encountered. Goto
statements are generally avoided in structured programming.
Syntax:
goto label;
----------
----------
label:
statement ;
Assignment:
2 mark Questions:
1. Give the syntax of simple if with example.(2007,2010)
2. What is the purpose of goto statement?(2008)
3. What is ternary operator? Give example.(2006.2008,2009)
4. Give the syntax of switch statement.(2011)
5 mark Questions:
1. Explain the various forms if statement with example.(2006,2007,2009)
2. Explain the working of switch statement with an example.(2005,2008,2011)
CHAPTER 6
DECISION MAKING AND LOOPING
Compiled by
Mrs. Panchajanyeswari 41
Srinivas Institute of Management Studies BCA – I Semester
Introduction
Looping is executing a sequence of statements until some conditions to terminate the loop are
satisfied. A program loop consists of 2 segments i.e. body of the loop and control statements.
The control statements test certain condition and then direct repeated execution of statements
contained in the body of the loop. A looping process includes the following steps
1. Setting and initializing of a counter
2. Execution of statements in a loop
3. Test for specified condition for executing the loop
4. Incrementing the counter
False
Test
Condition?
Body of loop
Entry
Compiled by
Mrs. Panchajanyeswari 42
Body of loop
Srinivas Institute of Management Studies BCA – I Semester
C language supports 3 loop constructs to perform looping operations. They are as follows
• While statement
• Do…while statement
• For statement
Example:
i=1;
while(i<=10)
Compiled by
Mrs. Panchajanyeswari 43
Srinivas Institute of Management Studies BCA – I Semester
{
printf(“%d”,i);
}
Compiled by
Mrs. Panchajanyeswari 44
Srinivas Institute of Management Studies BCA – I Semester
This loop is an exit controlled loop because the condition is checked after executing the
statements in the loop. Here the statements are executed first and then, checks the condition. The
body of the loop is executed at least once even if the condition is initially false. On reaching the
do statement the body of the loop is executed. The test condition in the while statement is
evaluated. If the condition is true, execution of the loop is repeated. This process continues as
long as the condition specified in the while statement is true. Once the condition becomes false,
the loop is terminated and the control goes to the statement after the while statement.
Compiled by
Mrs. Panchajanyeswari 45
Srinivas Institute of Management Studies BCA – I Semester
scanf("%d",&y);
i=1;
do
{
p=p*x;
i++;
}while(i<=y);
printf("%d power %d is %d",x,y,p);
getch();
}
Example :
#include<stdio.h>
void main()
{
int i;
clrscr();
for(i=1;i<=5;i++)
printf("%d\t",i);
getch();
}
Compiled by
Mrs. Panchajanyeswari 46
Srinivas Institute of Management Studies BCA – I Semester
Like a while statement, except that it tests the condition at the end of
do...while loop
the loop body
You can use one or more loop inside any another while, for or
nested loops
do..while loop.
Compiled by
Mrs. Panchajanyeswari 47
Srinivas Institute of Management Studies BCA – I Semester
break;
Compiled by
Mrs. Panchajanyeswari 48
Srinivas Institute of Management Studies BCA – I Semester
Assignment
2 mark Questions:
1. What is the purpose of break statement in C? (2005, 2007,2008,2011)
2. What is the purpose of continue statement in C? (2006,2009)
3. Give the difference between break and continue statements.(2010)
4. Give the syntax of while loop.
5. Give the syntax of do..while loop.
6. Give the syntax of for loop.
5 mark Questions:
1. Explain the working of while loop with syntax and example (2006,2007,2009)
2. Explain the working of do..while loop with syntax and example(2006,2009)
3. Explain the working of for loop with syntax and example(2005,2008)
4. Write a C program to find the sum of n natural numbers
5. Write a C program to find factorial of a number(2007,2009,2011)
6. Write a C program to find power of a number
7. Write a C program to find the sum of digits of a number(2007,2009,2010)
8. Write a C program to check whether a given number is armstrong or not
9. Write a C program to check whether a given number is prime or not
10. Write a C program to reverse a number (2010,2012)
Compiled by
Mrs. Panchajanyeswari 49
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 7
ARRAYS
7.1 Declaration and initialization
7.2 Accessing one dimensional array
7.3 Accessing two dimensional array
7.4 Sample programs in Arrays
7.4.1 C program to implement linear search
7.4.2 C program to sort an array in descending order
7.4.3 C program to add two matrices
7.4.4 C program to multiply two matrices
7.4.5 C Program to find transpose of a Matrix
Assignment questions
Introduction:
Definition: An array is a group of related data items that share a common name. Each element in
an array can be accessed by an index number or a subscript written in square brackets.
The complete set of values is referred to as an array and the individual values are called
elements. Arrays can be declared as any data type. Arrays can be of 2 types. They are
• One dimensional array
• Multidimensional array
Arrays are most useful when they have a large number of elements: that is, in cases where it
would be completely impractical to have a different name for every storage space in the memory.
It is then highly beneficial to move over to arrays for storing information for two reasons:
• The storage spaces in arrays have indices. These numbers can often be related to
variables in a problem and so there is a logical connection to be made between an array
an a program.
• In C, arrays can be initialized very easily indeed. It is far easier to initialize an array than
it is to initialize twenty or so variables.
Compiled by
Mrs. Panchajanyeswari 50
Srinivas Institute of Management Studies BCA – I Semester
type array-name[size];
Here, type specifies the data type of the elements contained in the array. The size indicates the
maximum number of elements that can be stored in an array.
Example:
int age[5];
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of array
age. All element in an array are of the same type (int, in this case).
When a variable is declared as an array the computer reserves the specified number of maximum
storage for that variable. C language treats strings as array of characters. The size in character
string represents the maximum number of characters it can hold.
Example:
char name[10];
name= “RAMA”
The variable name is stored in the array as follows:
Compiled by
Mrs. Panchajanyeswari 51
Srinivas Institute of Management Studies BCA – I Semester
scanf("%d",&age[i]);
/* Statement to insert value in (i+1)th element of array age[]. */
/* Because, the first element of array is age[0], second is age[1], ith is
age[i-1] and (i+1)th is age[i].
/*Statement to print the first element in the array*/
printf("%d",age[0]);
Size of array defines the number of elements in an array. Each element of array can be accessed
and used by user according to the need of program. For example:
Example:
float numbers[8][7];
Here, row size and column size are some constant. (The sizes of the two dimensions do not have
to be the same.) This is called a two dimensional array because it has two indices, or two labels
in square brackets. It has (SIZE * SIZE) or size-squared elements in it, which form an imaginary
grid, like a chess board, in which every square is a variable or storage area.
Example: If A is a 2x6 array, it can be represented as follows. Here the first number indicates the
row and the second represents the column. In C, each is written within square brackets.
Compiled by
Mrs. Panchajanyeswari 52
Srinivas Institute of Management Studies BCA – I Semester
Each dimension in the array is indexed from 0 to maximum size minus one. The first
index is used to select the row and the second index is used to select the column within that row.
If the values are missing in the initializer, they are automatically set to zero. If all the
elements in the array are to be set to zero then the following method is used
static int table[3][5]={{0},{0},{0}};
Multidimensional array:
C allows arrays of 3 or more dimensions. The exact limit on the number of dimensions
depends on the compiler. The general form of multidimensional array declaration is
type array-name [s1][s2]….[sm];
where si is the size of the ith dimension.
Example:
int survey[3][5][12];
The above declaration can be used to store the amount of rainfall in past 3 years, in five cities
during 12 months.
Compiled by
Mrs. Panchajanyeswari 53
Srinivas Institute of Management Studies BCA – I Semester
scanf("%d",&key);
flag=0;
for(i=1;i<=n;i++)
if(key==a[i])
{
flag=1;
break;
}
if(flag==1)
printf("Element is found at position %d",i);
else
printf("Element not found");
getch();
}
Compiled by
Mrs. Panchajanyeswari 54
Srinivas Institute of Management Studies BCA – I Semester
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j;
clrscr();
printf("Enter the number of rows for 1st matrix\n");
scanf("%d",&m);
printf("Enter the number of columns for 1st matrix\n");
scanf("%d",&n);
printf("Enter the number of rows for 2nd matrix\n");
scanf("%d",&p);
printf("Enter the number of columns for 2nd matrix\n");
scanf("%d",&q);
if(m!=p || n!=q)
printf("Matrix addition not possible");
else
{
printf("Enter the elements of the 1st matrix:");
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("Enter the elements of the 2nd matrix:");
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&b[i][j]);
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
c[i][j]=a[i][j]+b[i][j];
printf("The resultant matrix is \n");
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
printf("%d ",c[i][j]);
printf("\n");
}
}
getch();
}
Compiled by
Mrs. Panchajanyeswari 55
Srinivas Institute of Management Studies BCA – I Semester
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
printf("Enter the number of rows for 1st matrix\n");
scanf("%d",&m);
printf("Enter the number of columns for 1st matrix\n");
scanf("%d",&n);
printf("Enter the number of rows for 2nd matrix\n");
scanf("%d",&p);
printf("Enter the number of columns for 2nd matrix\n");
scanf("%d",&q);
if(n!=p)
printf("Matrix Multiplication not possible");
else
{
printf("Enter the elements of the 1st matrix:");
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("Enter the elements of the 2nd matrix:");
for(j=1;j<=p;j++)
for(k=1;k<=q;k++)
scanf("%d",&b[j][k]);
for(i=1;i<=m;i++)
for(k=1;k<=q;k++)
{
c[i][k]=0;
for(j=1;j<=n;j++)
c[i][k]=c[i][k]+(a[i][j]*b[j][k]);
}
printf("The resultant matrix is \n");
for(i=1;i<=m;i++)
{
for(k=1;k<=q;k++)
printf("%d ",c[i][k]);
printf("\n");
}
}
getch();
}
Compiled by
Mrs. Panchajanyeswari 56
Srinivas Institute of Management Studies BCA – I Semester
#include<conio.h>
void main()
{
int a[5][5],m,n,i,j;
clrscr();
printf("Enter the number of rows\n");
scanf("%d",&m);
printf("Enter the number of columns\n");
scanf("%d",&n);
printf("Enter the elements of the matrix:");
for(i=1;i<=m;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("The given matrix is :\n");
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
printf("%d ",a[i][j]);
printf("\n");
}
printf("The transpose of a matrix is \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
printf("%d ",a[j][i]);
printf("\n");
}
getch();
}
Assignment
2 mark Questions:
1. Define an array.
2. How do you declare a one dimensional array in C? Give example (2009,2010)
3. How do you declare a two dimensional array in C? Give example(2006,2008)
4. How do you initialize a one dimensional array in C? Give example(2007,2010)
5. How do you initialize a two dimensional array in C? Give example(2007)
5 mark Questions:
1. How do you work with one dimensional array in C? Give example(2010)
2. How do you work with two dimensional array in C? Give example(2011)
3. Write a C program to find the largest element in an array.(2012)
4. Write a C program to sort a list of elements in ascending order.(2006,2009,2010)
5. Write a C program to find the sum of diagonal elements in an array
Compiled by
Mrs. Panchajanyeswari 57
Srinivas Institute of Management Studies BCA – I Semester
UNIT III
CHAPTER 8
HANDLING OF CHARACTER STRINGS
8.1 Declaring and initializing string variables
8.2 Reading strings from terminal
8.3 Writing strings onto screen
8.4 Arithmetic operations on characters
8.5 Putting strings together – Concatenating Strings
8.6 Comparison of strings
8.7 String handling functions
8.8 Table of strings
Assignment
Introduction
A string is an array of characters. Any group of characters enclosed in double quotes is a
string constant.
E.g.: “Hello”
The common operations performed on strings are
1. Reading/Writing
2. Combining strings
3. Copying one string to another
4. Comparing two strings
5. Extracting a portion of strings
Compiled by
Mrs. Panchajanyeswari 58
Srinivas Institute of Management Studies BCA – I Semester
When a character string is assigned to a character array, the compiler automatically supplies a
null character (‘\0’) at the end of the string. Hence the size should always be equal to the
maximum number of characters plus one. C permits a character array to be initialized in either of
the following forms
static char city[9]= “NEW YORK”;
static char city[9]= {‘N’, ‘E’, ‘W’, ‘ ‘, ‘Y’, ‘O’, ‘R’, ‘K’ ‘\0’};
static char name[]= { ‘G’, ‘O’, ‘O’, ‘D’, ‘\0’};
When we initialize a character array by listing elements, a null character must be specified
explicitly. C also permits to initialize character strings without specifying the number of
elements.
Compiled by
Mrs. Panchajanyeswari 59
Srinivas Institute of Management Studies BCA – I Semester
putchar(ch);
}while(ch!=’\n’);
For example: This expression (ch>= ‘A’ && ch<= ‘Z’) would test if the character contained in
ch is an upper case letter.
We can also convert character digit to its equivalent integer value using the following statement.
x=ch-digit – ‘0’;
Here x is a variable and ch-digit is a character digit.
E.g. Let us assume that ch-digit contains the digit ‘7’, then
x= ASCII value of 7 – ASCII value of 0;
= 55-48 = 7
C library also supports a function that converts a string of digits to its equivalent integer
value. This is done using the function atoi. The general format of this function is
x= atoi(string);
where x is an integer variable and string is a character array containing a string of digits.
Compiled by
Mrs. Panchajanyeswari 60
Srinivas Institute of Management Studies BCA – I Semester
Strings cannot be compared directly. We have to compare the two strings character by
character. The comparison is done till there is a mismatch or one of the strings terminates to a
null character, whichever occurs first.
word2:
G O O D ‘\0’
strcat(word1,word2);
#include<stdio.h>
#include<string.h>
void main()
{
char str1[31]="Sri";str2[32]="nivas";
printf("\nFirst String is %s\n",str1);
Compiled by
Mrs. Panchajanyeswari 61
Srinivas Institute of Management Studies BCA – I Semester
Output:
First String is Sri
Second String is nivas
Resultant String Sri nivas
Program:
/*Use of Strcmp Function*/
#include<stdio.h>
#include<string.h>
void main(void)
{
char str1[31],str2[31];
int value;
printf("\n Enter string 1");
gets(str1);
printf("Enter Second String");
gets(str2);
value=strcmp(str1,str2);
if(value>0)
printf("string %s comes after %s in dictionary order\n"str1,str1);
else if(value<0)
printf("string %s comes before %s in dictionary order\n"str1,str2);
else
printf("Both Strings are same\n");
}
Output:
Enter string 1 Mangalore
Enter Second String Bangalore
Mangalore comes after Bangalore in dictionary order
Compiled by
Mrs. Panchajanyeswari 62
Srinivas Institute of Management Studies BCA – I Semester
This function works almost like a string-assignment operator. The general format of this
function is
strcpy(string1,string2);
The above statement assigns the content of string2 to string1. String2 may be character array or a
string constant.
E.g.:
strcpy(city, “DELHI”);
This statement will assign the string “DELHI” to string variable city.
If city1= “DELHI” and city2= “CHENNAI”. The statement strcpy(city1,city2); will assign the
contents of string variable city2 to city1. The size of array city1 should be large enough to
contain the contents of city2.
Program:
#include<stdio.h>
#include<string.h>
void main()
{
char str[31]="Sri";str1[32]="nivas";
printf("\nFirst String is %s\n",str1);
Output:
First String is Sri
Second String is nivas
Resultant String nivas
Compiled by
Mrs. Panchajanyeswari 63
Srinivas Institute of Management Studies BCA – I Semester
#include<stdio.h>
#include<string.h>
void main()
{
char str[31];
int len;
printf("\nEnter any String");
gets(str);
len=strlen(str);
printf("\nNumber of Character in%s=%d\n",str,len);
}
Output:
Enter any String
Jahnavi
Number of Character in Jahnavi=7
In order to access the ith city in the list, we write city[i-1]. Hence city[0] denotes
“Chennai”, city[1] denotes “Madgaon” and so on. This shows that once an array is declared as a
two-dimensional, it can be used like a one dimensional array for further manipulations. The table
can be treated as a column of strings.
Assignment
2 mark Questions:
Compiled by
Mrs. Panchajanyeswari 64
Srinivas Institute of Management Studies BCA – I Semester
5 mark Questions:
1. Explain the built in string functions with syntax and example. (2006,2008,2009,2010)
2. Write a C program to reverse a given string without using built-in functions(2008)
3. Write a C program to find the length of a given string without using built-in
functions(2009)
4. Write a C program to concatenate two strings without using built-in functions(2007)
5. Write a C program to compare two strings without using built-in functions(2006)
6. Write a C program to count the number of words in a given string(2013)
CHAPTER 9
USER DEFINED FUNCTIONS
9.1 Need for user defined functions
9.2 Declaring functions
9.3 Defining and calling functions
9.4 Function return values and their types
9.5 Categories of functions
9.6 Recursion
9.7 Function with arrays
9.8 Scope, visibility and lifetime of variables
Assignment questions
Introduction:
A function is a set of statements that perform a particular task. C functions can be
classified into two categories, namely, library functions and user-defined functions. Library
functions are those that are predefined and are already present in the various libraries. The
examples for library functions are printf, scanf, strlen,strcpy etc. User defined functions are
written by the user depending on the need of the application. main is an example of user defined
function.
Compiled by
Mrs. Panchajanyeswari 65
Srinivas Institute of Management Studies BCA – I Semester
It is always possible to write code for any program using a single main function. In this
case, the program becomes too large and complex and as a result the task of debugging and
maintenance becomes difficult. If a program is divided into functional units, then each part can
be independently coded and later combined into a single unit. These subprograms are called
‘functions’ are easier to understand, debug and test.
Main Program
A Multi-Function Program:
A function is a self contained block of code that performs a particular task. The inner
details of operation performed by the function are invisible to the rest of the program. All the
program knows is what goes in and what comes out. Every C program can be written as a set of
such functions.
main()
{
printline();
Compiled by
Mrs. Panchajanyeswari 66
Srinivas Institute of Management Studies BCA – I Semester
The program execution always begins at main(). Here both main and printline are 2 user
defined functions. At the very first statement, printline function is encountered. So, the control
transfers to the function printline. After the printline function is executed the control is
transferred back to the very next statement after the calling function in main. Now the execution
continues at the point where the function call was executed.
Any function can call any other function. A function can also call itself. A called function
can also call another function. A function can be called more than once. A called function can be
placed either before or after the calling function.
main()
{
----------------------
----------------------
function1();
----------------------
----------------------
function2();
----------------------
----------------------
function1();
----------------------
}
Compiled byfunction1()
{
Mrs. Panchajanyeswari 67
----------------------
----------------------
----------------------
}
function2()
{
Srinivas Institute of Management Studies BCA – I Semester
Call
return
Call
return
Call
return
function-name(argument list)
argument declaration;
{
Local variable declarations;
Executable statements;
:
:
return(expression);
}
Some of the above elements are optional. The argument list and its associated argument
declaration are optional. The declaration of local variables is required only when any local
variables are used in the function. A function can have any number of executable statements.
Compiled by
Mrs. Panchajanyeswari 68
Srinivas Institute of Management Studies BCA – I Semester
Sometimes a function can have no executable statements at all. The return statement is the
mechanism for returning a value to the calling function. This is also optional. Its absence
indicates that no value is being returned to the calling function.
Function name:
A function name must follow the same rules as the formation as any other variable
names. But care must be taken not to duplicate library routine names or any other system
commands.
Argument List:
The argument list contains valid variable names separated by commas. The list must be
surrounded by parentheses. No semicolon follows the closing parentheses. The argument
variables receive values from the calling function, thus providing a means of data
communication from the calling function to the called function. All argument variables must be
declared for their types after the function header and before the opening brace of the function
body.
Example:
power(x,n)
float x;
int n;
{
-------
-------
}
Compiled by
Mrs. Panchajanyeswari 69
Srinivas Institute of Management Studies BCA – I Semester
In the first form, the function does not return any value. It only acts as a closing brace for
that function. When a return is encountered, the control immediately passed to the calling
function.
Example: if(error)
return;
The second form of return with an expression returns the value of the expression.
Example:
mul(x,y)
int x.y;
{
int p;
p=x*y;
return(p);
}
In the above example, the value of p i.e. the product of two variables x ad y is returned to
the calling function. The last two statements can be combined into one statement as follows:
return(x*y);
A function can have more than one return statement that will return a value based on
certain conditions.
Example:
if(x<=0)
return(0);
else
return(1);
Compiled by
Mrs. Panchajanyeswari 70
Srinivas Institute of Management Studies BCA – I Semester
called function. There is no data transfer between the calling function and the called function.
There is only transfer of control between the two functions.
No data communication between the functions.
No input
function1() function2()
{ {
---------------- -------------
function2(); -------------
------------------- No output -------------
------------------- -------------
} }
main()
{
------------ [ACTUAL ARGUMENTS]
Function Call Function1(a1,a2,a3…..,am);
-------------
}
Called Function1(f1,f2,f3,…...,fn)
Function { [FORMAL ARGUMENTS]
------------
}
Compiled by
Mrs. Panchajanyeswari 71
Srinivas Institute of Management Studies BCA – I Semester
The calling function will validate the data and then send it to the called function. But the
called function will execute all the statements and will not return a value to the called function.
There is only one way communication between the calling function and the called function.
arguments
function1() function2(f)
{ {
---------------- -------------
function2(a); -------------
------------------- No return value -------------
------------------- -------------
} }
Compiled by
Mrs. Panchajanyeswari 72
Srinivas Institute of Management Studies BCA – I Semester
We can use functions that do not return any value. They simply execute a set of
statements. Such functions need not be declared in main. Even if they are declared, they are
declared with a qualifier void. This states explicitly that the function does not return any value.
The general format of this declaration is as follows:
void function-name();
Nesting of Functions:
C language supports nesting of functions. Calling of another function within another
function is called as nesting of functions.
9.6 Recursion:
When a function calls itself repeatedly until a terminating condition is satisfied, then the
concept is called recursion. Recursive functions can be effectively used to solve problems where
the solution is expressed in terms of successively applying the same solution to the subset of the
problem. When a recursive function is written, it must be ensured that terminating condition is
present. Otherwise, the process is repeated indefinitely.
Example:
factorial(n)
int n;
{
int fact;
if(n==1)
return(1);
else
fact=n*factorial(n-1);
return(fact);
}
Compiled by
Mrs. Panchajanyeswari 73
Srinivas Institute of Management Studies BCA – I Semester
int a[10],n,i;
clrscr();
printf("Enter Range\n");
scanf("%d",&n);
printf("Enter %d numbers\n",n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("The largest number is %d",largest(a,n));
}
int largest(a,n)
int a[],n;
{
int i,big;
big=a[1];
for(i=2;i<=n;i++)
if(big<a[i])
big=a[i];
return(big);
}
OUTPUT:
Enter Range
6
Enter 6 numbers
4
3
6
8
7
9
The largest number is 9
Compiled by
Mrs. Panchajanyeswari 74
Srinivas Institute of Management Studies BCA – I Semester
The declaration of automatic variables can take any one of the following forms:
main()
{
int num;
…….
…….
}
(Or)
main()
{
auto int num;
……….
……….
}
int number;
float len=7.5;
function1()
{
------
------
}
(or)
Compiled by
Mrs. Panchajanyeswari 75
Srinivas Institute of Management Studies BCA – I Semester
function()
{
extern int number;
extern float len=7.5;
-----
-----
}
Global variable is visible only from the point of declaration to the end of the program.
Example:
main()
{
y=5;
-------
-------
}
int y;
function1()
{
y=y+1;
}
In the above example, the value of y is not declared in function main. Hence the compiler
issues an error message. Here the value of y after the execution of function1 will be only 1 as the
undefined global variable will be initialized to zero by default.
function1()
{
extern int y; /*external declaration*/
y=y+1;
}
int y;/*declaration*/
Here although the variable y is encountered before is definition, the external declaration informs
that the variable has been defined else where in the program. This declaration will not allocate
any memory for the variable.
Compiled by
Mrs. Panchajanyeswari 76
Srinivas Institute of Management Studies BCA – I Semester
2 mark Questions:
1. Define a user defined function.
2. Define recursion.(2006,2008,2009)
3. What is actual parameter? Give example
4. What is formal parameter? Give example
5 mark Questions:
1. Explain the concept of user defined functions with an example(2007,2008,2010)
2. Explain the structure of user defined function in C(2007)
3. Explain the storage classes in C(2005,2008,2010)
4. Write a recursive program to find the factorial of a given number.(2006,2009)
5. Write a recursive program to find the power of a number (xy) (2007,2010)
6. Write a function in C to find the smallest of n numbers
UNIT IV
CHAPTER 10
STRUCTURES AND UNIONS
10.1 Structure definition
10.2 Giving values to members
10.3 Structure initialization
10.4 Comparison of structure variables
10.5 Array of structures
10.6 Arrays within structures
Compiled by
Mrs. Panchajanyeswari 77
Srinivas Institute of Management Studies BCA – I Semester
struct tag-name
{
Data type member1;
Data type member2;
……….
};
The keyword struct declares a structure to hold the details of the member fields. These
fields are also known as structure elements or members. Each member may belong to a different
data types. The name of the structure is also known as structure tag. The tag name can be used to
declare variables that have the tag’s structure.
Example:
struct book_bank
{
char title[20];
char author[15];
int pages;
float price;
};
The above format describes only a format called a template to represent information
struct book_bank
Compiled by
Mrs. Panchajanyeswari 78
Srinivas Institute of Management Studies BCA – I Semester
Example:
struct stud
{
char name[20];
int reg-no;
int mark1,mark2,mark3;
int total;
float avg;
Compiled by
Mrs. Panchajanyeswari 79
Srinivas Institute of Management Studies BCA – I Semester
};
struct stud student[10];
Here student is an array of 10 elements of type stud.
Compiled by
Mrs. Panchajanyeswari 80
Srinivas Institute of Management Studies BCA – I Semester
--------
}
10.9 Unions:
Unions follow the same syntax as structures. The major distinction between them is in
terms of storage. In structures each member has its own storage location, whereas in a union all
the members use the same storage location. This implies that although a union can contain many
members of different data types it can handle only one member at a time. Unions are declared as
follows
union item
{
int m;
float x;
char c;
} code;
Example:
struct person
{
unsigned gender: 1;
unsigned age: 7;
unsigned m_status: 1;
unsigned children: 3;
}emp;
The above example defines a variable named emp with four fields. The range of values each
field could have is as follows:
Bit field Bit length Range of values
Compiled by
Mrs. Panchajanyeswari 81
Srinivas Institute of Management Studies BCA – I Semester
gender 1 0 or1
Age 7 0-127(27-1)
m_status 1 0 or 1
Children 3 0-7(23-1)
Assignment
2 mark Questions:
1. Define structure.
2. Define union.
3. Differentiate between structure and union (2007,2008,2009)
4. What is the purpose of bit fields in C? (2012)
5. How do you declare a structure in C? Give example.(2005,2006,2009)
6. How do you declare a union in C? Give example.(2008,2010)
7. How do you define bit fields in C? Give example.(2012)
5 mark Questions:
1. Explain the concept of defining structures in C with examples.
2. How do you work with array of structures in C? Give examples. (2006)
3. Explain the concept of structures within structures with examples. (2007)
Compiled by
Mrs. Panchajanyeswari 82
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 11
POINTERS
11.1 Understanding pointers
11.2 Accessing a pointer variable
11.3 Declaring and initializing a pointer variable
11.4 Accessing a pointer variable
11.5 Pointer expressions
11.6 Pointer increments and scale factor
11.7 Pointers and arrays
11.8 Call by value
11.9 Call by reference
Assignment questions
Introduction:
Pointers are an important concept in C. There are a number of advantages of using
pointers. They are
• It enables us to access a variable that is defined outside a function.
• More efficient in handling arrays
• Reduce the length and complexity of a program
• Increase the execution speed
When a variable is declared, the system allocates memory location suitable to hold the
variable value. The memory location is called the address.
Consider the following statement:
int qty;
qty=179;
Representation of a variable in memory
qty Variable
179 Value
5000 Address
Definition: A pointer is a variable that represents the location of a data item such as variable or
array element.
Compiled by
Mrs. Panchajanyeswari 83
Srinivas Institute of Management Studies BCA – I Semester
Compiled by
Mrs. Panchajanyeswari 84
Srinivas Institute of Management Studies BCA – I Semester
Pointers to 2D arrays
Columns
0 1 2 3 4 5
0 p
1 p+1
2
Rows 3
4 4,0 4,3
5
6 p+6
Compiled by
Mrs. Panchajanyeswari 85
Srinivas Institute of Management Studies BCA – I Semester
{
p=p+10;
}
When this code is executed, the value 20 is passed as a function argument, the output is 20.
The value is only copied when it goes to the function change. The change in the function
does not affect the function main. Hence the output is only 20.
Assignment
2 mark Questions:
1. Define a pointer variable. (2006,2007,2009)
2. How do you declare pointers in C? Give example (2008)
3. How can you initialize pointers? Give example. (2009,2012)
4. How do you define array as a pointer? Give example(2006,2008,2010)
5. What do you mean by call by value? (2007,2009)
6. What do you mean by call by reference?(2008,2010)
5 mark Questions:
1. Explain the concept of working with pointers in C. (2005,2010)
2. Explain how pointers can be used in a one dimensional array with examples.
3. Explain how pointers can be used in a two dimensional array with examples.
4. Explain call by value with example.(2007,2008,2010)
5. Explain call by reference with example.(2006,2009)
Compiled by
Mrs. Panchajanyeswari 86
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 12
THE PREPROCESSOR
Introduction:
The preprocessor is a program that processes source code before it passes through the
compiler. It operates under the control of preprocessor command lines or directives. Preprocessor
directives are placed in the source program before the main line. Before the source code passes
through the compiler, to is examined by the preprocessor for any preprocessor directive. If there
are any, appropriate actions are taken and then the source program is handed over to the
compiler.
Preprocessor directives follow special syntax that is different from normal C syntax.
They all begin with the symbol # and do not require a semi-colon at the end of the statement.
Preprocessor directives:
Directive Function
#define Defines a macro substitution
#undef Undefines a macro
#include Specifies the files to be included
#ifdef Test for macro definition
#endif Specifies the end of #if
#if Test a compile time condition
#else Specifies alternatives when #if test fails
Compiled by
Mrs. Panchajanyeswari 87
Srinivas Institute of Management Studies BCA – I Semester
Compiled by
Mrs. Panchajanyeswari 88
Srinivas Institute of Management Studies BCA – I Semester
These are the directives which can be used for conditional compilation. Here, we can
make the compiler skip a part of source code by inserting the preprocessing commands #ifdef
and #endif. The general form of it is
#ifdef macroname
Statement 1;
Statement 2;
Statement 3;
#endif
If the macro name is defined the block of code will be executed as usual, otherwise not. It could
be used in the following cases
a. To comment out obsolete lines of code.
b. To make the programs portable
c. To check multiple declaration of files
Assignment
2 mark Questions:
1. Define preprocessor.(2012)
2. Define a macro.
3. What do you mean by command line arguments?(2012)
4. What are the rules to define a preprocessor directive?
5. What do you mean by nesting of macros? Give example.
5 mark Questions:
1. Explain the concept of macro substitution in C?(2012)
2. Explain file inclusion with example?
3. Write a note on command line arguments.
Compiled by
Mrs. Panchajanyeswari 89
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 13
FILE MANAGEMENT IN C
13.1 Introduction
13.2 Defining and opening a file
13.3 Closing a file
13.4 I/O operations on files
13.5 Error handling during I/O operations
Assignment questions
13.1 Introduction:
We use printf and scanf functions to write and read data from I/O devices. If the
data is small then, it is fine. But, most of the real life problems deal with voluminous data. In
such cases, entering data through the console becomes very difficult.
It is necessary to have a flexible approach where in data is stored on secondary
storage devices like disks and read data from it whenever necessary without destroying data.
A file is place on a disk where a group of related data is stored. The basic operations on files
are
• Naming a file
• Opening a file
• Reading data from a file
• Writing data on to a file
• Closing a file
Compiled by
Mrs. Panchajanyeswari 90
Srinivas Institute of Management Studies BCA – I Semester
mode in which the file should be opened. It specifies the purpose of opening the file. A file can
be opened in any one of the following modes
r-read mode
w-write mode
a- append mode
• When a file is opened in write mode, a file is created if the file does not exists. If it
already exists, the contents are deleted
• When a file is opened in the append mode, the contents remain intact if the file already
exists. If not, a new file is created
• When a file is opened in read mode, it is opened with the contents safe, if is already
exists. Otherwise an error occurs
fscanf: This function is used to read mixed data type values from a file. The general format is
fscanf(file-pointer, “ control string” , list);
Example:
fscanf(fp1, “%s %d “ , item,&qty);
fprintf: This function is used to write mixed data type values onto a file. The general format is
fprintf(file-pointer, “ control string” , list);
Compiled by
Mrs. Panchajanyeswari 91
Srinivas Institute of Management Studies BCA – I Semester
Example:
fprintf(fp1, “%s%d”, name,qty);
The feof function can be used to test for an end-of-file condition. It takes file pointer as an
argument and returns a non-zero integer value if all the data from specified file have been
read, and returns zero otherwise. If fp is a pointer to a file that has just been opened for
reading, then, the statement
if( feof(fp))
printf(“End of data\n”);
would display the message “End of data” on reaching the end of file condition
The ferror function reports the status of the file indicated. It takes file pointer as an argument
and returns a non-zero integer value if an error has been detected up to that point, during
processing. It returns zero otherwise. The statement
if( ferror(fp)!=0)
printf(“An error has occurred\n”);
would display the message if the reading is not successful.
We can also check whether a file is opened or not. When a file is opened using fopen
function, a file pointer is returned. If the file cannot be opened for some reason, then the
function returns a NULL pointer.
Example:
if(fp == NULL)
printf(“File Cannot be opened\n”);
Assignment
2 mark Questions:
1. Define a file.
2. How do you declare a file in C?
3. How do you open a file in C?
4. List the various operations performed on files. (2006,2009)
5. How do you close a file? Give example.
6. Why do you use feof function?
7. What is the purpose of ferror function?
Compiled by
Mrs. Panchajanyeswari 92
Srinivas Institute of Management Studies BCA – I Semester
5 mark Questions:
1. Explain the concept of opening a file in C? (2008,2009)
2. How do you perform I/O operations on files in C? Explain with syntax and
example(2007,2009, 2011)
Compiled by
Mrs. Panchajanyeswari 93
Srinivas Institute of Management Studies BCA – I Semester
CHAPTER 14
Advanced Topics in C
Example:
Program to compute factorial
/*****************************************************************************
*/
/* main.c */
Compiled by
Mrs. Panchajanyeswari 94
Srinivas Institute of Management Studies BCA – I Semester
#include <stdio.h>
int fact ( int ); /* Function prototype */
int main ( int argc, char *argv[] )
{
int x; /* Variable to hold parameter */
if ( argc != 2 )
{
printf ( "Usage: %s <number>\n", argv[0] );
exit ( 1 );
}
x = atoi ( argv[1] );
printf ( "Factorial of %d is %d\n", x, fact(x) );Advanced Topics 2
return ( 0 );
}
/*****************************************************************************
*/
/* fact.c */
int fact ( int x )
{
return ( x ? ( x * fact ( x - 1 ) ) : 1 );
}
/***************************************************************************/
Example:
/***************************************************************************/
#include <stdio.h>
extern int counter; /* Declaration of counter */
extern void inc_counter ( void );
main()
{
int index;
for ( index = 0; index < 10; index++ )
inc_counter();
printf ( "Counter is: %d\n", counter );
Compiled by
Mrs. Panchajanyeswari 95
Srinivas Institute of Management Studies BCA – I Semester
}
/*****************************************************************************
*/
int counter; /* Definition of counter */
void inc_counter ( void );
{
counter++;
}
/****************************************************************************/
Example
/* pfunc.c : Illustrating a pointer to a function */
#include <stdio.h>
#include <ctype.h>
#include <math.h>
main()
{
char ch;
double (*p)( double );
printf ("Enter c, s, or t to select one of the functions cos, sin, tan: ");
switch ( ch = tolower ( getchar () ) )
{
case ’c’: p = cos; break;
case ’s’: p = sin; break;
case ’t’: p = tan; break;
default : printf ( "Wrong character\n" ); exit ( 1 );
}
printf ( "\nArgument Function value\n" );
printf ( "%8.3f %12.8f\n", 0.1, (*p)(0.1) );
printf ( "%8.3f %12.8f\n", 0.3, (*p)(0.3) );
printf ( "%8.3f %12.8f\n", 1.6, (*p)(1.6) );
Compiled by
Mrs. Panchajanyeswari 96
Srinivas Institute of Management Studies BCA – I Semester
Example:
Compute the following series
sum= f(1)+f(1/2)+f(1/3)+…..+f(1/n)
/***************************************************************************/
/* main.h */
#include <stdio.h>
double fn_sum ( int, double (*)() ); /* Function to be summed */
double square ( double );
double cube ( double );
/*****************************************************************************
*/
/* main.c */
/* func_arg: Passing a function name as an argument */
#include "main.h"
main()
{
printf ( "Sum of squares: %f\n", fn_sum( 5, square ) );
printf ( "Sum of cubes : %f\n", fn_sum( 5, cube ) );
}
/******************************************************************/
/* fn_sum.c */
double fn_sum ( int n, double (*fn)() )
{
double s = 0;
int i;
for ( i =1; i <= n; s += (*fn)(1.0/i++) );
return ( s );
}
/******************************************************************/
/* square.c */
double square ( double x )
{
return ( x * x );
}
/********************************************************************/
/* cube.c */
double cube ( double x )
Compiled by
Mrs. Panchajanyeswari 97
Srinivas Institute of Management Studies BCA – I Semester
{
return ( x * x * x );
}
/*******************************************************************/
Compiled by
Mrs. Panchajanyeswari 98
Srinivas Institute of Management Studies BCA – I Semester
Note: Answer any ten questions from Part A and any one full
question from each Unit of Part B.
PART -A (2x10=20)
1. a) What is the difference between character constant and string constant? Give example for
each.
b) What is a variable? How do you declare a variable?
c) Determine the value of each of the following assume a = 6, b = -2 and c = - 7 :
i) X = (a > b) ? a + 3 : b + 3 * c .
ii) Y = pow (sqrt (9), 3)
d) What is the use of break and continue statements in a program?
e) What do you mean by scope and life time of a variable?
f) What is an entry controlled loop? Give example.
g) Differentiate array and structure.
h) Differentiate i ++ and ++ i with example.
i) List the categories of user defined functions.
j) What is a pointer? How is it declared?
k) What is a union? How does it differ from structure?
l) What is a file? List an advantage of a file.
PART-B
UNIT-I
UNIT -II
4. a) What is a loop? Explain any two looping statements with its syntax and example.
b) Explain the switch statement with syntax and example.
Compiled by
Mrs. Panchajanyeswari 99
Srinivas Institute of Management Studies BCA – I Semester
c) Write a program to reverse a given number and check for palindrome. (5+5+5)
UNIT –III
6. a) Explain any four string handling functions with syntax and example.
b) Explain any two categories of user-defined functions with examples.
c) What is Recursion? Write a program to find the factorial of a number using
recursion. (5+5+5)
UNIT –IV
9. a) What are preprocessor directives? Explain any two types of preprocessor directives.
b) Explain the usage of Bit fields in structure.
c) Distinguish between the following:
i) printf() and fprintf()
ii) feof() and ferror()
iii) getc() and getchar() (5+4+6)
Compiled by
Mrs. Panchajanyeswari 100