You are on page 1of 82

COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

UNIT - 1
Introduction to C

C is a programming language developed at AT & T‗s Bell Laboratories of USA in 1972.


It was designed and written by a man named Dennis Ritchie. In the late seventies C
began to replace the more familiar languages of that time like PL/I,

ALGOL, etc ANSI C standard emerged in the early 1980s,

There is a close analogy between learning English language and learning C language.
The classical method of learning English is to first learn the alphabets used in the
language, then learn to combine these alphabets to form words, which in turn are
combined to form sentences and sentences are combined to form paragraphs. Learning
C is similar and easier. Instead of straight-away learning how to write programs, we
must first know what alphabets, numbers and special symbols are used in C, then how
using them constants, variables and keywords are constructed, and finally how are
these combined to form an instruction. A group of instructions would be combined
later on to form a program. So a computer program is just a collection of the
instructions necessary to solve a specific problem. The basic operations of a computer
system form what is known as the computer‗s instruction set. And the approach or

method that is used to solve the problem is known as an algorithm.

Structure of C Language program

1 ) Comment line

2) Preprocessor directive
3 ) Global variable declaration

4) main function( )

Local variables; Statements;

User defined function

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Comment line

It indicates the purpose of the program. It is represented as

/*……………………………..*/

Comment line is used for increasing the readability of the program. It is useful in
explaining the program and generally used for documentation. It is enclosed within the
decimeters. Comment line can be single or multiple line but should not be nested. It can
be anywhere in the program except inside string constant & character constant.

Preprocessor Directive:

#include<stdio.h> tells the compiler to include information about the standard


input/output library. It is also used in symbolic constant such as #define PI 3.14(value).
The stdio.h (standard input output header file) contains definition & declaration of
system defined function such as printf( ), scanf( ), pow( ) etc.

Generally printf() function used to display and scanf() function used to read value.

Global Declaration:

This is the section where variable are declared globally so that it can be access by all the
functions used in the program. And it is generally declared outside the function.

main()

It is the user defined function and every function has one main() function from where
actually program is started and it is encloses within the pair of curly braces.

The main( ) function can be anywhere in the program but in general practice it is placed
in the first position.

Syntax :

main()

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

……..

……..

……..

The main( ) function return value when it declared by data type as int main( )

return 0;

Output: 0

The main function does not return any value when void (means null/empty) as void
main(void ) or void main()

printf (―C language‖);

Output: C language

The program execution start with opening braces and end with closing brace. And in
between the two braces declaration part as well as executable part is mentioned. And at
the end of each line, the semi-colon is given which indicates statement termination.

/*First c program with return statement*/

#include <stdio.h> int main (void)

printf ("welcome to c Programming language.\n"); return 0;

Output: welcome to c programming language.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Character set

A character denotes any alphabet, digit or special symbol used to represent


information. Valid alphabets, numbers and special symbols allowed in C are

The alphabets, numbers and special symbols when properly combined form constants,
variables and keywords.

Identifiers

Identifiers are user defined word used to name of entities like variables, arrays,
functions, structures etc. Rules for naming identifiers are:

1) name should only consists of alphabets (both upper and lower case), digits and
underscore (_) sign.

2) first characters should be alphabet or underscore

3) name should not be a keyword

4) since C is a case sensitive, the upper case and lower case considered differently,
for example code, Code, CODE etc. are different identifiers.

5) identifiers are generally given in some meaningful name such as value,


net_salary, age, data etc. An identifier name may be long, some implementation
recognizes only first eight characters, most recognize 31 characters. ANSI standard
compiler recognize 31 characters. Some invalid identifiers are 5cb, int, res#, avg no etc.

Keyword

There are certain words reserved for doing specific task, these words are known as
reserved word or keywords. These words are predefined and always written in lower
case or small letter. These keywords cann‗t be used as a variable name as it assigned
with fixed meaning. Some examples are int, short, signed, unsigned, default, volatile,
float, long, double, break, continue, typedef, static, do, for, union, return, while, do,
extern, register, enum, case, goto, struct, char, auto, const etc.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Data types

Data types refer to an extensive system used for declaring variables or functions of
different types before its use. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted. The value of a variable
can be changed any time.

C has the following 4 types of data types

basic built-in data types: int, float, double, char

Enumeration data type: enum

Derived data type: pointer, array, structure, union

Void data type: void

A variable declared to be of type int can be used to contain integral values only—that is,
values that do not contain decimal places. A variable declared to be of type float can be
used for storing floating- point numbers (values containing decimal places). The double
type is the same as type float, only with roughly twice the precision. The char data type
can be used to store a single character, such as the letter a, the digit character 6, or a
semicolon similarly A variable declared char can only store character type value.

There are two types of type qualifier in c

Size qualifier: short, long

Sign qualifier: signed, unsigned

When the qualifier unsigned is used the number is always positive, and when signed is
used number may be positive or negative. If the sign qualifier is not mentioned, then by
default sign qualifier is assumed. The range of values for signed data types is less than
that of unsigned data type. Because in signed type, the left most bit is used to

represent sign, while in unsigned type this bit is also used to represent the value. The
size and range of the different data types on a 16 bit machine is given below:

Constants

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Constant is a any value that cannot be changed during program execution. In C, any
number, single character, or character string is known as a constant. A constant is an
entity that doesn‗t change whereas a variable is an entity that may change. For example,
the number 50 represents a constant integer value. The character string "Programming
in C is fun.\n" is an example of a constant character string. C constants can be divided
into two major categories:

Primary Constants Secondary Constants

These constants are further categorized as

Numeric constant Character constant String constant

Numeric constant: Numeric constant consists of digits. It required minimum size of 2


bytes and max 4 bytes. It may be positive or negative but by default sign is always
positive. No comma or space is allowed within the numeric constant and it must have
at least 1 digit. The allowable range for integer constants is -32768 to 32767. Truly
speaking the range of an Integer constant depends upon the compiler.

For a 16-bit compiler like Turbo C or Turbo C++ the range is –32768 to 32767.

For a 32-bit compiler the range would be even greater. Mean by a 16-bit or a 32-bit
compiler, what range of an Integer constant has to do with the type of compiler.

It is categorized a integer constant and real constant. An integer constants are whole
number which have no decimal point. Types of integer constants are:

Decimal constant: 0 9(base 10)

Octal constant: 0 7(base 8)

Hexa decimal constant: 0----9, A F(base 16)

In decimal constant first digit should not be zero unlike octal constant first digit must
be zero(as 076, 0127) and in hexadecimal constant first two digit should be 0x/ 0X (such
as 0x24, 0x87A). By default type of integer constant is integer but if the value of integer
constant is exceeds range then value represented by integer type is taken to be
unsigned integer or long integer. It can also be explicitly mention integer and unsigned
integer type by suffix l/L and u/U.

Real constant is also called floating point constant. To construct real constant we must
follow the rule of ,

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

-real constant must have at least one digit.

-It must have a decimal point.

-It could be either positive or negative.

-Default sign is positive.

-No commas or blanks are allowed within a real constant. Ex.: +325.34, 426.0, -32.76

To express small/large real constant exponent(scientific) form is used where number is


written in mantissa and exponent form separated by e/E. Exponent can be positive or
negative integer but mantissa can be real/integer type, for example 3.6*105=3.6e+5. By
default type of floating point constant is double, it can also be explicitly defined it by
suffix of f/F.

Character constant

Character constant represented as a single character enclosed within a single quote.


These can be single digit, single special symbol or white spaces such as ‗9‗,‗c‗,‗$‗, ‗ ‗ etc.
Every character constant has a unique integer like value in machine‗s character code as
if machine using ASCII (American standard code for information interchange). Some
numeric value associated with each upper and lower case alphabets and decimal
integers are as:

A Z ASCII value (65-90)

a z ASCII value (97-122)

0 9 ASCII value (48-59)

; ASCII value (59)

String constant

Set of characters are called string and when sequence of characters are enclosed within
a double quote (it may be combination of all kind of symbols) is a string constant.
String constant has zero, one or more than one character and at the end of the string
null character(\0) is automatically placed by compiler. Some examples are ―,sarathina‖

, ―908‖, ―3‖,‖ ‖, ―A‖ etc. In C although same characters are enclosed within single and

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

double quotes it represents different meaning such as ―A‖ and ‗A‗ are different
because first one is string attached with null character at the end but second one is
character constant with its corresponding ASCII value is 65.

Symbolic constant

Symbolic constant is a name that substitute for a sequence of characters and, characters
may be numeric, character or string constant. These constant are generally defined at
the beginning of the program as

#define name value , here name generally written in upper case for example #define
MAX 10

#define CH ‗b‗

#define NAME ―sony‖

Variables

Variable is a data name which is used to store some data value or symbolic names for
storing program computations and results. The value of the variable can be change
during the execution. The rule for naming the variables is same as the naming
identifier. Before used in the program it must be declared. Declaration of variables
specify its name, data types and range of the value that variables can store depends
upon its data types.

Syntax:

datatype variable; eg. int a;

char c; float f;

Variable initialization

When we assign any initial value to variable during the declaration, is called
initialization of variables. When variable is declared but contain undefined value then it
is called garbage value. The variable is initialized with the assignment operator such as

Data type variable name=constant; Example: int a=20;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Or int a; a=20;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

UNIT - 2

Expressions

An expression is a combination of variables, constants, operators and function call. It


can be arithmetic, logical and relational for example:-

int z= x+y // arithmatic expression a>b //relational

a==b // logical

func(a, b) // function call

Expressions consisting entirely of constant values are called constant expressions. So,
the expression

121 + 17 – 110 is a constant expression because each of the terms of the expression is a
constant value. But if i were declared to be an integer variable, the expression 180 + 2 – j

would not represent a constant expression.

Operator

This is a symbol use to perform some operation on variables, operands or with the
constant. Some operator required 2 operand to perform operation or Some required
single operation.

Several operators are there those are, arithmetic operator, assignment, increment,
decrement, logical, conditional, comma, size of , bitwise and others.

1. Arithmatic Operator

This operator used for numeric calculation. These are of either Unary arithmetic
operator, Binary arithmetic operator. Where Unary arithmetic operator required only
one operand such as +,-, ++, --,!, tiled. And these operators are addition, subtraction,
multiplication, division. Binary arithmetic operator on other hand required two
operand and its operators are +(addition), -(subtraction), *(multiplication), /(division),

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

%(modulus). But modulus cannot applied with floating point operand as well as there
are no exponent operator in c.

Unary (+) and Unary (-) is different from addition and subtraction.

When both the operand are integer then it is called integer arithmetic and the result is
always integer. When both the operand are floating point then it is called floating
arithmetic and when operand is of integer and floating point then it is called mix type
or mixed mode arithmetic . And the result is in float type.

2. Assignment Operator

A value can be stored in a variable with the use of assignment operator. The assignment
operator(=) is used in assignment statement and assignment expression. Operand on
the left hand side should be variable and the operand on the right hand side should be
variable or constant or any expression. When variable on the left hand side is occur on
the right hand side then we can avoid by writing the compound statement. For
example,

int x= y;

int Sum=x+y+z;

3. Increment and Decrement

The Unary operator ++, --, is used as increment and decrement which acts upon single
operand. Increment operator increases the value of variable by one .Similarly
decrement operator decrease the value of the variable by one. And these operator can
only used with the variable, but cann't use with expression and constant as ++6 or

++(x+y+z).

It again categories into prefix post fix . In the prefix the value of the variable is
incremented 1st, then the new value is used, where as in postfix the operator is written
after the operand(such as m++,m--).

EXAMPLE

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

let y=12; z= ++y; y= y+1;

z= y;

Similarly in the postfix increment and decrement operator is used in the operation. And
then increment and decrement is perform.

EXAMPLE

let x= 5; y= x++; y=x;

x= x+1;

4. Relational Operator

It is use to compared value of two expressions depending on their relation. Expression


that contain relational operator is called relational expression. Here the value is assign
according to true or false value.

a.(a>=b) || (b>20)

b.(b>a) && (e>b)

c. 0(b!=7)

5. Conditional Operator

It sometimes called as ternary operator. Since it required three expressions as operand


and it is represented as (? , :).

SYNTAX

exp1 ? exp2 :exp3

Here exp1 is first evaluated. It is true then value return will be exp2 . If false then exp3.

EXAMPLE

void main()

int a=10, b=2

int s= (a>b) ? a:b; printf(―value is:%d‖);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Output:

Value is:10

6. Comma Operator

Comma operator is use to permit different expression to be appear in a situation where


only one expression would be used. All the expression are separator by comma and are
evaluated from left to right.

EXAMPLE

int i, j, k, l; for(i=1,j=2;i<=5;j<=10;i++;j++)

7. Sizeof Operator

Size of operator is a Unary operator, which gives size of operand in terms of byte that
occupied in the memory. An operand may be variable, constant or data type qualifier.
Generally it is used make portable program(program that can be run on different
machine). It determines the length of entities, arrays and structures when their size are
not known to the programmer. It is also use to allocate size of memory dynamically
during execution of the program.

EXAMPLE

main( )

int sum; float f;

printf( "%d%d" ,size of(f), size of (sum) ); printf("%d%d", size of(235 L), size of(A));

8. Bitwise Operator

Bitwise operator permit programmer to access and manipulate of data at bit level.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Various bitwise operator enlisted are one's complement (~)

bitwise AND (&) bitwise OR (|) bitwise XOR (^) left shift (<<) right shift (>>)

Logical or Boolean Operator

Operator used with one or more operand and return either value zero (for false) or one
(for true). The operand may be constant, variables or expressions. And the expression
that combines two or more expressions is termed as logical expression.

C has three logical operators :

Operator Meaning

&& AND

|| OR

! NOT

Where logical NOT is a unary operator and other two are binary operator. Logical AND
gives result true if both the conditions are true, otherwise result is false. And logical OR
gives result false if both the condition false, otherwise result is true.

Control Statement

Generally C program statement is executed in a order in which they appear in the


program. But sometimes we use decision making condition for execution only a part of
program, that is called control statement. Control statement defined how the control is
transferred from one part to the other part of the program. There are several control
statement like if...else, switch, while, do. while, for loop, break, continue, goto etc.

if statement

Statement execute set of command like when condition is true and its syntax is

If (condition) Statement;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

The statement is executed only when condition is true. If the if statement body is
consists of several statement then better to use pair of curly braces. Here in case
condition is false then compiler skip the line within the if block.

void main()

int n;

printf (― enter a number:‖); scanf(―%d‖,&n);

If (n>10)

printf(― number is greater‖);

Output:

Enter a number:12 Number is greater

if…..else Statement

it is bidirectional conditional control statement that contains one condition & two
possible action. Condition may be true or false, where non-zero value regarded as true
& zero value regarded as false. If condition are satisfy true, then a single or block of
statement executed otherwise another single or block of statement is executed.

Its syntax is:- if (condition)

Statement1;

Statement2;

else

Statement1;

Statement2;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Else statement cannot be used without if or no multiple else statement are allowed
within one if statement. It means there must be a if statement with in an else statement.
Example:-

/* To check a number is eve or odd */ void main()

int n;

printf (―enter a number:‖); sacnf (―%d‖, &n);

if (n%2==0)

printf (―even number‖); else

printf(―odd number‖);

Output: enter a number:121 odd number

Nesting of if …else

When there are another if else statement in if-block or else-block, then it is called
nesting of if-else statement.

Syntax is :-

if (condition)

if (condition) Statement1; else statement2;

Statement3;

If….else LADDER

In this type of nesting there is an if else statement in every else part except the last part.
If condition is false control pass to block where condition is again checked with its if
statement.

Syntax is :-

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

if (condition) Statement1;

else if (condition) statement2;

else if (condition) statement3;

else statement4;

This process continue until there is no if statement in the last block. if one of the
condition is satisfy the condition other nested ―else if‖ would not executed.

But it has disadvantage over if else statement that, in if else statement whenever the
condition is true, other condition are not checked. While in this case, all condition are
checked.

Switch case statement

A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
switch case.

Syntax

The syntax for a switch statement in C programming language is as follows −

The following rules apply to a switch statement −

• The expression used in a switch statement must have an integral or enumerated


type, or be of a class type in which the class has a single conversion function to an
integral or enumerated type.

• You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.

• The constant-expression for a case must be the same data type as the variable in
the switch, and it must be a constant or a literal.

• When the variable being switched on is equal to a case, the statements following
that case will execute until a break statement is reached.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

• When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.

• Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.

• A switch statement can have an optional default case, which must appear at the
end of the switch. The default case can be used for performing a task when none of the
cases is true. No break is needed in the default case.

Break statement(break)

Sometimes it becomes necessary to come out of the loop even before loop condition
becomes false then break statement is used. Break statement is used inside loop and
switch statements. It cause immediate exit from that loop in which it appears and it is
generally written with condition. It is written with the keyword as break. When break
statement is encountered loop is terminated and control is transferred to the statement,
immediately after loop or situation where we want to jump out of the loop instantly
without waiting to get back to conditional state. When break is encountered inside any
loop, control automatically passes to the first statement after the loop. This break
statement is usually associated with if statement.

Example :

void main()

int j=0; for(;j<6;j++) if(j==4) break;

Output:

0123

Continue statement (key word continue)

Continue statement is used for continuing next iteration of loop after skipping some
statement of loop. When it encountered control automatically passes through the
beginning of the loop. It is usually associated with the if statement. It is useful when we
want to continue the program without executing any part of the program.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

The difference between break and continue is, when the break encountered loop is
terminated and it transfer to the next statement and when continue is encounter control
come back to the beginning position.

In while and do while loop after continue statement control transfer to the test
condition and then loop continue where as in, for loop after continue control
transferred to the updating expression and condition is tested.

Example:- void main()

int n;

for(n=2; n<=9; n++)

if(n==4) continue; printf(―%d‖, n);

printf(―out of loop‖);

Output: 2 3 5 6 7 8 9 out of loop

Loops in C

Loop:-it is a block of statement that performs set of instructions. In loops Repeating


particular portion of the program either a specified number of time or until a particular
no of condition is being satisfied.

There are three types of loops in c

1. While loop

2. do while loop

3. for loop

While loop Syntax:- while(condition)

Statement 1;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Statement 2;

Or

while(test condition) Statement;

The test condition may be any expression .when we want to do something a fixed no of
times but not known about the number of iteration, in a program then while loop is
used.

Here first condition is checked if, it is true body of the loop is executed else, If condition
is false control will be come out of loop.

Example:-

/* wap to print 5 times welcome to C‖ */ #include<stdio.h>

void main()

int p=1; While(p<=5)

printf(―Welcome to C\n‖); p=p+1;

Output: Welcome to C Welcome to C Welcome to C Welcome to C Welcome to C

So as long as condition remains true statements within the body of while loop will get
executed repeatedly.

do while loop

This (do while loop) statement is also used for looping. The body of this loop may
contain single statement or block of statement. The syntax for writing this statement is:
Syntax:-

do

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Statement;

while(condition);

Example:- #include<stdio.h>

void main()

int X=4; do

Printf(―%d‖,X);

X=X+1;

while(X<=10); printf(― ‖);

Output: 4 5 6 7 8 9 10

Here firstly statement inside body is executed then condition is checked. If the
condition is true again body of loop is executed and this process continue until the
condition becomes false. Unlike while loop semicolon is placed at the end of while.

There is minor difference between while and do while loop, while loop test the
condition before executing any of the statement of loop. Whereas do while loop test
condition after having executed the statement at least one within the loop.

If initial condition is false while loop would not executed it‗s statement on other hand
do while loop executed it‗s statement at least once even If condition fails for first time. It
means do while loop always executes at least once.

Notes:

Do while loop used rarely when we want to execute a loop at least once.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

for loop

In a program, for loop is generally used when number of iteration are known in
advance. The body of the loop can be single statement or multiple statements. Its syntax
for writing is:

Syntax:- for(exp1;exp2;exp3)

Statement;

Or

for(initialized counter; test counter; update counter)

Statement;

Here exp1 is an initialization expression, exp2 is test expression or condition and exp3
is an update expression. Expression 1 is executed only once when loop started and used
to initialize the loop variables. Condition expression generally uses relational and
logical operators. And updation part executed only when after body of the loop is
executed.

Example:- void main()

int i; for(i=1;i<10;i++)

printf(― %d ‖, i);

Output:-1 2 3 4 5 6 7 8 9

Nesting of loop

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

When a loop written inside the body of another loop then, it is known as nesting of
loop. Any type of loop can be nested in any type such as while, do while, for. For
example nesting of for loop can be represented as :

void main()

int i,j; for(i=0;i<2;i++) for(j=0;j<5; j++) printf(―%d %d‖, i, j);

Output: i=0 j=0 1 2 3 4

i=1

j=0 1 2 3 4

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

UNIT – 3

ARRAYS AND STRINGS

Introduction:

ARRAYS

So far we have used only single variable name for storing one data item. If we need to
store multiple copies of the same data then it is very difficult for the user. To overcome
the difficulty a new data structure is used called arrays.

An array is a linear and homogeneous data structure

An array permits homogeneous data. It means that similar types of elements are stored
contiguously in the memory under one variable name.

An array can be declared of any standard or custom data type.

Example of an Array:

Suppose we have to store the roll numbers of the 100 students the we have to declare
100 variables named as roll1, roll2, roll3, ……. roll100 which is very difficult job.
Concept of C programming arrays is introduced in C which gives the capability to store
the 100 roll numbersin the contiguous memory which has 100 blocks and which can be
accessed by single variable name.

1. C Programming Arrays is the Collection of Elements

2. C Programming Arrays is collection of the Elements of the same data type.

3. All Elements are stored in the Contiguous memory

4. All elements in the array are accessed using the subscript variable (index).

Pictorial representation of C Programming Arrays

The above array is declared as int a [5];

a[0] = 4; a[1] = 5; a[2] = 33; a[3] = 13; a[4] = 1;

In the above figure 4, 5, 33, 13, 1 are actual data items. 0, 1, 2, 3, 4 are index variables.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Characteristics of an array:

1. The declaration int a [5] is nothing but creation of five variables of integer types
inmemory instead of declaring five variables for five values.

2. All the elements of an array share the same name and they are distinguished
from one another with the help of the element number.

3. The element number in an array plays a major role for calling each element.

4. Any particular element of an array can be modified separately without


disturbing theother elements.

5. Any element of an array a[ ] can be assigned or equated to another ordinary


variable or array variable of its type.

6. Array elements are stored in contiguous memory locations.

Array Declaration:

Array has to be declared before using it in C Program. Array is nothing but the
collection of elements of similar data types.

Syntax: <data type> array name [size1][size2] [sizen];

Syntax Parameter Significance

Data type Data Type of Each Element of the array

Array name Valid variable name

Size Dimensions of the Array

Array declaration requirements

Requirement Explanation

Data Type Data Type specifies the type of the array. We can compute the size
required for storing the single cell of array.

Valid Identifier Valid identifier is any valid variable or name given to the
array.Using this identifier name array can be accessed.

Size of Array It is maximum size that array can have.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

What does Array Declaration tell to Compiler?

1. Type of the Array

2. Name of the Array

3. Number of Dimension

4. Number of Elements in Each Dimension

Types of Array

1. Single Dimensional Array / One Dimensional Array

2. Multi Dimensional Array

Single / One Dimensional Array:

1. Single or One Dimensional array is used to represent and store data in a linear
form.

2. Array having only one subscript variable is called One-Dimensional array

3. It is also called as Single Dimensional Array or Linear Array

Single Dimensional Array Declaration and initialization:

Syntax for declaration: <data type> <array name> [size];

Examples for declaration: int iarr[3]; char carr[20]; float farr[3];

Syntax for initialization: <data type> <array name> [size] = {val1, val2, …, valn};
Examples for initialization:

int iarr[3] = {2, 3, 4};

char carr[20] = ―program‖;

float farr[3] = {12.5, 13.5, 14.5};

Different Methods of Initializing 1-D Array

Whenever we declare an array, we initialize that array directly at compile time.

Initializing 1-D Array is called as compiler time initialization if and only if we assign
certain set ofvalues to array element before executing program. i.e. at compilation time.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Here we are learning the different ways of compile time initialization of an array.

Ways of Array Initializing 1-D Array:

1. Size is Specified Directly

2. Size is Specified Indirectly

Method 1: Array Size Specified Directly

In this method, we try to specify the Array Size directly.int

num [5] = {2,8,7,6,0};

In the above example we have specified the size of array as 5 directly in the
initialization statement. Compiler will assign the set of values to particular element of
the array.

num[0] = 2; num[1] = 8; num[2] = 7; num[3] = 6; num[4] = 0;

As at the time of compilation all the elements are at specified position So This
initialization scheme is Called as ―Compile Time Initialization―.

Graphical Representation:

Method 2: Size Specified Indirectly

In this scheme of compile time Initialization, We do not provide size to an array but
instead we provide set of values to the array.

int num[ ] = {2,8,7,6,0};

Explanation:

1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and
Determinesthe Size of An Array.

2. After counting the number of elements inside the braces, The size of array is
considered as 5 during complete execution.

3. This type of Initialization Scheme is also Called as ―Compile Time


Initialization―

Example Program #include <stdio.h>int main()

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

int num[] = {2,8,7,6,0};

int i;

for (i=0;i<5;i++)

printf(―\n Array Element num [%d] = %d‖,i, num[i]); }return 0;

Output:

Array Element num[0] = 2 Array Element num[1] = 8

Array Element num[2] = 7 Array Element num[3] = 6 Array Element num[4] = 0

Accessing Array

1. We all know that array elements are randomly accessed using the subscript
variable.

2. Array can be accessed using array-name and subscript variable written inside
pair ofsquare brackets [ ].

Consider the below example of an array

In this example we will be accessing array like this

arr[3] = Forth Element of Array arr[5] = Sixth Element of Array

whereas elements are assigned to an array using below way

arr[0] = 51; arr[1] = 32; arr[2] = 43; arr[3] = 24; arr[4] = 5; arr[5] =26;

Example Program1: Accessing array

#include<stdio.h> #include<conio.h>

void main()

int arr[] = {51,32,43,24,5,26};

int i;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

for(i=0; i<=5; i++) {

printf("\nElement at arr[%d] is %d",i,arr[i]);

getch();

Output:

Element at arr[0] is 51 Element at arr[1] is 32

Element at arr[2] is 43 Element at arr[3] is 24 Element at arr[4] is 5 Element at arr[5] is 26

Accessing array a[i] means retrieving element from address (a + i).

Example Program2: Accessing array

#include<stdio.h> #include<conio.h>

void main()

int arr[] = {51,32,43,24,5,26};

int i;

for(i=0; i<=5; i++) { printf("\n%d ",arr[i]);

getch();

Output:

51

32

43

24

26

Operations with One Dimensional Array

1. Deletion – Involves deleting specified elements form an array.

2. Insertion – Used to insert an element at a specified position in an array.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

3. Searching – An array element can be searched. The process of seeking specific


elements in an array is called searching.

4. Merging – The elements of two arrays are merged into a single one.

5. Sorting – Arranging elements in a specific order either in ascending or in


descendingorder.

Example Programs:

1. C Program to delete duplicate elements from an array

#include<stdio.h> void main() {

int arr[20], i, j, k, size;

printf("\nEnter array size: "); scanf("%d", &size);

printf("\nAccept Numbers: "); for (i = 0; i < size; i++)

scanf("%d", &arr[i]); printf("\nArray with Unique list: "); for (i = 0; i < size; i++)

for (j = i + 1; j < size;j++)

if (arr[j] == arr[i])

for (k = j; k < size; k++)

arr[k] = arr[k + 1];

size--;

else j++;

for (i = 0; i < size; i++)

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("%d ", arr[i]);

Output:

Enter array size: 5

Accept Numbers: 1 3 4 5 3

Array with Unique list: 1 3 4 5

2. C Program to search an element in an array

#include<stdio.h>

void main()

int a[30], ele, num, i; printf("\nEnter no of elements:"); scanf("%d", &num);


printf("\nEnter the values :");

for (i = 0; i < num; i++)

scanf("%d", &a[i]);

//Read the element to be searched printf("\nEnter the elements to be searched :");


scanf("%d", &ele);

//Search starts from the zeroth locationi = 0; while (i < num && ele != a[i])

{ i++;

//If i < num then Match found if (i < num)

printf("Number found at the location = %d", i + 1);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

else

printf("Number not found");

};

Output:

Enter no of elements: 511 22

33 44 55

Enter the elements to be searched: 44Number found at the location = 4

3. C Program to copy all elements of an array into another array

#include<stdio.h> void main() {

int arr1[30], arr2[30], i, num; printf("\nEnter no of elements:"); scanf("%d", &num);

//Accepting values into Array printf("\nEnter the values:");

for (i = 0; i < num; i++)

{scanf("%d", &arr1[i]); }

/* Copying data from array 'a' to array 'b */ for (i = 0; i < num; i++)

arr2[i] = arr1[i];

//Printing of all elements of array printf("The copied array is:");

for (i = 0; i < num; i++) printf("\narr2[%d] = %d", i, arr2[i]);

Output:

Enter no of elements: 5

Enter the values: 11 22 33 44 55

The copied array is: 11 22 33 44 55

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

4. C program to merge two arrays in C Programming

#include<stdio.h> void main()

int arr1[30], arr2[30], res[60]; int i, j, k, n1, n2;

printf("\nEnter no of elements in 1st array:"); scanf("%d", &n1);

for (i = 0; i < n1; i++)

{scanf("%d", &arr1[i]);

printf("\nEnter no of elements in 2nd array:"); scanf("%d", &n2);

for (i = 0; i < n2; i++)

scanf("%d", &arr2[i]);

i = 0;

j = 0;

k = 0;

// Merging starts while (i < n1 && j < n2)

if (arr1[i] <= arr2[j])

res[k] = arr1[i];i++; k++;

else

res[k] = arr2[j];k++; j++;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

/*Some elements in array 'arr1' are still remaining where as the array'arr2' is
exhausted*/

while (i < n1)

res[k] = arr1[i];i++; k++; }

/*Some elements in array 'arr2' are still remaining where as the array'arr1' is exhausted

*/

while (j < n2)

res[k] = arr2[j]; k++;

j++;

//Displaying elements of array 'res' printf("\nMerged array is:");

for (i = 0; i < n1 + n2; i++) printf("%d ", res[i]);

Enter no of elements in 1st array: 11 22 33 44 Enter no of elements in 2nd array: 10 40 80

Merged array is: 10 11 22 33 40 44 80

Multi Dimensional Array:

1. Array having more than one subscript variable is called Multi-Dimensional


array.

2. Multi Dimensional Array is also called as Matrix.

Syntax: <data type> <array name> [row subscript][column subscript];

Example: Two Dimensional Arrays Declaration: Char name[50][20];

Initialization:

int a[3][3] = { 1, 2, 3

5, 6, 7

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

8, 9, 0};

In the above example we are declaring 2D array which has 2 dimensions. First
dimension will refer the row and 2nd dimension will refer the column.

Example: Three Dimensional Arrays Declaration: Char name[80][20][40];

The following information are given by the compiler after the declaration

Example

Type Array Name Dimension No. No. of Elements in Each Dimension

1 integer roll 1 10

2 character name 2 80 and 20

3 character name 3 80 and 20 and 40

Two Dimensional Arrays:

1. Two Dimensional Array requires Two Subscript Variables

2. Two Dimensional Array stores the values in the form of matrix.

3. One Subscript Variable denotes the ―Row‖ of a matrix.

4. Another Subscript Variable denotes the ―Column‖ of a matrix.

Declaration and use of 2D Arrays:

int a[3][4];

for(i=0;i<row,i++) for(j=0;j<col,j++)

printf("%d",a[i][j]);

Meaning of Two Dimensional Arrays:

1. Matrix is having 3 rows ( i takes value from 0 to 2 )

2. Matrix is having 4 Columns ( j takes value from 0 to 3 )

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

3. Above Matrix 3×4 matrix will have 12 blocks having 3 rows & 4 columns.

4. Name of 2-D array is „a„ and each block is identified by the row & column
number.

5. Row number and Column Number Starts from 0.

Two-Dimensional Arrays: Summary with Sample Example:

Summary Point Explanation

No of Subscript Variables Required 2

Declaration a[3][4]

No of Rows 3

No of Columns 4

No of Cells 12

No of for loops required to iterate 2

Memory Representation:

1. 2-D arrays are stored in contiguous memory location row wise.

2. 3 X 3 Array is shown below in the first Diagram.

3. Consider 3×3 Array is stored in Contiguous memory location which starts from
4000.

4. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored
to next memory location i.e. Elements stored row-wise

5. After Elements of First Row are stored in appropriate memory locations,


elements of next row get their corresponding memory locations.

6. This is integer array so each element requires 2 bytes of memory.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Initializing 2D Array

Method 1: Initializing all Elements row wise

For initializing 2D Array we need to assign values to each element of an array using the
below syntax.

int a[3][2] = { {1, 4}, {5, 2}, {6, 5} };

Example Program

#include<stdio.h> void main()

int i, j;

int a[3][2] = { { 1, 4 }, { 5, 2 }, { 6, 5 } };

for (i = 0; i < 3; i++)

for (j = 0; j < 2; j++)

printf("%d ", a[i][j]);

printf("\n"); }

Output:

1 4

5 2

6 5

We have declared an array of size 3 X 2, it contains overall 6elements. Row 1: {1, 4},

Row 2: {5, 2},

Row 3: {6, 5}

We have initialized each row independently a[0][0] = 1

a[0][1] = 4

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Method 2: Combine and Initializing 2D Array

Initialize all Array elements but initialization is much straight forward. All values are
assigned sequentially and row-wise

int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };

Example Program:

#include <stdio.h> void main()

int i, j;

int a[3][2] = { 1, 4, 5, 2, 6, 5 };

for (i = 0; i < 3; i++)

for (j = 0; j < 2; j++)

printf("%d ", a[i][j]);

printf("\n"); }

Output:

14

52

65

Method 3: Some Elements could be initialized

int a[3][2] = { { 1 }, { 5 , 2 }, { 6 } };

Now we have again going with the way 1 but we are removing some of the elements
from the array. Uninitialized elements will get default 0 value. In this case we have
declared and initialized 2-D array like this

#include <stdio.h> void main()

{int i, j;

int a[3][2] = { { 1 }, { 5, 2 }, { 6 }};

for (i = 0; i < 3; i++)

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

for (j = 0; j < 2; j++)

printf("%d ", a[i][j]);

printf("\n");

Output:

10

52

60

Accessing 2D Array Elements:

1. To access every 2D array we requires 2 Subscript variables.

2. i – Refers the Row number

3. j – Refers Column Number

4. a[1][0] refers element belonging to first row and zeroth column

Example Program: Accept & Print 2×2 Matrix from user

#include<stdio.h>

void main()

int i, j, a[3][3];

// i : For Counting Rows

// j : For Counting Columns for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("\nEnter the a[%d][%d] = ", i, j);

scanf("%d", &a[i][j]);

//Print array elements for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf("%d\t", a[i][j]);

printf("\n");

How it Works?

1. For Every value of row Subscript , the column Subscript incremented from 0 to
n-1 columns

2. i.e. For Zeroth row it will accept zeroth, first, second column (a[0][0], a[0][1],
a[0][2])elements

3. In Next Iteration Row number will be incremented by 1 and the column number
again initialized to 0.

4. Accessing 2-D Array: a[i][j] Element From ith Row and jth Column

1. C Program for addition of two matrices

#include<stdio.h> void main()

int i, j, mat1[10][10], mat2[10][10], mat3[10][10];

int row1, col1, row2, col2;

printf("\nEnter the number of Rows of Mat1 : "); scanf("%d", &row1);

printf("\nEnter the number of Cols of Mat1 : "); scanf("%d", &col1);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("\nEnter the number of Rows of Mat2 : "); scanf("%d", &row2);

printf("\nEnter the number of Columns of Mat2 : "); scanf("%d", &col2);

/* before accepting the Elements Check if no of rows and columns ofboth matrices is
equal */

if (row1 != row2 || col1 != col2)

printf("\nOrder of two matrices is not same "); exit(0);

//Accept the Elements in Matrix 1for (i

= 0; i < row1; i++) {

for (j = 0; j < col1; j++) {

printf("Enter the Element a[%d][%d] : ", i, j); scanf("%d", &mat1[i][j]);

//Accept the Elements in Matrix 2 for (i = 0; i < row2; i++)

for (j = 0; j < col2; j++)

printf("Enter the Element b[%d][%d] : ", i, j); scanf("%d", &mat2[i][j]);

//Addition of two matrices for (i = 0; i < row1; i++)

for (j = 0; j < col1; j++)

mat3[i][j] = mat1[i][j] + mat2[i][j];}

//Print out the Resultant Matrix

printf("\nThe Addition of two Matrices is : \n"); for (i = 0; i < row1; i++)

for (j = 0; j < col1; j++)

printf("%d\t", mat3[i][j]);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("\n");

Output:

Enter the number of Rows of Mat1 : 3 Enter the number of Columns of Mat1 : 3

Enter the number of Rows of Mat2 : 3

Enter the number of Columns of Mat2 : 3

Enter the Element a[0][0] : 1

Enter the Element a[0][1] : 2

Enter the Element a[0][2] : 3

Enter the Element a[1][0] : 2

Enter the Element a[1][1] : 1

Enter the Element a[1][2] : 1

Enter the Element a[2][0] : 1

Enter the Element a[2][1] : 2

Enter the Element a[2][2] : 1

Enter the Element b[0][0] : 1

Enter the Element b[0][1] : 2

Enter the Element b[0][2] : 3

Enter the Element b[1][0] : 2

Enter the Element b[1][1] : 1

Enter the Element b[1][2] : 1

Enter the Element b[2][0] : 1

Enter the Element b[2][1] : 2

Enter the Element b[2][2] : 1

The Addition of two Matrices is :

246

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

422

242

2. C Program to Multiply two 3 X 3 Matrices

#include<stdio.h> void main()

int a[10][10], b[10][10], c[10][10], i, j, k;

int sum = 0;

printf("\nEnter First Matrix : "); for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

scanf("%d", &a[i][j]);

printf("\nEnter Second Matrix :"); for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

scanf("%d", &b[i][j]);

printf("The First Matrix is : \n"); for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf(" %d ", a[i][j]);

printf("\n");

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("The Second Matrix is : \n"); for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf(" %d ", b[i][j]);

printf("\n");

//Multiplication Logic for (i = 0; i <= 2; i++)

for (j = 0; j <= 2; j++)

sum = 0;

for (k = 0; k <= 2; k++)

sum = sum + a[i][k] * b[k][j];

c[i][j] = sum;

printf("\nMultiplication Of Two Matrices : \n"); for (i = 0; i < 3; i++)

for (j = 0; j < 3; j++)

printf(" %d ", c[i][j]);

printf("\n");

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Output:

Enter First Matrix :

1 1 1

1 1 1

1 1 1

Enter Second Matrix :

2 2 2

2 2 2

2 2 2

The First Matrix is :

1 1 1

1 1 1

1 1 1

The Second Matrix is :

2 2 2

2 2 2

2 2 2

Multiplication Of Two Matrices :

6 6 6

6 6 6

6 6 6

Multiplication is possible if and only if

i. No. of Columns of Matrix 1 = No of Columns of Matrix 2

ii. Resultant Matrix will be of Dimension – c [No. of Rows of Mat1][No. of Columns


of Mat2]

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

STRINGS

A string is a sequence of character enclosed with in double quotes (― ‖) but ends


with

\0. The compiler puts \0 at the end of string to specify the end of the string. To get a
value of string variable we can use the two different types of formats. Using scanf()
function as: scanf(―%s‖, string variable);

Using gets() function as : gets(string variable); STRING HANDLING FUNCTIONS

C library supports a large number of string handling functions. Those functions are
stored under the header file string.h in the program.

Let us see about some of the string handling functions.

(i) strlen() function

strlen() is used to return the length of the string , that means counts the number of
characters present in a string.

Syntax

integer variable = strlen (string variable);

Example:

#include<stdio.h> #include<conio.h> void main()

char str[20];int strlength;clrscr(); printf(‚Enter String:‛); gets(str); strlength=strlen(str);

printf(‚Given String Length Is: %d‛, strlength);getch();

Output:

Enter String Welcome

Given String Length Is:7

(ii) strcat() function

The strcat() is used to concatenate two strings. The second string will be appended to
the end of the first string. This process is called concatenation.

Syntax

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

strcat (StringVariable1, StringVariable 2);

Example:

#include<stdio.h> #include<conio.h> void main()

char str1[20],str2[20];clrscr(); printf(‚Enter First String:‛); scanf(‚%s‛,str1);

printf(‚Enter Second String:‛); scanf(‚%s‛,str2);

printf(‚ Concatenation String is:%s‛, strcat(str1,str2));getch();

Output:

Enter First String Good

Enter Second String Morning

Concatenation String is: GoodMorning

(iii) strcmp() function

strcmp() function is used to compare two strings. strcmp() function does a case
sensitive comparison between two strings. The two strings are compared character by
character until there is a mismatch or end of one of the strings is reached (whichever
occurs first). If the two strings are identical, strcmp( ) returns a value zero. If they‟re
not, it returns the numeric difference between the ASCII values of the first non-
matching pairs of characters.

Syntax

strcmp(StringVariable1, StringVariable2);

Example:

#include<stdio.h> #include<conio.h> void main()

char str1[20], str2[20];int res; clrscr();

printf(‚Enter First String:‛); scanf(‚%s‛,str1);

printf(‚Enter Second String:‛); scanf(‚%s‛,str2);

res = strcmp(str1,str2);

printf(‚ Compare String Result is:%d‛,res);getch();

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Output:

Enter First String Good

Enter Second String Good

Compare String Result is: 0

(iv) strcmpi() function

strcmpi() function is used to compare two strings. strcmpi() function is not case
sensitive.

Syntax

strcmpi(StringVariable1, StringVariable2);

Example:

#include<stdio.h> #include<conio.h> void main()

Output:

char str1[20], str2[20];int res; clrscr();

printf(‚Enter First String:‛); scanf(‚%s‛,str1);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf(‚Enter Second String:‛); scanf(‚%s‛,str2);

res = strcmpi(str1,str2);

printf(‚ Compare String Result is:%d‛,res);getch();

Enter First String WELCOME

Enter Second String welcome

Compare String Result is: 0

(v) strcpy() function:

strcpy() function is used to copy one string to another. strcpy() function copy the
contents of second string to first string.

Syntax

strcpy(StringVariable1, StringVariable2);

Example:

#include<stdio.h> #include<conio.h> void main()

char str1[20], str2[20];int res; clrscr();

printf(‚Enter First String:‛); scanf(‚%s‛,str1);

printf(‚Enter Second String:‛); scanf(‚%s‛,str2); strcpy(str1,str2) printf(‚ First String


is:%s‛,str1);printf(‚ Second String is:%s‛,str2);getch();

Output:

Enter First String Hello

Enter Second String welcome

First String is: welcomeSecond String is: welcome

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

(vi) strlwr () function:

This function converts all characters in a given string from uppercase to lowercase
letter.

Syntax

strlwr(StringVariable);

Example:

#include<stdio.h> #include<conio.h> void main()

char str[20]; clrscr();

printf(‚Enter String:‛); gets(str);

printf(‚Lowercase String : %s‛, strlwr(str));getch();

Output:

Enter String WELCOME

Lowercase String : welcome

(vii) strrev() function:

strrev() function is used to reverse characters in a given string.

Syntax

strrev(StringVariable);

Example:

#include<stdio.h> #include<conio.h>

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

void main()

char str[20]; clrscr();

printf(‚Enter String:‛); gets(str);

printf(‚Reverse String : %s‛, strrev(str));getch();

Output:

Enter String WELCOME

Reverse String : emoclew

(viii) strupr() function:

strupr() function is used to convert all characters in a given string from lower case to
uppercase letter.

Syntax

strupr(Stringvariable);

Example:

#include<stdio.h> #include<conio.h> void main()

char str[20]; clrscr();

printf(‚Enter String:‛); gets(str);

printf(‚Uppercase String : %s‛, strupr(str)); getch();

Output:

Enter String welcome

Uppercase String : WELCOME

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

UNIT 4

POINTERS IN C

POINTERS

Definition:

• C Pointer is a variable that stores/points the address of the another variable.

• C Pointer is used to allocate memory dynamically i.e. at run time.

• The variable might be any of the data type such as int, float, char, double, short
etc.

Syntax : data_type *var_name; Example : int *p; char *p;

Where, * is used to denote that ―p‖ is pointer variable and not a normal variable.

Key points to remember about pointers in C:

• Normal variable stores the value whereas pointer variable stores the address of
the variable.

• The content of the C pointer always be a whole number i.e. address.

• Always C pointer is initialized to null, i.e. int *p = null.

• The value of null pointer is 0.

• & symbol is used to get the address of the variable.

• symbol is used to get the value of the variable that the pointer is pointing to.

• If pointer is assigned to NULL, it means it is pointing to nothing.

• The size of any pointer is 2 byte (for 16 bit compiler).

• No two pointer variables should have the same name.

• But a pointer variable and a non-pointer variable can have the same name.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

1 Pointer –Initialization:

Assigning value to pointer:

It is not necessary to assign value to pointer. Only zero (0) and NULL can be assigned
to a pointer no other number can be assigned to a pointer. Consider the following
examples;

int *p=0;

int *p=NULL;

The above two assignments are valid. int *p=1000;

This statement is invalid.

Assigning variable to a pointer:

int x; *p; p = &x;

This is nothing but a pointer variable p is assigned the address of the variable x. The
address of the variables will be different every time the program is executed.

Reading value through pointer:

int x=123; *p; p = &x;

Here the pointer variable p is assigned the address of variable x. printf(―%d‖, *p); will
display value of x 123.

This is reading value through pointer

printf(―%d‖, p); will display the address of the variable x. printf(―%d‖, &p); will
display the address of the pointer variable p. printf(―%d‖,x); will display the value of x
123.

printf(―%d‖, &x); will display the address of the variable x.

Note: It is always a good practice to assign pointer to a variable rather than 0 or NULL.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Pointer Assignments:

We can use a pointer on the right-hand side of an assignment to assign its value to
another variable.

Example: int main()

int var=50; int *p1, *p2; p1=&var; p2=p1;

Chain of pointers/Pointer to Pointer:

A pointer can point to the address of another pointer. Consider the following example.
int x=456,

*p1, **p2; //[pointer-to-pointer]; p1 = &x;

p2 = &p1;

printf(―%d‖, *p1); will display value of x 456. printf(―%d‖, *p2); will also display value
of x 456.

This is because p2 point p1, and p1 points x. Therefore p2 reads the value of x through
pointer p1. Since one pointer is points towards another pointer it is called chain pointer.
Chain pointer must be declared with ** as in **p2.

Manipulation of Pointers

We can manipulate a pointer with the indirection operator „*‟, which is known as
dereference operator. With this operator, we can indirectly access the data variable
content.

Syntax: *ptr_var;

Example:

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

#include<stdio.h> void main()

int a=10, *ptr; ptr=&a; printf(‖\n The value of a is ‖,a);

*ptr=(*ptr)/2;

printf(‖The value of a is.‖,(*ptr));

Output:

The value of a is: 10 The value of a is: 5

2 Pointer Expression & Pointer Arithmetic

C allows pointer to perform the following arithmetic operations:

A pointer can be incremented / decremented.

Any integer can be added to or subtracted from the pointer.

A pointer can be incremented / decremented.

In 16 bit machine, size of all types[data type] of pointer always 2 bytes.

Eg: int a; int *p; p++;

Each time that a pointer p is incremented, the pointer p will points to the memory
location of the next element of its base type. Each time that a pointer p is decremented,
the pointer p will points to the memory location of the previous element of its base
type.

int a,*p1, *p2, *p3; p1=&a;

p2=p1++; p3=++p1;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf(―Address of p where it points to %u‖, p1); 1000

printf(―After incrementing Address of p where it points to %u‖, p1); 1002

printf(―After assigning and incrementing p %u‖, p2); 1000

printf(―After incrementing and assigning p %u‖, p3); 1002

In 32 bit machine, size of all types of pointer is always 4 bytes.

The pointer variable p refers to the base address of the variable a. We can increment the
pointer variable,

p++ or ++p

This statement moves the pointer to the next memory address. let p be an integer
pointer with a current value of 2,000 (that is, it contains the address 2,000). Assuming
32-bit integers, after the expression

p++;

the contents of p will be 2,004, not 2,001! Each time p is incremented, it will point to the
next integer. The same is true of decrements. For example,

p--;

will cause p to have the value 1,996, assuming that it previously was 2,000. Here is why:
Each time that a pointer is incremented, it will point to the memory location of the next
element of its base type. Each time it is decremented, it will point to the location of the
previous element of its base type.

Any integer can be added to or subtracted from the pointer.

Like other variables pointer variables can be used in expressions. For example if p1 and
p2 are properly declared and initialized pointers, then the following statements are
valid.

y=*p1**p2; sum=sum+*p1; z= 5* - *p2/p1;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

*p2= *p2 + 10;

C allows us to add integers to or subtract integers from pointers as well as to subtract


one pointer from the other. We can also use short hand operators with the pointers
p1+=; sum+=*p2; etc., we can also compare pointers by using relational operators the
expressions such as p1 >p2 , p1==p2 and p1!=p2 are allowed.

/*Program to illustrate the pointer expression and pointer arithmetic*/

#include< stdio.h > #include<conio.h> void main()

int ptr1,ptr2; int a,b,x,y,z; a=30;

b=6;

ptr1=&a; ptr2=&b; x=*ptr1+ *ptr2 –6;

y=6*- *ptr1/ *ptr2 +30; printf(―\nAddress of a + %u‖,ptr1);

printf(―\nAddress of b %u‖, ptr2); printf(―\na=%d, b=%d‖, a, b);


printf(―\nx=%d,y=%d‖, x, y); ptr1=ptr1 + 70;

ptr2= ptr2;

printf(―\na=%d, b=%d‖, a, b);

/* Sum of two integers using pointers*/

#include <stdio.h> int main()

int first, second, *p, *q, sum; printf("Enter two integers to add\n"); scanf("%d%d",
&first, &second);

p = &first;

q = &second; sum = *p + *q;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("Sum of entered numbers = %d\n",sum); return 0;

3 Pointers and Arrays

Array name is a constant pointer that points to the base address of the array[i.e the first
element of the array]. Elements of the array are stored in contiguous memory locations.
They can be efficiently accessed by using pointers.

Pointer variable can be assigned to an array. The address of each element is increased
by one factor depending upon the type of data type. The factor depends on the type of
pointer variable defined. If it is integer the factor is increased by 2.

Consider the following example:

int x[5]={11,22,33,44,55}, *p;

p = x; //p=&x; // p = &x[0];

Remember, earlier the pointer variable is assigned with address (&) operator. When
working with array the pointer variable can be assigned as above or as shown below:

Therefore the address operator is required only when assigning the array with element.
Assume the address on x[0] is 1000 then the address of other elements will be as follows

x[1] = 1002

x[2] = 1004

x[3] = 1006

x[4] = 1008

The address of each element increase by factor of 2. Since the size of the integer is 2
bytes the memory address is increased by 2 bytes, therefore if it is float it will be
increase 4 bytes, and for double by 8 bytes. This uniform increase is called scale factor.

p = &x[0];

Now the value of pointer variable p is 1000 which is the address of array element x[0].
To find the address of the array element x[1] just write the following statement.

p = p + 1;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Now the value of the pointer variable p is 1002 not 1001 because since p is pointer
variable the increment of will increase to the scale factor of the variable, since it is
integer it increases by 2.

The p = p + 1; can be written using increment or decrement operator ++p; The values in
the array element can be read using increment or decrement operator in the pointer
variable using scale factor.

Consider the above example.

printf(―%d‖, *(p+0)); will display value of array element x[0] which is 11. printf(―%d‖,
*(p+1)); will display value of array element x[1] which is 22. printf(―%d‖, *(p+2)); will
display value of array element x[2] which is 33. printf(―%d‖, *(p+3)); will display value
of array element x[3] which is 44. printf(―%d‖, *(p+4)); will display value of array
element x[4] which is 55.

/*Displaying the values and address of the elements in the array*/

#include<stdio.h> void main()

int a[6]={10, 20, 30, 40, 50, 60};

int *p; int i; p=a;

for(i=0;i<6;i++)

printf(―%d‖, *p); //value of elements of array printf(―%u‖,p); //Address of array

getch();

/* Sum of elements in the Array*/ #include<stdio.h> #include<conio.h> void main()

int a[10]; int i,sum=0; int *ptr;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("Enter 10 elements:n"); for(i=0;i<10;i++) scanf("%d",&a[i]);

ptr = a; /* a=&a[0] */ for(i=0;i<10;i++)

sum = sum + *ptr; //*p=content pointed by 'ptr' ptr++;

printf("The sum of array elements is %d",sum);

/*Sort the elements of array using pointers*/

#include<stdio.h> int main()

int i,j, temp1,temp2;

int arr[8]={5,3,0,2,12,1,33,2};

int *ptr;

for(i=0;i<7;i++){ for(j=0;j<7-i;j++){ if(*(arr+j)>*(arr+j+1))

ptr=arr+j; temp1=*ptr++; temp2=*ptr;

*ptr--=temp1;

*ptr=temp2;

for(i=0;i<8;i++)

printf(" %d",arr[i]);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

4 Pointers and Multi-dimensional Arrays

The array name itself points to the base address of the array.

Example:

int a[2][3]; int *p[2];

p=a; //p points to a[0][0]

/*Displaying the values in the 2-d array*/

#include<stdio.h> void main()

int a[2][2]={{10, 20},{30, 40}};

int *p[2]; int i,j;

p=a; for(i=0;i<2;i++)

for(j=0;j<2;j++)

printf(―%d‖, *(*(p+i)+j)); //value of elements of array

getch();

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

UNIT 5
USER DEFINED FUNCTIONS

FUNCTION

Functions are created when the same process or an algorithm to be repeated several times in
various places in the program.

Function has a self-contained block of code, that executes certain task. A function has a name, a
list of arguments which it takes when called, and the block of code it executes when called.

Functions are two types:

Built-in / Library function.

ex:) printf(), scanf(), getch(), exit(), etc. User defined function.

User-Defined Functions

Functions defined by the users according to their requirements are called user-defined
functions. These functions are used to break down a large program into a small functions.

Advantage of User defined function:

1. Reduce the source code

2. Easy to maintain and modify

3. It can be called any where in the program.

Body of user defined function:

return_type f_name (argument1,argument 2)

local variables; statements; return_type;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

The body of user-defined shows that an user-defined functions has


following characteristics:

1. Return type

2. Function name

3. Parameter list of arguments

4. Local variables

5. Statements

6. Return value

S.no C function aspects : syntax 1 function definition

return_type function_name ( arguments list )

{ Body of function; }

2 function call

function_name ( arguments list );

3 function declaration

return_type function_name ( argument list );

Note: The function with return value must be the data type, that is return type and return value
must be of same data type.

User defined function has three parts:

1. Declaration part

ret_type f_name (arguments)

2. Calling part f_name(arguments);

3. Definition part

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Function Parameters:

Parameters provide the data communication between calling function and called function.

Two types:

Actual parameters:

These are the parameters transferred from the calling function[main function] to the called
function[user defined function].

Formal parameters:

Passing the parameters from the called functions[user defined function] to the calling
functions[main function].

Note:

Actual parameter – This is the argument which is used in function call. Formal parameter – This
is the argument which is used in function definition. Categories of User defined
function/Function Prototypes:

A function prototype declaration consists of the functions return type, name and
arguments list.

Always terminated with semicolon. The following are the function prototypes:

1. Function without return value and without argument.

2. Function without return value and with argument.

3. Function with return value and with argument.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

4. Function with return value and without argument.

Note: Function with more than one return value will not have return type and return statement
in the function definition.

Consider the following example to multiply two numbers:

void main( )

int x,y,z; scanf(―%d%d‖, &x,&y); z=x* y;

printf(―The result is %d‖, z);

1. Function without return value and without argument

In this prototype, no data transfers takes place between the calling function and the called
function. They read data values and print result in the same block.

Syntax:

void f_name(); //function declaration void f_name (void) //function definition

local variables; statements;

void main()

f_name(); //function call

The above example can be rewritten by creating function:

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

void f_mult(); //function definition void f_mult(void )

int x,y,z; scanf(―%d%d‖, &x,&y); z=x* y; printf(―The result is %d‖, z);

void main()

f_mult();

2. Function without return value and with argument

In this prototype, data is transferred from the calling function to called function. The called
function receives some data from the calling function and does not send back any values to the
calling functions.

Syntax:

void f_name(int x, int y ); //Function declaration

void f_name (int x, int y) //Function Definition //Formal Parameters

local variables; statements;

void main()

//variable declaration //input statement

f_name(c, d); //Function call //Actual Parameters

The above example can be rewritten by creating function void f_mult(int x, int y);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

void f_mult(int x, int y )

int z; z=x* y;

printf(―The result is %d‖, z);

void main()

int c, d;

printf(―Enter any two number‖); scanf(―%d%d‖, &c, &d); f_mult(c, d); //Function call

3. Function with return value and without argument

The calling function cannot pass any arguments to the called function but the called function
may send some return value to the calling function.

Syntax:

int f_name(); //Function declaration

int f_name (void) //Function Definition

local variables; statements; return int;

void main()

//variable declaration ret_var=f_name(); //Function call

The above example can be rewritten by creating function int f_mult(); int f_mult(void )

int x,y,z; scanf(―%d%d‖, &x,&y); z=x* y; printf(―The result is %d‖, z); return(z); } void main()

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

int c; c=f_mult(); getch();

4. Function with return value and with argument

In this prototype, the data is transferred between the calling function and called function. The
called function receives some data from the calling function and send back a value return to the
calling function.

Syntax:

int f_name (int x, int y); //Function declaration

int f_name (int x, int y) //Function definition //Formal Parameters

local variables; statements; return int;

void main()

//variable declaration //Input Statement

ret_value=f_mult(a, b); //Function Call //Actual Parameters

The above example can be rewritten by creating function: int f_mult(int x, int y);

int f_mult(int x, int y)

int z; z=x* y;

printf(―The result is %d‖, z); return(z);

void main()

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

int a,b,c;

printf(―Enter any two value:‖); scanf(―%d%d‖, &a, &b); c=f_mult(a, b);

Note:

If the return data type of a function is ―void‖, then, it can‟t return any values to the
calling function.

If the return data type of the function is other than void such as ―int, float, double etc‖,
then, it can return values to the calling function.

return statement:

It is used to return the information from the function to the calling portion of the program.

Syntax:

return; return();

return(constant); return(variable); return(exp); return(condn_exp);

By default, all the functions return int data type.

Do you know how many values can be return from C functions?

Always, only one value can be returned from a function.

If you try to return more than one values from a function, only one value will be
returned that appears at the right most place of the return statement.

For example, if you use ―return a,b,c‖ in your function, value for c only will be returned
and values a, b won‟t be returned to the program.

In case, if you want to return more than one values, pointers can be used to directly
change the values in address instead of returning those values to the function.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Function Call:

A function can be called by specifying the function_name in the source program with
parameters, if presence within the paranthesis.

Syntax:

Fn_name(); Fn_name(parameters); Ret_value=Fn_name(parameters);

Example:

#include<stdio.h> #include<conio.h>

int add(int a, int b); //function declaration void main()

int x,y,z;

printf(―\n Enter the two values:‖); scanf(―%d%d‖,&x,&y);

z=add(x,y); //Function call(Actual parameters) printf(―The sum is .%d‖, z);

int add(int a, int b) //Function definition(Formal parameters)

int c; c=a+b;

return(c); //return statement

2. Parameter Passing Methods/Argument Passing Methods

Call by Value/Pass by Value:

When the value is passed directly to the function it is called call by value. In call by value only a
copy of the variable is only passed so any changes made to the variable does not reflects in the
calling function.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Example:

#include<stdio.h> #include<conio.h> swap(int,int);

void main() int x,y;

printf("Enter two nos"); scanf("%d %d",&x,&y); printf("\nBefore swapping : x=%d y=%d",x,y);


swap(x,y); getch();

swap(int a,int b)

int t; t=a; a=b; b=t;

printf("\nAfter swapping :x=%d y=%d",a,b);

System Output:

Enter two nos 12 34

Before swapping :12 34

After swapping : 34 12

Call by Reference/Pass by Reference:

When the address of the value is passed to the function it is called call by reference. In call by
reference since the address of the value is passed any changes made to the value reflects in the
calling function.

Example:

#include<stdio.h> #include<conio.h> swap(int *, int *); void main()

int x,y;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf("Enter two nos"); scanf("%d %d",&x,&y); printf("\nBefore swapping:x=%d y=%d",x,y);


swap(&x,&y); printf("\nAfter swapping :x=%d y=%d",x,y); getch();

swap(int *a,int *b)

int t; t=*a; *a=*b; *b=t;

System Output:

Enter two nos 12 34

Before swapping :12 34

After swapping : 34 12

Call by Value

This is the usual method to call a function in which only the value of the variable is passed as
an argument

Any alternation in the value of the argument passed does not affect the function. Memory
location occupied by formal and actual arguments is different

Since a new location is created, this method is slow

There is no possibility of wrong data manipulation since the arguments are directly used in an
application

Call by Reference

In this method, the address of the variable is passed as an argument Any alternation in the
value of the argument passed affect the function.

Memory location occupied by formal and actual arguments is same and there is a saving of
memory location

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

Since the existing memory location is used through its address, this method is fast

There is a possibility of wrong data manipulation since the addresses are used in an expression.
A good skill of programming is required here.

STRUCTURES AND UNIONS

STRUCTURE

In general terms, the composition of a structure may be defined as struct tag

member 1;

member 2;

member m;

In this declaration, struct is a required keyword ,tag is a name that identifies structures of this
type.

The individual members can be ordinary variables, pointers, arrays or other structures. The
member names within a particular structure must be distinct from one another, though a
member name can be same as the name of a variable defined outside of the structure. A storage
class, however, cannot be assigned to an individual member, and individual members cannot
be initialized within a structure-type declaration. For example:

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

struct student

char name [80]; int roll_no; float marks;

};

we can now declare the structure variable s1 and s2 as follows:

struct student s1, s2;

s1 and s2 are structure type variables whose composition is identified by the tag student.

It is possible to combine the declaration of the structure com-position with that of the structure
variable as shown below.

storage- class struct tag

member 1;

member 2;

- ——

- —-

- member m;

} variable 1, variable 2 variable n;

The tag is optional in this situation.

struct student { char name [80]; int roll_no; float marks;

}s1,s2;

The s1, s2, are structure variables of type student.

Since the variable declarations are now combined with the declaration of the structure type, the
tag need not be included. As a result, the above declaration can also be written as

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

struct{

char name [80]; int roll_no; float marks ;

} s1, s2, ;

A structure may be defined as a member of another structure. In such situations, the declaration
of the embedded structure must appear before the declaration of the outer structure. The
members of a structure variable can be assigned initial values in much the same manner as the
elements of an array. The initial values must appear in the order in which they will be assigned
to their corresponding structure members, enclosed in braces and separated by commas. The
general form is

storage-class struct tag variable = { value1, value 2, , value m};

A structure variable, like an array can be initialized only if its storage class is either external or
static.

e.g. suppose there are one more structure other than student. struct dob

int month; int day;

int year;

};

struct student

char name [80]; int roll_no; float marks; struct dob d1;

};

static struct student st = { ― param‖, 2, 99.9, 17, 11, 01};

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

It is also possible to define an array of structure, that is an array in which each element is a
structure. The procedure is shown in the following example:

struct student

char name [80]; int roll_no ; float marks ;

} st [100];

In this declaration st is a 100- element array of structures.

It means each element of st represents an individual student record.

PROCESSING A STRUCTURE

The members of a structure are usually processed individually, as separate entities. Therefore,
we must be able to access the indi-vidual structure members. A structure member can be
accessed by writing

variable.member name.

This period (.) is an operator, it is a member of the highest prece-dence group, and its
associativity is left-to-right.

e.g. if we want to print the detail of a member of a structure then we can write as

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

printf(―%s‖,st.name); or printf(―%d‖, st.roll_no) and so on. More com-plex expressions


involving the repeated use of the period operator may also be written. For example, if a
structure member is itself a structure, then a member of the embedded structure can be ac-
cessed by writing.

variable.member.submember.

Thus in the case of student and dob structure, to access the month of date of birth of a student,
we would write

st.d1.month

The use of the period operator can be extended to arrays of structure, by writing array
[expression]. member

Structures members can be processed in the same manner as ordinary variables of the same
data type. Single-valued structure members can appear in expressions. They can be passed to
functions and they can be returned from functions, as though they were ordinary single- valued
variables.

e.g. suppose that s1 and s2 are structure variables having the same composition as described
earlier. It is possible to copy the values of s1 to s2 simply by writing

s2=s1;

It is also possible to pass entire structure to and from functions though the way this is done
varies from one version of 'C' to another. Let us consider an example of structure:

#include <stdio.h> struct date {

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

int month; int day; int year;

};

struct student{ char name[80]; char address[80]; int roll_no;

char grade; float marks; struct date d1;

}st[100];

main()

int i,n;

void readinput (int i); void writeoutput(int i); printf(―Student system‖);

printf(―How many students are there ?‖); scanf(―%d‖ &n);

for (i= ; i<n; ++i)

readinput (i);

if( st[i].marks <80) st[i].grade=‘A‘;

else st[i].grade='A'+;

for (i= ; i<n; ++i) writeoutput(i);

void readinput (int i)

printf(―\n student no % \n‖, i+1); printf(―Name:‖);

scanf(―%s‖, st[i].name); printf(―Address:‖); scanf(―%s", st[i].address); printf(―Roll number‖);


scanf(―%d‖, &st[i].roll_no); printf(―marks‖); scanf(―%f‖,&st[i].marks);

printf(―Date of Birth {mm/dd/yyyy)‖);

scanf(―%d%d%d‖, & st[i].d1.month & st[i].d1.day, & st[i].d1.year); return;

void writeoutput(int i)

printf(―\n Name:%s‖,st[i].name); printf(―Address %s\n‖, st[i].address); printf(―Marks % f \n‖,


st[i].marks); printf(―Roll number %d\n‖, st[i].roll_no); printf(―Grade %c\n‖,st[i].grade);

return;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

It is sometimes useful to determine the number of bytes required by an array or a structure.


This information can be obtained through the use of the sizeof operator.

USER-DEFINED DATA TYPES (Typedef)

The typedef feature allows users to define new data types that are equivalent to existing data
types. Once a user-defined data type has been established, then new variables, arrays,

structure and so on, can be declared in terms of this new data type. In general terms, a new data
type is defined as

typedef type new type;

Where type refers to an existing data type and new-type refers to the new user-defined data
type.

e.g. typedef int age;

In this declaration, age is user- defined data type equivalent to type int. Hence, the variable
declaration

age male, female;

is equivalent to writing int age, male, female;

The typedef feature is particularly convenient when defining structures, since it eliminates the
need to repeatedly write struct tag whenever a structure is referenced. As a result, the structure
can be referenced more concisely.

In general terms, a user-defined structure type can be written as typedef struct

member 1;

member 2:

- ---

- ---

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

member m;

}new-type;

The typedef feature can be used repeatedly, to define one data type in terms of other user-
defined data types.

UNIONS

Union, like structures, contain members whose individual data types may differ from one
another. However, the members that compose a union all share the same storage area within
the computer‘s memory, whereas each member within a structure is assigned its own unique
storage area. Thus, unions are used to conserve memory.

In general terms, the composition of a union may be defined as union tag

member1; member 2;

---

member m

};

Where union is a required keyword and the other terms have the same meaning as in a
structure definition. Individual union variables can then be declared as storage-class union tag
variable1, variable2, -----, variable n; where storage-class is an optional storage class specifier,
union is a required keyword, tag is the name that appeared in the union definition and variable
1, variable 2, variable n are union variables of type tag.

The two declarations may be combined, just as we did in the case of structure. Thus, we can
write.

Storage-class union tag

member1; member 2;

---

member m

}variable 1, varibale2, , variable n;

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

The tag is optional in this type of declaration.

Let us take a 'C' program which contains the following union declaration: union code

char color [5]; int size ;

}purse, belt;

Here we have two union variables, purse and belt, of type code.

Each variable can represent either a 5–character string (color) or an integer quantity (size) of
any one time.

A union may be a member of a structure, and a structure may be a member of a union.

An individual union member can be accessed in the same manner as an individual structure
members, using the operators (→) and.

Thus if variable is a union variable, then varibale.member refers to a member of the union.
Similarly, if ptr is a pointer variable that points to a union, then ptr→ member refers to a
member of that union.

Let us consider the following C program: # include <stdio.h>

main() union code

char color; int size;

};

struct

char company [10]; float cost ;

union code detail;

}purse, belt;

printf(―%d\n‖, sizeof (union code)); purse.detail.color=‘B‘;

printf(―%c%d\n‖, purse.detail.color,purse.detail.size); purse.detail.size=20;

printf(―%c%d\n‖, purse. detail.color,purse.detail.size);

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077
COURSE MATERIAL

Program & Sem: BCA & I Course code & Name: CAC02 Programming in C

The output is as follows: 2

B- 23190

@ 20

The first line indicates that the union is allocated 2 bytes of memory to accommodate an integer
quantity. In line two, the first data item [B] is meaningful, but the second is not. In line three,
the first data item is meaningless, but the second data item [20] is meaningful. A union variable
can be initialized, provided its storage class is either external or static. Only one member of a
union can be assigned a value at any one time. Unions are processed in the same manner, and
with the same restrictions as structures. Thus, individual union members can be processed as
though they were ordinary variables of the same data type and pointers to unions can be
passed to or from functions.

Prepared by
Prof S Vijaya Kumar, MCA, MBA, M.Phil(CS)
HOD & Associate Professor in BCA, Ebenezer Management College, Bengaluru - 560077

You might also like