0% found this document useful (0 votes)
18 views73 pages

Wa0003.

The document provides an overview of computer fundamentals, including the definition, characteristics, and components of computers. It explains the roles of hardware and software, the binary number system, programming languages, and problem-solving techniques such as algorithms and flowcharts. Additionally, it details the functions of input and output devices, memory types, and the processes involved in programming and executing tasks on a computer.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views73 pages

Wa0003.

The document provides an overview of computer fundamentals, including the definition, characteristics, and components of computers. It explains the roles of hardware and software, the binary number system, programming languages, and problem-solving techniques such as algorithms and flowcharts. Additionally, it details the functions of input and output devices, memory types, and the processes involved in programming and executing tasks on a computer.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

UNIT I

A Computer is an electronic device which performs operations such as accepts data As an


input, store the data, manipulate or process the data and produce the results an output.

Main task performed by a computer

• Accept the data

• Process or manipulate the data

• Display or store the result in the form of human understanding

• Store the data, instructions and results

Basic Characteristics of Computer


 Speed - A computer device‘s speed is extremely fast, as it can perform any calculation in
seconds. This is one of their key characteristics.
 Accuracy – This is an characteristic of computers, which is their high level of accuracy. It
is capable of performing 100% accurate calculations.
 Diligence - A computer is free of fatigue, lack of concentration, and so on. This is what
makes a computer work for hours without making any mistakes. It never gets tired.
 Reliability - A computer is a dependable machine that is capable of performing all tasks
and operations at high speeds and with near-perfect accuracy.

Memory - Memory is the storage space on it where data is processed and processing

instructions are stored. It has both primary and secondary memories.

The task we are currently working on is saved in the main memory, and the task we saved is

saved until we delete it.


Logical - A computer system has certain characteristics, such as the capability of thinking,

reasoning, and learning.

These characteristics help them perform tasks logically and these characteristics have been

further developed into what we today know as Artificial Intelligence.


Versatility - Because computers are so versatile, they can perform almost any task that can

be reduced to a series of logical steps.

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.

In computing, automation is typically accomplished through the use of a program, a script, or

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.

 Remembrance Power - A computer is capable of storing an unlimited amount of


information or data. Any information can be stored and retrieved for as long as you need it,
for an unlimited number of years.
.

Block Diagram of computer

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:

• Keyboard - A standard keyboard includes alphanumeric keys, function keys, modifi er


keys, cursor movement keys, spacebar, escape key, numeric keypad, and some special keys,
such as Page Up, Page Down, Home, Insert, Delete and End. The alphanumeric keys include
the number keys and the alphabet keys. The function keys are the keys that help perform a
specifi c task such as searching a fi le or refreshing a Web page

• 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.

The commonly used primary memories are as follows:

• 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

Decimal to Binary 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.

Three levels of programming languages are available. They are:

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

ORG 500 /Origin of program is location 500

LDA SUB /Load subtrahend to AC

CMA /Complement AC
INC /Increment AC

ADD MIN /Add minuend to AC

STA DIF /Store difference

HLT /Halt computer

3. procedure-oriented languages (high level languages) -- High level languages further


simplifi ed programming tasks by reducing the number of computer operation details that had
to be specifi ed. High level languages like COBOL, Pascal, FORTRAN, and C are more
abstract, easier to use, and more portable across platforms, as compared to low-level
programming languages. Instead of dealing with registers, memory addresses and call stacks,
a programmer can concentrate more on the logic to solve the problem with help of variables,
arrays or Boolean expressions. It has English like statements.

The program Control flow in computer

Assembler -- An assembler is a computer program that translates assembly language


statements into machine language codes. The assembler takes each of the assembly language
statements from the source code and generates a corresponding bit stream using 0‘s and 1‘s.
The output of the assembler in the form of sequence of 0‘s and 1‘s is called object code or
machine code.

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.

PROBLEM SOLVING TECHNIQUES

The following steps are performed while solving a problem:

1. Analyze the given problem.

2. Divide the process used to solve the problem in a series of elementary tasks.

3. Formulate the algorithm to solve the problem.

4. Express the algorithm as a precise notation, which is known as a computer program.

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

An algorithm should have step-by-step directions, which should be independent of any


programming code.It should be such that it could be run on any of the programming
languages.
Flowcharts
To visualize the working of an algorithm, one needs to take the help of a fl ow chart, which is
the pictorial representation of the algorithm depicting the fl ow of the various steps.

1. Algorithm to find biggest of 3 numbers

Step 1: Start

Step 2: Read 3 numbers and store in A, B, C

Step 3: Compare A and B. lf A > B then go to step 6

Step 4: Compare B and C if C > B then go to step 8

Step 5: print ―B is largest‖ go to step 9

Step 6: Compare A and C if C > A then go to step 8

Step 7: Print‖A is largest‖ go to step 9

Step 8: Print ―C is largest‖

Step 9: Stop
Flowchart

Algorithm to reverse an Integer

Step 1: start

Step 2 :Declare a variable n, reverse and remainder as integer;

Step 3: Read the number n;

Step 5:while n not equal 0

remainder=n%10;

reverse=reverse * 10 + remainder;

n=n/10;

Step 6: Print reverse

Step 7: stop
Flowchart

Algorithm for GCD of 2 integers

Step 1 :Start

Step 2. Read two input values using input function

Step 3. Convert them into integers

Step 4. Define a function to compute GCD

a. Find smallest among two inputs

b. Set the smallest

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

d. Return the gcd


Step 5. Call the function with two inputs

Step 6. Display the result

Step 7. Stop

Flowchart
Algorithm for Generating N prime numbers

Step 1 : Start

Step 2: Read lower & Upper bound values for the Range

Step 3. For each number in the Range

Step4. Divide the num by 2 to num-1

Step 5. Check the remainder

If Remainder == 0 then,

Num is not a prime number.

Else

Print the Number as Prime

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

1. Read the number of terms in the series, say n.

2. Set a = 0 and b = 1.

3. Print the value of a and b.

4. Set count = 2.

5. While count £ n, c = a + b.

6. Print the value of c.

7. Set a = b and b = c.

8. Increase the value of count by 1.

9. Repeat steps 5 to 8, until count becomes equal to n.

Flowchart
Algorithm for finding even or odd

Step 1: Start

Step 2: Read a number to N

Step 3: Divide the number by 2 and store the remainder in R.

Step 4: If R = O Then go to Step 6

Step 5: Print ―N is odd‖ go to step 7

Step 6: Print ―N is even‖

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.

Programs written in C are effi cient and fast.

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.

Rules for Naming Identifiers

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

const int c_var = 20;


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++.

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

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to 2,147,483,647

signed long int 4 byte -2,147,483,648 to 2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 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.

1. int age = 25;


2. char grade = 'A';
3. float temperature = 98.6;
4. double pi = 3.14159265359;

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

S. No. Symbol Operator Description Syntax

Adds two
+ Plus a+b
1 numeric values.

Subtracts right
– Minus operand from left a – b
2 operand.

3 * Multiply Multiply two a * b


numeric values.

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.

Flips the sign of


– Unary Minus -a
7 the value.

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.

S. No. Symbol Operator Description Syntax

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.

S. No. Symbol Operator Description Syntax

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.

S. No. Symbol Operator Description Syntax

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.

Flips all the set


Bitwise First
~ and unset bits on ~a
Complement
4 the number.

Shifts the number


in binary form by
<< Bitwise Leftshift one place in the a << b
operation and
5 returns the result.

Shifts the number


Bitwise in binary form by
>> a >> b
Rightshilft one place in the
6 operation and
returns the result.

Examples discussed in class

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.

S. No. Symbol Operator Description Syntax

Assign the value


Simple of the right
= a=b
Assignment operand to the
1 left operand.

Add the right


operand and left
operand and
+= Plus and assign a += b
assign this value
to the left
2 operand.

Subtract the right


operand and left
operand and
-= Minus and assign a -= b
assign this value
to the left
3 operand.

Multiply the right


operand and left
Multiply and operand and
*= a *= b
assign assign this value
to the left
4 operand.
Divide the left
operand with the
right operand and
/= Divide and assign a /= b
assign this value
to the left
5 operand.

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

Format Specifier Data Type

%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

printf(―Format Specifier‖, var1, var2, …., varn);

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

scanf(―Format Specifier‖, &var1, &var2, …., &varn);

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

sscanf(array_name, ―format specifier‖, &variable_name);

Unformatted Input/Output functions

 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.

2. In Most of Programs its necessary to


I. Select a set of statement from several alternatives
II. Skip certain statements depending on some condition and continue its execution
from some other point
III. Repeat set of statements for known number of times until a specific condition is
fulfilled
Under all the above situations we use control statements and they are called Control
Structures and they define the order of execution of statements in program.

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

Conditional Control Statements

 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

 Conditional Execution involves both decision making and branching

 Following are some of Conditional Control Statements


1. if - statement
2. if-else statement
3. Nested-if statement
4. switch statement

If.. statement :

1. Its is one -way branching statement


2. if statement is used to specify a block of code to be executed if a condition is true
3. Syntax
if (condition)

{
// block of code to be executed if the condition is true
}

4. How if statement works?


Step 1: When the program control comes to the if statement, the test expression is evaluated.

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.

// Program to display a number if it is negative

#include <stdio.h>

int main() {

int number;

printf("Enter an integer: ");

scanf("%d", &number);

if (number < 0) {

printf("You entered %d.\n", number);

}
printf("The if statement is easy.");

return 0;

Output 1

Enter an integer: -2

You entered -2.

The if statement is easy.

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

The if statement is easy.

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

//code executed when the condition is false

5. How if..else Statement Works ?


Step 1 :When the program control first comes to the if-else block, the test condition is
checked.

Step 2: If the test condition is true-The if block is executed.

Step 3 : If the test condition is false-The else block is executed

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;

if...else Ladder (Nested if)


1. Extension to the if-else statement
2. It is used when there are multiple cases to be performed for different conditions.
3. if a condition is true then the statements defined in the if block will be executed, otherwise
if some other condition is true then the statements defined in the else-if block will be
executed, at the last if none of the condition is true then the statements defined in the else
block will be executed
4. Syntax
if(condition1)

//code to be executed if condition1 is true

}else if(condition2)

//code to be executed if condition2 is true

else if(condition3)

//code to be executed if condition3 is true

else

//code to be executed if all the conditions are false

}
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:

code to be executed if all cases are not matched;

5. How Switch statement works ?


Step 1 : The switch expression is evaluated once

Step 2 : The value of the expression is compared with the values of each case

Step 3 : If there is a match, the associated block of code is executed

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;

printf("The day with number %d is ", day);

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;

Difference Between If else and Switch Statement :

goto statement

1. allows us to transfer control of the program to the specified label


2. jump statement which is sometimes also referred to as an unconditional jump statement.
3. The goto statement can be used to jump from anywhere to anywhere within a function.
4. Syntax
label:

//some part of the code;

goto label;

Example :

#include <stdio.h>
int main()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
return 0;
}

Loop Control Structures


1. Looping is the powerful programming technique through which a group of statements are
executed repeatedly until certain specified condition is satisfied.
2. Looping is also called a repetitive or iterative control
3. Loop program consists of 2 parts
A. Body of the loop
B. Control statements
Control statement perform logical test true or false based on that loop are executed otherwise
loop is terminated

4. There are 2 types of loop statements


A. Entry Controlled loop -- Control Statement written before body of loop statements
.
B. Exit Controlled Loop -- Control statement written after body of loop statements
5. C provides 3 types of loop control structures :
A. The while statement
B. The do .. while statement
C. The for statement
6. Why use loops in C language?
A. The looping simplifies the complex problems into the easy ones.
B. It enables us to alter the flow of the program so that instead of writing the same code
again and again, we can repeat the same code for a finite number of times.
C. For example, if we need to print the first 10 natural numbers then, instead of using
the printf statement 10 times, we can print inside a loop which runs up to 10 iterations.
7. Advantage of loops in C
1) It provides code re-usability.

2) Using loops, we do not need to write the same code again and again.

3) Using loops, we can traverse over the elements of data structures

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) {

// the body of the loop

5. How while loop works?


1) The while loop evaluates the test-expression inside the parentheses ().
2) If test-expression is true, statements inside the body of while loop are executed.
3) Then, test-expression is evaluated again.The process goes on until test-expression is
evaluated to false.
4) If test-expression is false, the loop terminates (ends).
Example :

// Print numbers from 1 to 5

#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;

Difference between while and do while


For loop
1. The for loop in C Language provides a functionality/feature to repeat a set of statements a
defined number of times. The for loop is in itself a form of an entry-controlled loop.
2. Unlike the while loop and do…while loop, the for loop contains the initialization,
condition, and updating statements as part of its syntax.
3. Syntax
for(initialization; check/test expression; increment/decrement)

// body consisting of multiple statements

4. Structure of for Loop


The for loop follows a very structured approach where it begins with initializing a condition
then checks the condition and in the end executes conditional statements followed by an
updation of values.

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.

5. How for Loop Works?

The working of for loop is mentioned below:

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 3: All the statements inside the loop are executed.

Step 4: Updating the values of variables has been done as defined in the loop.
Continue to Step 2 till the loop breaks.
Example :

// Print numbers from 1 to 10#include <stdio.h>

int main() {

int i;

for (i = 1; i < 11; ++i)

printf("%d ", 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.

The break statement

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:

To come out of the loop.

To come out from the nested loops.

To come out of the switch case.

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.

5. Example of break Statement


The statements inside the loop are executed sequentially. When the break statement is
encountered within the loop and the condition for the break statement becomes true, the
program flow breaks out of the loop, regardless of any remaining iterations.

#include <stdio.h>

int main()

int i;

// for loop

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


// when i = 6, the loop should end

if (i == 6) {

break;

printf("%d ", i);

printf("Loop exited.\n");

return 0;

Explanation:

Loop Execution Starts and goes normally till i = 5.

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

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

if (i == 2) {

// continue to be executed if i = 2

printf("Skipping iteration %d\n", i);

continue;

printf("Executing iteration %d\n", i);

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.

3. Here‘s a breakdown of how it works:


Exiting the Function: When a return statement is executed, the current function is
terminated immediately. If the return statement is in the main function, it terminates the
program.

Returning a Value: The expression in the return statement is optional. If provided, it is


evaluated, and its value is returned to the function caller. This is useful for functions that
compute a value that needs to be used by 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.

4. Usage in Functions Returning a Value:


In functions declared to return a value (other than void), the return statement is used to
specify the value to be returned.

For example, in a function returning an int, you might have:

int add(int a, int b) {

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!");

return; // Optional here, used for early exit

}
UNIT III

ARRAYS,STRINGS AND FUNCTIONS


DEFINATION :

 An array is an ordered list of homogeneous data elements


( Homogeneous data elements -- contain only similar type of data.

Example:-

Elements containing only integer or float values not both )

 The Elements in an array may be of datatype int,float,char or double


 All these elements are stored in consecutive memory locations (on RAM)
 It is the simplest data structure where each data element can be randomly accessed by
using its index number.
 It is a simple and fast way of storing multiple values under a single name

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 :

data_type array_name [size];

Where,

Array_name → name of array

Size → Number of elements of datatype

Size must be always in integer → Constant specified in square brackets

Data_type → int,char,float or double


Example :

1) int list[10] → Array named list of 10 integer constants


2) Char name[5] → Array named name and stores 20 characters
3) Float xyz[5] → Array named xyz and can store 5 floating point numbers

2. Rules for subscripts :

(i) Each subscript must be an unsigned positive integer constant or an expression

(ii) Subscript of a subscript is not permitted

(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 :

Total size = size * (sizeof(data_type));

Where ,

size → number of elements in an array

sizeof() → used to calculate the size (in bytes)that a data type occupies in the computer's
memory

data_type → basic data type.

Initialization of an array :

 Initialization is nothing but assigning some value to the array variable


1. Array Initialization with Declaration

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,

data_type → basic datatype

array_name → name of an array

size → maximum number of elements

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 :

int mark[5] = {19, 10, 8, 17, 9};

2. Array Initialization with Declaration without Size

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.

int mark[] = {19, 10, 8, 17, 9};

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)


We initialize the array after the declaration by assigning the initial value to each
element individually. We can use for loop, while loop, or do-while loop to assign the value to
each element of the array.

for (int i = 0; i < N; i++) {


array_name[i] = value[i];
}

Accessing of Array Elements :

 We can access elements of an array by indices.


 We can access any element of an array in C using the array subscript operator [ ] and the
index value i of the element.
Syntax

array_name [index];

 Suppose you declared an array mark as


int mark[5] = {19,10,8,17,9}

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.

Printf (―First Element = %d‖,mark[0])

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.

// Program to demonstrate the declaration,initialization and accessing of an array

#include <stdio.h>

void main()

int marks[5] = {19,10,8,17,9};

Printf(―Elements of an array are :\n‖);

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

Printf(―marks[%d]=%d \n‖,i,marks[i]);

Output :

Elements of an array are :

marks[0]=19

marks[1]=10

marks[2]=8

marks[3]=17

marks[4]=9

Processing of an array :

C does not support performing any operation on the entire 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.

They are as follows:

1. One Dimensional Arrays (1D Array)


2. Two Dimensional Arrays (2D Array / Multidimensional Arrays)

1. One Dimensional Array in C


 The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have
only one dimension.
 Its also called single dimensional array or single subscripted array
 It contains a series of elements of the same datatype.
 The elements are zero-indexed, meaning the first element is in position or index 0, and
the last element is in position or index (array size) - 1.

Syntax of 1D Array

array_name [size];

Example

#include <stdio.h>

int main()

int arr[5];

int n;

printf(―Enter umber of elements‖);

scanf(―%d‖,&n);

for (int i = 0; i < n; i++) {


Scanf(―%d‖,&arr[i]);

printf("Elements of Array: ");

for (int i = 0; i < n; i++) {

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

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,

size1: Size of the first dimension.

size2: Size of the second dimension.

Example :

#include <stdio.h>

int main()

int arr[2][3] = { 10, 20, 30, 40, 50, 60 };

printf("2D Array:\n");

for (int i = 0; i < 2; i++) {

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

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

}
printf("\n");

return 0;

Passing Arrays to Function :

 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:

return_type foo ( array_type array_name[size], ...);

 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>

float calculateSum(float num[]);

int main() {

float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

// num array is passed to calculateSum()

result = calculateSum(num);

printf("Result = %f", result);

return 0;

float calculateSum(float num[]) {

float sum = 0.0;

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

sum += num[i];

return sum;

Array of strings

 In C programming String is a 1-D array of characters and is defined as an array of


characters.
 But an array of strings in C is a two-dimensional array of character types.
 Each String is terminated with a null character (\0). It is an application of a 2d array.

Syntax:

char variable_name[r] = {list of string};

Here,

variable_name is the name of the variable in C.


r is the maximum number of string values that can be stored in a string array.

c is the maximum number of character values that can be stored in each string array.

Example:

// C Program to print Array of strings

#include <stdio.h>

// Driver code

int main()

char arr[3][10] = {"apple", "mango", "grapes"};

printf("String array Elements are:\n");

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

printf("%s\n", arr[i]);

return 0;

Invalid Operations in Arrays of Strings

We can‘t directly change or assign the values to an array of strings in C.

Example:

char arr[3][10] = {"apple", "mango", "grapes"};


Functions
A function is itself a block of code which can solve simple or complex task/calculations. A
function performs calculations on the data provided to it is called "parameter" or "argument".
A function always returns single value result.
In c, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by {}. A function can be
called multiple times to provide reusability and modularity to the C program. In other words,
we can say that the collection of functions creates a program. The function is also known
as procedureor subroutine in other programming languages.

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.

o Reusability is the main achievement of C functions.

o However, Function calling is always a overhead in a C program.

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:

Syntax: <return type > <function name>(<type of argument>)


The declaration of function name, its argument and return type is called function declaration.

2.) Function Calling:

The process of calling a function for processing is called function calling.


Syntax: <var_name>=<function_name>(<list of arguments>).

3.) Function defination:

The process of writing a code for performing any specific task is called function defination.
Syntax:
<return type><function name>(<type of arguments>)
{

<statement-1> <statement-2> return(<vlaue>)


}

Write a Program to compute cube of a number using function.


#include<stdio.h>

#include<conio.h>

void main()

int c,n;

int cube(int);

printf("Enter a no.");

scanf("%d",&n);

c=cube(n);

printf("cube of a no. is=%d",c);

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.

Different aspects of function calling

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.

o function without arguments and without return value

o function without arguments and with return value

o function with arguments and without return value

o function with arguments and with return value

Function without argument and return value

Example 1

#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("Everyone");
}

Output

Hello Everryone

Function without argument and with return value

#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

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Function with argument and without return value


#include<stdio.h>
void 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);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Function with argument and with return value

#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.

2 conio.h This is a console input/output header file.

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.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header file.

10 setjmp.h This file contains all the jump functions.

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.


Local and Global variables
A variable is a name given to a memory location to store values in a computer program. It is
used to store information that can be referenced and manipulated in a program.

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:

o Global Variable: Outside of all the functions

o Local Variable: Within a function block:

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 It can be accessed by any function present in the 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 Only a single declaration is required.

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.

Advantages of Local Variable

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 Variable 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);
}
}

You might also like