Wa0003.
Wa0003.
Memory - Memory is the storage space on it where data is processed and processing
The task we are currently working on is saved in the main memory, and the task we saved is
Logical - A computer system has certain characteristics, such as the capability of thinking,
These characteristics help them perform tasks logically and these characteristics have been
Versatility - Because computers are so versatile, they can perform almost any task that can
It refers to the ability or adaptation to quickly switch from one task to another.
Automation - Automation is the use of technology to complete a task with as little human
interaction as possible.
batch processing.
Consistency - In the context of databases, consistency means that data cannot be written
because it would violate the database‘s own rules for valid data.
A computer system comprises of hardware and software components. Hardware refers to the
physical parts of the computer system and software is the set of instructions or programs that
are necessary for the functioning of a computer to perform certain tasks. Hardware includes
the following components: • Input devices — They are used for accepting the data on which
the operations are to be performed. The examples of input devices are keyboard, mouse and
track ball. • Processor — Also known as CPU, it is used to perform the calculations and
information processing on the data that is entered through the input device. • Output devices
— They are used for providing the output of a program that is obtained after performing the
operations specifi ed in a program. The examples of output devices are monitor and printer.
Memory — It is used for storing the input data as well as the output of a program that is
obtained after performing the operations specifi ed in a program. Memory can be primary
memory as well as secondary memory. Primary memory includes Random Access Memory
(RAM) and secondary memory includes hard disks and floppy disks.
PROCESSOR The CPU consists of Control Unit (CU) and ALU. CU stores the instruction
set, which specifi es the operations to be performed by the computer. CU transfers the data
and the instructions to the ALU for an arithmetic operation. ALU performs arithmetical or
logical operations on the data received. The CPU registers store the data to be processed by
the CPU and the processed data also.
INPUT DEVICES Input devices can be connected to the computer system using cables. The
most commonly used input devices among others are:
• Mouse - Mouse The mouse allows the user to select elements on the screen, such as tools,
icons, and buttons, by pointing and clicking them. The mouse is also known as a pointing
device because it helps change the position of the pointer or cursor on the screen.
• Scanner - Scanner A scanner is an input device that converts documents and images as the
digitized images understandable by the computer system. The digitized images can be
produced as black and white images, gray images, or colored images.
OUTPUT DEVICES - The data, processed by the CPU, is made available to the end user by
the output devices. The most commonly used output devices are:
• Monitor - A monitor is the most commonly used output device that produces visual displays
generated by the computer. The monitor, also known as a screen, is connected as an external
device using cables or connected either as a part of the CPU case.
• Printer - The printer is an output device that transfers the text displayed on the screen, onto
paper sheets that can be used by the end user. The various types of printers used in the market
are generally categorized as dot matrix printers, inkjet printers, and laser printers.
• Speaker - Speaker The speaker is an electromechanical transducer that converts an electrical
signal into sound. They are attached to a computer as output devices, to provide audio output,
such as warning sounds and Internet audios.
• Plotter - The plotter is another commonly used output device that is connected to a
computer to print large documents, such as engineering or constructional drawings. Plotters
use multiple ink pens or inkjets with color cartridges for printing.
Primary Memory The primary memory is available in the computer as a built-in unit of the
computer. The primary memory is represented as a set of locations with each location
occupying 8 bits. Each bit in the memory is identifi ed by a unique address.
• ROM — ROM represents Read Only Memory that stores data and instructions, even when
the computer is turned off. It is the permanent memory of the computer where the contents
cannot be modifi ed by an end user.
RAM — RAM is the read/write memory unit in which the information is retained only as
long as there is a regular power supply. When the power supply is interrupted or switched off,
the information stored in the RAM is lost.
Cache memory — Cache memory is used to store the data and the related application that
was last processed by the CPU. When the processor performs processing, it fi rst searches the
cache memory and then the RAM, for an instruction.
Secondary Memory -- Secondary memory represents the external storage devices that are
connected to the computer. They provide a non-volatile memory source used to store
information that is not in use currently. A storage device is either located in the CPU casing
of the computer or is connected externally to the computer. The secondary storage devices
can be classifi ed as:
• Magnetic storage device — The magnetic storage devices store information that can be
read, erased and rewritten a number of times. These include fl oppy disk, hard disk and
magnetic tapes.
• Optical storage device — The optical storage devices are secondary storage devices that use
laser beams to read the stored data. These include CD-ROM, rewritable compact disk (CD-
RW), digital video disks with read only memory (DVD-ROM), etc.
• Magneto-optical storage device — The magneto-optical devices are generally used to store
information, such as large programs, fi les and back up data. The end user can modify the
information stored in magneto-optical storage devices multiple times. These devices provide
higher storage capacity as they use laser beams and magnets for reading and writing data to
the device.
BINARY NUMBER SYSTEM
Binary to Decimal Conversion
PROGRAMMING LANGUAGES
The communication between two parties, whether they are machines or human beings,
always needs a common language or terminology. The language used in the communication
of computer instructions is known as the programming language. The computer has its own
language and any communication with the computer must be in its language or translated into
this language.
1. machine languages (low level languages) -- As computers are made of two-state electronic
devices they can understand only pulse and no-pulse (or ‗1‘ and ‗0‘) conditions. Therefore,
all instructions and data should be written using binary codes 1 and 0. The binary code is
called the machine code or machine language.
2. assembly (or symbolic) languages -- The assembly language, also referred to as the
second-generation programming language, is also a low-level language. In an assembly
language, the 0s and 1s of machine language are replaced with abbreviations or mnemonic
code.
For example
CMA /Complement AC
INC /Increment AC
Compiler The compiler is a computer program that translates the source code written in a
high-level language into the corresponding object code of the low-level language. This
translation process is called compilation. The entire high-level program is converted into the
executable machine code file.
Interpreter The interpreter is a translation program that converts each high-level program
statement into the corresponding machine code. This translation process is carried out just
before the program statement is executed. Instead of the entire program, one statement at a
time is translated and executed immediately.
Linker: A linker is special program that combines the object files, generated by
compiler/assembler and other pieces of code to originate an executable file has .exe
extension. In the object file, linker searches and append all libraries needed for execution of
file. It regulates the memory space that will hold the code from each module. It also merges
two or more separate object programs and establishes link among them.
Loader: It is special program that takes input of executable files from linker, loads it to main
memory, and prepares this code for execution by computer. Loader allocates memory space
to program. Even it settles down symbolic reference between objects.
2. Divide the process used to solve the problem in a series of elementary tasks.
5. Feed the computer program in the computer. CPU interprets the given program, processes
the data accordingly, and generates the result.
6. Send the generated result to the output unit, which displays it. Algorithms and fl owcharts
are two important techniques that help users in solving problems or accomplishing tasks
using a computer.
Algorithms
An algorithm is a complete, detailed, and precise step-by-step method for solving a problem
independently of the software or hardware of the computer. Algorithms are very essential, as
they instruct the computer what specifi c steps it needs to perform to carry out a particular
task or to solve a problem.
1)Input specified
The input is the data to be transformed during the computation to produce the output.An
algorithm should have 0 or more well-defined inputs.Input precision requires that you know
what kind of data, how much and what form the data should be
2)Output specified
The output is the data resulting from the computation (your intended result). An algorithm
should have 1 or more well-defined outputs, and should match the desired output.Output
precision also requires that you know what kind of data, how much and what form the output
should be (or even if there will be any output at all!).
3)Definiteness
Algorithms must specify every step and the order the steps must be taken in the
process.Definiteness means specifying the sequence of operations for turning input into
output. Algorithm should be clear and unambiguous.Details of each step must be also be
spelled out (including how to handle errors).It should contain everything quantitative and not
qualitative.
4)Effectiveness
For an algorithm to be effective, it means that all those steps that are required to get to output
must be feasible with the available resources.It should not contain any unnecessary and
redundant steps which could make an algorithm ineffective.
5)Finiteness
The algorithm must stop, eventually.Stopping may mean that you get the expected output OR
you get a response that no solution is possible. Algorithms must terminate after a finite
number of steps.An algorithm should not be infinite and always terminate after definite
number of steps.
There is no point in developing an algorithm which is infinite as it will be useless for us.
6)Independent
Step 1: Start
Step 9: Stop
Flowchart
Step 1: start
remainder=n%10;
reverse=reverse * 10 + remainder;
n=n/10;
Step 7: stop
Flowchart
Step 1 :Start
c. Divide both inputs by the numbers from 1 to smallest+1 If the remainders of both
divisions are zero Assign that number to gcd
Step 7. Stop
Flowchart
Algorithm for Generating N prime numbers
Step 1 : Start
Step 2: Read lower & Upper bound values for the Range
If Remainder == 0 then,
Else
Step 6. Repeat the Steps 2 to 4 until reach the Upper bound of the Range
Step 7: Stop
Flowchart:
Algorithm for Computing Fibonacci series
2. Set a = 0 and b = 1.
4. Set count = 2.
5. While count £ n, c = a + b.
7. Set a = b and b = c.
Flowchart
Algorithm for finding even or odd
Step 1: Start
Step 7: Stop
Flowchart
Programming Basics
Overview of C
C is a structured, high-level, machine independent language. C was evolved from ALGOL,
BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972.
IMPORTANCE OF C
The increasing popularity of C is probably due to its many desirable qualities. It is a robust
language whose rich set of built-in functions and operators can be used to write any complex
program.
There are only 32 keywords in ANSI C and its strength lies in its built-in functions. Several
standard functions are available which can be used for developing programs.
C is highly portable. This means that C programs written for one computer can be run on
another with little or no modifi cation.
C language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules or blocks.
Tokens in C
1. Keywords
2. Identifiers
3. Constants
4. Strings
5. Special Symbols
6. Operators
Keywords
The keywords are pre-defined or reserved words in a programming language. Each
keyword is meant to perform a specific function in a program. Since keywords are referred
names for a compiler, they can‘t be used as variable names because by doing so, we are
trying to assign a new meaning to the keyword which is not allowed.
C language supports 32 keywords which are given below:
Identifiers
Identifiers are used as the general terminology for the naming of variables, functions, and
arrays. These are user-defined names consisting of an 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.
Certain rules should be followed while naming c identifiers which are as follows:
They must begin with a letter or underscore(_).
They must consist of only letters, digits, or underscore. No other special character is
allowed.
It should not be a keyword.
It must not contain white space.
It should be up to 31 characters long as only the first 31 characters are significant.
Constants
The constants refer to the variables with fixed values. They are like normal variables but
with the difference that their values can not be modified in the program once they are
defined.
Constants may belong to any of the data types.
Examples of Constants in C
Examples of String
char string[20] = {‗g‘, ‘e‘, ‗e‘, ‗k‘, ‗s‘, ‗f‘, ‗o‘, ‗r‘, ‗g‘, ‘e‘, ‗e‘, ‗k‘, ‗s‘, ‗\0‘};
char string[20] = ―hello world‖;
Special Symbols
The following special symbols are used in C having some special meaning and thus,
cannot be used for some other purpose. Some of these are listed below:
Brackets[]: Opening and closing brackets are used as array element references. 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 mark the start and end of a block of
code containing more than one executable statement.
Comma (, ): It is used to separate more than one statement like for separating
parameters in function calls.
Colon(:): It is an operator that essentially invokes something called an initialization
list.
Semicolon(;): It is known as a statement terminator. It indicates the end of one logical
entity. That‘s why each individual statement must be ended with a semicolon.
Asterisk (*): It is used to create a pointer variable and for the multiplication of
variables.
Assignment operator(=): It is used to assign values and for logical operation
validation.
Pre-processor (#): The preprocessor is a macro processor that is used automatically by
the compiler to transform your program before actual compilation.
Period (.): Used to access members of a structure or union.
Tilde(~): Used as a destructor to free some space from memory.
Basic structure of C Program
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the
variable can store like integer, character, floating, double, etc. Each data type requires
different amounts of memory and has some specific operations which can be performed
over it. The data type is a collection of data with values having fixed values, meaning as
well as its characteristics.
The data types in C can be classified as follows:
Data Types Memory Size Range
float 4 byte
double 8 byte
Int:
Integers are entire numbers without any fractional or decimal parts, and the int data type is
used to represent them.
It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between
around -2 billion and +2 billion.
Char:
Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols,
or commas. There are 256 characters that can be represented by a single char, which takes up
one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.
Float:
To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be
very precise. It can store values with an accuracy of about 6 decimal places and a range of
about 3.4 x 1038 in 4 bytes of memory.
Double:
Use two data types to represent two floating integers. When additional precision is needed,
such as in scientific calculations or financial applications, it provides greater accuracy
compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places,
yields larger values. C treats floating point numbers as doubles by default if no explicit type
is supplied.
In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two
variables for the number pi.
UNIT II
Operators in C:
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and
variables. The values and variables used with operators are called operands. So we can say
that the operators are the symbols that perform operations on operands.
Operators can be classified into three types on the basis of the number of operands they
work on:
1. Unary Operators: Operators that work on single operand.
2. Binary Operators: Operators that work on two operands.
3. Ternary Operators: Operators that work on three operands
Unary Operators
1. Unary Minus
2. Bitwise 1‘s complement
3. Logical Not
1. Unary minus- works on single operand. Changes the sign from + to –ve and –ve to and
Example:
A=20,b=10;
C=a+(-b);
Answer is a-b= 10
Binary Operators
Arithmetic operators
Relational Operators
Logical operators
Bitwise operators
Other operators
Arithmatic operators
Adds two
+ Plus a+b
1 numeric values.
Subtracts right
– Minus operand from left a – b
2 operand.
Divide two
/ Divide a/b
4 numeric values.
Returns the
remainder after
% Modulus diving the left a % b
operand with the
5 right operand.
Used to specify
+ Unary Plus the positive +a
6 values.
Increases the
++ Increment value of the a++
8 operand by 1.
Decreases the
— Decrement value of the a–
9 operand by 1.
Relational Operators in C
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.
Returns true if
the left operand is
< Less than less than the right a < b
operand. Else
1 false
Returns true if
the left operand is
> Greater than greater than the a > b
right operand.
2 Else false
Returns true if
the left operand is
Less than or less than or equal
<= a <= b
equal to to the right
operand. Else
3 false
Returns true if
the left operand is
Greater than or greater than or
>= a >= b
equal to equal to right
operand. Else
4 false
Returns true if
== Equal to both the operands a == b
5 are equal.
Returns true if
!= Not equal to both the operands a != b
6 are NOT equal.
Logical Operator in C
Logical Operators are used to combine two or more conditions/constraints or to
complement the evaluation of the original condition in consideration. The result of the
operation of a logical operator is a Boolean value either true or false.
Returns true if
&& Logical AND both the operands a && b
1 are true.
Returns true if
|| Logical OR both or any of the a || b
2 operand is true.
Returns true if
! Logical NOT the operand is !a
3 false.
Bitwise Operators in C
The Bitwise operators are used to perform bit-level operations on the operands. The
operators are first converted to bit-level and then the calculation is performed on the
operands.
Performs bit-by-
bit AND
& Bitwise AND a && b
operation and
1 returns the result.
Performs bit-by-
bit OR operation
| Bitwise OR a || b
and returns the
2 result.
Performs bit-by-
bit XOR
^ Bitwise XOR a^b
operation and
3 returns the result.
Other Operators
Assignment Operators in C
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left
side otherwise the compiler will raise an error.
The assignment operators can be combined with some other operators in C to provide
multiple operations using single operator. These operators are called compound operators.
Assign the
remainder in the
Modulus and division of left
%= a %= b
assign operand with the
right operand to
6 the left operand.
Performs bitwise
AND and assigns
&= AND and assign a &= b
this value to the
7 left operand.
Performs bitwise
OR and assigns
|= OR and assign a |= b
this value to the
8 left operand.
Performs bitwise
XOR and assigns
^= XOR and assign a ^= b
this value to the
9 left operand.
Performs bitwise
Rightshift and
Rightshift and
>>= assign this value a >>= b
assign
to the left
10 operand.
Performs bitwise
Leftshift and
Leftshift and
<<= assign this value a <<= b
assign
to the left
11 operand.
Input/output functions
Formatted IO Functions
Formatted I/O functions are essential for handling user inputs and displaying outputs in a
user-friendly way. They enable programmers to:
1. Receive User Inputs: Formatted input functions help programs collect user input in a
structured manner. They use format specifiers to interpret and extract specific data
types from user input.
2. Present Data to Users: Formatted output functions allow programs to present data to
users in various formats. Format specifiers are used to control how data is displayed,
making it more readable and visually appealing.
3. Support Multiple Data Types: These I/O functions are versatile and support a wide
range of data types, including integers, floating-point numbers, characters, and more.
Each data type has corresponding format specifiers for precise formatting.
4. Formatting Control: Programmers can use format specifiers to control the alignment,
width, precision, and other formatting aspects of displayed data, ensuring it‘s
presented as intended.
Different format specifiers
%d or %i int
%f or %F float
%lf double
%c char
%s Used for strings (text), which you will learn more about in a la
The following are the formatted I/O functions
1. printf()
2. scanf()
3. sprintf()
4. sscanf()
1. printf():
In C, printf() is a built-in function used to display values like numbers, characters, and strings
on the console screen. It‘s pre-defined in the stdio.h header, allowing easy output formatting
in C programs.
Syntax 1
2. scanf():
scanf(): In C, scanf() is a built-in function for reading user input from the keyboard. It
can read values of various data types like integers, floats, characters, and
strings. scanf() is a pre-defined function declared in the stdio.h header file. It uses
the & (address-of operator) to store user input in the memory location of a variable.
Syntax
3. sprintf():
sprintf(): Short for ―string print,‖ sprintf() is similar to printf() but it stores the formatted
string into a character array instead of displaying it on the console screen.
4. sscanf():
sscanf(): Abbreviated for ―string scanf,‖ sscanf() resembles scanf() but reads data
from a string or character array rather than from the console screen.
Syntax
Unformatted I/O Functions: These functions are used exclusively for character data
types or character arrays/strings. They are designed for reading single inputs from the
user at the console and for displaying values on the console.
Why ―Unformatted‖?: They are referred to as ―unformatted‖ I/O functions because
they do not support format specifiers. Unlike formatted I/O functions
like printf() and scanf(), you cannot use format specifiers to control the formatting of
the data. They display or read data as-is without formatting options.
The following are unformatted I/O functions
1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()
1. getch():
getch(): In C, getch() reads a single character from the keyboard without displaying it on the
console screen. It immediately returns without requiring the user to press the Enter key. This
function is declared in the conio.h header file and is often used for controlling screen display.
Syntax
getch();
or
variable-name = getch();
2. getche():
In C, getche() reads a single character from the keyboard, displays it on the console screen,
and immediately returns without requiring the user to press the Enter key. This function is
declared in the conio.h header file.
Syntax
getche();
or
variable_name = getche();
3. getchar():
In C, getchar() reads a single character from the keyboard and waits until the Enter key is
pressed. It processes one character at a time. This function is declared in the stdio.h header
file
Syntax
Variable-name = getchar();
4. putchar():
In C, putchar() is used to display a single character at a time, either by passing the character
directly or by using a variable that stores the character. This function is declared in
the stdio.h header file.
Syntax
putchar(variable_name);
5. gets():
In C, gets() reads a group of characters or strings from the keyboard, and these characters are
stored in a character array. It allows you to input space-separated texts or strings. This
function is declared in the stdio.h header file. However, please note that gets() is considered
unsafe due to the risk of buffer overflow and is generally discouraged in favor of safer
alternatives like fgets().
Syntax
char str[length of string in number]; //Declare a char type variable of any length
gets(str);
6. puts():
In C programming, puts() is used to display a group of characters or strings that are already
stored in a character array. This function is declared in the stdio.h header file.
Syntax
puts(identifier_name );
7. putch():
In C, putch() is used to display a single character provided by the user, and it prints the
character at the current cursor location. This function is declared in the conio.h header file
Syntax
putch(variable_name);
BRANCHING AND LOOPING
1. The Execution of program in the order in which it appear in the program is called
Sequential Execution.
3. C Provides different types of control statements to control the sequence of the statements
to be executed in C Program .
A. Conditional Control Statements (Decision Making and Branching)
B. The goto Statement
The Execution of program based on some condition the condition results in either true or
false based on the set of statements will be executed .This is known as Conditional
Execution
If.. statement :
{
// block of code to be executed if the condition is true
}
Step2: If the condition is true, the statements inside the if block are executed.
Step3: If the expression is false, the statements inside the if body are not executed.
Step4: Program control moves out of the if block and the code after the if block is executed.
#include <stdio.h>
int main() {
int number;
scanf("%d", &number);
if (number < 0) {
}
printf("The if statement is easy.");
return 0;
Output 1
Enter an integer: -2
When we enter -2, the number then -2<0 is evaluated to true. Hence, You entered -2 is
displayed on the screen. Along with The if statement is easy.
Output 2
Enter an integer: 5
When we enter 5, as number then 5<0 is evaluated to false and the statement inside the body
of if is not executed
if...else Statement :
1. Perform two operations for a single condition .
2. One is for the true block of that condition, and the other is for the false block of the
condition
3. if and else block cannot be executed simultaneously
4. Syntax
if(expression)
{
// code executed when the condition is true
}
else
Step 4 : After that, the program control continues to the statements below the if-else
statement.
Example :
#include <stdio.h>
int main()
int num = 9;
if (num % 2 = = 0) {
printf("Number is even");
}
else {
printf("Number is Odd");
return 0;
}else if(condition2)
else if(condition3)
else
}
Example :
#include <stdio.h>
int main()
int n = 0;
if (n > 0) {
printf("Positive");
else if (n < 0) {
printf("Negative");
else {
printf("Zero");
return 0;
Switch Statement :
1. The switch statement in C is an alternate to if-else-if ladder statement which allows us to
execute multiple operations for the different possibles values of a single variable called
switch variable.
2. Switch case statements follow a selection-control mechanism and allow a value to change
control of execution.
3. multi way branch statement
4. Syntax
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
Step 2 : The value of the expression is compared with the values of each case
Step 4 : The break statement breaks out of the switch block and stops the execution
Step 5 : The default statement is optional, and specifies some code to run if there is no case
match
Example :
#include <stdio.h>
int main()
int day = 2;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
case 7:
printf("Sunday");
break;
default:
printf("Invalid Input");
break;
return 0;
goto statement
goto label;
Example :
#include <stdio.h>
int main()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
return 0;
}
2) Using loops, we do not need to write the same code again and again.
While Loop
1. The while loop in c is to be used in the case where we don't know the number of iterations
in advance.
2. The block of statements is executed in the while loop until the condition specified in the
while loop is satisfied.
3. It is also called a pre-tested loop or entry - control loop
4. Syntax
while (test-expression) {
#include <stdio.h>
int main() {
int i = 1;
while (i <= 5) {
printf("%d\n", i);
++i;
return 0;
do..while statement
1. The do-while loop continues until a given condition satisfies
2. The test condition is checked after executing the body of the loop. Due to this, the
statements in the do…while loop will always be executed at least once no matter what the
condition is..
3. It is also called post tested loop or exit control loop
4. It is used when it is necessary to execute the loop at least once
5. Syntax
do{
//code to be executed
}while(condition);
6. Example
Print the table based on number
#include<stdio.h>
int main(){
int i=1,number=0;
printf("Enter a number: ");
scanf("%d",&number);
do{
printf("%d \n",(number*i));
i++;
}while(i<=10);
return 0;
1) Initialization: This step initializes a loop control variable with an initial value that
helps to progress the loop or helps in checking the condition. It acts as the index value
when iterating an array or string.
2) Check/Test Condition: This step of the for loop defines the condition that determines
whether the loop should continue executing or not. The condition is checked before each
iteration and if it is true then the iteration of the loop continues otherwise the loop is
terminated.
3) Body: It is the set of statements i.e. variables, functions, etc that is executed repeatedly
till the condition is true. It is enclosed within curly braces { }.
4) Updation: This specifies how the loop control variable should be updated after each
iteration of the loop. Generally, it is the incrementation (variable++) or decrementation
(variable - -) of the loop control variable.
Step 1: Initialization is the basic step of for loop this step occurs only once during the start of
the loop. During Initialization, variables are declared, or already existing variables are
assigned some value.
Step 2: During the Second Step condition statements are checked and only if the condition is
the satisfied loop we can further process otherwise loop is broken.
Step 4: Updating the values of variables has been done as defined in the loop.
Continue to Step 2 till the loop breaks.
Example :
int main() {
int i;
return 0;
Jumps in Loops
1. Thease are used to transfer the program control from one part of the code to another.
2. C provides three types of Jump Statements in C, namely, break, continue, and goto.
1. It used to terminate the execution of a loop or switch statement. When the break statement
is encountered, the program control jumps to the statement following the loop or switch.
2. The break statement exits or terminates the loop or switch statement based on a certain
condition, without executing the remaining code
3. Uses of break in C
The break statement is used in C for the following purposes:
4. Note: If the break statement is used inside an inner loop in a nested loop, it will break the
inner loop without affecting the execution of the outer loop.
#include <stdio.h>
int main()
int i;
// for loop
if (i == 6) {
break;
printf("Loop exited.\n");
return 0;
Explanation:
When i = 6, the condition for the break statement becomes true and the program control
immediately exits the loop.
The control continues with the remaining statements outside the loop.
6. The break statement is also used inside the switch statement to terminate the switch
statement after the matching case is executed.
The continue statement
1. It is used to skip the remaining code in the current iteration of a loop and move to the next
iteration. When the continue statement is encountered, the program control jumps to the
beginning of the loop.
2. The continue statement in C is used to skip the remaining code after the continue
statement within a loop and jump to the next iteration of the loop.
3. When the continue statement is encountered, the loop control immediately jumps to the
next iteration, by skipping the lines of code written after it within the loop body.
4. Example of Continue statement
#include <stdio.h>
int main()
int i;
// loop
if (i == 2) {
// continue to be executed if i = 2
continue;
return 0;
Explanation: The for loop iterates from 0 to 4. Inside the loop, we check if i is equal to 2.
If the condition is true, the continue statement is executed, and it skips the remaining code
within the loop for that iteration. If the condition is false, the code proceeds normally.
5. Note: While using continue in loop, we have to make sure that we put the continue after
the loop variable updation or else it will result in an infinite loop.
Return Statement in C
1. The return statement in C is used to terminate the execution of a function and return a
value to the caller. It is commonly used to provide a result back to the calling code.
Syntax
return expression;
2. The return statement is used to exit a function and return control to the calling function.
This statement can also return a value to the calling function.
Data Type: The type of the returned value must match the return type specified in the
function declaration. For instance, if a function is declared to return an int, the expression
in the return statement must be evaluated as an int.
No Return Value: For functions declared with a void return type, the return statement can
be used without an expression to exit the function. In this case, it simply serves to end the
function‘s execution.
Control Flow: The return statement can be placed anywhere within a function, but it‘s
typically used at the end or within conditional statements to return different values based on
certain conditions.
return a + b;
In functions declared as void (meaning they do not return a value), the return statement can
be used to exit the function early without an expression. For example:
void displayMessage() {
printf("Hello, World!");
}
UNIT III
Example:-
Declaration of Arrays :
We have to declare an array by specifying its name, the type of its elements, and the size
of its dimensions.
When we declare an array in C, the compiler allocates the memory block of the specified
size to the array name.
1. Syntax of an array :
Where,
(iii) Maximum subscript appearing in a program for a subscripted variable should not exceed
the declared one
(iv) Subscript value ranges from 0 to one less than the maximum size.
If an array has three elements then first subscript is 0 second subscript 1 and last
subscript is 2.
3. Total Size :
Where ,
sizeof() → used to calculate the size (in bytes)that a data type occupies in the computer's
memory
Initialization of an array :
In this method, we initialize the array along with its declaration. We use an initializer
list to initialize multiple elements of the array. An initializer list is the list of values enclosed
within braces { } separated b a comma
.
Syntax :
data_type array_name[size]
={element1,element2,…..element n}
Where,
element1,element2,…element n → are the initial values enclosed within a pair of curly braces
and all these elements must be separated by comma and these elements must be written in the
order in which they will be assigned.
Example :
If we initialize an array using an initializer list, we can skip declaring the size of the
array as the compiler can automatically deduce the size of the array in these cases. The size of
the array in these cases is equal to the number of elements present in the initializer list as the
compiler can automatically deduce the size of the array.
The size of the above arrays is 5 which is automatically deduced by the compiler.
array_name [index];
The first element is mark[0], the second element is mark[1] and so on.
Important Points :
1. Arrays have 0 as the first index, not 1.
In this example, mark[0] is the first element.
output :
First Element = 19
2. If the size of an array is n, to access the last element, the n-1 index is used. In this
example, mark[4]
3. Suppose the starting address of mark[0] is 2120d. Then, the address of
the mark[1] will be 2124d. Similarly, the address of mark[2] will be 2128d and so
on.This is because the size of a float is 4 bytes.
#include <stdio.h>
void main()
for(int i =0 ; i<5;i++)
Printf(―marks[%d]=%d \n‖,i,marks[i]);
Output :
marks[0]=19
marks[1]=10
marks[2]=8
marks[3]=17
marks[4]=9
Processing of an array :
The whole array cannot be processed as a single element .But it allows programmer to
perform certain operation element by element basis
Types of Array in C
There are two types of arrays based on the number of dimensions it has.
Syntax of 1D Array
array_name [size];
Example
#include <stdio.h>
int main()
int arr[5];
int n;
scanf(―%d‖,&n);
return 0;
2. Two-Dimensional Array
Two-Dimensional array or 2D array in C is an array that has exactly two dimensions.
Multi-dimensional Arrays in C are those arrays that have more than one dimension.
Some of the popular multidimensional arrays are 2D arrays and 3D arrays.
They can be visualized in the form of rows and columns organized in a two-dimensional
plane.
Syntax of 2D Array
array_name[size1] [size2];
Here,
Example :
#include <stdio.h>
int main()
printf("2D Array:\n");
printf("%d ",arr[i][j]);
}
printf("\n");
return 0;
In C, the whole array cannot be passed as an argument to a function. However, you can
pass a pointer to an array without an index by specifying the array‘s name.
Arrays in C are always passed to the function as pointers pointing to the first element of
the array.
Syntax
In C, we have three ways to pass an array as a parameter to the function. In the
function definition, use the following syntax:
Mentioning the size of the array is optional. So the syntax can be written as:
return_type foo ( array_type array_name[], ...);
In both of the above syntax, even though we are defining the argument as array it will
still be passed as a pointer. So we can also write the syntax as:
return_type foo ( array_type* array_name, ...);
But passing an array to function results in array decay due to which the array loses
information about its size. It means that the size of the array or the number of elements of
the array cannot be determined anymore.
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
int main() {
result = calculateSum(num);
return 0;
sum += num[i];
return sum;
Array of strings
Syntax:
Here,
c is the maximum number of character values that can be stored in each string array.
Example:
#include <stdio.h>
// Driver code
int main()
printf("%s\n", arr[i]);
return 0;
Example:
Advantage of functions in C
o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
Types of Functions
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
Parts of a function:
1. Function declaration/Prototype/Syntax.
2. Function Calling.
3. Function Definition.
1.)Function Declaration:
The process of writing a code for performing any specific task is called function defination.
Syntax:
<return type><function name>(<type of arguments>)
{
#include<conio.h>
void main()
int c,n;
int cube(int);
printf("Enter a no.");
scanf("%d",&n);
c=cube(n);
int cube(int n)
{
c=n*n*n;
return(c);
}
Return Value
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.
A function may or may not accept any argument. It may or may not return any value. Based
on these facts, There are four different aspects of function calls.
Example 1
#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Everyone");
}
Output
Hello Everryone
#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
The sum is 34
The sum is 34
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30
C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by
the designers of compilers. All C standard library functions are defined inside the different
header files saved with the extension .h. We need to include these header files in our program
to make use of the library functions defined in such header files. For example, To use the
library functions such as printf/scanf we need to include stdio.h in our program which is a
header file that contains all the library functions regarding standard input/output.
SN Header Description
file
1 stdio.h This is a standard input/output header file. It contains all the library
functions regarding standard input/output.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(),
calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like
sqrt(), pow(), etc.
9 signal.h All the signal handling functions are defined in this header file.
Scope of Variable
Each variable is defined and can be used within its scope and determines that wherein the
program this variable is available to use. The scope means the lifetime of that variable. It
means the variable can only be accessed or visible within its scope.
The scope of variables can be defined with their declaration, and variables are declared
mainly in two ways:
Global Variable
o Global variables are those variables which are declared outside of all the functions or
block and can be accessed globally in a program.
o Once we declare a global variable, its value can be varied as used with different
functions.
o The lifetime of the global variable exists till the program executes. These variables are
stored in fixed memory locations given by the compiler and do not automatically
clean up.
o Global variables are mostly used in programming and useful for cases where all the
functions need to access the same data.
#include<stdio.h>
int a=50, b=40;
void main()
{
printf("a = %d and b=%d",a,b);
}
Advantages of Global Variable
o Global variables can be accessed by all the functions present in the program.
o Very useful if all the functions are accessing the same data.
Local Variable
o Variables that are declared within or inside a function block are known as Local
variables.
o These variables can only be accessed within the function in which they are declared.
o The lifetime of the local variable is within its function only, which means the variable
exists till the function executes. Once function execution is completed, local variables
are destroyed and no longer exist outside the function.
o The reason for the limited scope of local variables is that local variables are stored in
the stack, which is dynamic in nature and automatically cleans up the data stored
within it.
#include<stdio.h>
void main()
{
int x=50, y=40;
printf("x = %d and y=%d",x, y);
}
In the above example, we have declared x and y two variables inside the main function.
Hence these are local variables.
o The same name of a local variable can be used in different functions as it is only
recognized by the function in which it is declared.
o Local variables use memory only for the limited time when the function is executed;
after that same memory location can be reused.
Comparison Chart Between Global Variable and Local Variable
Global variables are declared outside all Local Variables are declared within a function block.
the function blocks.
The scope remains throughout the The scope is limited and remains within the function
program. only in which they are declared.
Any change in global variable affects the Any change in the local variable does not affect other
whole program, wherever it is being functions of the program.
used.
A global variable exists in the program A local variable is created when the function is
for the entire time the program is executed, and once the execution is finished, the
executed. variable is destroyed.
It can be accessed throughout the It can only be accessed by the function statements in
program by all the functions present in which it is declared and not by the other functions.
the program.
If the global variable is not initialized, it If the local variable is not initialized, it takes the
takes zero by default. garbage value by default.
Global variables are stored in the data Local variables are stored in a stack in memory.
segment of memory.
We cannot declare many variables with We can declare various variables with the same name
the same name. but in other functions.
Recursion
Recursion is the process which comes into existence when a function calls a copy of itself to
work on a smaller problem. Any function which calls itself is called recursive function, and
such function calls are called recursive calls. Recursion involves several numbers of recursive
calls. However, it is important to impose a termination condition of recursion. Recursion code
is shorter than iterative code however it is difficult to understand.
A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is returned from the function.
Recursive function for Calculating factorial of a number
#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}