Professional Documents
Culture Documents
c Lang II Bcom Even Sem(200)
c Lang II Bcom Even Sem(200)
programming in c
very Graduate should leave the College with a Degree in one hand
and a Placement order in other hand
Y Jagadeesh
Department of Computer Science
924 66 666 46
Kakinada
ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY
Some more Algorithms – Flow Charts. Introduction to C: Structure of C Program Writing the first C
Program – File used in C Program – Compiling and Executing C Programs – Using Comments –
Keywords – Identifiers – Basic Data Types in C – Variables – Constants – I/O Statements in C-
Operators in C- Programming Examples – Type Conversion and Type Casting
UNIT-II:
Decision Control and Looping Statements: Introduction to Decision Control Statements – Conditional
Branching Statements – Iterative Statements – Nested Loops – Break and Continue Statement – Go to
Statement
UNIT-III:
Functions: Introduction – using functions – Function declaration/ prototype – Function definition –
function call – return statement – Passing parameters – Scope of variables – Storage Classes –
Recursive function
UNIT- IV:
Arrays: Introduction – Declaration of Arrays – Accessing elements of the Array – Storing Values in
Array – Calculating the length of the Array – Operations on Array – one dimensional array for inter-
function communication – Two dimensional Arrays –Operations on Two Dimensional Arrays, Strings:
Introduction String and Character functions
UNIT-V:
Pointers: Understanding Computer Memory – Introduction to Pointers – declaring Pointer Variables – -
Passing Arguments to Functions using Pointer – Pointer and Arrays – Passing Array to Function.
Structure, Union, and Enumerated Data Types: Introduction – Nested Structures – Arrays of Structures
– Structures and Functions - Unions – Enumerated Data Types.
QUESTION PAPER PATTERN FOR ALL SEMESTER W.E. FROM 2016-17 ADMITTED BATCH
(For all Papers except Foundation Course papers & Special English Paper )
Time: 3 Hours Maximum Marks: 75
Section - A
I. Answer any Five questions
5 X 5 = 25 Marks
1. Unit- I
2. Unit- II
3. Unit-III
4. Unit- IV
5. Unit-V
6.
7.
8. Each one from any of
the three units out of
five units.
Section- B
II. Answer All the Questions
5 X 10 = 50 Marks
1. (a) or (b) from Unit -I
2. (a) or (b) from Unit -II
3. (a) or (b) from Unit -III
4. (a) or (b) from Unit -IV
5. (a) or (b) from Unit -V
ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY
CBCS/Semester System (W.e.f. 2015-16 Admitted Batch)
V SEMESTER, COMPUTER APPLICATIONS
Model Question Paper - Programming in C
Section – A
Answer Any Five Questions
5 X 5 = 25 Marks
1. Explain the various data types available in C [Page No.13 to14]
2. What is type casting ? Explain [Page No.13 to14]
3. Explain switch statement with example [Page No.21 to22]
4. What is recursive function? Explain [Page No.33 to34]
5. Explain various string handling functions [Page No.32 to33]
6. Explain the difference between Structure and Union [Page No.45 & 49]
7. Explain pointer and structures [Page No.42 to 43& 45]
8. Write a short notes on Enmurated data types [Page No. 50]
Section – B
Answer All Questions
5 X 10 = 50 Mark
A. Write algorithm and draw flowchart to find the roots of quadratic equation [Notes] OR
B. Explain the various operators in C [Page No.16 to 19]
A. Explain the various looping structures [Page No.22 to 24] OR
B. Write a C program to generate prime numbers up to 20 [Notes]
A. Explain the various types of arrays [Page No.36 to 38] OR
B.Write a C program to find the product of the two matrices [Notes]
A. Explain structure arrays and structure within structures [Page No.46 to 47] OR
B. Write a C program to find the smallest of the given numbers using pointers [Notes]
A. Differentiate Structures and Unions. [Page No.45 & 49] OR
B. Write about array of structures with suitable example. [Page No.45]
ADIKAVI NANNAYA UNIVERSITY, RAJAHMUNDRY
2. A. Explain about while, do-while and for loop with suitable examples [Page No.22 to 24] OR
B. Write a C program to compute sum of individual digits of given number( 123=1+2+3=10) [Notes]
3. A. Discuss different categories of user define functions illustrate with examples [Page No.26 &27 to 29 ]
OR
B. Explain about the different paratemer passing mechanism of the functions [Page No.30 to 31]
4. A. Write about various String handling functions used in with syntax [Page No.32 to33] OR
B. Write a C program to find the multiplication of two matrics. [Notes]
5. A. Explain the following: 1.Pointer Function. 2. Nested Structures. [Page No.31 & 47] OR
B. 1. Differentiate Structures and Unions. [Page No.45 & 49]
2. Write about array of structures with suitable example [Page No.45]
UNIT-I
ALGORITHM:
1. The algorithm is the basic technique used to get the job done.
2. Step by step procedure designed to perform an operation, and which (like a map or
Flowchart) will lead to the sought result if followed correctly.
3. Algorithms have a definite beginning and a definite end, and a finite number of steps.
4. Algorithms can be combined to perform complex tasks such as writing a computer
programs.
5.It is a step by step repetition of a solution to a given problem, which is very easy to understand.
6.It has got a definite procedure.
7.It easy to first develop an algorithm & then covert it into a flowchart& then into a computer program.
8.It is independent programming language.
9.It is easy to debug as every step is got its own logical sequence
ALGORITHM REPRESENTATION OF COMPUTER FUNCTIONS:
It is time consuming
It is more complexity
it as an algorithm is developed first which is converted into flowchart and then in to a computer
program.
what is flowchart? explain about various flowchart symbols and features of flowchart?
FLOWCHART:
Flowchart is a graphical or pictorial representation of an algorithm. Before drawing flowcharts you need
to understand the different symbols used in Flowcharts. There are many more symbols to make
flowchart more meaningful. Below are standard flowchart symbols and their meaning.
PROGRAM FLOWCHART:
INTRODUCTION:
History of C Language:
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in U.S.A. Dennis Ritchie is known as the founder of c language.
It was developed to overcome the problems of previous languages such as B, BCPL etc. Initially, C
language was developed to be used in UNIX Operating System. It inherits many features of previous
languages such as B and BCPL. Programming languages that were developed before C language.
FEATURES OF C LANGUAGE:
C is the widely used language. It provides a lot of features that are given below.
1. Simple 2. Machine Independent or Portable 3. Mid-level programming language
4. structured programming language 5. Rich Library 6. Memory Management
7. Fast Speed 8. Pointers 9. Recursion 10. Extensible
1. Simple:
C is a simple language in the sense that it provides structured approach (to break the problem into
parts)
2. Machine Independent or Portable:
C is also used to do low level programming . It also supports the feature of high level language . That is
why it is known as mid-level language.
4. Structured prorgramming language:
C is a structured programming language in the sense that we can break the program into parts using
functions.
5. Rich Library:
7. Speed:
8. Pointers:
C provides the feature of pointers. We can directly interact with the memory by using the pointers. We can
10. Extensible:
[STRUCTURE OF A C -PROGRAM:
The first line of the program #include <stdio.h> is a preprocessor command, which tells a C compiler to
include stdio.h file before going to actual compilation.
2. Functions:
The next line int main() is the main function where the program execution begins.
3. Variables:
A variable is a name of memory location. It is used to store data. Its value can be changed and it
can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Ex1: int a; Ex2: float b; Ex3: char c; Ex4: char n[10]; Ex5: int a,b,c;
4. Statements & Expressions:
The body of the function contains valid C statements and expressions. These statements are
solve the given task.
5. Comments:
Comments /*...*/ will be ignored by the compiler and it has been put to add additional comments in the
program. So such lines are called comments in the program. ]
WRITING THE FIRST C PROGRAM:
2. The next line int main() is the main function where the program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional
comments in the program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "
To save the source code in a file, and how to compile and run it. Following are the simple steps Open a
2. Open a command prompt and go to the directory where you have saved the file.
3. open hello.c and press Ctrl F9 to compile your code.
4. If there are no errors in your code, the command prompt will take you to the next line and
would generate hello.bak and hello.exe executable file.
5. Now, type hello.exe to execute your program.
6. You will see the output "HELLOW, WELCOME TO C WORLD" printed on the screen.
COMMENTS IN C:
Comments in C language are used to provide information about lines of code. It is widely used for
documenting code. There are 2 types of comments in C language.
1. Single Line Comments
2. Multi Line Comments
1. Single Line Comments:
Single line comments are represented by double slash \\. An example of single line comment
Example:
//printing information
printf("Hello C");
2. Mult Line Comments:
Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code
but it can't be nested.
An example of multi line comment in C.
/*printing
information*/
printf("Hello C");
Output:
Hello C
C-CHARACTER SET:
C character Set consists of 1. Source Characters and 2. Excution or White space or Backslah or Escape
Sequences.
1. Source Characters:
A source character is a character that represents itself when used. In C language, Source Character Set
consists of following catagerious of characters.
S.No. Category Characters
1. Alphabets A to Z and UnderScore ( _)
2. Digits 0 to 9
3. Special Symbols ~, !, #, $, %, ^, &, *, @, /, etc.,
4. Punctuations ., ,, ‘, ”, :, :, (, ), [, ], {, }, etc.,
An escape sequence in C language is a sequence of characters that doesn't represent itself when used
inside string literal or character. It is composed of two or more characters starting with backslash \. For example: \
n represents new line.
List of Escape Sequences in C:
S.No. Escape Sequence Meaning
1. \a Alarm or Beep
2. \b Backspace
3. \f Form Feed
4. \n New Line
5. \r Carriage Return
6. \t Tab (Horizontal)
7. \v Vertical Tab
8. \\ Backslash
9. \' Single Quote
10. \" Double Quote
11. \? Question Mark
12. \nnn octal number
13. \xhh hexadecimal number
14. \0 Null
WORDS IN C LANGUAGE:
A word is nothing but group of characters. In C Language words are classified into two types.
1. Key Words or Reserved Words 2. User defined Words or Programmer supplied words
1. Keywords in C:
Key words are defined by the scientists. A Key Word is fixed and predefined meaning
to the compiler. A keyword is a reserved word. You cannot use it as a variable name,
constant name etc. There are only 32 reserved words (keywords) in C language. A list of 32
keywords in c language is given below:
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while
These words are defined by the User or programmer. The Variable names, Data Names, Constant names,
Etc., are user defined words.
Ex1 : int a,b,c; Ex2: float jack, rose;
In the above statements int, float are Key Words and a, b, c, jack and rose are user defined words.
VARIABLES or IDENTIFIERS IN C:
A variable or Identifier is a name of memory location. It is used to store data. Its value can be
changed and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified. The
syntax to declare a variable or Identifier:
Syntax: DataType Variable_name or variables_list;
Where the Data types can be int (integer), char (character), float (real) etc
The example of declaring variable is given below:
Ex1: int a; Ex2: float b; Ex3: char c; Ex4: char n[10]; Ex5: int a,b,c;
Here, a, b, c are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
int a=10,b=20; //declaring 2 variable of integer type
Rules for defining variables or Identifiers:
Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well. Constants are treated
just like regular variables except that their values cannot be modified after their definition.
1. Integer Constants or Literals:
An integer constant is known as a string of digits without decimal point. It can be a decimal,
octal, or hexadecimal constant.
Examples of integer literals:
1. 85 /* decimal */ 2. 0213 /* octal */ 3. 0x4b /* hexadecimal */
4. 30 /* int */ 5. 30u /* unsigned int */ 6. 30l /* long */
7. 30ul /* unsigned long */
2. Floating-point Constants or Literals:
A float constant is known as a string of digits with decimal point. A floating-point literal has an
integer part, a decimal point or a fractional part, and an exponent part. Examples of floating-point literals
1. 3.14159 2. 314159E-5L
3. Character Constants or Literals:
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple variable
of char type. A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a
universal character (e.g., '\u02C0').
4. String Constants or Literals:
String literals or constants are enclosed in double quotes "". A string contains characters that
are similar to character literals: plain characters, escape sequences, and universal characters. You can
break a long line into multiple lines using string literals and separating them using white spaces.
Examples of string literals.
1. “ YRL COLLEGE “ 2. “ JAGADEESH ” 3. “ A9*ABC “
DATA TYPES IN C:
A data type specifies the type of data that a variable can store such as integer, floating,
character etc.
The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals. The memory size of basic data types may change according to 32 or 64
bit operating system. the following are basic data types. Its size is given according to 32 bit
architecture.
They are 4 types of data types are there (1) integer (2)character (3 )flaot (4)double
(1)Integer datatype:
(4)double datatype:
Double datatype is also same as flaot datatype which allows upto 10 digits after
decimal.
The range of 8bytes 1e-3.7 to1e-3.7
Here, “%lf” is a format specification for double datatype.
Enumerated datatype:
Enumeration datatype consists named integers constant as a list.
It starts with 0 by default and value is incremented by 1 for the sequential identifiers list.
Enumerated sytax in c
Enum identifier[ optional{enumerated list}];
Here you want use “#define” is preprocessor directive.
Void datatype:
Void is an empty datatype that has no value.
The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file) These functions are known as formatted Input
and Output functions.
Formatted Output function (printf()):
The printf() function is used for output. It prints the given statement to the console. The syntax of
printf() function is given below:
Syntax1:
Where the format string can be %d (integer), %c (character), %s (string), %f (float) etc
Ex1: printf(" The result is %d ", R);
Ex2: printf("%d is result ", R);
Ex3: Printf(" The result %d is", R);
The scanf() function is used for input. It reads the input data from the console. The syntax of scanf()
function is given below:
Syntax:
The gets() and puts() functions are unformatted String Input and Output functions. Both
functions are defined in <stdio.h> header file.
Unformatted String Input gets() function:
In C language, the gets()function reads string from user. The general format of gets() function is
Syntax:
gets(string variable);
Example:
gets(name);
In C language, the puts() function prints the string. The general format of puts() function is
Syntax:
puts(string variable);
Example:
puts(name);
The getchar() and putchar() functions are unformatted character Input and Output functions. Both
functions are defined in <stdio.h> header file.
The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in a loop in case you want to
read more than one character. The syntax is
Syntax:
<character Variable>=getchar();
Example:
c=getchar();
The putchar() function displays the character passed to it on the screen and returns the same
character. This function displays only a single character at a time. In case you want to display more
than one characters, use putchar() method in a loop.
Syntax:
putchar(character Variable);
Example:
putchar(C);
[C OPERATORS:
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like Arithmetic, Relational, Logical and Bitwise Operators etc. The following types of
operators are performs different types of operations in C language.
1. Arithmetic Operators 2. Relational Operators 3. Logical Operators
4. Bitwise Operators 5. Ternary or Conditional Operators 6. Assignment Operator
7. Shift Operators
1. Arithmetic Operators:
Arithmetic operators performs basic arithmetic operations like Addition, Subtraction, Multiplication,
Division and Modulus division etc., Assume variable a holds 10 and variable b holds 20, then:
S.No. Operator Description Example
1. + Addition - Adds values on either side of the operator a + b will give 30
2. - Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
3. * Multiplication - Multiplies values on either side of the operator a * b will give 200
4. / Division - Divides left hand operand by right hand operand b / a will give 2
Modulus - Divides left hand operand by right hand operand and
5. % b % a will give 0
returns remainder
6. ++ (Increment)- Increases an integer value by one A++ will gives 11
These Operators are used to compare two or more Operands or Variables and then produce either True or
False. These Operators are used to build Relational Or Boolean Expressions. Assume variable a holds 10 and
3. Logical Operators:
C Language supports the following logical operators – Logical Operators are used to combine two or more
Relational expressions in to a Logical expression. These Logical expressions produce either True or False. Assume
|| (Logical OR) If any of the two operands are non-zero, then the condition becomes true. Ex: (A || B)
2
is true.
! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the Logical NOT
3
operator will make it false. Ex: !(A && B) is false.
4. BITWISE OPERATORS:
Bitwise Operators are used to perform operations on Bits and Bytes, these operations are called Boolean
Operations. C Language supports the following Bitwise O perators −Assume variable A holds 2 and B holds 3,
then
S.No Operator and Description
1 & (Bitwise AND) It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2.
2 | (BitWise OR) It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3.
^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR
3
means that either operand one is true or operand two is true, but not both. Ex: (A ^ B) is 1.
4 ~ (Bitwise Not) It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4.
<< (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second
5 operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to multiplying it by 2,
shifting two positions is equivalent to multiplying by 4, and so on. Ex: (A << 1) is 4.
>> (Right Shift) Binary Right Shift Operator. The left operand’s value is moved right by the number of bits
6
specified by the right operand. Ex: (A >> 1) is 1.
>>> (Right shift with Zero) This operator is just like the >> operator, except that the bits shifted in on the left
7
are always zero. Ex: (A >>> 1) is 1.
5. ASSIGNMENT OPERATORS:
+= (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand.
2
Ex: C += A is equivalent to C = C + A
−= (Subtract and Assignment)It subtracts the right operand from the left operand and assigns the result to the
3
left operand. Ex: C -= A is equivalent to C=C–A
*= (Multiply and Assignment) It multiplies the right operand with the left operand and assigns the result to the
4
left operand. Ex: C *= A is equivalent to C = C * A
/= (Divide and Assignment) It divides the left operand with the right operand and assigns the result to the left
5
operand. Ex: C /= A is equivalent to C = C / A
%= (Modules and Assignment) It takes modulus using two operands and assigns the result to the left operand.
6
Ex: C %= A is equivalent to C = C % A
6. Conditional Operator (? :) :
conditional operator ? : which can be used to replace if...else statements. It has the following general form
Syntax:
Numeric_Variable=(Test-Condition) ? (const1/Variable1/Exp1) : (const2/Variable2/Exp2);
Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition
is true then const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable
otherwise const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Example1: K=(A>B && A>C) ? A : B;
Example2: R=(X==Y) ? (X+Y) : (X-Y);
Example3: N=(A>B) ? 100 : 200;]
Type casting allows us to convert one data type into other. In C language, we use cast operator
for type casting which is denoted by (type). The syntax of the Type Casting is
Syntax:
(type)value;
Example:
Without Type Casting:
int f= 9/4;
#include <stdio.h>
#include <conio.h>
void main()
{
clrscr();
float f= (float)9/4;
printf("f : %f\n", f );
getch();
}
Two types of conversions are there implicit and explicit.
Implicit: when the type coversion is performed automatically by the compiler with out programmers
intervention.
Ex:int x
For(x=97;x<=122;x++)
{
Printf(“%ch”,x);
}
Explicit:the type conversion performed by the programmer by passing the datatype of the expression
of specific type is known as explicit conversion
Ex: int x;
For(x=97;x<=122;x++)
{
Printf(“%ch”,(char)x);
}
All the integers are converted to float
All float types to be converted to double.
All character types to be converted to integer.
Examples, int x=7,y=5;
Float z;
Z=(float)x\(float)y;
UNIT-II
CONTROL STATEMENTS:
While writing a program, there may be a situation when you need to adopt one out of a given
set of paths. In such cases, you need to use Control statements that allow our program to make correct
decisions and right actions. These Statements are 1. Decision Making and Branching Statements
2. Decision Making and Looping Statements
C Language supports Decision Making and Branching Statements which are used to perform
different actions based on different conditions. C Language supports the following If statements:
The if statement in C language is used to perform operation on the basis of condition. These
statements can perform operations either condition is true or false. There are many ways to use if
statement in C language:
1. Simple if statement 2. if...else statement 3. if...else if... statement.(Nested if)
The simple if statement in C language is used to execute the code if condition is true. The
syntax of if statement is given below:
Syntax:
if(Test-Condition)
{
Single Statement; or Group of Statements; //code to be executed
}
Example:
if(a<b)
printf("%d is is small",a);
2. if-else Statement:
The if-else statement in C language is used to execute the code if condition is true or false. The
syntax of if-else statement is given below:
Syntax:
if(Test-Condition)
Single Statement; or Group of Statements; // code to be executed if condition is true
else
Single Statement; or Group of Statements; // code to be executed if condition is false
Example:
if(a<b)
printf("%d is small",a);
else
printf("%d is small",b);
The Nested if ( if else-if ladder ) is used to execute one code from multiple conditions. The
syntax of Nested if ( if else-if ladder )statement is given below:
Syntax:
if(Test-condition1)
Statement or Statements block //code to be executed if condition1 is true
else
if(condition2)
Statement or Statements block //code to be executed if condition2 is true
else
if(condition3)
Statement or Statements block //code to be executed if condition3 is true
---
---
else
Statement or Statements block //code to be executed if all the conditions are false
Example:
Where const1,2 or Variable1,2 or Exp1,2 Numeric values. In the above syntax If Test condition is true
then const1/Variable1/Exp1 is evaluated and then result is assigned to Numeric_Variable otherwise
const2/Variable2/Exp2 is evaluated and then result is assigned to Numeric_Variable.
Example1: K=(A>B && A>C) ? A : B;
Example2: R=(X==Y) ? (X+Y) : (X-Y);
Example3: N=(A>B) ? 100 : 200;
[5. switch-case-default Statement:
The switch statement in C language is used to execute the code from multiple conditions. It is
like Nested if( if else-if ladder) statement. The syntax of switch statement in c language is given below:
Syntax:
switch(Variable orConstant or any expression){
case value1: Statement or Statements block; //code to be executed;
break; //optional
case value2: Statement or Statements block; //code to be executed;
break; //optional
case value3: Statement or Statements block; //code to be executed;
break; //optional
------------- -------------
------------- -------------
default: Statement or Statements block; // code to be executed if all cases are not matched;
}
The break statement in switch case is not must. It is optional. If there is no break statement
found in switch case, all the cases will be executed after matching the case value. It is known as fall
The most basic loop in C language is the while loop. The purpose of a while loop is to execute a
statement or statement block repeatedly as long as an expression or Test-condition is true. Once the
expression becomes false, the loop terminates. It iterates the code until condition is false.
The while loop checks the Tes condition at the beginning of the loop. This means that this loop
will always be executed if the condition is True. So, it is called Entry Controlled Loop.
Syntax:
Exp1;
while (Test-condition)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
Exp2;
}
Where Test-condition is Boolean Expression, Exp1 is initialization expression and Exp2 is
Increment or Decrement expressions. Exp1 and Exp2 are optional.
Example:
i=1;
while(i<=n)
{
printf(“%d \n “, i);
i++; }
2. The do...while Loop:
The do...while loop is similar to the while loop except that the condition check happens at the end
of the loop. This means that the loop will always be executed at least once, even if the condition is
false. So, it is called Exit Controlled Loop.
Syntax: Exp1;
do
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
Exp2;
}while (Test-condition);
Where Test-condition is Boolean Expression, Exp1 is initialization expression and Exp2 is
Increment or Decrement expressions. Exp1 and Exp2 are optional
Example: i=1;
do
{
printf(“%d \n “, i);
i++;
}while(i<=n);
Difference Between Entry Controlled And Exit Controlled Loops:
The following C progrming code shoes the difference between entry controlled and exit
controlled loops
i=6; i=6;
while(i<=5) do
{ {
printf(“%d \n “, i); i++; } printf(“%d \n “, i); i++; }while(i<=5);
This code does not produce the output. This code produces the output 6.
In C language, Loop inside the loop is called Nested loops. We can write nested loops by using while(), do-
while() and for() structures. The syntax of Nested loop is
Syntax:
The syntax of for Nested loops using for() loop as follows
for (Initialization Statements; Test Condition1; Iteration Statements)
{
for (Initialization Statements; Test Condition2; Iteration Statements)
{
Statement or Statements;
----------
----------
---------- //body of the Inner loop code to be executed
}
Statement or Statements;
----------
----------
---------- //body of the Outer loop code to be executed
}
Example:
}
} ]
[C Transfer statements: ( break & continue ):
C Language provides transfer statements ( break and continue ) to change the default sequential
order of execution of looping Statements and Switch-Case-Default Statement.
break Statement:
1. The break statement in C language is used to break the execution of loop (while, do while and for)
and switch case. In case of inner loops, it terminates the control of inner loop only.
Syntax: for (Initialization Statements; Test Condition; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
if( Test Condition )
break;
}
Example:
for( i=1; i<=5; i++)
{if (i==3)
break;
printf(“%d \n “, i);}
C continue statement:
The continue statement in C language is used to continue the execution of loop (while, do while
and for). It is used with if condition within the loop. In case of inner loops, it continues the control of
inner loop only.
Syntax:
for (Initialization Statements; Test Condition; Iteration Statements)
{
Statement or Statements;
----------
---------- //body of the loop code to be executed
if( Test Condition )
continue;
}
The if statement and continue Statement can be write in while loop, do while loop, for loop
statements.
Example:
for( i=1; i<=5; i++)
{
if (i==3)
continue;]
}
C goto statement(Unconditional Transfer or Jumping Statement):
The goto statement is known as jump statement in C language. It is used to unconditionally
jump to other label. It transfers control to other parts of the program.
Syntax:
gotolabel Name;
goto Jack;
Example to use goto statement in C language.
#include <stdio.h>
main()
{
int age;
clrscr();
Jack:
printf("You are not eligible to vote!\n");
printf("Enter you age:\n");
scanf("%d", &age);
if(age<18)
goto Jack;
else
printf("You are eligible to vote!\n");
getch();
}
UNIT-III
FUNCTIONS
Function:
A function is a group of statements that together perform a specific task. Every C program has
at least one function, which is main(). A function can also be referred as a method or a sub-routine or a
procedure, etc. A function definition in C programming consists of a function header and a function
body. Here are all the parts of a function
1. Return Type: A function may return a value. The return_type is the data type of the value the function
returns. Some functions perform the desired operations without returning a value. In this case, the
return_type is the keyword void.
2. Function Name: This is the actual name of the function. The function name and the parameter list
together constitute the function signature.
3. Parameters: A parameter is like a placeholder. When a function is invoked, We pass a value to the
parameter. This value is referred to as actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are optional; that is, a function
may contain no parameters.
4. Function Body: The function body contains a collection of statements that define what the function
does.
Types of functions:
The C standard library provides various built-in functions that your program can call. For
example, strcat() to concatenate two strings, sqrt() to find squareroot of the given number and many
more functions.
[2. User defined functions:
These functions are defined by user. User can divide up code into separate functions. How the
user divide up the code among different functions is users choice, but logically the division is such that
each function performs a specific task.]
Function Declarations:
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately. The general format of the
function declaration is
Syntax:
<retur type or prototype> <name of the function>( with or without parameters list);
Example:
int add(int x, int y);
A function declaration tells the compiler about a function's name, return type, and parameters. A
function definition provides the actual body of the function. The general form of a function definition in C
programming language is as follows
Syntax:
<return type or prototype> <name of the function>( with or without parameters list)
{
body of the function /* function defination */
}
Example:
int jack(int x, int y)
{
int z; / * function defination */
z=x+y;
return(z);
}
Calling a Function:
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main program. To
call a function, you simply need to pass the required parameters along with the function name, and if
the function returns a value, then you can store the returned value.
Syntax:
<name of the function>(with or without parameters);
Example:
main()
{
int a=10;
int b=20;
int c;
c=jack(a,b); /* function calling */
printf(" The addition of given two Numbers is : %d", c);
}
[Types of user defined Functions:
User defined or Library functions are basically classified into three types. They are
1. Function without arguments
2. Function with arguments
3. Function with arguments and return value
1. Function without arguments:
Example:
int jack()
{
int z; / * function defination */
z=x+y;
Printf("The Addition of the given two numbers is %d", z);
}
Sample program for Function without parameters:
Example:
#include<stdio.>
main()
{
clrscr();
add();
sub();
getch();
}
void add()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
c=a+b;
printf(" The Addition of the given two numbers is %d", c);
}
void sub()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
c=a-b;
printf(" The Subtraction of the given two numbers is %d", c);
}
A function may one or more parameters or arguments. These functions can have type
parameters such as int, float, char, String,. These parameters are also known as formal parameters or
arguments. The general format Declaration of Function with arguments is
Syntax:
<return type or prototype> <name of the function>(data type parameter1, data type parameter1,....
, data type parameter-n)
{
------------;
------------; Body of the function
------------;}
Example:
#include<stdio.>
main()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
clrscr();
add(int a, int b);
sub(int a, int b);
getch();
}
To return any value from the function, We need to use any data type such as int, float, char,
String,etc,. The return type depends on the value to be returned from the function. A function may or
may not return a value from the function. If a function dont't return a value use void for the return
type. The general format Declaration of Function with arguments and return is
Syntax:
<return type or prototype> <name of the function>(data type parameter1, data type parameter1,....
, data type parameter-n)
{
------------;
------------; Body of the function
------------;
return(exp/const/var); / *Syntax of return statement */
}
Example:
#include<stdio.>
main()
{
int a,b,c;
printf(" Enter any Two values ");
scanf("%d %d",&a,&b);
clrscr();
c=add(int a, int b);
printf(" The Addition of the given two numbers is %d", c);
c=sub(int a, int b);
printf(" The Addition of the given two numbers is %d", c);
getch();
}
void add(int x, int y)
{
int z;
z=x+y;
return(z); / *Example of return statement */
}
void sub(int x, int y)
{ return(x-y);
}
]
[Passing parameters:
There are two ways to pass value or data to function in C language. They are Call by value and call
by reference in C. Original value is not modified in call by value but it is modified in call by reference.
Call by value and Call by reference.
a. Call by value in C:
In call by value, original value is not modified and value being passed to the function is locally
stored by the function parameter in stack memory location. If you change the value of function
parameter, it is changed for the current function only. It will not change the value of variable inside the
caller method such as main(). The concept of call by value in c language is
Example:
#include <stdio.h>
main()
{
int x=100, y=200;
clrscr();
printf("Before swap in main x=%d and y=%d \n", x,y);
swap(x,y); //passing values to function
printf("After swap in main x=%d and y=%d\n", x,y);
getch();
}
swap(int x, int y)
{
int t;
printf("Before swap in swap function x=%d and y=%d \n", x,y);
t=x;
x=y;
y=t;
printf("After swap in swap function x=%d and y=%d\n", x,y);
}
Output:
b. Call by reference in C:
In call by reference, original value is modified because we pass reference (address). Here, address
of the value is passed in the function, so actual and formal arguments shares the same address space.
Hence, value changed inside the function, is reflected inside as well as outside the function. The
concept of call by reference in c language is
#include <stdio.h>
main()
{
int *x=100, *y=200;
clrscr();
printf("Before swap in main x=%d and y=%d \n", x,y);
swap(*x, *y); //passing references to function
printf("After swap in main x=%d and y=%d\n", x,y);
getch();
}
By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function. ]
2. Library Functions:
The C standard library provides various built-in functions that your program can call. For
example, strcat() to concatenate two strings, sqrt() to find squareroot of the given number and many more
functions.
[String Functions:
String: In C language is an array of characters that is terminated by \0 (null character). There
many important string functions defined in "string.h" library.
String Taxonomy or String Operations or String functions:
strcat(first_string, concats or joins first string with second string. The result of the string
3
second_string) is stored in first string.
strcmp(first_string, compares the first string with second string. If both strings are same,
4
second_string) it returns 0.
clrscr();
Conversion Functions:
The library also contains two conversion functions that accepts and returns an "int".
S.N. Function & Description
1 int tolower(int c): This function converts uppercase letters to lowercase.
2 int toupper(int c): This function converts lowercase letters to uppercase.
[Recursive functions:
Recursion:
A function is recursive if it makes a call to itself directly or indirectly. If a function f( ) calls itself within from
its own body, it is called recursive. Secondly, if a function f( ) calls another function g( ) that ultimately calls back
to f( ), then it can also be considered a recursive function. The general format of recursive function is
Syntax:
<prototype> <name of the Recursive function>( with or without arguments)
{
body of the function;
------------; Body of the function
------------;
recursion function();
}
Types of Recursions:
Following variants of recursion tell us making recursive calls in different ways depending upon the problem .
Storage classes are used to define scope and life time of a variable. There are four storage
classes in C programming.
1. auto 2. extern 3. static 4. register
Storage Storage
Default Value Scope Life-time
Classes Place
Auto RAM Garbage Value Local Within function
Till the end of main program, May be declared anywhere
Extern RAM Zero Global
in the program
Till the end of main program, Retains value between
static RAM Zero Local
multiple functions call
register Register Garbage Value Local Within function
1. auto:
The auto keyword is applied to all local variables automatically. It is the default storage class
that is why it is known as automatic variable. The following examples shows the working of auto
storage class.
Example:
#include <stdio.h>
void main()
{
int a=10;
auto int b=10; //same like above
printf("%d %d",a,b);
}
Output:
10 10
2. register:
The register variable allocates memory in register than RAM. Its size is same of register size. It
has a faster access than other variables. The use of register variable only for quick access such as in
counter.
Example:
register int counter=0;
3. static:
The static variable is initialized only once and exists till the end of the program. It retains its
value between multiple functions call. The static variable has the default value 0 which is provided by
compiler. The following examples shows the working of static storage class.
Example:
#include <stdio.h>
void main()
{
jack();
jack();
jack();
}
void jack()
{
static int i=0; //static variable
int j=0; //local variable
i++;
j++;
printf("i= %d and j= %d\n", i, j);
}
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
4. extern:
The extern variable is visible to all the programs. It is used if two or more files are sharing same
variable or function.
Example:
Advantage of C Arrays:
3. Easy to sort data: To sort the elements of array, we need a few lines of code only.
4. Random Access: We can access any element randomly using the array.
Disadvantage of C Arrays:
1. Fixed Size: Whatever size, we define at the time of declaration of array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList.
Types of Arrays:
Single Dimensional Arrays in C language is a collection or group of elements (data). All the
We can declare Single Dimensional Arrays in C language in the following way. The general
format is
Syntax:
data_type array_name[array_size];
Example:
int N[5];
Here, int is the data_type, N is the array_name and 5 is the array_size.
A simple way to initialize array is by index. Array index starts from 0 and ends with [SIZE - 1].
Example:
marks[0]=80; //initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//initialization of array
N[0]=80; //StoringValues in Array
N[1]=60;
N[2]=70;
N[3]=85;
N[4]=75;
//traversal of array or
//Accessing elements of the Array
for(i=0;i<5;i++)
{
printf("%d \n",N[i]);
} //end of for loop
getch();
}
Output
80 60 70 85 75
We can declare Single Dimensional Arrays in C language in the following way. The general
format is
int N[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as the following code.
int N[]={20,30,40,50,60};
The two dimensional array in C language is represented in the form of rows and columns, also
known as matrix. It is also known as array of arrays or list of arrays. The two dimensional, three
dimensional or other dimensional arrays are also known as multidimensional arrays.
Declaration of two dimensional Array in C:
We can declare an array in the c language in the following way. The general format is
Syntax:
data_type array_name[size1][size2];
Example:
int N[4][3];
Here, int is the data type, N is array name 4 is the row size and 3 is the column size.
Initialization of Two dimensional Arrays in C:
We can initialize the two dimensional array at the time of declaration in the following way
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two dimensional array example in C
#include <stdio.h>
#include <conio.h>
void main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
clrscr();
for(i=0;i<4;i++) //traversing 2D array
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
} //end of j
} //end of i
getch();
}
Output:
arr[0][0] = 1 arr[0][1] = 2 arr[0][2] = 3 arr[1][0] = 2 arr[1][1] = 3 arr[1][2] = 4
arr[2][0] = 3 arr[2][1] = 4 arr[2][2] = 5 arr[3][0] = 4 arr[3][1] = 5 arr[3][2] = 6 ]
To reuse the array operation, we can create functions that receives array as argument. To pass
array in function, we need to write the array name only in the function call. The general format is
Syntax:
Functionname(arrayname); //passing array
} //end of function
Output: minimum number is 3
Operations that can be performed on Arrays:
Following operations can be performed on arrays:
1. Traversing 2. Searching 3. Insertion 4. Deletion 5. Sorting 6. Merging
1. Traversing: It is used to access each data item exactly once so that it can be processed.
Example:
Suppose item to be searched is 20. We will start from beginning and will compare 20 with each element.
This process will continue until element is found or array is finished. Here:
1. Compare 20 with 15
20 # 15, go to next element.
2. Compare 20 with 50
20 # 50, go to next element.
3. Compare 20 with 35
20 #35, go to next element.
4. Compare 20 with 20
20 = 20, so 20 is found and its location is 4.
3. Insertion: It is used to add a new data item in the given collection of data items.
Example:
We have linear array A as below:
1 2 3 4 5
10 20 50 30 15
New element to be inserted is 100 and location for insertion is 3. So shift the elements from 5th location to 3rd
location downwards by 1 place. And then insert 100 at 3rd location. It is shown below:
4. Deletion: It is used to delete an existing data item from the given collection of data items.
Example:
1 2 3 4 5
10 20 50 40 25 60
The element to be deleted is 50 which is at 3rd location. So shift the elements from 4th to 6th location upwards by
1 place. It is shown below:
1 2 3 4 5
10 50 40 20 30
After arranging the elements in increasing order by using a sorting technique, the array will be:
1 2 3 4 5
10 20 30 40 50
6. Merging: It is used to combine the data items of two sorted files into single file in the sorted
C STRINGS
String:
String in C language is an array of characters that is terminated by \0 (null character). There are
two ways to declare string in c language.
1. By char array
2. By string literal
Declaring Strings in C Language:
In such case, '\0' will be appended at the end of string by the compiler.
Difference between char array and string literal:
The only difference is that string literal cannot be changed whereas string declared by char array
can be changed.
Example:
We can declare and print string, the '%s' is used to print string in c language.
#include <stdio.h>
void main ()
{
char ch[10]={'j', 'a', 'g', 'a', 'd', 'e', 'e', 's', 'h', '\0'};
char ch2[10]="jagadeesh";
printf("Char Array Value is: %s\n", ch);
printf("String Literal Value is: %s\n", ch2);
}
Output:
Char Array Value is: jagadeesh
String Literal Value is: jagadeesh
C POINTERS
[Pointer:
A Pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, we must declare a pointer before using it to store any
variable address
multiplication. However, in this statement the asterisk is being used to designate a variable as a
pointer. The following are some of the valid pointer declarations
int *ip; /* pointer to an integer */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, that
represents a memory address. The only difference between pointers of different data types is the data
type of the variable or constant that the pointer points to address.
The following example makes use of pointer operations:
#include <stdio.h>
int main ()
{
int b = 20; /* actual variable declaration */
int *a; /* pointer variable declaration */
a = &b; /* store address of var in pointer variable*/
printf("Address of b variable: %x\n", &b ); /* address stored in pointer variable */
printf("Address stored in a variable: %x\n", a ); /* access the value using the pointer */
printf("Value of *a variable: %d\n", *a );
return 0;
}
Output:
Address of b variable: bffd8b3c
Address stored in a variable: bffd8b3c
Value of *a variable: 20 ]
…..
…..
}
Way-3:
Formal parameters as an unsized array −
Syntax:
void myFunction(int parameter[])
{
…..
…..
…..
}
Example:
double getAverage(int arr[], int size)
{
int i;
float avg;
float sum = 0;
for (i = 0; i < size; ++i)
{
sum += arr[i];
}
avg = sum / size;
return avg;
}
Now, let us call the above function as follows
POINTER ARRAY
dynamically.
4. The assembly code of Pointer is different 4. The assembly code of Array is different than
than Array Pointer.
STRUCTURE IN C
[Structure in c language is a user defined datatype that allows we to hold different type of
elements. Each element of a structure is called a member. It is widely used to store student
information, employee information, product information, book information etc.
Defining structure:
The struct keyword is used to define structure. The syntax to define structure in c is
struct structure_name
{
data_type member1;
data_type member2;
.
.
data_type memeberN;
};
Example:
struct book
{
int p;
floatc;
char n[10;
};
Here, struct is the keyword, book is the tag name of structure; p, c and n are the members or fields of the
structure.
]
Declaring structure variable:
We can declare variable for the structure, so that we can access the member of structure easily.
There are two ways to declare structure variable:
1. By struct keyword within main() function
2. By declaring variable at the time of defining structure.
1st way:
Let's see the example to declare structure variable by struct keyword. It should be declared within the
main function. struct employee
{
int id;
char name[50];
float salary;
};
Now write given code inside the main() function. struct employee e1, e2;
2nd way:
Nested Structure can have another structure as a member. There are two ways to define nested
structure in c language:
1. By separate structure
2. By Embedded structure
1. Separate structure:
We can create 2 structures, but dependent structure should be used inside the main structure as
a member. Let's see the code of nested structure.
struct Date
{
int d;
int m;
int y;
};
struct Employee
{
int id;
char n[20];
struct Date doj;
} emp1;
In the above example, doj (date of joining) is the variable of type Date. Here doj is used as a
member in Employee structure. In this way, we can use Date structure in many structures.]
2. Embedded structure:
We can define structure within the structure also. It requires less code than previous way. But it
can't be used in many structures.
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}emp1;
We can access the member of nested structure by Outer Structure. Nested_ Structure.member
as given below:
e1.doj.dd
e1.doj.mm
e1.doj.yyyy
Example:
#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
}doj;
}e1;
main( )
{
e1.id=101; //storing employee information
strcpy(e1.name,"Jagadeesh"); //copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;
printf( "employee id : %d\n", e1.id); //printing first employee information
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,1.doj.yyyy); return 0;
} ]
C UNION
[C Union:
In C, like structure, Union in c language is a user defined datatype that is used to hold different type
of elements. But it doesn't occupy sum of all members size. It occupies the memory of largest member
only. It shares memory of largest member.
It occupies less memory because it occupies the memory of largest member only.
Disadvantage of union over structure:
Defining Union:
union employee
{
int id;
char name[50];
float salary;
};
Example:
#include <stdio.h>
#include <string.h>
union employee
{
int id;
char name[50];
}e1; //declaring e1 variable for union
int main( )
{
e1.id=101; //store first employee information
strcpy(e1.name, "Jagadeesh"); //copying string into char array
printf( "employee 1 id : %d\n", e1.id); //printing first employee information
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output: employee 1 id : 1869508435
employee 1 name : Jagadeesh]
Enumerated data type variables can only assume values which have been previously declared.
enum month { jan = 1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec };