C Program All Modules New
C Program All Modules New
Syllabus
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 1 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Instruction
A basic command/order. An instruction is a segment of code that contains
steps that need to be executed by the computer processor. For a computer to do
something, instructions have to be given to the computer processor so it knows how
to do what it is being asked to do.
For example, if you were to ask the computer to draw a square, it would need a set
of instructions on how to draw the square, so it can complete the task.
Computer Program
A computer program is a collection of instructions that performs a specific
task when executed by a computer. A computer requires programs to function and
typically executes the program's instructions in a central processing unit. A
computer program is usually written by a computer programmer in a programming
language.
Programming
It is a process of writing set of rules/instructions that provides a way of
telling a computer what operations to perform.
Programmer
A computer programmer, or coder, is someone who writes computer
software. The term computer programmer can refer to a specialist in one area of
computer programming or to a generalist who writes code for many kinds of
software.
Role of a Programmer
The programmer's job is to convert problem solutions into instructions for the
computer. That is, the programmer prepares the instructions of a computer program
and runs those instructions on the computer, tests the program to see if it is working
properly, and makes corrections to the program. The programmer also writes a
report on the program. These activities are all done for the purpose of helping a user
fill a need, such as paying employees, billing customers, or admitting students to
college.
Programming Language
All the human beings in this world communicate with each other by a
language. Similarly, in order to communicate with computer user also needs a
language that should be understandable by computers.
PL is an interface between human & computer they allow us to communicate
with computer in order to perform task. This are used to develop system and
applications software’s.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 2 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
The main disadvantage of this language is that it is written only for a single type of
CPU and does not run on any other CPU. But its speed makes it the most used low
level language till today which is used by many programmers.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 3 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
4th Generation Language
4GLs are closer to human language than other high-level languages and are
accessible to people without formal training as programmers. They allow multiple
common operations to be performed with a single programmer-entered command.
They are intended to be easier for users than machine languages (first-
generation), assembly languages (second-generation), and older high-level
languages (third-generation). 4GLs are designed to reduce the overall time, effort
and cost of software development.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 4 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
UNIT – 1
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 5 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Introduction of C Programming
Overview of C language
C is a structured, general purpose, high level programming language
developed by American programmer Dennis M. Ritchie in the year 1972 at AT &
T’s (American Telephone & Telegraph) Bell Laboratories. C is a powerful, flexible,
portable programming language. It is one of the most popular computer languages
today because of its structure, high-level abstraction, machine independent feature.
C language was developed with UNIX operating system, so it is strongly associated
with UNIX, which is one of the most popular network operating system in use today
and heart of internet data superhighway.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 6 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
✓ Many of C’s principles and ideas were derived from the earlier language B.
(Ken Thompson was the developer of B Language.)
✓ BCPL and CPL are the earlier ancestors of B Language
✓ CPL is common Programming Language. In 1967, BCPL Language ( Basic
CPL ) was created as a scaled down version of CPL
✓ As many of the features were derived from “B” Language that’s why it was
named as “C”.
✓ After 7-8 years, C++ came into existence, which was first example of object-
oriented programming.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 7 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
4. Hardware control:
C programming language provides close control on hardware. It can be used
to write efficient programs to control hardware components of computer
system.
5. Small language:
C is a small language. It has a small number of keywords and programming
controls. But still it is very powerful for developing different types of
programs.
6. Portability:
C Programs are portable i.e. they can run on any Compiler with little or No
Modification. Compiler and Pre-processor make it possible for C Programs to
run it on Different Platforms.
7. More Efficient:
C Programming language is more efficient to other languages.
8. Powerful:
Provides wide verity of “Data Types”
Provides wide verity of “Functions”
Provides useful Control and Loop Control Statements.
9. Fast code generation:
The compilers of C language generate very fast code. The code executes very
efficiently. So the programs take less time to execute.
10. Extensibility:
C language has the ability to extend itself, it is the collection of functions
which are supported by the C library this makes us easier to add our own
functions to C library, Because of the availability of large number of functions,
the programming task becomes simple.
11. Easy to Learn:
C programming language is easy to learn (Syntax is near to English
Language), C language syntax is very easy to understand, and it uses
keywords that we are using in our day-to-day life to convey meaning or to get
some decisions.
12. POP: Procedure Oriented Paradigm
C programming language is procedure oriented language, so, the user creates
procedures or functions to execute their task, the procedure-oriented
language is very much easy to learn because it follows algorithm to execute
your statements.
13. Bit Manipulation:
C Programs can be manipulated using bits. We can perform different
operations at bit level. It provides wide verity of bit manipulation Operators.
We have bitwise operators to manage Data at bit level.
14. Efficient Use of Pointers:
Pointers have direct access to memory. C supports efficient use of pointer.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 8 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
1. A sample C Program:
Below C program is a very simple and basic program in C programming
language. This C program displays “Hello World!” in the output window. And, all
syntax and commands in C programming are case sensitive. Also, each statement
should be ended with semicolon (;) which is a statement terminator.
1 #include <stdio.h>
2 int main()
3{
4 /* Our first simple C basic program */
5 printf("Hello World! ");
6 getch();
7 return 0;
8}
Output:
Hello World!
1. Create
2. Compile
3. Execute or Run
4. Get the Output
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 9 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 10 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
OPTIONAL
Documentation Section
The documentation section contains a set of comment lines which contain the
name of the program other necessary details. Comment lines are used for readability
and understand ability. Comments are ignored by compiler and are used to provide
documentation to people who reads that code. Documentation section helps anyone
to get an overview of the program. Comment lines are of two types:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 11 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
//This is single line comment
2. Multi Line Comment
Multiple Line Comment is used to comment in more than one Line in the
Code. It is used to provide Multi liner Description of line.
/*This is
multi line
comment */
Example:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 12 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Syntax:
<datatype> variable name;
Example:
const int a=10;
int b=10;
In the above example, a and b are two Global variables which may be used
anywhere in the C program. ‘a’ value is constant throughout the program while ‘b’
value changes.
Subprogram section:
•This section contains all the User-defined functions that are called and
declared in the other functions like main().
• User-defined functions must be placed immediately after the main() function
even they may appear in order.
• This section may or may not be included in the C program. It is optional.
• These functions perform user tasks, and this also contains a set of program
statements.
Sample C Program Explanation
This is a pre-processor command that includes standard
#include <stdio.h> input output header file(stdio.h) from the C library
before compiling a C program
This is the main function from where execution of any C
void main()
program begins. void means returning nothing.
{ This indicates the beginning of the main function.
whatever is given inside the command “/* */” in any
/*_some_comments_*/ C program, won’t be considered for compilation and
execution.
printf(“Hello_World! “); printf command prints the output onto the screen.
This command waits for any character input from
getch();
keyboard.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 13 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Character set of C
character: - It denotes any alphabet, digit or special symbol used to represent
information.
Character set: - The character set is the fundamental raw material of any language
and they are used to represent information. Like natural languages, computer
language will also have well defined character set, which is useful to build the
programs.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 14 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
C Tokens
• In a C source file, each word, and punctuations mark are called as Tokens.
• As we know, some the smallest individual units in a program are known as
Tokens.
• Tokens are also called as Lexical Units.
• These are the building blocks in C language which are used to write a
program.
List of Keywords:
Identifier or Variables
Identifiers are the names that are given to various program elements such as
variables, symbolic constants and functions. Variable or function identifier that is
called a symbolic constant name.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 15 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Rules for using identifiers
1. First character should be an alphabet or underscore ( _ ).
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters are not allowed except underscore.
4. A keyword cannot be used as a variable name or an identifier name. (such as
int , float, if ,break, for etc)
5. Identifiers are also case sensitive in C. For example, name and Name are two
different identifiers in C.
6. Successive underscores are not allowed( __ ).
Valid Names
num
Num
Num1
_NUM
NUM_temp2
Int
Invalid Identifiers
1num
1_num
365_days
Reason : First Character must be underscore or Alphabet
number 1
num 1
addition of program
Reason : blanks are not allowed
int
char
continue
Reason: Reserve words are not allowed
Constants or Literals
Constants refer to fixed values that don’t change during its execution. These
fixed values are also called literals. DOB is considered as constant.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are enumeration constants as
well.
Constants are treated just like regular variables except that their values cannot be
modified after their definition.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 16 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Types of Constants
Integer Constants
An integer constant is a sequence of digits from 0 to 9 without decimal points
or fractional part or any other symbols. The number may be positive or negative.
These constants are combination of digits from 0 to 9.
There are 3 types of integers namely decimal integer, octal integers and
hexadecimal integer.
Octal Integers constant consists of any combination of digits from 0 through 7 with a
O at the beginning. Some examples of octal integers are
Octal constants: int a=021, b=077, c=033 etc
Real Constants
Real Constants consists of a fractional part in their representation. Integer
constants are inadequate to represent quantities that vary continuously. These values
are represented by numbers containing fractional parts like 26.082. Example of real
constants are
float x=6.3; //here 6.3 is a double constant.
float y=6.3f; //here 6.3f is a float constant.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 17 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
float z=6.3e+2; //here 6.3 e + 2 is a exponential constant.
float s = 6.3L ; //here 6.3L is a long double constant
Real Numbers can also be represented by exponential notation. The general
form for exponential notation is mantissa exponent. The mantissa is either a real
number expressed in decimal notation or an integer. The exponent is an integer
number with an optional plus or minus sign.
All character constants have an equivalent integer value, which are called ASCII
(AMERICAN STANDARD CODE FOR INFORMATION INTERCHANGE) Values.
String Constants
A string constant is a set of characters enclosed in double quotation marks.
The characters in a string constant sequence may be a alphabet, number, special
character and blank space. Example of string constants are
"VISHAL" "1234” “God Bless" "!.....?"
Datatypes
What is Data Type in C Programming?
1. A Data Type is a Type of Data.
2. Data Type is a Data Storage Format that can contain a Specific Type or Range
of Values.
3. When computer programs store data in variables, each variable must be
assigned a specific data type.
4. Datatype is a set of value with predefined characteristics. Datatypes are used
to declare variable, constants, arrays, pointers and functions.
Explanation:
1. Whenever we declare variable in Computer’s memory, Computer must know
the type of the data to be stored inside the memory.
2. If we need to store the single character, then the size of memory occupied will
be different than storing the single integer number.
3. The memory in our computers is organized in bytes. A byte is the minimum
amount of memory that we can manage in C.
4. A byte can store a relatively small amount of data one single character or a
small integer (generally an integer between 0 and 255).
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 18 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 19 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
char - Character types
Keyword char is used for declaring character type variables. For example:
char test = 'h';
Here, test is a character variable. The value of test is 'h'.
The size of character variable is 1 byte.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 20 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
It is important to note that, sign qualifiers can be applied to int and char types only.
Let's see the basic data types. Its size is given according to 32-bit architecture.
Derived Datatypes
Derived datatypes are user-defined data types. The derived datatypes are also
called as user defined datatypes or secondary datatypes. In c programming
language, the derived datatypes are created using the following concepts...
• Arrays
• Structures
• Unions
• Enumeration
void Datatype
The void datatype means nothing or no value. Generally, void is used to
specify a function which does not return any value. We also use the void datatype to
specify empty parameters of a function.
Variables
Variable is a value which changes during the execution of program. Variables
in c programming language are the named memory locations where user can store
different values of same datatype during the program execution. That means,
variable is a name given to a memory location in which we can store different values
of same datatype. In other words, a variable can be defined as a storage container to
hold values of same datatype during the program execution. The formal definition of
datatype is as follows...
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 21 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Variable is a name given to a memory location where we can store different values of
same datatype during the program execution.
Every variable in c programming language must be declared in the
declaration section before it is used. Every variable must have a datatype that
determines the range and type of values to be stored and size of the memory to be
allocated.
A variable name may contain letters, digits and underscore symbol. The following
are the rules to specify a variable name...
1. Variable name should not start with digit.
2. Keywords should not be used as variable names.
3. Variable name should not contain any special symbols except underscore (_).
4. Variable name can be of any length but compiler considers only the first 31
characters of the variable name.
Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of
memory with specified variable name and allows only specified datatype values into
that memory location. In C programming language, the declaration can be
performed either before the function as global variables or inside any block or
function. But it must be at the beginning of block or function.
Declaration Syntax:
datatype variableName;
Example
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the
compiler to create variables named i, j and k of type int.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 22 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
For definition without an initializer: variables with static storage duration are
implicitly initialized with NULL (all bytes have the value 0); the initial value of all
other variables are undefined.
Symbolic Constant
A symbolic constant is a symbol, often similar to a variable name, which
represents one and only one value. You can think of them as variables that never
change (not while the program is running anyway). Often times in a program you
might want to use a single value for something over and over. Well, that is what
symbolic constants are for. Before I go on, let us see how to make a symbolic
constant.
#define PI 3.141593
#define TRUE 1
#define FALSE 0
Note that the pre-processor statements begin with a #symbol, and are not end with
a semicolon. By convention, pre-processor constants are written in UPPERCASE.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 23 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
The function is used to read data more than one variable at a time.
Syntax:–
scanf(“control string”, &arg);
Ex:–
scanf(“%d”, &no);
Syntax:
scanf(“control stirng”&arg1, &arg2, . . . ,&argn);
The control string specifies the field format in which the data is to be entered & the args
arg1,…. arg n specify the addition of the locations where the data is stored.
Control string contains filed specifications, which direct the interpretation of i/p data. If
may include:
1. Field (or format) specifications, consisting of the conversion character %, a data type
character and an optional number specifying the field width.
The data character indicates the type of data that is to be assigned to the variable
associated with the corresponding argument.
The field width specifies is optional.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 24 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Commonly used scanf ( ) FORMAT CODES are:
Code or Control Strings Meaning
%c Read a single character
%d Read decimal integer
%f Read a floating point value
%e Read a floating point value
%O Read a octal integer
%s Read a string
%u Read an unsigned decimal integer
%x Read a hexadecimal integer
%[“] Read a string of word(s)
Hexadecimal number \x
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 25 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Syntax: – %wd
The % sign indicates that a conversion specification follows. W is a integer number that
specifies the field width of the number to be read and d, known as data type character,
indicates that the number to be read is in integer mode.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 26 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Syntax:–
printf(“control string”, arg1, arg2,….,argn);
The arguments should match in number, order and type with format specifications.
Output of integer numbers:
The format specification for printif on integer number is:
%wd
Where w specifies the minimum field width for the o/p d specifies that the value to be
printed is an integer.
Ex:– printf(“%6d”,9876); 9 8 7 6
it is possible to force the printing to be left–justified by placing a minus sign directly after
the %character.
Ex:– printf(“%–6d”,9876); 9 8 7 6
it is also possible to pad with zero’s the leading blanks by placing a 0 before the field
width specifier.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 27 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Ex:– printf(“%06d”,9876); 0 0 9 8 7 6
Ex:– printf(“%d”,9876); 9 8 7 6
%w.pf
The integer w indication the minimum number of positions that are to be used for the
display of the value and the integer p indicates the number of digits to be displayed after
the decimal point (precision) f format specifies.
We can also display a real no in exponential notation by using the specification.
%w.pe
Ex:– y=98.76546 9 8 . 7 6 5 4
printf(“%7.4f”, y);
printf(“%7.2f”,y); 9 8 . 7 7
printf(“%-7.2f”, y); 9 8 . 7 7
Printing of a single character:
A single character can be displayed in a desired position using the format:
%wc
The character will be displayed right justified in the field of w columns. We can make
the display left–justified by placing a minus sign before the integer w the minus sign
before the integer w. The defaults value for w is 1.
Printing of strings:
The format specification for out putting strings is similar to real numbers
%w.ps
Where w specifies the field width for display and p instructs that only the first P
characters of the string are to be displayed. The display is right–justified.
Ex:
%20s N E W D E L H I 1 1 0 0
%20.10s N E W D E L H I
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 28 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
If there are not enough variables or if they are of the wrong type, the o/p results will be
incorrect.
Ex:– printf(“%d%f%s%c”,a, b, c, d);
Unformatted input and output functions are only work with character data
type. Unformatted input and output functions do not require any format specifiers.
Because they only work with character data type.
variable_name = getchar();
variable_name is a valid C name that has been declared as char type. When this
statement is encountered, the computer waits until a key is pressed and then
assigns this character as a value to getchar function. Since getchar is used on the
right-hand side of an assignment statement, the character value of getchar is in
turn assigned to the variable name on the left.
For example
char name;
name = getchar();
will assign the character 'H' to the variable name when we press the key H on the
keyboard. Since getchar is a function, it requires a set of parentheses as shown.
Example program:
# include < stdio.h > // assigns stdio-h header file to your program
void main ( ) // Indicates the starting point of the program.
{
char C, // variable declaration
printf (“Type one character:”) ; // message to user
C = getchar () ; // get a character from key board and Stores it in variable C.
printf (” The character you typed is = %c”, C) ; // output
} // Statement which displays value of C on
// Standard screen.
C supports testing of the character keyed in by the user by including the file
ctype.h & the functions which can be used after including this file are
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 29 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c a digit?
islower(c)Is c a lower case character?
isprint(c)Is c a printable character?
ispunct(c)Is c a punctuation mark?
isspace(c)Is c a white space character?
isupper(c) Is c a upper case character?
Where variable is a valid C type variable that has already been declared Ex:-
putchar ( );
#include < stdio.h > // Inserts stdio.h header file into the Pgm
void main ( ) // Beginning of main function.
{
char in; // character declaration of variable in.
printf (” please enter one character”); // message to user
in = getchar ( ) ; // assign the keyboard input value to in.
putchar (in); // output ‘in’ value to standard screen.
}
The puts function displays the contents stored in its parameter on the standard
screen.
The standard form of the gets function is
gets (str)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 30 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Here "str" is a string variable.
NOTE: It is recommended NOT to make use of gets() function. It is unsafe and can
even crash the C program itself. Above description is for theoretical illustration
purpose only.
puts (str)
Where str is a string variable.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 31 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
UNIT – 2
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 32 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
C Operators& Expressions
An operator is a symbol that tells the compiler to perform specific
mathematical or logical operations.
C programming language has wide range of operators to perform
various operations. For better understanding of operators, these operators can
be classified as:
Types of Operators
Unary Operator
A unary operator, in C, is an operator that takes a si ngle operand in an
expression or a statement.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 33 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
pre-increment (++ variable)
In pre-increment first increment the value of variable and then used
inside the expression (initialize into another variable).
Syntax
++ variable;
post-increment (variable ++)
In post-increment first value of variable is used in the expression
(initialize into another variable) and then increment the value of variable.
Syntax
variable ++;
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 34 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Binary Operators
Compound Assignment
Operators
= Assignment Operator
Arithmetic Operators
Arithmetic operators, in C, are operators used to perform arithmetic
operations that include multiplication, division, addition and subtraction. All these
operators are binary operators which means they operate on two operands.
Following table shows all the arithmetic operators supported by C language.
Assume variable A=10 and variable B=20, then:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 35 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Example of working of arithmetic operators
Explanation
Here, the operators +, - and * performed normally as you expected. In
normal calculation, 15/10 equals to 1.5. And, finally a%b is 0, i.e., when a=15 is
divided by b=10 , remainder is 0.
Suppose a=5.0, b=2.0, c=5 and d=2
In C programming,
a/b=2.5
a/d=2.5
c/b=2.5
c/d=2
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 36 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Assignment Operators
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 37 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
#include <stdio.h>
void main()
{
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
getch();
}
When you compile and execute the above program it produces the following result:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 38 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Relational Operator
Relational operator’s checks relationship between two operands. If the
relation is true, it returns value 1 and if the relation is false, it re turns value 0.
For example: a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then,
it returns 0.
Following table shows all the relational operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then:
Operator Description Example
Checks if the values of two operands are equal or not, if yes (A == B) is not
==
then condition becomes true. true.
Checks if the values of two operands are equal or not, if
!= (A != B) is true.
values are not equal then condition becomes true.
Checks if the value of left operand is greater than the value (A > B) is not
>
of right operand, if yes then condition becomes true. true.
Example
Try the following example to understand all the relational operators available in C
programming language:
#include <stdio.h>
void main()
{
int a = 21; int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 39 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5; b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program it produces the following result:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 40 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Logical Operators
Logical operators are used to combine expressions containing relation
operators. In C, there are 3 logical operators:
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then:
Operator Description Example
Called Logical AND operator. If both the operands are
&& (A && B) is false.
non-zero, then condition becomes true.
Called Logical OR Operator. If any of the two operands is
|| (A || B) is true.
non-zero, then condition becomes true.
Called Logical NOT Operator. Use to reverses the logical
! state of its operand. If a condition is true then Logical !(A && B) is true.
NOT operator will make false.
Example
Try the following example to understand all the logical operators available in C
programming language:
#include <stdio.h>
void main()
{
int a = 5; int b = 20; int c ;
if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0; b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true\n" );
}}
When you compile and execute the above program it produces the following result:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 41 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Bitwise Operators
Bitwise operators are special types of operators that are used in
programming the processor. In processor, mathematical operations like:
addition, subtraction, addition and division are done using the bitwise
operators which makes processing faster and saves power.
Operator Description
Binary AND Operator copies a bit to the result if it exists in both
&
operands.
Binary XOR Operator copies the bit if it is set in one operand but not
^
both.
Binary Ones Complement Operator is unary and has the effect of
~
'flipping' bits.
Binary Left Shift Operator. The left operands value is moved left by the
<<
number of bits specified by the right operand.
Binary Right Shift Operator. The left operands value is moved right by
>>
the number of bits specified by the right operand.
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables
for &, |, and ^ are as follows:
P Q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 42 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Bitwise AND operator in C programming.
The output of logical AND is 1 if both the corresponding bits of
operand is 1. If either of bit is 0 or both bits are 0, the output will be 0. It is a
binary operator (works on two operands) and indicated in C programming
by & symbol. Let us suppose the bitwise AND operation of two integer s 12
and 25.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
&00011001
________
00001000 = 8 (In decimal)
As, every bitwise operator works on each bit of data. The corresponding
bits of two inputs are check and if both bits are 1 then only the output will be
1. In this case, both bits are 1 at only one position, i.e, fourth position from the
right, hence the output bit of that position is 1 and all other bits are 0.
#include <stdio.h>
void main()
{
int a=12,b=39;
printf("Output=%d",a&b);
getch();
}
Output
Output=4
Bitwise OR operator in C
The output of bitwise OR is 1 if either of the bit is 1 or both the bits are 1.
In C Programming, bitwise OR operator is denoted by |.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
#include <stdio.h>
int main()
{
int a=12,b=25;
printf("Output=%d",a|b);
return 0;
}
Output
Output=29
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 43 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
C Programming Bitwise XOR (exclusive OR) operator
The output of bitwise XOR operator is 1 if the corresponding bits of two
operators are opposite (i.e., To get corresponding output bit 1; if
corresponding bit of first operand is 0 then, corresponding bit of second
operand should be 1 and vice-versa.). It is denoted by ^.
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
#include <stdio.h>
int main()
{
int a=12,b=25;
printf("Output=%d",a^b);
return 0;
}
Output=21
2's Complement
Two's complement is the operation on binary numbers which allows
number to write it in different form. The 2's compleme nt of number is equal to
the complement of number plus 1. For example:
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)
Note: Overflow is ignored while computing 2's complement.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 44 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
If we consider the bitwise complement of 35, 220(in decimal) is converted into
2's complement which is -36. Thus, the output shown by computer will be -36
instead of 220.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 45 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Right Shift by 1: 106
Right Shift by 2: 53
Left Shift by 0: 212
Left Shift by 1: 424
Left Shift by 2: 848
Interesting thing to note in Left and Right Shift
For any positive number, right shift is equal to integer division of that number
by (shift bit plus one) and for any integer left shift is equal to the
multiplication of that number by (shift bit plus one)
where
• expression1 is Condition
• expression2 is Statement Followed if Condition is True
• expression2 is Statement Followed if Condition is False
Meaning of Syntax:
• Expression1 is nothing but Boolean Condition i.e it results into either TRUE
or FALSE
• If result of expression1 is TRUE then expression2 is Executed
• Expression1 is said to be TRUE if its result is NON-ZERO
• If result of expression1 is FALSE then expression3 is Executed
• Expression1 is said to be FALSE if its result is ZERO
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 46 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Example of conditional operator
#include <stdio.h>
void main()
{
char feb;
int days;
printf("Enter l if the year is leap year otherwise enter 0: ");
scanf("%c",&feb);
days=(feb=='l')?29:28;
/*If test condition (feb=='l') is true, days will be equal to 29. */
/*If test condition (feb=='l') is false, days will be equal to 28. */
printf("Number of days in February = %d",days);
getch();
}
OUTPUT
Enter l if the year is leap year otherwise enter n: l
Number of days in February = 29
Other operators such as &(reference operator), *(dereference operator) and -
>(member selection) operator will be discussed in pointer chapter.
Comma Operator
Comma operators are used to link related expressions together. For example:
int a,c=5,d;
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 47 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Expressions
Operands are variables or expressions which are used in operators to evaluate the
expression.
Combination of operands and operators form an Expression. Statements like a = b +
3, ++z and 300 > (8 * k) are all expressions.
Every expression consists of at least one operand and can have one or more
operators. Operands are values, whereas operators are symbols that represent
particular actions. In the expression
x+5
x and 5 are operands, and + is an operator.
Expressions are used in programming languages, database systems, and
spreadsheet applications.
Arithmetic Expressions
Arithmetic expression in C is a combination of variables, constants and
operators written in a proper syntax. C can easily handle any complex mathematical
expressions but these mathematical expressions have to be written in a proper
syntax. Some examples of mathematical expressions written in proper syntax of C
are:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 48 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Types of Expressions
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 49 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Expression Evaluation
Expressions are evaluated using an assignment statement of the form:
In the above syntax, variable is any valid C variable name. When the
statement like the above form is encountered, the expression is evaluated first and
then the value is assigned to the variable on the left hand side. All variables used in
the expression must be declared and assigned values before evaluation is attempted.
Examples of expressions are:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 50 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
So how do you get the result with correct precision? Just cast the type of expression to the
type you need! You can see the solution below.
#include <stdio.h>
void main()
{
int value1 = 10, value2 = 3;
float result;
result = (float) value1 / value2;
printf("Result without type casting: %f", result);
getch();
}
Output:
Result without type casting: 3.333333
One important thing to notice here is that, type casting has more precedence than the divide
operation (/). At first, value1 will be converted to float type and then division operation is
performed on the float variable
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 51 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Step 1: x = 9-4 + 3 * 2 – 1
Step 2: x = 9 – 4 + 6 – 1
Second Pass
Step 1: x = 5 + 6 – 1
Step 2: x = 11 – 1
Step 3: x = 10
But when parenthesis is used in the same expression, the order of evaluation gets
changed.
For example,
x = 9 – 12 / (3 + 3) * (2 – 1)
When parentheses are present then the expression inside the parenthesis are
evaluated first from left to right. The expression is now evaluated in three passes as:
First Pass
Step 1: x = 9 – 12 / 6 * (2 – 1)
Step 2: x= 9 – 12 / 6 * 1
Second Pass
Step 1: x= 9 – 2 * 1
Step 2: x = 9 – 2
Third Pass
Step 3: x= 7
There may even arise a case where nested parentheses are present (i.e.
parenthesis inside parenthesis). In such case, the expression inside the innermost set
of parentheses is evaluated first and then the outer parentheses are evaluated.
For example, we have an expression as:
x = 9 – ((12 / 3) + 3 * 2) – 1
The expression is now evaluated as:
First Pass:
Step 1: x = 9 – (4 + 3 * 2) – 1
Step 2: x= 9 – (4 + 6) – 1
Step 3: x= 9 – 10 -1
Second Pass
Step 1: x= - 1 – 1
Step 2: x = -2
Note: The number of evaluation steps is equal to the number of operators in the
arithmetic expression.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 52 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Example 1:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 53 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Control Structures
Control statements enable us to specify the flow of program control; i.e., the
order in which the instructions in a program must be executed. They make it
possible to make decisions, to perform tasks repeatedly or to jump from one section
of code to another.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 54 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
In C four conditional control statements are widely used:
❖ If-statement
❖ If-else statement
❖ Nested-if-else statement
❖ else-if ladder
The general syntax and execution flow of the simple if statement is as follows...
Where
Condition: is a logical expression that results in TRUE or FALSE.
Statement: a simple statement (single statement) or compound statement (collection
of two or more statement).
Explanation: If the logical condition is TRUE then statement1 is executed and If the
logical condition is FALSE then control transfers to the next executable statement.
Simple if statement is used when we have only one option that is executed or
skipped based on a condition.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 55 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
//Program to convert negative value to absolute using simple if
#include<stdio.h>
#include<conio.h>
void main()
{
int number;
printf( " Type a number: ");
scanf( "%d", &number);
// check whether the number is negative number
if (number < 0)
{
// If it is a negative then convert it into positive.
number = -number;
printf( " The absolute value is % d\n ", number);
}
getch();
}
OUTPUT
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 56 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Where
Condition: is a logical expression that results in TRUE or FALSE.
Statement: a simple statement (single statement) or compound statement (collection
of two or more statement).
Explanation: If the condition specified in the if statement evaluates to true, the
statements inside the if-block are executed and then the control gets transferred to
the statement immediately after the if-block. Even if the condition is false and no
else-block is present, control gets transferred to the statement immediately after the
if-block.
The else part is required only if a certain sequence of instructions needs to be
executed if the condition evaluates to false. It is important to note that the condition
is always specified in parentheses and that it is a good practice to enclose the
statements in the if block or in the else-block in braces, whether it is a single
statement or a compound statement.
The if-else statement is used when we have two options and only one option
has to be executed based on a condition result (TRUE or FALSE).
Run 2:
Enter the values of a & b
35
45
45 is larger than 35.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 57 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Where
Condition: is a logical expression that results in TRUE or FALSE.
Statement: a simple statement (single statement) or compound statement (collection
of two or more statement).
Explanation: if 'condition1' is false the 'statement-block3' will be executed, otherwise
it continues to perform the test for ‘condition2’. If the 'condition2' is true the
'statement-block1' is executed otherwise 'statement-block2' is executed.
// Example for Nested If in C Programming
#include <stdio.h>
#include<conio.h>
void main()
{
int age;
printf("Please Enter Your Age Here:\n");
scanf("%d",&age);
if ( age < 18 )
{
printf("You are Minor.\n");
printf("Not Eligible to Work");
}
else
{
if (age >= 18 && age <= 60 )
{
printf("You are Eligible to Work \n");
printf("Please fill in your details and apply\n");
}
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 58 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
else
{
printf("You are too old to work as per the Government rules\n");
printf("Please Collect your pension! \n");
}
}
getch();
}
OUTPUT
OUTPUT 2: Enter the age 27. First If condition is FALSE. Nested IF condition is
TRUE
OUTPUT 3: Enter the age 61. Both If condition and also Nested IF condition failed
here
else-if ladder
The Else If Statement in C is very useful when we have to check several
conditions. We can also use the Nested If statement to achieve the same but as the
number of conditions increase, code complexity will also increase. Let us see the
syntax of the Else if statement:
The general format of a nested if-else statement is:
if(condition1)
{
// statement(s);
}
else if(condition2)
{
//statement(s);
}
.
.
else if (conditionN)
{
//statement(s);
}
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 59 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
else
{
//statement(s);}
Else If statement handle multiple statements effectively by executing them
sequentially. It will check for the first condition, if the condition is TRUE then it will
execute the statements present in that block. If the condition is FALSE then it will
check the Next one (Else If condition) and so on.
There will be some situations where condition 1, condition 2 is TRUE, for example:
x= 20, y=10
Condition 1: x > y //TRUE
Condition 2: x != y //TRUE
In these situations, statements under the Condition 1 will be executed because ELSE
IF conditions will only be executed if its previous IF or ELSE IF statement fails.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 60 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
OUTPUT
OUTPUT 1: We are going to enter Totalmarks = 570. Here first If condition is TRUE
OUTPUT 3: We are going to enter Totalmarks = 401 means first IF condition, else if
(Totalmarks >= 480) are FALSE. So, It will check the else if (Totalmarks >= 401),
which is TRUE so it will print the statements inside this block.
OUTPUT 4: We are going to enter Totalmarks = 380 means all the IF conditions Fail.
So, It will print the statements inside the else block.
Note: When we use conditional control statement like if statement, condition might
be an expression evaluated to a numerical value, a variable or a direct numerical
value. If the expression value or direct value is zero the condition becomes FALSE
otherwise becomes TRUE.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 61 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
The switch statement has the following syntax and execution flow diagram...
The switch statement contains one or more number of cases and each case has
a value associated with it. At first switch statement, compares the first case value
with the switchValue, if it gets matched the execution starts from the first case. If it
does not match the switch statement compares the second case value with the
switchValue and if it is matched the execution starts from the second case. This
process continues until it finds a match. If no case value matches with the
switchValue specified in the switch statement, then a special case called default is
executed.
When a case value matches with the switchValue, the execution starts from
that particular case. This execution flow continues with next case statements also. To
avoid this, we use "break" statement at the end of each case. That means
the break statement is used to terminate the switch statement. However, it is
optional.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 62 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
//Program to check whether the given character is vowel or not using switch case.
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter any character\n");
scanf("%c",&ch);
switch(ch)
{
case 'A':
case 'a':
case 'E':
case 'e':
case 'I':
case 'i':
case 'O':
case 'o':
case 'U':
case 'u':printf("%c is a vowel\n",ch);
break;
default :printf("%c is not a vowel\n",ch);
break;
}
getch();
}
OUTPUT
Run 1:
Enter any character E
E is a vowel
Run 2:
Enter any character s
s is not a vowel
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 63 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 64 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
TIP: For single statement, curly braces are not required but if we omit them for
multiple statements then it will execute the first statement only. It is always good
practice to use braces all the time.
➢ While loop will check for the condition at the beginning of the loop.
➢ If the condition is True then it will execute the statements inside the loop.
➢ Next we have to use Increment and Decrement Operator inside the while loop
to increment and decrements the value. Please refer Increment and Decrement
Operator in C article to understand the functionality
➢ Again it will check for the condition after the value incremented. As long as
the condition is True, the statements inside the while loop will be executed.
➢ If the condition is False then it will exit from the While loop
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 65 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
printf("Enter the stop value for natural number series\n");
scanf("%d",&n);
i=1; //initialize
while(i<=n) //condition check
{
printf("%d\t",i);
sum=sum+i;
i++; //increment i by 1
}
printf("\nSum of %d natural numbers=%d",n,sum);
getch();
}
OUTPUT
Enter the stop value for natural number series
100
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
Points to be remembered
When we use while statement, we must follow the following...
✓ while is a keyword so it must be used only in lower case letters.
✓ If the condition contains variable, it must be assigned a value before it is used.
✓ The value of the variable used in condition must be modified according to the
requirement inside the while block.
✓ In while statement, the condition may be a direct integer value, a variable or a
condition.
✓ A while statement can be an empty statement.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 66 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
do while Syntax
The syntax of the Do While Loop in C Programming is as shown below:
do
{
statement 1;
statement 2;
………….
statement n;
} while (condition);
Where
Statement: simple or compound statement
do: keyword
while: keyword
Condition : results in TRUE or FALSE
First it will execute the statements inside the loop and then after reaching the end, it
will check the condition inside the while. If the condition is true then it will repeat
the process. If the condition fails then Do While Loop will be terminated.
NOTE: We have to place semi-colon after the While condition.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 67 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
// Program to print the Fibonacci series for first n terms using do while loop
#include<stdio.h>
#include<conio.h>
void main()
{
int a ,b,c,i,n;
clrscr();
printf("Enter the final value\n");
scanf("%d",&n);
a=0; b=1;
printf(" Fibonacci Series....\n");
if(n==0)
printf(“0\n”);
else if(n==1)
printf(“0\n1\n”);
else
{
printf("%d\n",a);
printf("%d\n",b);
i=2;
do
{
c=a+b;
printf("%d\n",c);
a=b;
b=c;
i++;
} while(i<=n);
}
getch();
}
OUTPUT
Run 1:
Enter the final value 7
Fibonacci value.... 0 1 1 2 3 5 8
Run 2:
Enter the final value 1
Fibonacci value.... 0 1
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 68 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Points to be remembered
When we use do-while statement, we must follow the following...
✓ Both do and while are keywords so they must be used only in lower case
letters.
✓ If the condition contains variable, it must be assigned a value before it is used.
✓ The value of the variable used in condition must be modified according to the
requirement inside the do block.
✓ In do-while statement the condition may be, a direct integer value, a variable
or a condition.
✓ A do-while statement can be an empty statement.
✓ In do-while, the block of statements are executed atleast once.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 69 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Flow Chart for loop in C
Below screenshot will show you the flow chart of the For Loop
Test condition: It will check for the condition against the counter variable. If the
condition is True then it will execute the statements inside the for loop. If the
condition is False then it will exit from the loop
After completing the iteration it will execute the Increment and Decrement Operator
inside the for loop to increment or decrement the value.
Again it will check for the condition after the value incremented. As long as the
condition is True, the statements inside the for loop will be executed.
//Program to find the factorial of a given number using for loop.
#include<stdio.h>
#include<conio.h>
void main()
{
long int fact=1,n,i;
clrscr();
printf("Enter the number\n");
scanf("%ld",&n);
if(n<=0)
fact=1;
else
{
for(i=1;i<=n;i++)
fact=fact*i;
}
printf("\nFactorial of %ld=%ld\n",n,fact);
getch();
}
OUTPUT
Enter the number 7
Factorial of 7=5040
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 70 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
POINTS TO BE REMEMBERED
When we use for statement, we must follow the following...
✓ for is a keyword so it must be used only in lower case letters.
✓ Every for statement must be provided with initialization, condition and
modification (They can be empty but must be separated with ";")
Ex: for ( ; ; ) or for ( ; condition ; modification ) or for ( ; condition ; )
✓ In for statement, the condition may be a direct integer value, a variable or a
condition.
✓ The for statement can be an empty statement.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 71 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
We have nested a for loop inside another for loop, this is called nesting of loops.
Such type of nesting is often used for handling multidimensional arrays.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 72 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
6 It is called as Pre Check loop It is called as Post Check loop
7 while (condition) do
{ {
Statements; Statements;
} }while(condition);
break statements
In C programming, break statement is used with conditional if statement.
The break is used in terminating the loop immediately after it is encountered.
it is also used in switch...case statement. which is explained in next topic.
1. break statement is used to terminate switch case statement
2. break statement is also used to terminate looping statements like while, do-
while and for.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 73 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!\n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}
OUTPUT
Enter Y / N : Y
Okay!!! Repeat again !!!
Enter Y / N : Y
Okay!!! Repeat again !!!
continue statement
The continue statement is used to move the program execution control to the
beginning of looping statement. When continue statement is encountered in a
looping statement, the execution control skips the rest of the statements in the
looping block and directly jumps to the beginning of the loop.
The continue statement can be used with looping statements like while, do-while
and for.
When we use continue statement with while and do-while statements the
execution control directly jumps to the condition. When we use continue statement
with for statement the execution control directly jumps to the modification portion
(increment / decrement / any modification) of the for loop. The continue statement
execution is as shown in the following figure.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 74 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
//Program to illustrate continue statement.
#include <stdio.h>
#include<conio.h>
void main(){
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
printf("Entered number is EVEN!!! Try another number!!!\n") ;
continue ;
}
else
{
printf("You have entered ODD number!!! Bye!!!") ;
exit(0) ;
}
}
getch() ;
}
OUTPUT
Enter any integer numbers: 50
Entered number is EVEN!!! Try another number!!!
Enter any integer number: 15
You have entered ODD number!!! Bye!!!
goto statementsstatement
The goto statement is used to jump from one line to another line in the
program. Using goto statement we can jump from top to bottom or bottom to top. To
jump from one line to another line, the goto statement requires a label. Label is a
name given to the instruction or line in the program. When we use goto statement in
the program, the execution control directly jumps to the line with specified label.
Syntax:
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier.
When, the control of program reaches to goto statement, the control of the program
will jump to the label: and executes the code below it.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 75 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Forward Backward
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 76 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
UNIT – 3
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 77 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Derived Datatypes in C
Array
Array is a collection of variables belongings to the same data type. You can
store group of data of same data type in an array. Array is set of homogenous
elements.
• It allocates sequential memory locations.
• Individual values are called as elements.
Need of array
Consider a scenario wherein you have to store 100 integer numbers, entered by
user, in order to find out the average of them. To program this scenario, you have
two ways – 1) Define 100 variable of integer type and at last perform the average
operation. 2) Have a single integer array to store all the values.
Which solution is better as per you? Obviously the second solution, it is
convenient to store same data types in one single variable and later access them
using array index.
• Array might be belonging to any of the data types
• Array size must be a constant value.
• Always, Contiguous (adjacent) memory locations are used to store array
elements in memory.
• It is a best practice to initialize an array to zero or null while declaring, if we
don’t assign any values to array.
Characteristics of Arrays in C
1) An array holds elements that have the same data type.
2) Array elements are stored in subsequent memory locations.
3) Two-dimensional array elements are stored row by row in subsequent memory
locations.
4) Array name represents the address of the starting element.
5) Array size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.
TYPES OF C ARRAYS:
There are 3 types of C arrays. They are,
1. One dimensional array.
2. Two dimensional array.
3. Multi-dimensional array
a. Three dimensional array
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 78 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
b. four dimensional array etc…
1. ONE DIMENSIONAL or 1-D ARRAY
• Single or One Dimensional array is used to represent and store data in a linear
form.
• Array having only one subscript variable is called One-Dimensional array
• It is also called as Single Dimensional Array or Linear Array
Syntax:
datatype array_name[array_size];
• datatype: What kind of values array can store (Example: int, float, char).
• array_name:To identify the array.
• array_size(INDEX): The maximum number of values that the array
can hold.
Example:
int number[5];
number
0 1 2 3 4
MEMORY REPRESENTATION OF ONE DIMENSIONAL ARRAY
Syntax for creating an array without size and with initial values
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 79 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Example
int number [5] = { 35, 20, 40, 57, 19 };
Will declare the array size as an array of size 5 and will assign different values
to each element if the number of values in the list is less than the number of
elements, then only that many elements are initialized. The remaining elements will
be set to zero automatically.
In the declaration of an array the size may be omitted, in such cases the
compiler allocates enough space for all initialized elements.
Example
int counter [ ] = {1,1,1,1};
Will declare the array to contain four elements with initial values 1. this
approach works fine as long as we initialize every element in the array.
Example
char studentName [ ] = "MedhaBCA”;
In the above example declaration, size of the array studentName is 8. This is
because in case of character array, compiler stores one extra character
called \0 (NULL) at the end.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 80 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
scanf("%d",&a[i]);
printf("Array elements are....\n");
for(i=0;i<5;i++)
printf("a[%d]=%d\n",i,a[i]);
getch();
}
------------------------------------------------OUTPUT-----------------------------------------
Enter the array elements 10 20 30 40 50
Array elements are....
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
• datatype: What kind of values array can store (Example: int, float, char).
• array_name:To identify the array.
• row_size(INDEX): The maximum number of rows that the array
can hold.
• column_size(INDEX): The maximum number of columns that the array
can hold.
Example:
int number[3][3];
• The above statement declares a number variable to be an array.
containing 5 elements.
• The array INDEX (also known as subscripts) starts from zero.
• This means that the array number will contain 5 elements in all.
• The first element will be stored in number[0].
• The second element will be stored in number[4].
Reserved Space
number [0] [1] [2]
[0]
[1]
[2]
MEMORY REPRESENTATION OF TWO DIMENSIONAL ARRAY
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 81 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Example:
int number[3][3] = {
{ 1 , 4 , 8 },
{ 5 , 2 , 9 },
{ 6 , 5 , 10}
};
The following array: Storing values after initialization
number [0] [1] [2]
[0] 1 4 8
[1] 5 2 9
[2] 6 5 10
Example:
int a[3][2] = {1 , 4 , 5 , 2 , 6 , 5 };
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 82 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
//Program to read a matrix and display its transpose implementation of 2D array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],r,c,i,j;
printf("\n Enter the order of the matrix");
scanf("%d %d",&r,&c);
printf("Enter %d matrix elements\n",r*c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
printf("Matrix A is\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%3d",a[i][j]);
}
printf("\n");
}
printf("Transpose of A is\n");
for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf("%3d",a[j][i]);
}
printf("\n");
}
getch();
}
------------------------------------------------OUTPUT-----------------------------------------
Enter the order of the matrix 2 3
Enter 6 matrix elements
123
456
Matrix A is
1 2 3
4 5 6
Transpose of A is
1 4
2 5
3 6
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 83 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
STRING
• C Strings are nothing but array or collection of characters ended with null
character (‘\0’).
• This null character indicates the end of the string.
• Strings are always enclosed by double quotes. Whereas, character is enclosed
by single quotes in C.
Declaration of strings:
Declaring a string is as simple as declaring a one dimensional array. Below is
the basic syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size
is used define the length of the string, i.e the number of characters’ strings will store.
Please keep in mind that there is an extra terminating character which is the
Null character (‘\0’) used to indicate termination of string which differs strings from
normal character arrays.
Example: char str [50],name [25];
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 84 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
• In this type of initialization, we don’t need to put NULL or Ending /
Terminating character at the end of string. It is appended automatically by the
compiler.
char name [ ] = "MEDHA";
Live Example:
#include<stdio.h>
void main ( )
{
char name [20];
printf("\n Enter the Name : ");
gets(name);
}
Explanation:
• Whenever gets() statement encounters then characters entered by user (the
string with spaces) will be copied into the variable.
• If user start accepting characters, and if new line character appears then the
newline character will not be copied into the string variable (i.e name).
• A terminating null character is automatically appended after the characters
copied to string variable (i.e name)
• gets() uses stdin (Standard Input Output) as source, but it does not include
the ending newline character in the resulting string and does not allow to
specify a maximum size for string variable (which can lead to buffer overflows).
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 85 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
No After Enter
gets(city) Accepting Name of City
Specification Key
No After Enter
gets(address) Accepting address with Spaces
Specification Key
No After Enter
gets(bname) Accepting book name
Specification Key
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 86 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Notes or Facts:
1. printf is included in header file “stdio.h”
2. As name suggest it used for Printing or Displaying Messages or Instructions
Uses:
1. Printing Message
2. Ask user for entering the data (Labels. Instructions)
3. Printing Results
Live Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
printf("Enter the String : ");
Notes or Facts:
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 87 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Live Example:
#include< stdio.h>
#include< conio.h>
void main()
{
char string [ ] = "This is an example string\n";
puts(string); // String is variable Here
puts("String"); // String is in Double Quotes
getch();
}
Output:
String is: This is an example string
String is: String
C – strlen() function
• strlen( ) function in C gives the length of the given string. Syntax for strlen( )
function is given below.
len = strlen ( str );
• strlen( ) function counts the number of characters in a given string and
returns the integer value.
• It stops counting the character when null character is found. Because, null
character indicates the end of the string in C.
C – strlwr() function
• strlwr( ) function converts a given string into lowercase. Syntax for strlwr( )
function is given below.
char strlwr(string);
• strlwr( ) function is non standard function which may not available in
standard library in C.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 88 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
C – strupr() function
• strupr( ) function converts a given string into uppercase. Syntax for strupr( )
function is given below.
char *strupr(char *string);
• strupr( ) function is non standard function which may not available in
standard library in C.
C – strrev() function
• strrev( ) function reverses a given string in C language. Syntax for strrev( )
function is given below.
char *strrev(char *string);
• strrev( ) function is non standard function which may not available in
standard library in C.
C – strdup() function
• strdup( ) function in C duplicates the given string. Syntax for strdup( )
function is given below.
char *strdup(const char *string);
• strdup( ) function is non standard function which may not available in
standard library in C.
C – strcmp() function
• strcmp( ) function in C compares two given strings and returns zero if they
are same.
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2,
it returns > 0 value. Syntax for strcmp( ) function is given below.
int strcmp ( const char * str1, const char * str2 );
• strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different
characters.
Return Type
Return Type Condition
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 89 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
• If length of string1 < string2, it returns < 0 value. If length of string1 > string2,
it returns > 0 value. Syntax for strcmp( ) function is given below.
int strcmpi ( const char * str1, const char * str2 );
C – strcat() function
• strcat( ) function in C language concatenates two given strings. It concatenates
source string at the end of destination string. Syntax for strcat( ) function is
given below.
char * strcat ( char * destination, const char * source );
• Example:
strcat ( str2, str1 ); – str1 is concatenated at the end of str2.
strcat ( str1, str2 ); – str2 is concatenated at the end of str1.
• As you know, each string in C is ended up with null character (‘\0’).
• In strcat( ) operation, null character of destination string is overwritten by
source string’s first character and null character is added at the end of new
destination string which is created after strcat( ) operation.
C – strcpy() function
• strcpy( ) function copies contents of one string into another string. Syntax for
strcpy function is given below.
char * strcpy ( char * destination, const char * source );
• Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
• If destination string length is less than source string, entire source string value
won’t be copied into destination string.
• For example, consider destination string length is 20 and source string length
is 30. Then, only 20 characters from source string will be copied into destination
string and remaining 10 characters won’t be copied and will be truncated.
C – strncpy() function
• strncpy( ) function copies portion of contents of one string into another string.
Syntax for strncpy( ) function is given below.
char * strncpy ( char * destination, const char * source, size_t num );
• Example:
strncpy ( str1, str2, 4) – It copies first 4 characters of str2 into str1.
strncpy ( str2, str1, 4) – It copies first 4 characters of str1 into str2.
• If destination string length is less than source string, entire source string value
won’t be copied into destination string.
• For example, consider destination string length is 20 and source string length
is 30.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 90 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
• If you want to copy 25 characters from source string using strncpy( ) function,
only 20 characters from source string will be copied into destination string and
remaining 5 characters won’t be copied and will be truncated.
C – strncat() function
• strncat( ) function in C language concatenates (appends) portion of one string
at the end of another string. Syntax for strncat( ) function is given below.
char * strncat ( char * destination, const char * source, size_t num );
• Example :
strncat ( str2, str1, 3 ); – First 3 characters of str1 is concatenated at the end of
str2.
strncat ( str1, str2, 3 ); – First 3 characters of str2 is concatenated at the end of
str1.
• As you know, each string in C is ended up with null character (‘\0’).
• In strncat( ) operation, null character of destination string is overwritten by
source string’s first character and null character is added at the end of new
destination string which is created after strncat( ) operation.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 91 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
UNIT – 4
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 92 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Every C program must contain at least one function called main ( ). However, a
program may also contain other functions.
Advantages of functions:
1. Program development made easy: Work can be divided among project
members thus implementation can be completed in parallel.
2. Program testing becomes easy : Easy to locate and isolate a faulty
function for further investigation
3. Code sharing becomes possible: A function may be used later by many
other programs this means that a c programmer can use function written
by others, instead of starting over from scratch.
4. Code re-usability increases: A function can be used to keep away from
rewriting the same block of codes which we are going use two or more
locations in a program. This is especially useful if the code involved is
long or complicated.
5. Increases program readability: It makes possible top down modular
programming. In this style of programming, the high-level logic of the
overall problem is solved first while the details of each lower level
functions is addressed later. The length of the source program can be
reduced by using functions at appropriate places.
6. Function facilitates procedural abstraction: Once a function is written, it
serves as a black box. All that a programmer would have to know to
invoke a function would be to know its name, and the parameters that it
expects
7. Functions facilitate the factoring of code: Every C program consists of
one main( ) function typically invoking other functions, each having a
well-defined functionality.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 93 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Function Definition
The function definition provides the actual code of that function. The function
definition is also known as body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be
performed by a function are written in function definition. The actual instructions of
a function are written inside the braces "{ }". The function definition is can be written
before main function or after main function.
Actual code...
}
Note: If the function definition is defined before main function then function
prototyping is ignored or not required.
Function Call
The function call tells the compiler when to execute the function definition.
When a function call is executed, the execution control jumps to the function
definition where the actual code is executed and returns to the same functions call
once the execution completes. The function call is performed inside main function,
inside any other function, or inside the function itself.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 94 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Types of Functions in C
In C Programming Language, based on providing the function definition,
functions are divided into two types. Those are as follows.
Points to be remembered
✓ System defined functions are declared in header files
✓ System defined functions are implemented in .dll files. (DLL stands
for Dynamic Link Library).
✓ To use system-defined functions the respective header file must be included.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 95 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
//program to implement functions
#include <stdio.h>
#include<conio.h>
int addition(int,int) ; // function declaration
void main()
{
int num1, num2, result ;
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("SUM = %d", result);
getch() ;
}
Based on the data flow between the calling function and called function, the
functions are classified as follows
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 96 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 97 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
/*Program to read 3 sides of triangle and find the area and parameter of triangle
using functions. */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void triangle(int a,int b,int c) //function definition
{
float s,area;
s=(a+b+c)/2.0;
area=sqrt(s*((s-a)*(s-b)*(s-c)));
printf("The area of triangle=%.2f\n",area);
if((a==b)&&(b==c))
printf("The given triangle is equilateral\n");
else if((a==b)||(b==c)||(c==a))
printf("The given triangle is isosceles\n");
else
printf("The given triangle is scalene\n");
}
void main()
{
int a,b,c;
clrscr();
printf("Enter the 3 sides of triangle\n");
scanf("%d%d%d",&a,&b,&c);
triangle(a,b,c); //function Call
getch();
}
------------------------------------------------OUTPUT----------------------------------------
Enter the 3 sides of triangle 6 6 6
The area of triangle=15.59
The given triangle is equilateral
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 98 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 99 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
------------------------------------------------OUTPUT----------------------------------------
Enter any two-integer numbers: 22 55
Sum = 77
Call by Value
1. While Passing Parameters using call by value, Xerox copy of original
parameter is created and passed to the called function.
2. Any update made inside method will not affect the original value of
variable in calling function.
3. In the below example, a and b are the original values, Xerox copy of these
values is passed to the function, and these values are copied into a, b
variable of sum function respectively.
4. As their scope is limited to only function so, they cannot alter the values
inside main function.
// Program to swap two integer values using function (call by value).
#include<stdio.h>
#include<conio.h>
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 100 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
b=temp;
printf("Values inside the function a=%d and b=%d\n",a,b);
}
void main()
{
int a,b;
clrscr();
printf("Enter any two no's\n");
scanf("%d%d",&a,&b);
printf("Before swapping a=%d and b=%d\n",a,b);
swap(a,b);
printf("After swapping a=%d and b=%d\n",a,b);
getch();
}
------------------------------------------------OUTPUT-----------------------------------------
Enter any two no's
52
Before swapping a=5 and b=2
Values inside the function a=2 and b=5
After swapping a=5 and b=2
a
a
a
Parameter
In computer programming, a parameter is a special kind of variable, used in a
subroutine to refer to one of the pieces of data provided as input to the subroutine.
These pieces of data are called arguments.
Note:
• Parameter Means Values Supplied to Function so that Function can Utilize
These Values.
• Parameters are Simply Variables.
• Difference between Normal Variable and Parameter is that “These Arguments
are defined at the time of Calling Function“.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 101 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Parameter: The names given in the function definition are called Parameters.
Argument: The values supplied in the function call are called Arguments.
1. Formal Parameter :
2. Actual Parameter :
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 102 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
void main()
{
int a,b;
printf("Enter any two numbers\n");
scanf("%d%d",&a,&b);
printf("Before swapping a=%d and b=%d\n",a,b);
swap(&a,&b);
printf("After swapping a=%d and b=%d\n",a,b);
getch();
}
------------------------------------------------OUTPUT-----------------------------------------
Enter any two numbers 9 5
Before swapping a=9 and b=5
Values inside the function a=5 and b=9
After swapping a=5 and b=9
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 103 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
a
a
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 104 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Summary of Call By Value and Call By Reference:
Point Call by Value Call by Reference
A Pointer is a variable that holds address of another variable of same data type.
Unlike other variables that hold values of a certain type, pointer holds the address of
a variable.
For example, an integer variable holds (or you can say stores) an integer value,
however an integer pointer holds the address of an integer variable. In this guide,
we will discuss pointers in C programming with the help of examples.
Concept of Pointer
Whenever a variable is declared in the program, system allocates a location
i.e. an address to that variable in the memory, to hold the assigned value. This
location has its own address number.
Let us assume that system has allocated memory location 80F for a variable a.
int a=10;
Value 10 Location
a
Name of the Location 80F
address
We can access the value 10 by either using the variable name a or the address 80F.
Since the memory addresses are simply numbers they can be assigned to some other
variable. The variable that holds memory address are called pointer variables. A
pointer variable is therefore nothing but a variable that contains an address, which is
a location of another variable. Value of pointer variable will be stored in another
memory location.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 105 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Address of a 80F
ptr
Pointer name 82C
Address of a pointer
DECLARING A POINTER VARIABLE
General syntax of pointer declaration is,
data-type *pointer_name;
Data type of a pointer must be same as the data type of a variable to which the
pointer variable is pointing. void type pointer works with all data types, but is not
used often used.
Initialization of Pointer variable
Pointer Initialization is the process of assigning address of a variable to
pointer variable. Pointer variable contains address of variable of same data type. In
C language address operator & is used to determine the address of a variable. The &
(immediately preceding a variable name) returns the address of the variable
associated with it.
int a = 10 ;
int *ptr ; //pointer declaration
ptr = &a ; //pointer initialization
or, i
nt *ptr = &a ; //initialization and declaration together
float a;
int *ptr;
ptr = &a; //ERROR, type mismatch
Note: If you do not have an exact address to be assigned to a pointer variable while
declaration, It is recommended to assign a NULL value to the pointer variable. A
pointer which is assigned a NULL value is called a null pointer.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 106 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Points to remember:
➢ While declaring/initializing the pointer variable, * indicates that the variable
is a pointer.
➢ The address of any variable is given by preceding the variable name with
Ampersand '&'.
➢ The pointer variable stores the address of a variable. The declaration int *a
doesn't mean that a is going to contain an integer value. It means that a is
going to contain the address of a variable storing integer value.
➢ To access the value of a certain address stored by a pointer variable, * is used.
Here, the * can be read as 'value at'.
/*Program to show the declaration of the pointer and access the values and
display its value. */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,*iptr;
float f1,*fptr;
clrscr();
printf("Enter the integer\n");
scanf("%d",&i);
printf("Enter the floating no\n");
scanf("%f",&f1);
iptr=&i;
fptr=&f1;
printf("\n Value of i=%d\n",i);
printf("\n Address of i=%u\n",iptr);
printf("\n Value of f=%f\n",f1);
printf("\n Address of f=%u\n",fptr);
getch();
}
------------------------------------------------OUTPUT-----------------------------------------
Enter the integer 123
Enter the floating no 147.4
Value of i=123
Address of i=65524
Value of f=147.4
Address of f=65518
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 107 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
UNIT – 5
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 108 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
STRUCTURE
DECLARATION OF STRUCTURE
We use struct keyword to create a structure in C. The struct keyword is a
short form of structured data type.
struct struct_name
{
DataType member1_name;
DataType member2_name;
DataType member3_name;
…
};
Here struct_name can be anything of your choice. Members data type can be
same or different. Once we have declared the structure we can use the struct name as
a data type like int, float etc.
First we will see the syntax of creating struct variable, accessing struct
members etc and then we will see a complete example.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 109 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
Example of Structure
struct Book
{
char name[15];
int price;
int pages;
};
Here the struct Book declares a structure to hold the details of book which
consists of three data fields, namely name, price and pages. These fields are
called structure elements or members. Each member can have different data type,
like in this case, name is of char type and price is of int type etc. Book is the name of
the structure and is called structure tag.
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 110 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
ACCESS DATA MEMBERS OF A STRUCTURE USING A STRUCT VARIABLE
Structure members can be accessed and assigned values in number of ways.
Structure member has no meaning independently. In order to assign a value to a
structure member, the member name must be linked with the structure variable
using dot. operator also called period or member access operator.
var_name.member1_name;
var_name.member2_name;
Example:
struct Book
{
char name[15];
int price;
int pages;
} b1 , b2 ;
We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", b1.name);
scanf(" %d ", &b1.price);
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 111 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
have to create an array of structure or object. As we know, an array is a collection of
similar type, therefore an array can be of structure type.
POINTER TO STRUCTURE
Like we have array of integers, array of pointers etc, we can also have array of
structure variables. And to make the use of array of structure variables efficiently,
we use pointers of structure type. We can also have pointer to a single structure
variable, but it is mostly used with array of structure variables.
struct Book
{
char name[10];
int price;
}
void main()
{
struct Book a; //Single structure variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 112 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
OUTPUT:
NAME: StudyTonight
NUMBER: 35
RANK: 1
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 113 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
UNION
C Union is also like structure, i.e. collection of different data types which are
grouped together. Each element in a union is called member.
• Union and structure in C are same in concepts, except allocating memory for
their members.
• Structure allocates storage space for all its members separately.
• Whereas, Union allocates one common storage space for all its members
• We can access only one member of union at a time. We can’t access all
member values at the same time in union. But, structure can access all
member values at the same time. This is because, Union allocates one
common storage space for all its members. Whereas Structure allocates
storage space for all its members separately.
• Many union variables can be created in a program and memory will be
allocated for each union variable separately.
• Below table will help you how to form a C union, declare a union, initializing
and accessing the members of the union.
Syntax: Syntax:
union tag_name union tag_name
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
Example: Example:
union student union student
{ {
int mark; int mark;
char name[10]; char name[10];
float average; float average;
}; };
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 114 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 115 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
No of Questions Weightage
Sl. No Module
1M 5M 10M (Marks)
1 Unit - 1 2 1 1 17
2 Unit – 2 2 1/2 1 17/22
3 Unit – 3 2 1/2 1 17/22
4 Unit – 4 2 1/2 1 17/22
5 Unit – 5 2 1/2 1 17/22
60 (without Choice)
Grand Total 10 30 50
90 (with choice)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 116 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 117 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 118 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 119 of 120
PROGRAMMING IN C FOR BCA I SEM (NEP)
From the Desk of Mr. Manjunatha Balluli , S.M.D College, Ballari. Page 120 of 120