Professional Documents
Culture Documents
Module 1
Hardware Components
Processor, memoryand Input/Output devices, are the important components of adigital computer.
Processor will have ALU (Arithmetic Logic Unit) and Control Unit(CU) as its components.
Memory can be subdivided into primary and secondary memory.
Input devices accept data and control signals from the user. Examples of input devices are
keyboard, mouse, pen based systems, data scanners, game controllers, voice recognition systems
etc.
Output devices communicate the processed data to the user. Examples of output devices are
Monitor, Printer, Plotter, sound system etc.
Processor
Central Processing Unit (CPU) -It is the brain of the computer. It performs the bulk ofthe data
processing operations. The function of the processor is to fetch the instructionfrom memory,
examine (decode) the instruction and execute the instructions. It consists of Control unit,
Arithmetic Logic Unit (ALU) and registers. Control unit is responsible for fetching the
instructions from memory and interpreting them. ALU performs arithmetic and logical
operations. Registers are very high speed memory unitsfor storing very small amount of data.
Program counter, Instruction register, Memoryaddress register, memory buffer register and
accumulator are some examples of registers.Bus is a collection of wires. They may be
unidirectional or bidirectional. Bus is usedto connect different parts of a computer. Bus may be
serial or parallel. USB is anexample of a serial bus. Bus connecting computer and a dot matrix
printer is normallya parallel bus. Parallel bus carries several bits at a time. These bits may
indicateinstruction, data, address or commands. Bus width and Bus speed are the two major
components for performance measure of a computer.
Memory
In the memory, the information is stored in terms of bits or bytes or words. Byte ismade of 8 bits
and word is a collection of 16, 32 or 64 bits. Memory can be volatile ornon volatile. Information
present in Volatile memory is lost as soon as the power isturned off. Figure-1 gives the
classification of memory devices in a digital computer. Secondary memories are non volatile in
nature. Examples of secondary memoryinclude Hard disk, Pen drive, DVD-ROM, Recordable
DVD,CD-RW, Blue-Ray,Magnetic tapes. Main memory devices are ones in which any memory
location can beaccessed in any order (not necessarily in a sequential order). RAM (Random
AccessMemory) and ROM(Read Only Memory) are the two types of main memory
devices.RAM is also called Read-Write Memory. It is volatile memory. ROM is non-
volatilememory. It is also considered an example of firmware.
Cache memory is a memory placed between CPU and main memory. It contains a partof main
memory content. Processor when needs some information, first looks in thecache. If not found in
cache, the portion of memory containing the needed information ismoved to the cache and is also
read by the processor. Both internal and external cache memories are volatile in nature. External
cache is mounted on the motherboard. Registers are small memory units internally available
within the processor.
C Language : An Introduction
The documentation section consists of a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to use later.
2. Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using
the #define directive.
4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all
the user-defined functions.
5. main () function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program
executionbegins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
declaration and executable part end with a semicolon.
6. Subprogram section: If the program is a multi-function program then the subprogram
section contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main () function,
although they may appear in any order.
All section, except the main () function section may be absent when they are not required.
2) Writing first program:
#include <stdio.h>
void main()
{
printf("Welcome to C Programming!!");
Output:
Welcome to C Programming!!
Line 2 [voidmain() ] There must to be starting point from where execution of compiled C
program begins. In C, the execution typically begins with first line of main(). The void written
before main indicates return type of main(). The value returned by main indicates status of
program termination.
Line 3 and 6: [ { and } ] In C language, a pair of curly brackets define a scope and mainly used
in functions and control statements like if, else, loops. All functions must start and end with curly
brackets.
In a C program, all lines that start with # are processed by preprocessor which is a special
program invoked by the compiler. In a very basic term, preprocessor takes a C program and
produces another C program without any #.
#include<stdio.h>
#define max 100
int main()
{
printf("max is %d", max);
return 0;
}
// Output: max is 100
// Note that the max inside "" is not replaced
4) The macro arguments are not evaluated before macro expansion. For example consider the
following program
#include <stdio.h>
#define MULTIPLY(a, b) a*b
int main()
{
// The macro is expended as 2 + 3 * 3 + 5, not as 5*8
printf("%d", MULTIPLY(2+3, 3+5));
return 0;
}
// Output: 16
Benefits of C language
1. As a middle level language, C combines the features of both high level and low level
languages. It can be used for low-level programming, such as scripting for drivers and
kernels and it also supports functions of high level programming languages, such as
scripting for software applications etc.
2. C is a structured programming language which allows a complex program to be broken
into simpler programs called functions. It also allows free movement of data across these
functions.
3. Various features of C including direct access to machine level hardware APIs, presence
of C compilers, deterministic resource use and dynamic memory allocation make C
language an optimum choice for scripting applications and drivers of embedded systems.
4. C language is case-sensitive which means lowercase and uppercase letters are treated
differently.
5. C is highly portable and is used for scripting system applications which form a major part
of Windows, UNIX and Linux operating system.
6. C is a general purpose programming language and can efficiently work on enterprise
applications, games, graphics, and applications requiring calculations etc.
7. C language has a rich library which provides a number of built-in functions. It also offers
dynamic memory allocation.
Escape Sequences in C
In C programming language, there are 256 numbers of characters in character set. The entire
character set is divided into 2 parts i.e. the ASCII characters set and the extended ASCII
characters set. But apart from that, some other characters are also there which are not the part of
any characters set, known as ESCAPE characters.
\a Alarm or Beep
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Tab (Horizontal)
\v Vertical Tab
\\ Backslash
\' Single Quote
\" Double Quote
\? Question Mark
\ooo octal number
\xhh hexadecimal number
\0 Null
C Tokens
A token is the smallest element of a program that is meaningful to the compiler. Tokens can be
classified as follows:
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
While in C++ there are 31 additional keywords other than C Keywords they are:
Identifiers: Identifiers are used as the general terminology for naming of variables, functions
and arrays. These are user defined names consisting of arbitrarily long sequence of letters and
digits with either a letter or the underscore(_) as a first character. Identifier names must differ in
spelling and case from any keywords. You cannot use keywords as identifiers; they are reserved
for special use. Once declared, you can use the identifier in later program statements to refer to
the associated value. A special kind of identifier, called a statement label, can be used in
gotostatements.
There are certain rules that should be followed while naming c identifiers:
name Remark
_A9 Valid
Temp.var Invalid as it contains special character other than the underscore
void Invalid as it is a keyword
C program:
void main()
{
int a = 10;
}
Constants: Constants are also like normal variables. But, only difference is, their values can not
be modified by the program once they are defined. Constants refer to fixed values. They are also
called as literals.
Constants may belong to any of the data type.Syntax:
const
Types of Constants:
Octal & Hexadecimal constants – Example: octal: (013 )8 = (11)10, Hexadecimal: (013)16 = (19)10
Strings: Strings are nothing but an array of characters ended with a null character (‘\0’).This null
character indicates the end of the string. Strings are always enclosed in double quotes. Whereas,
a character is enclosed in single quotes in C and C++.Declarations for String:
char string[20] = {‘g’, ’e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ’e’, ‘e’, ‘k’, ‘s’,
‘\0’};
char string[20] = “geeksforgeeks”;
char string [] = “geeksforgeeks”;
When we declare char as “string[]”, memory space will be allocated as per the requirement
during execution of the program
Special Symbols: The following special symbols are used in C having some special meaning
and thus, cannot be used for some other purpose.[] () {}, ; * = #
Brackets[]: Opening and closing brackets are used as array element reference. These indicate
single and multidimensional subscripts.
Parentheses(): These special symbols are used to indicate function calls and function
parameters.
Braces{}: These opening and ending curly braces marks the start and end of a block of code
containing more than one executable statement.
comma (, ): It is used to separate more than one statements like in for loop is separates
initialization, condition and increment.
semi colon : It is an operator that essentially invokes something called an initialization list.
pre processor(#): The preprocessor is a macro processor that is used automatically by the
compiler to transform your program before actual compilation.
Operators: Operators are symbols that triggers an action when applied to C variables and other
objects. The data items on which operators act upon are called operands.
Depending on the number of operands that an operator can act upon, operators can be classified
as follows:
Unary Operators: Those operators that require only single operand to act upon are known as
unary operators.For Example increment and decrement operators
Binary Operators: Those operators that require two operands to act upon are called binary
operators. Binary operators are classified into :
1. Arithmetic operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Bitwise Operators
Ternary Operators:These operators requires three operands to act upon. For Example
Conditional operator(?:).
A variable in simple terms is a storage place which has some memory allocated to it. So
basically a variable used to store some form of data. Different types of variables require different
amounts of memory and have some specific set of operations which can be applied on them.
Variable Declaration:
A typical variable declaration is of the form:
typevariable_name;
or for multiple variables:
type variable1_name, variable2_name, variable3_name;
A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‘_’ character. However, the name must not start with a number.
#include <stdio.h>
intmain()
{
// declaration and definition of variable 'a123'
chara123 = 'a';
// This is also both declaration and definition as 'b' is allocated
// memory and assigned some garbage value.
floatb;
// multiple declarations and definitions
int_c, _d45, e;
// Let us print a variable
printf("%c \n", a123);
return0;
}
Output:
Keywords are specific reserved words in C each of which has a specific feature associated with
it. Almost all of the words which help us use the functionality of the C language are included in
the list of keywords. So you can imagine that the list of keywords is not going to be a small one!
const: const can be used to declare constant variables. Constant variables are variables which
when initialized, can’t change their value. Or in other words, the value assigned to them is
unmodifiable.
Syntax:
constdata_typevar_name = var_value;
Note: Constant variables need to be compulsorily be initialized during their declaration itself.
const keyword is also used with pointers. Please refer the const qualifier in C for understanding
the same.
static: static keyword is used to declare static variables which are popularly used while writing
programs in C language. Static variables have a property of preserving their value even after they
are out of their scope! Hence, static variables preserve the value of their last use in their scope.
So we can say that they are initialized only once and exist till the termination of the program.
Thus, no new memory is allocated because they are not re-declared. Their scope is local to the
function to which they were defined. Global static variables can be accessed anywhere in the
program. By default, they are assigned the value 0 by the compiler.
Syntax:
staticdata_typevar_name = var_value;
In C, variables are always statically (or lexically) scoped i.e., binding of a variable can be
determined by program text and is independent of the run-time function call stack.
For example, output for the below program is 0, i.e., the value returned by f() is not dependent on
who is calling it. f() always returns the value of global variable x.
intx = 0;
intf()
{
returnx;
}
intg()
{
intx = 1;
returnf();
}
intmain()
{
printf("%d", g());
printf("\n");
getchar();
}
Scope rules in C
Scope of an identifier is the part of the program where the identifier may directly be accessible.
In C, all identifiers are lexically (or statically) scoped. C scope rules can be covered under
following two categories.
// filename: file1.c
inta;
intmain(void)
{
a = 2;
}
// filename: file2.c
// When this file is linked with file1.c, functions of this file can access a
externinta;
intmyfun()
{
a = 2;
}
To restrict access to current file only, global variables can be marked as static.
Block Scope: A Block is a set of statements enclosed within left and right braces ({ and }
respectively). Blocks may be nested in C (a block may contain other blocks inside it). A variable
declared in a block is accessible in the block and all inner blocks of that block, but not accessible
outside the block.
What if the inner block itself has one variable with the same name?
If an inner block declares a variable with the same name as the variable declared by the outer
block, then the visibility of the outer block variable ends at the pint of declaration by inner block.
intmain()
{
{
intx = 10, y = 20;
{
// The outer block contains declaration of x and y, so
// following statement is valid and prints 10 and 20
printf("x = %d, y = %d\n", x, y);
{
// y is declared again, so outer block y is not accessible
// in this block
inty = 40;
Output:
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
intmain()
{
intx = 10;
return0;
Output:
intmain()
{
intx = 1, y = 2, z = 3;
printf(" x = %d, y = %d, z = %d \n", x, y, z);
{
intx = 10;
floaty = 20;
printf(" x = %d, y = %f, z = %d \n", x, y, z);
{
intz = 100;
printf(" x = %d, y = %f, z = %d \n", x, y, z);
}
}
return0;
}
C Input/Output Statements
a)getchar()
b)putchar()
c)gets()
d)puts()
e)getch()
f)getche()
a) getchar()
This function is an Input function. It is used for reading a single character from the keyborad.
It is buffered function. Buffered functions get the input from the keyboard and store it in the
memory buffer temporally until you press the Enter key.
/*To read a single character from the keyboard using the getchar() function*/
main()
{
charn;
n = getchar();
}
b) putchar()
This function is an output function. It is used to display a single character on the screen. The
general syntax is as:
putchar(v);
A simple program is written as below, which will read a single character using getchar() function
and display inputted data using putchar() function:
c) gets()
This function is an input function. It is used to read a string from the keyboar. It is also
buffered function. It will read a string, when you type the string from the keyboard and press the
Enter key from the keyboard. It will mark nulll character ('\0') in the memory at the end of the
string, when you press the enter key. The general syntax is as:
gets(v);
main()
{
char n[20];
gets(n);
}
d) puts()
This is an output function. It is used to display a string inputted by gets() function. It is also
used to display an text (message) on the screen for program simplicity. This function appends a
newline ("\n") character to the output.
OUTPUT IS:
Enter the Name
Laura
Name is:
Laura
e) getch()
This is also an input function. This is used to read a single character from the keyboard like
getchar() function. But getchar() function is a buffered is function, getchar() function is a non-
buffered function. The character data read by this function is directly assign to a variable rather it
goes to the memory buffer, the character data directly assign to a variable without the need to
press the Enter key.
Another use of this function is to maintain the output on the screen till you have not press the
Enter Key. The general syntax is as:
v = getch();
OUTPUT IS:
Enter the Char
Char is L
f) getche()
All are same as getch(0 function execpt it is an echoed function. It means when you type the
character data from the keyboard it will visible on the screen. The general syntax is as:
v = getche();
main()
{
char n;
puts("Enter the Char");
n = getche();
puts("Char is :");
putchar(n);
getche();
}
OUTPUT IS:
Enter the Char L
Char is L
Formatted I/O functions which refers to an Input or Ouput data that has been arranged in a
particular format. There are mainly two formatted I/O functions discussed as follows:
a)scanf()
b)printf()
a) scanf()
The scanf() function is an input function. It used to read the mixed type of data from keyboard.
You can read integer, float and character data by using its control codes or format codes. The
general syntax is as:
scanf("controlstrings",arg1,arg2,..............argn);
or
scanf("control strings",&v1,&v2,&v3,................&vn);
Where arg1,arg2,..........argn are the arguments for reading and v1,v2,v3,........vn all are the
variables.
The scanf() format code (spedifier) is as shown in the below table:
Format Code Meaning
%c To read a single character
%d To read a signed decimal integer (short)
%ld To read a signed long decimal integer
%e To read a float value exponential
%f To read a float (short0 or a single precision value
%lf To read a double precision float value
%g To read double float value
%h To read short integer
%i To read an integer (decimal, octal, hexadecimal)
%o To read an octal integer only
%x To read a hexadecimal integer only
%u To read unsigned decimal integer (used in pointer)
%s To read a string
%[..] To read a string of words from the defined range
%[^] To read string of words which are not from the defined range
/*Program to illustrate the use of formatted code by using the formatted scanf() function */
main()
{
char n,name[20];
intabc;
float xyz;
printf("Enter the single character, name, integer data and real value");
scanf("\n%c%s%d%f", &n,name,&abc,&xyz);
getch();
}
b) printf()
This ia an output function. It is used to display a text message and to display the mixed type
(int, float, char) of data on screen. The general syntax is as:
printf("controlstrings",&v1,&v2,&v3,................&vn);
or
printf("Message line or text line");
Where v1,v2,v3,........vn all are the variables.
The control strings use some printf() format codes or format specifiers or conversion characters.
These all are discussed in the below table as:
main()
{
int a;
float b;
char c;
printf("Enter the mixed type of data");
scanf("%d",%f,%c",&a,&b,&c);
getch();
}
Data Types in C
Each variable in C has an associated data type. Each data type requires different amounts of
memory and has some specific operations which can be performed over it. Let us briefly describe
them one by one:
Following are the examples of some very common data types used in C:
char: The most basic data type in C. It stores a single character and requires a single byte of
memory in almost all compilers.
int: As the name suggests, an int variable is used to store an integer.
float: It is used to store decimal numbers (numbers with floating point value) with single
precision.
double: It is used to store decimal numbers (numbers with floating point value) with double
precision.
Different data types also have different ranges upto which they can store numbers. These ranges
may vary from compiler to compiler. Below is list of ranges along with the memory requirement
and format specifiers on 32 bit gcc compiler.
Type modifiers/qualifiers :
A type modifiers alter the meaning of the base data type to yield a new type. There are four types
of modifiers in C they are
signed
unsigned
short
long
1. Each of these type modifiers can be applied to the base type int.
2. Type modifiers signed and unsigned can also be applied to the base type char.
3. In addition, long can be applied to double.
Accessibility range
Data type Format Memory size
char[ ] (string) %s
%o Octal Base
%p Memory address
Type Conversion in C
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In such
condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with largest data
type.
It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).
Example of Type Implicit Conversion:
1. Output:
x = 107, z = 108.000000
2. Explicit Type Conversion– This process is also called type casting and it is user defined.
Here the user can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
int main()
{
double x = 1.2;
return 0;
}
Output:
sum = 2
Operators in C
Operators are the foundation of any programming language. Thus the functionality of C language
is incomplete without the use of operators. Operators allow us to perform different kinds of
operations on operands. In C, operators in Can be categorized in following categories:
o Addition: The ‘+’ operator adds two operands. For example, x+y.
o Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
o Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
o Division: The ‘/’ operator divides the first operand by the second. For example,
x/y.
o Modulus: The ‘%’ operator returns the remainder when first operand is divided
by the second. For example, x%y.
int main()
{
int a = 10, b = 4, res;
//printing a and b
printf("a is %d and b is %d\n", a, b);
return 0;
}
Output:
a is 10 and b is 4
a+b is 14
a-b is 6
a*b is 40
a/b is 2
a%b is 2
The ones falling into the category of unary arithmetic operators are:
Increment: The ‘++’ operator is used to increment the value of an integer. When placed
before the variable name (also called pre-increment operator), its value is incremented
instantly. For example, ++x.
And when it is placed after the variable name (also called post-increment operator), its
value is preserved temporarily until the execution of this statement and it gets updated
before the execution of the next statement. For example, x++.
Decrement: The ‘–‘ operator is used to decrement the value of an integer. When placed
before the variable name (also called pre-decrement operator), its value is decremented
instantly. For example, –x.
And when it is placed after the variable name (also called post-decrement operator), its
value is preserved temporarily until the execution of this statement and it gets updated
before the execution of the next statement. For example, x–.
int main()
{
int a = 10, b = 4, res;
// post-increment example:
// res is assigned 10 only, a is not updated yet
res = a++;
printf("a is %d and res is %d\n", a, res); //a becomes 11 now
// post-decrement example:
// res is assigned 11 only, a is not updated yet
res = a--;
printf("a is %d and res is %d\n", a, res); //a becomes 10 now
// pre-increment example:
// res is assigned 11 now since a is updated here itself
res = ++a;
// a and res have same values = 11
printf("a is %d and res is %d\n", a, res);
// pre-decrement example:
// res is assigned 10 only since a is updated here itself
res = --a;
// a and res have same values = 10
printf("a is %d and res is %d\n",a,res);
return 0;
}
Output:
a is 11 and res is 10
a is 10 and res is 11
a is 11 and res is 11
a is 10 and res is 10
Relational Operators:
Relational operators are used for comparison of two values. Let’s see them one by one:
‘==’ operator checks whether the two given operands are equal or not. If so, it returns
true. Otherwise it returns false. For example, 5==5 will return true.
‘!=’ operator checks whether the two given operands are equal or not. If not, it returns
true. Otherwise it returns false. It is the exact boolean complement of the ‘==’ operator.
For example, 5!=5 will return false.
‘>’ operator checks whether the first operand is greater than the second operand. If so, it
returns true. Otherwise it returns false. For example, 6>5 will return true.
‘<‘ operator checks whether the first operand is lesser than the second operand. If so, it
returns true. Otherwise it returns false. For example, 6<5 will return false.
‘>=’ operator checks whether the first operand is greater than or equal to the second
operand. If so, it returns true. Otherwise it returns false. For example, 5>=5 will return
true.
‘<=’ operator checks whether the first operand is lesser than or equal to the second
operand. If so, it returns true. Otherwise it returns false. For example, 5<=5 will also
return true.
int main()
{
int a=10, b=4;
// relational operators
// greater than example
if (a > b)
printf("a is greater than b\n");
else printf("a is less than or equal to b\n");
// equal to
if (a == b)
printf("a is equal to b\n");
else printf("a and b are not equal\n");
// not equal to
if (a != b)
printf("a is not equal to b\n");
else printf("a is equal b\n");
return 0;
}
Output:
a is greater than b
a is greater than or equal to b
a is greater than or equal to b
a is greater than b
a and b are not equal
a is not equal to b
Logical Operators:
They are used to combine two or more conditions/constraints or to complement the evaluation of
the original condition in consideration. They are described below:
Logical AND: The ‘&&’ operator returns true when both the conditions in consideration
are satisfied. Otherwise it returns false. For example, a && b returns true when both a
and b are true (i.e. non-zero).
Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in
consideration is satisfied. Otherwise it returns false. For example, a || b returns true if one
of a or b is true (i.e. non-zero). Of course, it returns true when both a and b are true.
Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied.
Otherwise it returns false. For example, !a returns true if a is false, i.e. when a=0.
int main()
{
int a=10, b=4, c = 10, d = 20;
// logical operators
return 0;
}
Output:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a=10, b=4;
bool res = ((a == b) &&printf("GeeksQuiz"));
return 0;
}
But below program prints “GeeksQuiz” as first operand of logical AND is true.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a=10, b=4;
bool res = ((a != b) &&printf("GeeksQuiz"));
return 0;
}
In case of logical OR, the second operand is not evaluated if first operand is true. For example,
program 1 below doesn’t print “GeeksQuiz” as the first operand of logical OR itself is true.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a=10, b=4;
bool res = ((a != b) || printf("GeeksQuiz"));
return 0;
}
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a=10, b=4;
bool res = ((a == b) || printf("GeeksQuiz"));
return 0;
}
| (bitwise OR)Takes two numbers as operands and does OR on every bit of two numbers. The
result of OR is 1 any of the two bits is 1.
^ (bitwise XOR) Takes two numbers as operands and does XOR on every bit of two numbers.
The result of XOR is 1 if the two bits are different.
<< (left shift)Takes two numbers, left shifts the bits of the first operand, the second operand
decides the number of places to shift.
>> (right shift)Takes two numbers, right shifts the bits of the first operand, the second operand
decides the number of places to shift.
#include<stdio.h>
intmain()
return0;
Output:
a = 5, b = 9
a&b = 1
a|b = 13
a^b = 12
~a = 250
b1 = 4
1) The left shift and right shift operators should not be used for negative numbersThe result
of is undefined behaviour if any of the operands is a negative number. For example results of
both -1 << 1 and 1 << -1 is undefined. Also, if the number is shifted more than the size of
integer, the behaviour is undefined. For example, 1 << 33 is undefined if integers are stored
using 32 bits. See this for more details.
2) The bitwise XOR operator is the most useful operator from technical interview
perspective. It is used in many problems. A simple example could be “Given a set of numbers
where all elements occur even number of times except one number, find the odd occurring
number” This problem can be efficiently solved by just doing XOR of all numbers.
intfindOdd(intarr[], intn) {
intres = 0, i;
res ^= arr[i];
returnres;
voidmain() {
intn = sizeof(arr)/sizeof(arr[0]);
return0;
intmain()
intx = 2, y = 5;
return0;
4) The left-shift and right-shift operators are equivalent to multiplication and division by 2
respectively.
As mentioned in point 1, it works only if numbers are positive.
intmain()
intx = 19;
return0;
// Output: 38 9
5) The & operator can be used to quickly check if a number is odd or even
The value of expression (x & 1) would be non-zero only if x is odd, otherwise the value would
be zero.
intmain()
intx = 19;
return0;
// Output: Odd
intmain()
unsigned intx = 1;
return0;
/* Output:
Signed Result -2
Operator precedence determines which operator is performed first in an expression with more
than one operators with different precedence. For example 10 + 20 * 30 is calculated as 10 + (20
* 30) and not as (10 + 20) * 30.
Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left. For example ‘*’ and ‘/’ have same
precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as
“(100 / 10) * 10”.
Precedence and Associativity are two characteristics of operators that determine the evaluation
order of subexpressions in absence of brackets.
1) Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single operator
are evaluated. For example consider the following program, associativity of the + operator is left
to right, but it doesn’t mean f1() is always called before f2(). The output of following program is
in-fact compiler dependent. See this for details.
// is compiler dependent.
intx = 0;
intf1() {
x = 5;
returnx;
intf2() {
x = 10;
returnx;
intmain() {
return0;
Expression
a+b
3.14*r*r
b*b-4*a*c
1) Expression Statements
2) Compound Statements
3) Control Statements
a=10;
a+=20;
printf(“Hello,Goodmorning!\n”);
display(a,b); /*A function call*/
c=a+b; /* An assignment statement*/
c+sum(a+b); /* A valid , but strange statement*/
; /*An empty or null statement*/
{
pi=3.14;
area=pi*radius*radius;
}
The particular compound statement consists of two assignment-type expression
statements.
Control Statements:Statements used to specify the flow of program control; ie, the order in
which the instructions in a program must be executed. It is possible to make decisions, to
perform tasks repeatedly or to jump from one section of code to another.
Sample Questions
Questions CO’s RBT
Levels
Define tokens in C with examples. CO1,CO2 L1
Explain all the operators present in C. CO1,CO2 L1
Define algorithm and write its uses. CO1,CO2 L1
Define flowchart. List its symbols with meaning. CO1,CO2 L1
Describe the different data types in C with CO1,CO2 L1
example of each
Define constant and its classification by giving CO1,CO2 L1
suitable example
Differentiate keyword and identifier with rules CO1,CO2 L1
and suitable examples.
Branching:
if (testExpression)
// statements
Statement x;
If the test expression is evaluated to true (nonzero), statements inside the body of if is executed.
If the test expression is evaluated to false (0), statements inside the body of if is skipped from execution
and control goes to statement x
Flowchart of if statement
.
#include<stdio.h>
void main()
{
int number;
Output 1:
Enter an integer: -2
Output 2:
Enter an integer: 5
Syntax of if...else
if (testExpression) {
else {
}
If test expression is true, codes inside the body of if statement is executed and, codes inside the body
of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes inside the body
of if statement is skipped.
#include<stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2==0)
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return0;
}
Output:1
Enter an integer: 7
7 is an odd integer.
When user enters 7, the test expression ( number%2 == 0 ) is evaluated to false. Hence, the
statement inside the body of else statement printf("%d is an odd integer"); is executed
and the statement inside the body of if is skipped.
Output:2
Enter an integer: 4
4 is an even integer.
#include<stdio.h>
int main()
{
int var1, var2;
printf("Input the value of var1:");
scanf("%d",&var1);
printf("Input the value of var2:");
scanf("%d",&var2);
if(var1 != var2)
{
printf("var1 is not equal to var2\n");
//Nested if else
if(var1 > var2)
{
printf("var1 is greater than var2\n");
}
else
{
printf("var2 is greater than var1\n");
}
}
else
{
printf("var1 is equal to var2\n");
}
return0;
}
Output:
if(condition1)
{
//These statements would execute if the condition1 is true
}
elseif(condition2)
{
//These statements would execute if the condition2 is true
}
elseif(condition3)
{
//These statements would execute if the condition3 is true
}
.
.
else
{
//These statements would execute if all the conditions return false.
}
#include<stdio.h>
#include<conio.h>
intmain(){
intmarks;
getch();
return(0);
}
Output
Enter your marks
96
YOUR GRADE : A
Enter your marks
75
YOUR GRADE : B
Enter your marks
60
YOUR GRADE : C
Enter your marks
35
YOUR GRADE : Failed
Cascaded if..else
A cascading if-else is a composite of if-else statements where the false path of outer if statement
is a nested if-else statement. The nesting can continue to several levels.
if ( expression )
statement
else
if (expression )
statement
else
if ( expression )
statement
else
statement
C switch...case Statement
The if..else..if ladder allows you to execute a block code among many alternatives. If you are
checking on the value of a single variable in if...else...if, it is better to use switchstatement.
The switch statement is often faster than nested if...else (not always)
Syntax of switch...case
switch (int_expr)
case constant1:
break;
case constant2:
break;
.
.
default:
When a case constant is found that matches the switch expression, control of the program passes to the
block of code associated with that case.
In the above pseudocode, suppose the value of n is equal to constant2. The compiler will execute the
block of code associate with the case statement until the end of switch block, or until the break statement
is encountered.
The break statement is used to prevent the code running into the next case.
switch Statement Flowchart
# include <stdio.h>
int main(){
charoperator;
doublefirstNumber,secondNumber;
switch(operator)
{
case'+':
printf("%.1lf + %.1lf = %.1lf",firstNumber,secondNumber,firstNumber+secondNumber);
break;
case'-':
printf("%.1lf - %.1lf = %.1lf",firstNumber,secondNumber,firstNumber-secondNumber);
break;
case'*':
printf("%.1lf * %.1lf = %.1lf",firstNumber,secondNumber,firstNumber*secondNumber);
break;
case'/':
printf("%.1lf / %.1lf = %.1lf",firstNumber,secondNumber,firstNumber/firstNumber);
break;
return0;
}
Output
12.4
he - operator entered by the user is stored in operator variable. And, two operands 32.5 and 12.4 are
stored in variables firstNumber and secondNumber respectively.
If break statement is not used, all cases after the correct case is executed.
C – goto statement
When a goto statement is encountered in a C program, the control jumps directly to the label mentioned in
the goto statement
gotolabel_name;
..
..
label_name: C-statements
Example of goto statement
#include<stdio.h>
int main()
{
int sum=0;
for(int i =0; i<=10; i++){
sum=sum+i;
if(i==5){
goto addition;
}
}
addition:
printf("%d", sum);
return0;
}
Output:
15
Explanation: In this example, we have a label addition and when the value of i (inside loop) is equal to 5
then we are jumping to this label using goto. This is reason the sum is displaying the sum of numbers till
5 even though the loop is set to run from 0 to 10.
It is sometimes desirable to skip some statements inside the loop or terminate the loop immediately
without checking the test expression.
break Statement
The break statement terminates the loop (for, while and do...while loop) immediately when it is
encountered. The break statement is used with decision making statement such as if...else. In C
programming, break statement is also used with switch...case statement.
Syntax of break statement
break;
# include <stdio.h>
void main()
{
int i;
double number, sum =0.0;
for(i=1; i <=10;++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
printf("Sum = %.2lf",sum);
}
Output
Enter a n4: -3
Sum = 10.30
Continue Statement
The continue statement skips some statements inside the loop. The continue statement is lso used with
decision making statement such as if...else.
continue;
Flowchart of continue Statement
How continue statement works?
# include <stdio.h>
int main()
{
int i;
double number, sum =0.0;
for(i=1; i <=10;++i)
{
printf("Enter a n%d: ",i);
scanf("%lf",&number);
printf("Sum = %.2lf",sum);
return0;
}
Output
Enter a n10: 12
Sum = 59.70
In the program, when the user enters positive number, the sum is calculated using sum +=
number; statement.
When the user enters negative number, the continue statement is executed and skips the negative
number from calculation.
A set of statements may have to be repeatedly executed for a specified number of times or till
a condition is satisfied. The statements that help us to execute a set of statements repeatedly
are called looping or repetitive or iterative statements.
while loop
for loop
do-while loop
any looping construct will have to perform 3 tasks namely initialization, condition checking and
incrementation. The difference between yhe three looping control constructs is the order in
which they perform the 3 tasks i.i (initialization, increment, condition checking)
It’s a pretest or entry controlled loop and hence the condition is evaluated first and body of the
loop is executed only if the condition is true. Its also a condition controlled or event controlled
loop.
Syntax
initialization;
while(condition)
Statement;
updation;
Statement;
Working
3. If the condition is evaluated to true then control enters the body of the loop and
executes the statements in the body.
4. Next updates the loop counter variable after which control goes back to the condition
check. If the condition is true, again the body is executed.
5. This process repeats as long as the condition evaluates to be true. Once, the condition
evaluates to be false, the control flows to the statement outside the body of the loop.
Example:
#include<stdio.H
void main()
int i;
i=0; /* initialization*/
printf(“%d\n”,i);
i++; /*updation*/
getch();
Note: study corresponding lab programs and the programs given in theory class.
for loop
Using this we can execute set of statements repeatedly for a specified number of times. So it’s
also called as counter controlled loop. It’s a pretest or top testing loop.
Syntax
Statements
working:
3. Condition is checked. If the condition evaluates to be true , then the control enter the
body of the loop. The statements in the body are executed.
4. Updation of the loop counter is performed. After which again the control goes back to
condition check. . If the condition is true, again the body is executed.
5. This process repeats as long as the condition evaluates to be true. Once, the condition
evaluates to be false, the control flows to the statement outside the body of the loop.
Example:
void main()
int i;
for(i=0;i<=10;i++)
printf(“%d\n”,i);
getch();
Note: study corresponding lab programs and the programs given in theory class.
Do-while:
It is post-test or bottom test loop and hence the body of the loop is executed first and then the
condition is checked.
Syntax:
Initialization;
do
statement;
updation;
statements
Working:
2. Then the statements inside the body of the loop are executed one after another
3. Updation is performed at the end of the body and then the condition is checked
4. If the condition is evaluated to be true, then the control re-enters the body and
executes the statements within the body
6. When the condition becomes false , the control comes out of the loop body.
Example:
#include<stdio.H
void main()
int i;
i=0; /* initialization*/
do
printf(“%d\n”,i);
i++; /*updation*/
getch();
Note: study corresponding lab programs and the programs given in theory class.
initialization; Initialization;
while(condition) do
{ {
Statement; statement;
updation; updation;
} }while(condition);
Statement; Statement;
3 It is pre-test loop and if the expression is It is post-test loop and the body of the
evaluated to false in the beginning itself, loop will be executed atleast once
then the statements within the body of the even if the condition is false.
loop will not be executed even once.
4 Example Example
i=0; i=0;
sum=0; sum=0;
while(i<=n) do
{ {
sum=sum+i; sum=sum+i;
i=i+1; i=i+1;
} } while(i<=n);
goto
break
continue
It’s a jump statement that transfers the control to the specified statement in a program. This is
an unconditional branch statement. Its identified by symbolic name ending with colon (:).
Syntax
goto label:
here
goto is a keyword
example
sum=0;
i=0;
top: sum=sum+i;
i++;
Disadvantage:
It’s a jump statement which can be used in switch statement and loops.
Working
1. In switch statement it causes control to terminate switch statement and statement
following switch statement will be executed.
2. If break is executed in loop(for, while, do-while), the control comes out of the loop and
the statement following the loop will be executed.
Note: if break appears in the inner loop of a nested loop, control only comes out of the inner
loop.
for(…………)
for(…………)
…………………..
if(error)
break;
………
………………………………
Continue statement:
Working:
On encountering continue statement , the rest of the statements within the body of the loop
are skipped and the conditional expression in the loop is executed.
Pictorial representation:
While(expression) do for(exp1;exp2;exp3)
{ { {
} } while(expression); }
Break Continue
3 Example: Example:
for(i=1;i<=5;i++) for(i=1;i<=5;i++)
{ {
if(i==3) if(i==3)
break; continue;
printf(“%d\t”,i) printf(“%d\t”,i)
} }
Output: Output:
12 1245
Nested loops:
for( ; ; )
…………
for( ; ; )
……………….
SAMPLE QUESTIONS
Questions CO’S RBT
Levels
Explain in brief the simple if, if-else and CO2,CO3 L2
nested if-else statement with example
Explain the concept of For, While and CO2,CO3 L2
Do-While loops with example.
Explain switch-case statement with CO2,CO3 L2
syntax
Discuss break and continue statements CO2,CO3 L2
with an example.
Discuss for loop with syntax and an CO2,CO3 L2
example
Apply conditional operator into a CO2,CO3 L3
suitable program
Develop a Flowchart & write an CO2,CO3 L3
Algorithm to swap three numbers
Illustrate conditional operator with CO2,CO3 L3
syntax and a suitable programming
example.
With example explain the while and do- CO2,CO3 L4
while loop, and justify your opinion
which one is best with one scenario
Analogy: CO2,CO3 L4
Student is categorized based on the
marks they secured in the CIE, the
analogy is show below:
Marks>=75 Distinction
Marks >=60 and <75 First Class
Marks >=50 and <60 Second Class
Marks >=40 and <50 Third Class
Marks <40 Fail
Design a flow chart for above scenario
with proper message and flow.
Design a flowchart and pseudo code to CO2,CO3 L6
find sum of ‘n’ natural number without
using any looping statement.
Design a Flowchart & write an Algorithm CO2,CO3 L6
to swap three numbers
Explain switch-case statement in C with CO2,CO3 L6
an example.
Write an algorithm to find roots of a CO2,CO3 L6
quadratic equation.
Design a Flowchart to find the result of a CO2,CO3 L6
student as distinction, first class, pass,
fail and absent.
Write a C program to find whether a CO2,CO3 L6
given year is leap year or not.
Write a C program to find the sum of 1st CO2,CO3 L6
100 numbers
Write a C program to find the given CO2,CO3 L6
triangle is equilateral, isosceles or
scalene.
What is the output of the following CO2,CO3 L6
program
#include <stdio.h>
void main()
{
inti = 0;
for (i = 0;i < 5; i++)
if (i< 4)
{
printf("Hello");
break;
}
}
Write a program to find whether a given CO2,CO3 L6
number is even or odd
#include<stdio.h>
void main()
Int i = 0;
if (i> 4)
printf(“Hello”);
break;
}
}
1 2
1 2 3
1 2 3 4
Module 3
Arrays, Strings AndFunctions
What is function?
A large program can be divided into manageable pieces called modules where each module
does a specific task. Each module is called as function. It’s a self contained small program called
program segment that carry out some specific, well-defined task.
Library functions
The functions written by the manufacturers of c compilers are called library functions. The
implementation details of these functions are not known to the programmers. The library
functions are also called as predefined or built -in or in- built or standard library functions. C
library has a collection of various functions which perform standard and pre-defined tasks.
These functions are ready to be used in our program.
#include<stdio.h>
#include<math.h>
void main()
floats,n;
scanf(“%d”,&n);
s=sqrt(n);
printf(“Squareroot=%d\n”,s);
Note: declaration of printf and scanf are available in stdio.h and declaration of sqrt is available
in math.h header file.
main() is a user defined function, it controls and coordinates all the activities by executing each
statements in sequence.
A function that is invoked by writing the name of the function is called “called function” and the
invoking function is called “calling function”.
In the above example, main() is calling function and sqrt() is called function
Advantage:
The programmer’s job is made easier because, the functions are already available.
It reduces program development time.
Disadvantage:
They are limited in number, programmer cannot completely rely on these library functions.
The functions written by the user/programmer to do the specific tasks are called user defined
functions. They are also called as programmer defined functions.
Function definition
Function call
Function declaration
Function definition
The program module that is written to achieve a specific task is called function definition. Each
function definition consists of two parts:
Function header: consisting of datatype of the value returned by the function, the name
of the function and parameters.
Function body: consisting of set of statements to do the specific task.
Syntax:
Declaration part;
Executable part;
Return statement;
Example:
int sum;
return sum;
Function header:
It consists of 3 parts.
Return type: this is the data type of the value that the function is expected to return.
The data type can be int, float, char, double, void etc.. (any valid C data type)
Function name: it’s the name of the function. It can be any valid identifier.
Parameters: these are list of variables enclosed within parentheses. All these variables
should be separately declared and each declaration should be separated by comma.
Function body:
The compound statement immediately following the function header is function body. It
consists of 3 elements.
Declaration: all the variables used in the function body should be declared in the
declaration part. But, the variables used in the function header should not be declared
again.
Executable part: this part contains statements or instructions that perform the specified
activity.
return: it’s a keyword. It’s used to return control to the calling function with/without a
value.
Note: if the function is not returning any value, then we need to specify the return type as void.
If return type is not explicitly written, it’s assumed that return type is integer. So, integer is the
default return value.
Function declaration
The function should be declared before they are used. This process of declaring the functions
before they are used is called function prototype or function declaration.
Function declaration contains only the function header but terminated with semi colon. It
informs the compiler about
Syntax:
type function-name(type p1, type p2, ……… type pn); /*semi colon is must*/
where
type – is type of the value returned from the function such as void, int, float etc.
p1,p2,……….pn – are parameters. All the parameters have to be separately declared and each
declaration should be separated by comma.
Function calls
The method of calling a function to achieve a specified task is called function call. The function
can be called by writing the name of the function and passing appropriate number of
arguments. The number and the type of the argument in function call should match the number
and type of the parameters in function definition.
#include<stdio.h>
void main()
int result;
printf(“sum=%d\n”,result);
returna+b;
Rules:
The number of arguments in the function call must be equal to the number of
parameters in function prototype and header.
The type of the arguments arguments in the function call must be equal to the type of
parameters in function prototype and header.
A void function doesn’t return a value. So, when a function is called , it can’t be used in
an expression or print statement. It can be used only as statement.
If function return type is void, then it should not return any value. It results in syntax
error.
Function can return at most one value
The variables defined in the function header of function definition are called formal
parameters. All the variables must be separately declared and each declaration must be
separated by commas. The formal parameters receive data from actual parameters.
Actual parameters/arguments
The variables that are used in function call are called actual parameters. Using actual
parameters, the data can be transferred to the function. The corresponding formal parameters
in the function definition receive them. The actual parameter and formal parameter should
match in number and type of data.
Categories of functions
Based on the parameters and return value, the functions are categorized as follows:
This category is called “void function with no parameters”. There is no data transfer between
the calling function and called function. So, calling function cannot send values and called
function cannot receive the data.
#include<stdio.h>
void add();
void main()
{
void add()
inta,b,c;
scanf(“%d%d”,&a,&b);
c=a+b;
printf(“sum=%d\n”,c);
This is called “void functions with parameters”. There is a data transfer from the calling function
to the called function using parameters. But, no data transfer from called function to the calling
function.
#include<stdio.h>
void main()
inta,b;
scanf(“%d%d”,&a,&b);
int z;
z=x+y;
printf(“sum=%d\n”,z);
There is no data transfer from the calling function to the called function. But, there is data
transfer from called function to the calling function. When the function returns a value, the
calling function receives one value from the called function.
#include<stdio.h>
int add();
void main()
int z;
z=add(); /*no arguments passed returned value will be saved in variable z*/
printf(“sum=%d\n”,z);
int add()
inta,b,c;
c=a+b;
There is data transfer between calling and called function. When parameters are passed, the
called function can receive values from the calling function. When the function returns a value,
the calling function can receive a value from the called function.
#include<stdio.h>
void main()
inta,b,c;
scanf(“%d%d”,&a,&b);
c=add(a,b); /*two arguments are passed to the called function and result stored in c*/
printf(“sum=%d\n”,c);
int z;
z=x+y;
return z;
}
Pass by value
Here, the values of actual parameters are copied into formal parameters i.e., formal
parameters contain only the copy of actual parameters. So, even if the values of the formal
parameters changes in the called function, the values of the actual parameters are not
changed.
Advantage:
Disadvantage:
It does not allow information to be transferred back to calling function via arguments.
#include<stdio.h>
void main()
int a=10,b=20;
exchange(a,b);
printf(“a=%d\nb=%d\n”,a,b);
void exchange(intm,int n)
{
int temp;
temp=m;
m=n;
n=temp;
Output:
a=10
b=20
Working:
Execution starts from main() and the variables a and b are assigned the values 10 and 20
respectively.
The function exchange() is called with actual parameter a and b whose values are 10,20
In exchange() function, the formal parameter m and n receive 10 and 20 repectively.
The values of m and n are exchanged here.
But, the values of actual parameters a and b in function main() have not been
exchanged.
Pass by address
Here, when the function is called, the addresses of actual parameters are sent. In the called
function, the formal parameters should be declared as pointers with the same type as the
actual parameters. The addresses of actual parameter are copied to formal parameter. Using
these addresses, the values of the actual parameters can be changed. This way of changing the
actual parameters indirectly using its address is called pass by address.
#include<stdio.h>
void main()
int a=10,b=20;
exchange(&a,&b);
printf(“a=%d\nb=%d\n”,a,b);
int temp;
temp=*m;
*m=*n;
*n=temp;
Output:
a=20
b=10
Working:
Execution starts from main() and variables a and b are assigned 10 and 20 respectively
The function exchange() is called by sending the address of a and b.
In function exchange(), the formal parameters m and n declared using * to hold the
addresses of a and b
Using *m and *n we can access the values of a and b and they are exchanged.
When control comes to the calling function, the values of a and b have been exchanged.
Recursion
Calling a same function again and again until some termination conditions are satisfied is called
recursion. Recursive function should contain base case and general case. While designing
recursive function decide about the base case and general case carefully, it should not generate
infinite loop.
Base case is a special case where the solution can be obtained without using the recursion. It is
also called as terminal condition. Each recursive function must have a base case. A base case
serves two purposes:
It acts as terminating condition
The recursive function obtains the solution from the base case it reaches.
General casethis portion of the code contains the logic required to reduce the size of the
problem so as to move towards the base case or terminal condition. Here, each time the
function is called, the size of the problem is reduced.
Ex:
/*factorial of a number*/
#include<stdio.h>
void main()
intn,res;
scanf(“%d”,&n);
res=fact(n);
printf(“factorial=%d\n”,res);
getch();
int fact(int m)
return 1;
else
}
Arrays
An array is a collection of similar data items. All elements of the array share a common name.
Each element in the array is identified by the subscript (index).
It’s also called as one dimensional array. It’s a linear list consisting of related data items of same
type. In memory, all data elements are stored in contiguous memory locations one after the
other.
2 5 10 50 34 21
Since array is identified by a common name any element in the array can be accessed by
specifying its index or subscript. Index gives the position of an element in the array.
Arrays must be declared and defined before it is used. The declaration informs the compiler
about the:
Syntax:
Data_typearray_name[int expression];
Ex: inta[10];
Here a is an array of 10 integers.
Rules:
Assigning values to a variable before processing is called initialization. Array elements can be
initialized at the time of declaration.
Syntax:
Type array_name[expression]={v1,v2,v3,…………vn};
Where
Ex:
int a[6]={10,15,20,25,30};
10 15 20 25 30 35
int a[5]={10,15};
10 15 0 0 0
int a[]={10,20,30,40,50};
10 20 30 40 50
The compiler will calculate the size of the array based on the number of initial values. Here the
size is 5.
scanf(“%d”,&a[i]);
printf(“%d\n”,a[i]);
Ex:/*program to read n items from the keyboard and display it on the monitor*/
#include<stdio.h>
void main()
scanf(“%d”,&n);
for(i=0;i<n;i++)
scanf(“%d”,&a[i]);
printf(“%d\n”, a[i]);
getch();
Individual array elements can be passed to a function like any other variable. But,
The type of array element passed to the function and the type of parameter in the
corresponding function definition should be same.
The array element is passed as a value parameter i.e., any change in the formal
parameter will not affect the actual parameter i.e.,array element.
Ex: /* passing individual array element to afunction and print its square*/
#include<stdio.h>
void main()
scanf(“%d”,&n);
scanf(“%d”,&a[i]);
getch();
void print_square(int x)
printf(“%d”,x*x);
Passing whole array to a function is similar to pass by reference. Any change made to the array
in the called function will reflect to the original array.
#include<stdio.h>
void main()
int a[5]={10,20,30,40,50};
reverse(a);
printf(“%d\t”,a[i]);
b[0]=50, b[1]=40,b[2]=30,b[3]=20,b[4]=10;
Output:
50 40 30 20 10
Note: in the above program, the parameter b is an array, any change in array b will have the
corresponding changes in array a.
Searching
Process of finding a particular item in the large amount of data is called searching. There are 2
searching techniques.
Linear search
Binary search
Linear search: it’s also called as sequential search. Here, we search for a given element in the
list in linear order i.e., one after the other from first element to last element or vice versa. If the
element is present, we say search is successful, otherwise, search is unsuccessful.
#include<stdio.h>
void main()
int a[5],n,i,key,found=0;
scanf(“%d”,&n);
for(i=0; i<n;i++)
scanf(“%d”,&a[i]);
scanf(“%d”,&key);
found=1;
break;
if(found==1)
else
getch();
Advantage:
Disadvantage:
Binary search: This technique can be applied if the array elements are sorted.
Working:
Initialize position of the first element to variable low and position of last element to
variable high. i.e., low=0 and high=n-1
Using above initial values obtain the position of middle element as mid=(low+high)/2
The key to be searched is compared with middle element. If the key is same as middle
element, then element found and stop searching process. If key is not same as middle
element, it may be present in the left part or right part of the array.
If key is less than the middle element, then left part of the array has to be compared
from low to mid-1. So change upper bound as high=mid-1
If key is greater than the middle element, then right part of the array has to be
compared from mid+1 to high. So change lower bound as low=mid+1
The above 4 steps has to be repeatedly executed as long as low is less than or equal to high.
Finally, when the value of low exceeds the value of high indicates that key is not present in the
array.
#include<stdio.h>
void main()
int a[5],n,i,key,found=0,low,high;
scanf(“%d”,&n);
for(i=0; i<n;i++)
scanf(“%d”,&a[i]);
scanf(“%d”,&key);
low=0;
high=n-1;
found=1;
break;
else if(key>a[mid])
low=mid+1;
else
high=mid-1;
if(found==1)
else
getch();
Advantage
Simple technique
Very efficient searching technique
Disadvantage
Sorting
It is the process of arranging the random numbers either in the ascending order or in the
descending order. There are many different sorting techniques such as bubble sort, selection
sort, merge sort etc.
Bubble sort
Here, compare the adjacent elements. If the number to the left is greater than the number to
the right, then exchange them. If the number to the left is not greater than the number to the
right, then don’t exchange them. At the end of each pass largest element will be in its sorted
position. This is also called as sinking sort.
/*bubble sort*/
#include<stdio.h>
#include<conio.h>
void main()
{
inti,j,n,a[20],temp;
clrscr();
printf("Enter the size: ");
scanf("%d",&n);
printf("Enter %d numbers \n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{ for(j=0;j<n-i;j++)
{ if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("\nThe sorted array is \n");
for(i=0;i<n;i++)
printf("%d \n",a[i]);
getch();
}
Advantage
Disadvantage
Less efficient
It requires n-1 passes even if the elements are sorted
Declaration of 2D array
Syntax
Data_typearray_name[exp1][exp2];
Where
Ex:
int a[10][20];
the array a is an integer array with 10 rows and 20 coloumns. it reserves 10*20=200 locations
contiguously one after the other.
Initialization
Data_typearray_name[exp1][exp2]={
{a1,a2,……………an},
{b1,b2, ………….bn},
…………………………….
……………………………..
{z1,z2,……………….zn}
};
Where
Data-type can be int,floatetc
Exp1 and exp2 are row and column numbers respectively
A1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2 nd row
and so on.
Ex:
inta[4][3]={
{11,22,33},
{44,55,66},
{77,88,99},
{10,11,12},
};
Pictorial representation of above initialization is as shown below
columns
0 1 2
11 22 33
44 55 66
rows
77 88 99
10 11 12
0
1
2
3
Partial array initialization: if the numbers of values to be initialized are less than the size of the
array, then the elements are initialized from left to right one after the other. The remaining
locations will be initialized to zero automatically.
{33,44},
{55,66},
{77,88}
};
scanf(“%d”,&a[i][j]);
scanf(“%d”,&a[j][i]);
}
}
Printing(writing) matrix
printf(“%d\t”,a[i][j]);
Printf(“\n”);
Example programs
#include<stdio.h>
void main()
int a[10][10],b[10][10],c[10][10],m,n,i,j;
scanf(“%d%d”,&m,&n);
scanf(“%d”,&a[i][j]);
scanf(“%d”,&b[i][j]);
c[i][j]=a[i][j]+b[i][j];
printf(“%d\t”,c[i][j]);
printf(“\n”);
getch();
/*matrix multiplication*/
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10]={0};
intm,n,p,q,i,j,k;
clrscr();
printf("\n Enter the order of the matrix A :");
scanf("%d%d",&m,&n);
printf("\n Enter the order of the matrix B :");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("multiplication not possible\n");
getch();
exit(0);
}
printf("\n Enter the elements of matrix A in row major order\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("\n Enter the elements of matrix B in column major order \n");
for(i=0;i<q;i++)
{
for(j=0;j<p;j++)
{
scanf("%d",&b[j][i]);
}
}
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
for(k=0;k<n;k++)
{
c[i][j]=c[i][j]+ a[i][k] * b[k][j];
}
}
}
printf("\n MATRIX A \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < n ; j++)
{
printf(" %d \t", a[i][j]);
}
printf("\n");
}
printf("\n MATRIX B \n");
for(i = 0 ; i< p ; i++)
{
for(j = 0 ; j < q ; j++)
{
printf(" %d \t", b[i][j]);
}
printf("\n");
}
printf("\n MATRIX C \n");
for(i = 0 ; i< m ; i++)
{
for(j = 0 ; j < q ; j++)
{
printf(" %d \t", c[i][j]);
}
printf("\n");
}
getch();
}
#include<stdio.h>
void main()
int a[10][10],b[10][10],m,n,i,j;
scanf(“%d%d”,&m,&n);
scanf(“%d”,&a[i][j]);
}
b[j][i]=a[i][j];
printf(“%d\t”,b[i][j]);
printf(“\n”);
getch();
Strings
A string is an array of characters terminated by NULL character which is denoted by the escape
sequence ‘\0’.
V T U \0
char a[20];
the string variable a can hold maximum of 20 characters including null character.
String initialization
Working
If white spaces are present before the string, then they are removed from the keyboard
buffer
All nonwhite space characters are copied into the array till it finds another white space.
Then the copied string is terminated by ‘\0’. Remaining characters are left in the
keyboard buffer.
char s1[15];
scanf(”%s”,s1);
printf(%s\n”,s1);
The gets() function used to read a string. It allows us to read al the characters including
whitespace into an array. It stops on pressing ENTER key and appends null character to a string.
Syntax:
gets(str);
the puts() function takes string as a parameter and displays its content on the monitor and
prints newline character.
puts(str);
#include<stdio.h>
void main()
{
charstr[50];
printf(“enter a string\n”);
gets(str);
puts(str);
Arrays of strings
Syntax:
0
1 char a[row][col];
2 where,
row------>number of strings
4 col-------> maximum length of each string
above array a can contain at most 5 strings with each string can have at most 20 characters.
char a[4][10]={“ANU”,
“BHANU”,
“DHANYA”,
“MADHU”};
Memory representation
0 1 2 3 4 5 6 7 8 9
A N U \0
B H A N U \0
D H A N Y A \0
M A D H U \0
for(i=0;i<n;i++) /*reading*/
scanf(“%s”,a[i]);
for(i=0;i<n;i++) /*writing*/
printnf(“%s\n”,a[i]);
strlen(str)
This function returns the length of the string str i.e., it counts all the characters up to ‘\0’ except
\0. So, an empty string has length zero.
#include<stdio.h>
#include<string.h>
void main()
char s[]=”hello”;
getch();
Output
#include<stdio.h>
void main()
char s[]=”hello”;
inti=0;
while(s[i]!=’\0’)
i++;
printf(“length=%d\n”,i);
getch();
Output
length=5
strcpy(dest,src)
Copies the contents of source string src to destination string dest including ‘\0’. So, the size of
destination string dest should be greater or equal to the size of source string src. After copying,
the original contents of destination string dest are lost.
#include<stdio.h>
#include<string.h>
void main()
char s1[]=”hello”;
char s2[10];
strcpy(s2,s1);
getch();
Output
#include<stdio.h>
#include<string.h>
void main()
inti;
gets(s1);
i=0;
while(s1[i]!=’\0’)
s2[i]=s1[i];
i++;
s2[i]=’\0’;
getch();
Output
hello
strncpy(dest,src,n);
Working
If source string is less than n, the entire string is copied from source to destination and
then null character is placed at the end.
If the source string src is longer than n characters, only n characters are copied into
destination. Then, the destination string will not have a delimiter ‘\0’ and hence it will
be invalid string.
Ex:
char s1[10];
char s2[8]=”VTU123”;
strncpy(s1,s2,5);
before copying
s1
0 1 2 3 4 5 6 7 8 9
And s2
V T U 1 2 3 \0
0 1 2 3 4 5 6 7
After copying
s1
V T U 1 2 \0
0 1 2 3 4 5 6 7 8 9
And s2
V T U 1 2 3 \0
0 1 2 3 4 5 6 7
strcat(str1,str2)
This function copies all the characters of string str2 to the end of string str1. The delimiter of
string str1 is replaced by the first character of str2. The size of str1 should be large enough to
store a string whose length is str1+str2.
Str1
h i
Str2
h e l l o
afterstrcat
Str1
h i h e l l o \0
Str2
h e l l o
Sample Questions
Questions CO’s RBT
Level
How functions are categorized. Explain with C02,CO3 L3
an example.
Explain the characteristics of 2-Dimensional CO3 L2
array with an example
Describe any 3 string handling function with C02,CO3 L1
an example.
Explain with an example how arrays can be CO3 L2
passed into a function
What are the characteristics of recursive C02,CO3 L4
function? Explain with an example
What are arrays? Classify the declaration of CO3 L4
one dimensional and 2 dimensional array.
Classify function declaration, function CO3 L4
definition and calling function with
example.
Classify string manipulation library function CO2, L4
and explain them with example CO3, CO5
Compare the working of recursion in a C CO3 L5
program with example.
Develop a C program to search an element CO3 L6
using linear search
Develop a C program to search an element CO3 L6
using binary search
Develop a C program to arrange elements CO2, L6
in descending order using bubble sort CO3, CO5
Write a program to print the sum of CO2, L6
CO3, CO5
positive and negative numbers and return
average value
Write a program to find the Fibonacci series CO2, L6
using arrays CO3, CO5
Write a program to find the smallest CO2, L6
element in an array CO3, CO5
Develop a C program to perform addition of CO2, L6
2 matrices CO3, CO5
Develop a C program to perform product of CO2, CO3 L6
2 matrices
Develop a C program to implement CO2, CO3 L6
STRCOPY operation that copies one sting
STR1 to another string STR2 without using
library function
Develop a C program to find the Number of CO2, CO3 L6
Vowels, Consonants, Digits and White
space in a String
Write a program to concatenate 2 strings CO2, CO3 L6
Write a program to find the length of the CO2, CO3 L6
given string
Write a program to reverse a given string CO2, CO3 L6
Write a program to find prime and CO2, CO3 L6
Armstrong number using functions
Write a program to find the factorial using CO2, CO3 L6
recursion
Module 4
Structures and file management
The type definition
The typedef is a keyword that allows the programmer to create a new datatype name for an
already existing data type. i.e it redefines the name of an existing data type.
Syntax:
here MARKS & ID_NUMBER are called user defined data types.
MARKS sub1,sub2,sub3;
Advantage:
Example program:
#include<stdio.h>
typedef float
AMOUNT; typedef
float TIME; typedef
float RATE; void main()
{
AMOUNT p,si;
TIME t;
RATE r;
printf(“Enter p,t,r\n”);
scanf(“%f%f%f”,&p,&t,&r);
Page 1
si=p*t*r/100;
printf(“Simple interest=%f\n”,si);
}
STRUCTURES
Structures:
A structure is a collection of one or more variables of same data type or dissimilar data types,
grouped together under a single name.
Example: A student information to be grouped may consists of Name of the student University
number Average marks
struct tagname
Type1 member1;
Type2 member2;
};
Where struct is a keyword which tells the compiler that structure is being defined
Tagname is the name of the structure
Variables in a structure such as member1,member 2 are called as the members of the
structure of fields of the structure.
Members can be int,float,char etc..
There should be semicolon at the end of the closing brace.
Note:
The structure definition does not reserve any space in memory for the members. It is just a
template.
Structure Declaration:
Page 2
Tagged structure:
Synatx:
struct tagname
{
Type1 member1;
Type2 member2;
};
Example:
struct student
{
char name[10];
int usn, marks;
};
Student is the name of the structure(tag name)
Struct student together represent the data type.
To allocate memory for structure ,variables must be declared.
Example:
Once the variable are declared , memory for the variables s1 amd s2 are allocated. The number
of bytes allocated for the variables s1 and s2 are 14 bytes respectively
The total size of the memory allocated is the sum of sizes of individual members.
Syntax:
struct
{
Type1 member1;
Type2 member2;
Page 3
}v1,v2…vn;
Example:
struct
{
char name[10];
int usn,marks;
}s1,s2;
In the absense of tag name, immediately after the right brace we have to declare the
variables.
Type-defined structure:
The structure definition associated with the keyword typedef is called typedefined structure
Syntax:
typedef struct
{
Type1 member1;
Type2 member2;
}TYPE_ID;
EXAMPLE:
typedef struct
{
char name[10];
int usn,marks;
}STUDENT;
Struct and typedef are keywords.
STUDENT is the new data type created using typedef which can be used for the variable
declaration.
TYPE_ID v1,v2..vn;
Example:
STUDENT s1,s2;
Structure initialization:
Syntax:
Page 4
Where struct tagname is derived data type
Example:
struct student
{
char name[10];
int usn, marks;
}s1={“ram”,10,90};
(or)
struct student
{
char name[10];
int usn, marks;
};
struct student s1={“ram”,10,90};
(or)
struct student
{
char name[10];
int usn,marks;
} s1={“ram”,10,90},s2={“bheem”,11,99};
Accessing structures:
The member of the structure can be accessed by specifying the variable name followed by a
period(.) followed by the member name
Syntax:
Variable.member
Example:
struct student
{
char name[10];
int usn,marks;
} s1={“ram”,10,90};
The members can be accessed as follows:
Page 5
By specifying S1.marks, we can access 90.
NESTED STRUCTURES:
A structure which includes another strucure is called as nested structure(i.e) a structure can be
used a member of another structure.
Example:
struct subject
{
int marks1;
int marks2;
int marks3;
};
typedef struct
{
char name[10];
int usn;
struct subject marks;
}STUDENT;
The above structure consists of a member marks whose type is struct subject(another
structure). So this is called as nested structure.
STUDENT s;
s.name;
s.usn;
s.marks.marks1;
s.marks.marks2;
s.marks.marks3;
A single or multi dimensional array of int, float,char and double can be used within the structure
Syntax:
Typedef struct
{
Char name[10];
Int marks[3];
}STUDENT;
Page 6
Delcaring structure variable
STUDENT S;
Accessing members:
S.name;
s.marks[0];
s.marks[1];
s.marks[2];
ARRAY OF STRUCTURES:
Example:
Suppose we want to store the details of 50 students consisting of name and marks
typedef struct
{
char name[20];
int marks;
}STUDENT;
We can declare an array of structures as follows
STUDENT s[50];
The structure or structure members can be passed to the function in various ways
struct student
{
char name[50];
Page 7
int usn;
};
void disp(char name[ ],int usn);------ function prototype
void main()
{
struct student s1;
printf(“Enter name and usn\n”);
scanf(“%s%d”,s1.name,&s1.usn);
disp(s1.name,s1.usn);----- function
call getch();
}
void disp(char name[ ],int usn)-- function definition
{
Printf(“name=%s\n”,name);
Printf(“usn=%d\n”,usn);
}
Explanation:
In the above example , function disp is called by passing individual member of the structure to
the user-defined function. In the user-defined function, formal parameters are created to
receive the value of name and usn from the actual paramters.
struct student
{
char name[50];
int usn;
};
void disp(struct student stu);------ function prototype
void main()
{
struct student s1;
printf(“Enter name and usn\n”);
scanf(“%s%d”,s1.name,&s1.usn);
disp(s1);----- function call
getch();
}
void disp(struct student stu)-- function definition
Page 8
{
Printf(“name=%s\n”,stu.name);
Printf(“usn=%d\n”,stu.usn);
}
Explanation:
In the above example, function disp is called by passing whole the structure to the user-
defined function. In the user-defined function, formal parameter is declared is of type
structure to receive the value of the actual parameter.
FILES
If you want to store the data in a file in the secondary memory we must specify certain things
about the file to the os.
File name
Data structure
Purpose
File name:
File name is a string of characters that make up a valid file name for the operating system
It may contain 2 parts, a primary name and an optional period with the extension
Example:
Prog.c
Data.txt
Output.c
Data strucuture:
Data structure of a file is defined as a structure FILE in stdio.h. Therefore all files should
be declared as type FILE before they are used.
When we open a file we must specify what we want ot do with the file(i.e) we may write
data to the file or read the already existing data .
The first statement declares the variable fp as a pointer to the datatype FILE
Page 9
The second statement opens the named file and assigns an identifier to FILE pointer fp. This
pointer contains all the information about the file.
The second parameter specifies the purpose of opening the file. Mode can be
r open the file for reading only
w open the file for writing only
a open the file for appending data
a. When the mode is ‘writing’ , a file with the specified name is created if the file doesn’t
exists. The contents are deleted if the file already exists.
b. When the purpose is appending , the file opened with the current content safe. A file
with the specified name is created if the file doesn’t exists.
c. When the purpose is reading and if exists, then the file is opened with the current
content safe, otherwise an error occurs.
FILE *P1,*P2,*P3;
P1=fopen(“ABC.TXT”,”r”);
P2=fopen(“xyz.c”,”w”);
P3=fopen(“pgm1.c”,”a”);
CLOSING A FILE:
A file must be closed all operations on it have been completed. It prevents any accidental
misuse of a file.
Synatx:
fclose(filepointer);
These functions are identical to printf and scanf except that they work on files.
Syntax:
fprintf(fp,”control string”,list);
fscanf(fp,”control string”,list);
Page 10
In both the functions, the first parameter is a file pointer which specifies which file has to be
used here. The second parameter contains format specifier for the items in the list. The third
parameter list can be a variable, constant or string.
Example :
Copying the content of a file containing name and roll no to another file.
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
char name[10];
int rollno;
fp1=fopen(“file1.txt”,”r”);
fp2=fopen(“file2.txt”,”w”);
fscanf(fp1,”%s%d”,name,&rollno);
fprintf(fp2,” ,”%s\t%d\n”,name,rollno);
getch();
}
These functions are used to read & write a string of character from and to file.
Syntax of fgets:
ps=fgets(str,n,fp);
fp is a file pointer
If this function is successful, it returns pointer to the string read in. Otherwise it returns NULL.
It reads n-1 character or a newline which ever comes first.If it reads a new line, it retains it as
a part of the string and appends a null character. If it does not read a new line then it reads n-
1 characters and appends null character at the end.
Example:
Page 11
Program to read a line from file
#include<stdio.h>
void main()
{
FILE *fp;
char str[15];
char *ps;
fp=fopen(“input.dat”,”r”);
ps=fgets(str,10,fp);
if(ps!=NULL)
{
puts(str);
}
else
printf(“unsuccessfulreading”);
}
Syntax of fputs:
Fputs(str,fp);
Str string to be written to a file pointed by fp.It doesn’t automatically writes a new line to file.If
its present then only it writes.
Example:
void main()
{
FILE *fp;
char str[15];
char *ps;
printf(“enter the string\n”);
gets(str);
fp=fopen(“file.txt”,”w”);
fputs(str,fp);
fclose(fp);
}
fgetc and fputc():
Syntax:
Page 12
fputc(c,fp1);
C=fgetc(fp1);
Example:
void main()
{
FILE *fp1,*fp2;
char c;
fp1=fopen(“f1.txt”,”r”);
fp2=fopen(“f2.txt”,”w”);
c=fgetc(fp1);
fputc(c,fp2);
}
MODULE 5:
Array: Array is collection of similar data type, you can insert and
deleted element form array without follow any order.
Stack: Stack work on the basis of Last-In-First-Out (LIFO). Last entered
element removed first.
Queue: Queue work on the basis of First-In-First-Out (FIFO). First
entered element removed first.
Linked List: Linked list is the collection of node, Here you can insert
and delete data in any order.
Tree: Stores data in a non linear form with one root node and sub
nodes.
void main()
{
inti,a[5],no,pos;
clrscr();
printf("Enter element in array: ");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("\nStored element in array: ");
for(i=0;i<5;i++)
{
printf(" %d",a[i]);
}
printf("\nEnter position for enter element: ");
scanf("%d",&pos);
if(pos>5)
{
printf("\nThis is out of range");
}
else
{
printf("\nEnter new element: ");
scanf("%d",&no);
--pos;
for(i=5;i>=pos;i--)
{
a[i+1]=a[i];
}
a[pos]=no;
printf("\nStored data in array: ");
for(i=0;i<6;i++)
{
printf(" %d",a[i]);
}
}
getch();
}
Output
Enter elements in array:4
4
2
5
7
Stored data in array:4257
Enter position for enter element:2
Enternew element:8
Stored data in array:42578
#include <stdio.h>
void main()
{
intvectorx[10];
int i, n,pos, element, found =0;
if(found ==1)
{
for(i =pos; i < n -1; i++)
{
vectorx[i]=vectorx[i +1];
}
}
else
printf("Element %d is not found in the vector\n", element);
Program Explanation
5.1.2 Queue in C
Ticket Counter: First person get ticket first and go out first
Queues are used for any situation where you want to efficiently maintain a
First-in-first out order on some entities. Transport and operations research
where various entities are stored and held to be processed later i.e the queue
performs the function of a buffer.
In a multitasking operating system, the CPU cannot run all jobs at once, so jobs
must be batched up and then scheduled according to some policy. Again, a
queue might be a suitable option in this case.
Operation on a queue
In queue insert any element form Rear. If you insert new element in queue
value of Rear will be increased by 1.
void insert()
{
int item;
printf("Element : ");
scanf("%d",&item);
if(front==(rear+1)%3)
{
printf("Queue is Full");
return;
}
if(front==-1)
{
rear=front=0;
}
else
{
rear=(rear+1)%3;
}
cque.cqueue[rear]=item;
printf("Successfully Insert");
}
Delete any element from the queue.
In queue delete an element form Front. If you delete an element from queue
value of Front will be increased by 1.
voiddel()
{
intnum;
if(front==-1)
{
printf("Queue Empty");
return;
}
else
{
num=cque.cqueue[front];
printf("Deleted item : %d",num);
}
if(front==rear)
{
front=-1;
}
else
front=(front+1)%3;
}
Example of Queue
#include<stdio.h>
#include<conio.h>
void insert();
voiddel();
void display();
structcirc
{
intcqueue[5];
};
structcirccque;
int rear=0,front=-1;
void main()
{
while(1)
{
intnum;
clrscr();
printf("1.Insertion\n2.Deletion\n3.Display\n0.Exit\n");
printf("\n\nSelect Option : ");
scanf("%d",&num);
switch(num)
{
case1:
insert();
break;
case2:
del();
break;
case3:
display();
break;
case0:
exit(0);
break;
default:
printf("\n\n Invalid Option ");
}
getch();
}
}
void insert()
{
int item;
printf("Element : ");
scanf("%d",&item);
if(front==(rear+1)%3)
{
printf("Queue is Full");
return;
}
if(front==-1)
{
rear=front=0;
}
else
{
rear=(rear+1)%3;
}
cque.cqueue[rear]=item;
printf("Successfully Insert");
}
voiddel()
{
intnum;
if(front==-1)
{
printf("Queue Empty");
return;
}
else
{
num=cque.cqueue[front];
printf("Deleted item : %d",num);
}
if(front==rear)
{
front=-1;
}
else
front=(front+1)%3;
}
void display()
{
int i;
if(front==-1)
{
printf("Queue Empty");
return;
}
else
{
printf("\n\nItems : ");
for(i=front;i<=rear;i++)
{
printf(" %d",cque.cqueue[i]);
}
}
}
https://www.sitesbay.com/data-structure/c-queue
Linked list is a special type of data structure where all data elements are
linked to one another. Linked list is the collection of nodes and every nodes
contains two parts data part and address part.
Suppose you want ot store marks of 50 students, so need to write code like
below;
Example
int marks[50];
But some time you need to store more than 50 students marks, in that case
you can not increase memory of array, and some time you need to store less
than 50 students marks in this case extra memory will be wastage. To
overcome this problem you need to use Linked List because in linked list
memory will be created at run time.
Dynamic Data Structure: The size of linked list increase and decrease
during program execution.
No memory wastage: In linked list memory will be allocated at the time
of program execution so no memory wastage.
Easily insert and delete data: In linked list you can insert any data at
specific position and also delete any data from specific position.
Need more memory: For store data in linked list you need more memory
space, you need memory space for both data and address part.
A common example of linked list is train, in this case all the buggies are nodes
and two coaches are connected using the connectors, peoples seating
arrangement inside the coaches is called as data part of linked list while
connection between two buggies is address filed of linked list.
Like linked list, trains also have last coach which is not further connected to
any of the buggies. Engine can be called as first node of linked list and last
buggies are last node of linked list.
https://www.sitesbay.com/data-structure/c-linked-list
5.1.4 Stack in C
Stack is linear data structure. In stack addition of new data item and deletion
of already existing data item is done from only one end, known as top.
Working of stack on the basis of Last-in-First-out (LIFO) principal, it means
last entered item remove first.
A most popular example of stack is plates in marriage party. Fresh plates are
pushed onto to the top and popped from the top.
Stack Operation
In stack data structure mainly perform two operation; push and pop
pop: In case of stack deletion of any item from stack is called pop.
push: In case of stack Insertion of any item in stack is called push.
Push Operation
In case of stack Insertion of any item in stack is called push. In stack any item
is inserted from top of the stack, When you insert any item in stack top will be
increased by 1.
Algorithm for push
void push()
{
int item;
if(top==size-1)
{
printf("\n stack is full");
}
else
{
top=top+1;
printf("\n\n Enter element in stack: ");
scanf("%d",&s.item);
s.stack[top]=s.item;
}
}
POP Operation
In case of stack deletion of any item from stack is called pop. In any item is
delete from top of the stack, When you delete any item from stack top will be
decreased by 1.
Algorithm for pop
Example
void pop()
{
int item;
if(top==0)
{
printf("\nStack is empty: ");
}
else
{
s.item=s.stack[top];
top=top-1;
printf("deleted data is: %d",s.item);
}
}
https://www.sitesbay.com/data-structure/c-stack-pop-operation
Example of Stack in C
Program of stack is very simple when you insert any item in stack top will be
increased by 1 and when you pop any item from stack top will be decreased
by 1. Both insertion and deletion operation in stack perform from top of stack.
Example
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define size 5
void pop();
void push();
void display();
struct stack
{
int item;
int stack[size];
}s;
int top=-1;
void push()
{
if(top==size-1)
{
printf("\n stack is full");
}
else
{
top=top+1;
printf("\n\n Enter element in stack: ");
scanf("%d",&s.item);
s.stack[top]=s.item;
}
}
void pop()
{
if(top==0)
{
printf("\nStack is empty: ");
}
else
{
s.item=s.stack[top];
top=top-1;
printf("deleted data is: %d",s.item);
}
}
void display()
{
int i;
if(top==0)
{
printf("\n Stack is empty: ");
}
else
{
for(i=top;i>0;i--)
{
printf("\n%d",s.stack[i]);
}
}
}
void main()
{
charch,c;
do
{
u:
clrscr();
printf("\n\n1: push");
printf("\n2: pop");
printf("\n3: display");
printf("\n4: exit");
printf("\nenter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case1:
up:
push();
break;
case2:
pop();
break;
case3:
display();
break;
case4:
exit(0);
break;
default:
printf("\nwrong choice");
}
printf("\n\n Pushed an element (Y/N)");
c=getch();
if(c=='y'||c=='Y')
{
goto up;
}
else
{
goto u;
}
}
while(ch!=5);
}
https://www.sitesbay.com/data-structure/c-stack-example
Tree Vocabulary: The topmost node is called root of the tree. The elements
that are directly under an element are called its children. The element directly
above something is called its parent. For example, a is a child of f and f is the
parent of a. Finally, elements with no children are called leaves.
tree
----
j <-- root
/ \
f k
/ \ \
a h z <-- leaves
Why Trees?
1. One reason to use trees might be because you want to store information
that naturally forms a hierarchy. For example, the file system on a computer:
file system
-----------
/ <-- root
/ \
... home
/ \
ugrad course
/ / | \
... cs101 cs112 cs113
Binary Tree: A tree whose elements have at most 2 children is called a binary
tree. Since each element in a binary tree can have only 2 children, we typically
name them the left and right child.
1. malloc()
2. calloc()
3. realloc()
4. free()
Now let's have a quick look at the methods used for dynamic memory
allocation.
For complete tutorial of dynamic memory allocation refer to the link below:
https://www.youtube.com/watch?v=xDVC3wKjS64
5.3 C - Preprocessors
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text
substitution tool and it instructs the compiler to do required pre-processing
before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first
nonblank character, and for readability, a preprocessor directive should begin
in the first column. The following section lists down all the important
preprocessor directives −
1. #include
The #include preprocessor directive is used to paste code of given file into
current file. It is used include system-defined and user-defined header files. If
included file is not found, compiler renders error. It has three variants:
#include <file>
This variant is used for system header files. It searches for a file named file in
a list of directories specified by you, then in a standard list of system
directories.
#include "file"
This variant is used for header files of your own program. It searches for a file
named file first in the current directory, then in the same directories used for
system header files. The current directory is the directory of the current input
file.
2. Macro's (#define)
Syntax
1. Object-like Macros
2. Function-like Macros
1. Object-like Macros
#define PI 3.1415
Here, PI is the macro name which will be replaced by the value 3.14. Let's see
an example of Object-like Macros :
#include <stdio.h>
#define PI 3.1415
main()
{
printf("%f",PI);
}
Output:
3.14000
2. Function-like Macros
Here, MIN is the macro name. Let's see an example of Function-like Macros :
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
voidmain(){
printf("Minimum between 10 and 20 is: %d\n",MIN(10,20));
}
Output:
/*
*/ # /*
*/defi\
ne FO\
O 10\
20
3. #undef
To undefine a macro means to cancel its definition. This is done with the
#undef directive.
Syntax:
#undef token
#include <stdio.h>
#define PI 3.1415
#undef PI
main(){
printf("%f",PI);
}
Output:
Syntax:
#ifdef MACRO
//code
#endif
5. #ifndef
Syntax:
#ifndef MACRO
//code
#endif
6. #if
Syntax:
#if expression
//code
#endif
7. #else
Syntax:
#if expression
//if code
#else
//else code
#endif
#if expression
//if code
#elif expression
//elif code
#else
//else code
#endif
Example
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
voidmain(){
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}
Output
The #error preprocessor directive indicates error. The compiler gives fatal
error if #error directive is found and skips further compilation process.
C #error example
#include<stdio.h>
#ifndef __MATH_H
#error First include then compile
#else
voidmain(){
float a;
a=sqrt(7);
printf("%f",a);
}
#endif
5.4 C - Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are
performed more easily with pointers, and other tasks, such as dynamic
memory allocation, cannot be performed without using pointers. So it
becomes necessary to learn pointers to become a perfect C programmer. Let's
start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location
has its address defined which can be accessed using ampersand (&) operator,
which denotes an address in memory. Consider the following example, which
prints the address of the variables defined −
Live Demo
#include<stdio.h>
int var1;
char var2[10];
return0;
}
When the above code is compiled and executed, it produces the following
result −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable. The asterisk * used to declare a
pointer is the same asterisk used for multiplication. However, in this
statement the asterisk is being used to designate a variable as a pointer. Take
a look at some of the valid pointer declarations −
The actual data type of the value of all pointers, whether integer, float,
character, or otherwise, is the same, a long hexadecimal number 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.
There are a few important operations, which we will do with the help of
pointers very frequently. (a) We define a pointer variable, (b) assign the
address of a variable to a pointer and (c) finally access the value at the
address available in the pointer variable. This is done by using unary operator
* that returns the value of the variable located at the address specified by its
operand. The following example makes use of these operations −
Live Demo
#include<stdio.h>
When the above code is compiled and executed, it produces the following
result −
This program shows how a pointer is declared and used. There are several
other things that we can do with pointers, we have discussed them later in
this guide. For now, we just need to know how to link a pointer to the address
of a variable.
Important point to note is: The data type of pointer and the variable must
match, an int pointer can hold the address of int variable, similarly a pointer
declared with float data type can hold the address of a float variable. In the
example below, the pointer and the variable both are of int type.
#include<stdio.h>
int main()
{
//Variable declaration
intnum=10;
//Pointer declaration
int*p;
Output:
Lets discuss the operators & and * that are used with Pointers in C.
We have already seen in the first example that we can display the address of a
variable using ampersand sign. I have used &num to access the address of
variable num. The & operator is also known as “Address of” Operator.
Point to note: %p is a format specifier which is used for displaying the address
in hex format.
Now that you know how to get the address of a variable but how to store that
address in some other variable? That’s where pointers comes into picture. As
mentioned in the beginning of this guide, pointers in C programming are used
for holding the address of another variables.
Pointer is just like another variable, the main difference is that it stores
address of another variable rather than a value.
The above are the few examples of pointer declarations. If you need a pointer
to store the address of integer variable then the data type of the pointer
should be int. Same case is with the other data types.
double a =10;
double*p;
p =&a;
*p would give us the value of the variable a. The following statement would
display 10 as output.
printf("%d",*p);
*p =200;
It would change the value of variable a. The statement above will change the
value of a from 10 to 200.
intvar=10;
Output:
After the above operation, the ptr will point to the location 1004 because each
time ptr is incremented, it will point to the next integer location which is 4
bytes next to the current location. This operation will move the pointer to the
next memory location without impacting the actual value at the memory
location. If ptr points to a character whose address is 1000, then the above
operation will point to the location 1001 because the next character will be
available at 1001.
Incrementing a Pointer
Live Demo
#include<stdio.h>
intvar[]={10,100,200};
int i,*ptr;
return0;
}
When the above code is compiled and executed, it produces the following
result −
Live Demo
#include<stdio.h>
intvar[]={10,100,200};
int i,*ptr;
return0;
}
When the above code is compiled and executed, it produces the following
result −
Pointers may be compared by using relational operators, such as ==, <, and >.
If p1 and p2 point to variables that are related to each other, such as elements
of the same array, then p1 and p2 can be meaningfully compared.
Live Demo
#include<stdio.h>
intvar[]={10,100,200};
int i,*ptr;
while(ptr<=&var[MAX -1]){
return0;
}
When the above code is compiled and executed, it produces the following
result −
Sample Questions
Page 13
Sample Questions
RBT
Questions CO’s
Levels
Describe structures. Explain how to declare and initialize a CO4,
L1
structure. CO5
CO4,
Describe file. Explain different modes of files. L1
CO5
What is the output of this C code?
#include <stdio.h>
struct student
{
char *name;
};
CO4,
L2
void main() CO5
{
struct student s, m;
s.name = "st";
m = s;
printf("%s%s", s.name, m.name);
}
Explain the operations which are illegal in structure CO4,
L2
implementation CO5
Illustrate with an example how structures are defined, CO4,
L3
declared and initialized. CO5
Illustrate with an example how structure members are CO4,
L3
accessed CO5
CO4,
Illustrate with syntax how a file can be opened and closed. L3
CO5
CO4,
What are the characteristics of files L4
CO5
CO4,
What are the characteristics of structure L4
CO5
Trace the following code and explain what will be the
output.
#include<stdio.h>
struct
{
int i;
float ft;
CO4,
}decl; L5
CO5
int main()
{
decl.i = 4;
decl.ft = 7.96623;
printf("%d %.2f", decl.i, decl.ft);
return 0;
}
What is the similarity between a structure, union and CO4,
L5
enumeration? CO5
Develop a C program to search for a name in an array of CO4,
L6
structure CO5
Develop a C program to read student name and USN from CO4,
L6
two different files and write into a different file. CO5
Write a C program to read n numbers from keyboard and CO4,
L6
write into a file. CO5
Write a C program to copy contents of one file to another CO4,
L6
file CO5
Write a program to Store Information(name, roll and CO4,
L6
marks) of a Student Using Structure CO5
Write a C program to write all the members of an array of
CO4,
structures to a file using fwrite(). Read the array from the L6
CO5
file and display on the screen.
Write a C program to read name and marks of n number
CO4,
of students from user and store them in a file. If the file L6
CO5
previously exits, add the information of n students.
Write a C program to Calculate Difference Between Two CO4,
L6
Time Periods using structures. CO5
Page 15