Programming For Problem Solving-4
Programming For Problem Solving-4
Course Outcomes
The student will learn
To formulate simple algorithms for arithmetic and logical problems.
To translate the algorithms to programs (in C language).
To test and execute the programs and correct syntax and logical errors.
To implement conditional branching, iteration and recursion.
To decompose a problem into functions and synthesize a complete program using divide and conquer
approach.
To use arrays, pointers and structures to formulate algorithms and programs.
To apply programming to solve matrix addition and multiplication problems and searching and sorting
problems.
To apply programming to solve simple numerical method problems, namely rot finding of function,
differentiation of function and simple integration.
Unit 1
Introduction to Programming (4 lectures)
Introduction to components of a computer system (disks, memory, processor, where a program is stored
and executed, operating system, compilers etc.) - (1 lecture).
Idea of Algorithm: steps to solve logical and numerical problems. Representation of Algorithm:
Flowchart/Pseudocode with examples. (1 lecture)
From algorithms to programs; source code, variables (with data types) variables and memory locations,
Syntax and Logical Errors in compilation, object and executable code- (2 lectures)
Unit 2
Arithmetic expressions and precedence (2 lectures)
Conditional Branching and Loops (6 lectures)
Writing and evaluation of conditionals and consequent branching (3 lectures)
Iteration and loops (3 lectures)
Unit 3
Arrays (6 lectures) Arrays (1-D, 2-D), Character arrays and Strings
Unit 4
Basic Algorithms (6 lectures) Searching, Basic Sorting Algorithms (Bubble, Insertion and Selection),
Finding roots of equations, notion of order of complexity through example programs (no formal definition
required)
Unit 5
Function (5 lectures) Functions (including using built in libraries), Parameter passing in functions, call by
value, Passing arrays to functions: idea of call by reference
Unit 6
Recursion (4 -5 lectures) Recursion, as a different way of solving problems. Example programs, such as
Finding Factorial, Fibonacci series, Ackerman function etc. Quick sort or Merge sort.
Unit 7
Structure (4 lectures) Structures, Defining structures and Array of Structures
Unit 8
Pointers (2 lectures) Idea of pointers, Defining pointers, Use of Pointers in self-referential structures,
notion of linked list (no implementation)
Unit 9
File handling (only if time is available, otherwise should be done as part of the lab)
Introduction to Programming
Programming is the mental process of thinking up instructions to give to a machine (like a computer).
Coding is the process of transforming those ideas into a written language that a computer can
understand.
A programming language is a set of rules that provides a way of telling a computer what
operations to perform.
A programming language defines a set of instructions that are compiled together to perform a
specific task by the CPU (Central Processing Unit).
A programming language is a set of rules for communicating an algorithm.
It provides a linguistic framework for describing computations.
Low-level language
The low-level language is a programming language that provides no abstraction from the hardware, and it
is represented in 0 or 1 forms, which are the machine instructions. The languages that come under this
category are the Machine level language and Assembly language.
Machine-level language
The machine-level language is a language that consists of a set of instructions that are in the binary form
0 or 1. Operation code- such as addition or subtraction. Operands specifies the data to be processed.
Machine language is machine dependent as it is the only language the computer can understand. Very
efficient code but difficult to write. It is error-prone as it is not easy to understand, and its maintenance is
also very high. A machine-level language is not portable as each computer has its machine instructions,
so if we write a program in one computer will no longer be valid in another computer. The different
processor architectures use different machine codes, for example, a PowerPC processor contains RISC
architecture, which requires different code than intel x86 processor, which has a CISC architecture.
Assembly Language
The assembly language contains some human-readable commands such as mov, add, sub, etc. The
problems which we were facing in machine-level language are reduced to some extent by using an
extended form of machine-level language known as assembly language. Symbolic operation code
replaced binary operation codes. Each assembly language instruction is translated into one machine
language instruction. It is very efficient code and easier to write. As we know that computers can only
understand the machine-level instructions, so we require a translator that converts the assembly code into
machine code. The translator used for translating the code is known as an assembler. The assembly
language code is not portable because the data is stored in computer registers, and the computer has to
know the different sets of registers. The assembly code is not faster than machine code because the
assembly language comes above the machine language in the hierarchy, so it means that assembly
language has some abstraction from the hardware while machine language has zero abstraction.
High-Level Language
The high-level language is a programming language that allows a programmer to write the programs
which are independent of a particular type of computer. The high-level languages are considered as high-
level because they are closer to human languages than machine-level languages. When writing a
program in a high-level language, then the whole attention needs to be paid to the logic of the
problem. A compiler is required to translate a high-level language into a low-level language.
o The high-level language is easy to read, write, and maintain as it is written in English like words.
o The high-level languages are designed to overcome the limitation of low-level language, i.e.,
portability. The high-level language is portable; i.e., these languages are machine-independent.
C Programming Language
The C Language is developed by Dennis Ritchie in early 1970s for creating system applications that
directly interact with the hardware devices such as drivers, kernels, etc. C programming is considered as
the base for other programming languages, that is why it is known as mother language. C provides control
and efficiency of assembly language. Eg. UNIX is written in C.
C as a mother language
C language is considered as the mother language of all the modern programming languages because most
of the compilers, JVMs, Kernels, etc. are written in C language, and most of the programming
languages follow C syntax, for example, C++, Java, C#, etc.
It provides the core concepts like the array, strings, functions, file handling, etc. that are being used in
many languages like C++ (It is C language with additional features and widely used for developing
system and application software. With the help of C++, graphical user interfaces can be developed easily
with visual programming tools),
Java (It is an object-oriented language similar to C++ which allows a web page developer to create
programs for applications, called applets that can be used through a browser)., C#, etc.
It can't be used for internet programming like Java, .Net, PHP, etc.
C as a procedural language
A procedure is known as a function, method, routine, subroutine, etc. A procedural language specifies a
series of steps for the program to solve the problem.
A procedural language breaks the program into functions, data structures, etc.
C is a procedural language. In C, variables and function prototypes must be declared before being used.
n the C language, we break the program into parts using functions. It makes the program easier to
understand and modify.
A Low-level language is specific to one machine, i.e., machine dependent. It is machine dependent, fast
to run. But it is not easy to understand.
A High-Level language is not specific to one machine, i.e., machine independent. It is easy to understand
Formerly: Run-time performance (when computers were more expensive than programmers).
Now: Life-cycle (human) cost is more important
Writability: It specifies the quality of a language that enables a programmer to use it ot express a
computational clearly, correctly, concisely and quickly.
Readability: The quality of a language that enables a programmer to understand and comprehend the
nature of a computation easily and accurately.
Orthogonality: This parameter specifies the features provided have as few restrictions as possible and be
combinable in any meaningful way.
Reliability: The quality of a language that assures a program will not behave in unexpected of disastrous
ways during execution.
Maintainability: The quality of a language which eases of error finding and correction and new features
support.
Generality: This quality avoids special cases in the availability or use of constructs and by combining
closely related constructs into a single more general one.
Uniformity: This quality specifies that similar features should look similar and behave similar.
Extensibility: It provides some general mechanism for the user to add new constructs to a language.
Standardability: Quality that allows program written to be transported from one computer to another
without significant change in a language structure.
Implementability: Quality of a language that provides a translator or interpreter can be written. This can
address to complexity of the language definition.
Computer
A computer is an electronic device that accepts data from the user, processes it, produces results,
displays them to the users, and stores the results for future usage.
Data is a collection of unorganized facts (unstructured) & figures and does not provide any further
information regarding patterns, context, etc. Hence data means "unstructured facts and figures".
Information is a structured data i.e. organized meaningful and processed data. To process the data and
convert into information, a computer is used.
Components of Computer System
Computer systems consist of three components as shown in below image: Central Processing Unit,
Input devices and Output devices.
1. Central Processing Unit
The Central Processing Unit (CPU) is called "the brain of computer" as it controls operation of all parts
of computer. It consists of two components: Arithmetic Logic Unit (ALU), and Control Unit.
(a)Arithmetic Logic Unit (ALU) - Data entered into computer is sent to RAM, from where it is then sent
to ALU, where rest of data processing takes place. All types of processing, such as comparisons,
decision-making and processing of non-numeric information takes place here and once again data is
moved to RAM.
(b) Control Unit - As name indicates, this part of CPU extracts instructions, performs execution,
maintains and directs operations of entire system. Control unit performs following functions:
2. Input devices
It provides data input to processor, which processes data and generates useful information that’s displayed
to the user through output devices. This is stored in computer’s memory. Eg. Keyboard, Mouse &
microphone etc.
3. Output Devices
These devices include printed documents, on-screen data and sound. An output device allows data to be
transmitted by the computer in a human-friendly form, for example, sound being played through a
speaker.
Monitor - The main output device of a computer. It forms images by converting electrical energy into
light in the form of tiny dots on the screen called pixels. The sharpness of the image depends upon the
number of pixels.
Printer - Used to print information on paper. Commonly uses either lasers or inkjets to precisely place
ink onto the page to recreate text and high-quality images.
Speaker - Converts digital signals into audible sound waves.
Projector - A device that is used to project video output from the computer onto a wall or screen.
Memory Unit
This is unit in which data and instructions given to computer as well as results given by computer are
stored. Unit of memory is "Byte". 1 Byte = 8 Bits
Primary Memory : Primary memory is the main memory of computer present in motherboard. Primary
memory is of two types as shown in the image below.
2 The contents are temporary; data is lost The contents are permanent; data is not lost
when electricity supply is lost. even when power is switched off.
7 It is of two types, SRAM and DRAM. It comes in different types such as PROM,
EPROM, EEPROM and flash memory.
Secondary Memory
Sometimes when data to be processed is large, it cannot fit in primary memory as it is limited, in such
cases, we use supplement memory or secondary memory. Secondary memory helps to store information
permanently and is non-volatile. Examples of secondary storage memory are compact disk, floppy disk,
pen drive, external hard drive, etc.
Computer Disks
a computer data storage device such as a hard drive or floppy disk that contains a computer disk
containing sensitive information. Disk may be floppy disk or hard Disk.
Floppy Disk: A floppy disk is a type of storage media that reads data storage information, also known as
a floppy diskette, floppy, or floppy disk that is used to store electronic data, like a computer file.
o Portability: They are relatively small and portable, which is one of the main advantages of
floppy disks. As compared to CDs, 3.5-inch floppy disks are smaller in size. Also, in the case of
transport, they do not require to place. The floppy disk is designed with a plastic casing that
makes it stronger and protects the disk from inside. Comparing with CDs and DVDs, the chance
of scratching the disk is lower as it is always enclosed by the casing.
o Compatibility: It is also an important advantage in terms of data storage devices with older
computers. As older computers may not accept other data storage devices; they are often
compatible with floppy disks. For example, in the early 1990s, computers might not include
a CD or DVD drive at all. Floppy disks were only the option to transfer files off the computer.
Although many newer PCs have floppy drives, these drives are not included in modern PCs and
being phased out. When computer manufacturers were building a custom-made PC, they may
provide floppy drives as an option.
o Storage Space: Floppy disk drives contain limited space for holding information. It provides very low
storage capacity as compared to modern storage mediums.
o File Corruption: File corruption is one of the main disadvantages of the floppy disk. The FDDs are affected
by external factors like heat and magnetic fields. Thus, the stored file could be corrupted on it.
Furthermore, comparing any other storage mediums, floppy disks do not provide more security as they are
more vulnerable to viruses that can be a reason for file damage.
o Reliability Over time:, the use of floppy disks has decreased or stopped till the 2000s. Therefore, many
computer manufacturers had been stopped, including a floppy disk with computers. After this period, it
becomes an unreliable source of storage.
o Physical Damages: The plastic casing was used to make the floppy disk that is very delicate and flexible. It
may get easily break if anyone catches it without proper care.
hard disk
A hard disk is also known as a hard drive or fixed disk. It is said to be rigid magnetic disc that stores data.
It is located within a drive unit. Hard disk is a non-volatile storage device that contains platters and
magnetic disks rotating at high speeds. Non-volatile means the data retains when the computer shuts
down. It is installed internally in our computer systems. Hard disk is located within a drive unit on the
computer's motherboard and comprises one or more platters packed in an air-sealed casing.
The hard disks are robust and can be used for a long time. But hard disks can be crashed, and the main
reason is head crash. If the hard drive is crashed, we may lose all our documents, photos, etc., stored in it.
Compilers
compiler, is a computer software that translates (compiles) source code written in a high-level
language (e.g., C++) into a set of machine-language instructions that can be understood by a digital
computer’s CPU. Compilers are very large programs, with error-checking and other abilities. Some
compilers translate high-level language into an intermediate assembly language, which is then translated
(assembled) into machine code by an assembly program or assembler. Other compilers generate machine
language directly. When executing (running), the compiler first parses (or analyzes) all of the language
statements syntactically one after the other and then, in one or more successive stages or "passes", builds
the output code, making sure that statements that refer to other statements are referred to correctly in the
final code. Traditionally, the output of the compilation has been called object code or sometimes an object
module . (Note that the term "object" here is not related to object-oriented programming.) The object code
is machine code that the processor can execute one instruction at a time.
The Java programming language, a language used in object-oriented programming, introduced the
possibility of compiling output (called bytecode ) that can run on any computer system platform for
which a Java virtual machine or bytecode interpreter is provided to convert the bytecode into instructions
that can be executed by the actual hardware processor. Using this virtual machine, the bytecode can
optionally be recompiled at the execution platform by a just-in-time compiler. A compiler works with
what are sometimes called 3GL and higher-level languages. An assembler works on programs written
using a processor's assembler language.
Operating system
Operating systems usually come pre-loaded on any computer you buy. Most people use the operating
system that comes with their computer, but it's possible to upgrade or even change operating systems. The
three most common operating systems for personal computers are Microsoft Windows, macOS,
and Linux.
Modern operating systems use a graphical user interface, or GUI (pronounced gooey). A GUI lets you
use your mouse to click icons, buttons, and menus, and everything is clearly displayed on the screen
using a combination of graphics and text. Each operating system's GUI has a different look and feel, so if
you switch to a different operating system it may seem unfamiliar at first. However, modern operating
systems are designed to be easy to use, and most of the basic principles are the same.
As computer is the symbol-manipulating machine that follows the set of instructions called a program.
Any computing has to be performed independently without depending on the programming language and
computer. The problem solving techniques includes the following steps:
3. Develop an algorithm
3. As long as the data value exist, add the next data value to the sum and add another data value to the
count.
20+30=50; 50/2=25.
Program
A program consists of a series of instructions that a computer processes to perform, the required
operation. In addition, it also contains some fixed data, required to perform the instructions, and the
process of defining those instructions and data.
Set of computer programs that describe the program are called software.
The process of software development is called Programming and the person who develops the computer
programs is called Programmer. Thus, in order to design a program, a programmer must determine three
basic requirements:
To perform a task using a program, a programmer has to consider various inputs of the program along
with the process, which is required to convert input into desired output. Suppose we want to calculate the
sum of two numbers, A and B, and store the sum in C, here A and B are the inputs, addition is the
process, and C is the output of the program as shown below:
A,B C=A+B C
Input Processing Output
Characteristics of a program
Writability: It specifies the quality of a language that enables a programmer to use it ot express a
computational clearly, correctly, concisely and quickly.
Readability: The quality of a language that enables a programmer to understand and comprehend the
nature of a computation easily and accurately.
Orthogonality: This parameter specifies the features provided have as few restrictions as possible and be
combinable in any meaningful way.
Reliability: The quality of a language that assures a program will not behave in unexpected of disastrous
ways during execution.
Maintainability: The quality of a language which eases of error finding and correction and new features
support.
Generality: This quality avoids special cases in the availability or use of constructs and by combining
closely related constructs into a single more general one.
Uniformity: This quality specifies that similar features should look similar and behave similar.
Extensibility: It provides some general mechanism for the user to add new constructs to a language.
Standardability: Quality that allows program written to be transported from one computer to another
without significant change in a language structure.
Implementability: Quality of a language that provides a translator or interpreter can be written. This can
address to complexity of the language definition.
Problem Analysis
Design Algorithm and Flowchart development
Program coding
Program compilation and execution.
Program debugging and Testing
Documentation
Problem Analysis
Design-Algorithm Flowchart
Problem Coding
Documentation
Once the programme is free from the errors, it is the duty of the programmer to document
all the necessary documents which is provided to the program users as manual.
Helps the users to operate correctly.
Algorithm
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a
certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language. Different algorithms may accomplish the same task, with a different set of instructions,
in more or less same time, space and efforts.
Eg. To determine the largest number out of three numbers A,B and C.
Step 1: Start
Step 2: Read three numbers A,B,C
Step 3: Find the larger number between A and B and store is in MAX AB.
Step 4: Find the larger number between MAX AB and C and store it in MAX.
Step 5: Display MAX.
Step 6: Stop.
The above-mentioned algorithm terminates after six steps. This explains the feature of finiteness.
Every action of the algorithm is precisely defined, hence, there is no scope for ambiguity. Once the
solution is properly designed, the only job left is to code that logic into a programming language.
Characteristics of Algorithm
Flowchart
Pseudocode
Pseudocode is made of two words: pseudo and code. Pseudo means imitation and code refers
to instructions, written in programming language. As the name suggests, it is not a real
programming code, but it models and may even look like programming code.
It uses plain English statements rather than symbols to represent the processes of a computer
program. It is also known as PDL and main emphasizes on design aspect of a computer
program or structured. English, because usually pseudo code instructions are written in
normal English, but in a structured way.
If an algorithm is written in English, the description may be at such a high level that it may
prove difficult to analyze the algorithm and then to transform it into actual code.
Therefore, the goal of writing pseudo code is to provide a high-level description of an
algorithm, which facilitates analysis and eventual coding, but at the same time suppresses
many of the details that are insignificant.
Eg. The pseudocode given below calculates the area of a rectangle.
STOP
Pseudocode uses some keywords to denote programming processes which are as follows:
Input: READ, OBTAIN, GET and PROMPT
Output: PRINT, DISPLAY and SHOW
Compute: COMPUTE, CALCULATE and DETERMINE
Initialize: SET and INITIALISE
Add one: INCREMENT
Advantages of pesudocode
A flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of
various kinds, and their order by connecting these with arrows. This diagrammatic representation can give
a step-by-step solution to a given problem.
1. b) Semantic Errors: Errors in the meaning of the program. This error occurs when the statements
written in the program are not meaningful to the compiler.
2. c) Logical Errors: Errors in logic of the program. Compiler cannot diagnose these kinds of errors. On
compilation and execution of a program, desired output is not obtained when certain input values
are given. These types of errors which provide incorrect output but appears to be error free are
called logical errors. These are one of the most common errors done by beginners of programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.
d) Runtime Errors: i) Insufficient memory ii)Floating exception Errors which occur during program
execution(run-time) after successful compilation are called run-time errors. One of the most common
run-time error is division by zero also known as Division error. These types of error are hard to find as
the compiler doesn’t point to the line at which the error occurs. In the given example, there is Division
by zero error. This is an example of run-time error i.e errors occurring while running the program.
ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with programming, we
should be acquainted with the basic elements that build the language. Character Set Communicating with
a computer involves speaking the language the computer understands. In C, various characters have been
given to communicate. Character set in C consists of;
Keywords: Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a new meaning to
the keyword, which is not allowed by the computer. There are only 32 keywords available in C. Below
figure gives a list of these keywords for your ready reference.
in two forms—Fractional form and Exponential form. A real constant must have at least one digit.
No commas or blanks are allowed within a real constant. Ex. +325.34, 426.0, -32.76, -
48.5792 Rules for constructing real constants expressed in exponential form: The mantissa part and the
exponential part should be separated by a letter e.
The mantissa part may have a positive or negative sign. Default sign of mantissa part is positive.
The exponent must have at least one digit, which must be a positive or negative integer. Default sign is
positive. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38.
VARIABLES
Variables are names that are used to store values. It can take different values but one at a time. A data
type is associated with each variable & it decides what values the variable can take. Variable declaration
requires that you inform C of the variable's name and data type. Syntax – data type variable name; Eg:int
page_no; char grade; float salary; long y;
Declaring Variables: There are two places where you can declare a variable: After the opening brace of a
block of code (usually at the top of a function) Before a function name (such as before main() in the
program)
Consider various examples:
Initialization of Variables When a variable is declared, it contains undefined value commonly known as
garbage value. If we want we can assign some initial value to the variables during the declaration itself.
This is called initialization of the variable. Eg-int pageno=10;
Expressions An expression consists of a combination of operators, operands, variables & function calls.
An expression can be arithmetic, logical or relational. Here are some expressions: a+b
– arithmetic operation a>b- relational operation a == b
- logical operation func (a,b) – function call Statements Statements are the primary building blocks of a
program. A program is a series of statements with some necessary punctuation. A statement is a complete
instruction to the computer. In C, statements are indicated by a semicolon at the end. a semicolon is
needed to identify instructions that truly are statements.
Object and executable files
Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension. Which is un-
compiled (when written for the first time or whenever a change is made in it and saved).
Object code is the output of a compiler after it processes the source code. The object code is usually
a machine code, also called a machine language, which can be understood directly by a specific type
of CPU (central processing unit), such as x86 (i.e., Intel-compatible) or PowerPC. However, some
compilers are designed to convert source code into an assembly language or some other another
programming language. An assembly language is a human-readable notation using
the mnemonics symbolic name for a single executable machine language instruction called an opcode)
in the ISA ( Instruction Set Architecture) of that particular CPU .
Executable (also called the Binary) is the output of a linker after it processes the object code. A
machine code file can be immediately executable (i.e., runnable as a program), or it might
require linking with other object code files (e.g. libraries) to produce a complete executable program.
Linker also contain other object files and libraries.
A linker is special program that combines the object files, generated by compiler/assembler, and other
pieces of codes to originate an executable file have. 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.
The loader is special program that takes input of object code 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. It is in charge of loading programs and libraries in
operating system. The embedded computer systems don’t have loaders. In them, code is executed
through ROM.
LINKER LOADER
Whereas main objective of
The main function of Linker is to generate Loader is to load executable files
1 executable files. to main memory.
And the loader takes input of
The linker takes input of object code executable files generated by
2 generated by compiler/assembler. linker.
Loading can be defined as
Linking can be defined as process of process of loading executable
combining various pieces of codes and codes to main memory for further
3 source code to obtain executable code. execution.
Loaders are of 4 types: Absolute,
Linkers are of 2 types: Linkage Editor and Relocating, Direct Linking,
4 Dynamic Linker. Bootstrap.
Another use of linker is to combine all object It helps in allocating the address
5 modules. to executable codes/files.
Unit 2
Arithmetic expressions and precedence (2 lectures)
Conditional Branching and Loops (6 lectures)
Writing and evaluation of conditionals and consequent branching (3 lectures)
Iteration and loops (3 lectures)
Arithmetic expressions and precedence (part of syllabus)
C has a wide range of operators. An arithmetic expression is composed of operators and operands.
Operators act on operands to yield a result. Commonly used arithmetic operators are +, -, *, / and %. The
plus sign (+) is used to add two values, the minus sign (-) to subtract one value from another, the
asterisk(*) to multiply two values, the division (/) to divide a value and the modulus (%) to obtain the
reminder of integer division. These are known as binary operators since they operate on two values or
variables.
When an expression contains only integral operands, then it is known as pure integer expression when it
contains only real operands, it is known as pure real expression, and when it contains both integral and
real operands, it is known as mixed mode expression.
The expressions are evaluated by performing one operation at a time. The precedence and associativity of
operators decide the order of the evaluation of individual operations.
o When both the operands (a,b) are of type integer, then arithmetic will be performed, and the result
of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional
part is ignored.
o When both the operands are of type float, then arithmetic will be performed, and the result of the
operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
o If one operand is of type integer and another operand is of type real, then the mixed arithmetic
will be performed. In this case, the first operand is converted into a real operand, and then
arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first
value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.
Unary operator A unary operator is one which operates on one value or operand. The minus sign (-) plays
a dual role, it is used for subtraction as a binary operator and for negation as a unary operator. This
operator has a precedence higher than the rest of the arithmetic operators. result = -x * y; in the above
expression, if x has a value 20 and y has a value 2, then result will contain a negative value of 40 which is
-40.
In C, there are increment (++) and decrement (--) operators. These can be pre-fixed or post-fixed. When
these are pre-fixed to a variable in an expression, then the value is computed before the expression is
evaluated. When these are post-fixed, the value is computed after the expression is evaluated.
/* Usage of pre-fixing and post-fixing the increment operator */
#include
main()
{
int x = 10;
printf("Value of x after pre-fixing ++ is %d\n", ++x);
printf("Value of x after post-fixing ++ is %d\n",x++);
}
The above program will yield the following output: Value of x after pre-fixing ++ is 11 is 11 Notice that
even after we post-fix an increment operator to x, we still get the result as 11. This is because x is
evaluated before the increment operation occurs.
Comma operator Comma can be used in an expression. Each comma separated expression is evaluated
and the value of the rightmost expression will be returned. Consider the following example :
/* Comma seperated expressions */
#include
main()
{
int Total, Val, Count;
Total = 100;
Val = 10;
Count = 50;
Total =(Val++,Count-2);
printf("%d\n", Total);
}
The above program displays a value of 48, since the last expression Count-2 is considered last. If the
parentheses had been absent, then the value in Val before increment would have been returned to Total,
this is because the assignment operator has a higher precedence then the comma operator.
x%2 = This condition is used to check whether the x is an even number or not. The relational expression
=0 results in value 1 if x is an even number otherwise results in value 0.
== Equal to
!= Not equal to
Logical Expressions
x > 10 || y It is a test condition used to check whether x is greater than 10 or y is less than 11. The result of the
<11 test condition is true if either of the conditions holds true value.
Conditional Expressions
o The above expression is a conditional expression which is evaluated on the basis of the value of
the exp1 expression. If the condition of the expression exp1 holds true, then the final conditional
expression is represented by exp2 otherwise represented by exp3.
Operators Precedence and associatively are two characteristics of operators that determine the
evaluation order of sub-expressions in absence of brackets
For example: Solve 100 + 200 / 10 - 3 * 10
1) Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single operator are
evaluated. For example, consider the following program, associativity of the + operator is left to right,
but it doesn’t mean f1() is always called before f2(). The output of the following program is in-fact
compiler dependent.
2) All operators with the same precedence have same associativity
This is necessary, otherwise, there won’t be any way for the compiler to decide evaluation order of
expressions which have two operators of same precedence and different associativity. For example +
and – have the same associativity.
4) Comma has the least precedence among all operators and should be used carefully
5) There is no chaining of comparison operators in C
In Python, expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining doesn’t
happen in C. The output of following program is “FALSE”.
Description
Operator
Associativity
() Parentheses (function call) (see Note 1)
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ — Postfix increment/decrement (see Note 2) left-to-right
++
— Prefix increment/decrement
+ – Unary plus/minus
! ~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type)
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to
> >= Relational greater than/greater than or equal to left-to-right
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment right-to-left
, Comma (separate expressions) left-to-right
It is good to know precedence and associativity rules, but the best thing is to use brackets, especially
for less commonly used operators (operators other than +, -, *.. etc). Brackets increase the readability
of the code as the reader doesn’t have to see the table to find out the order.
A Bitwise And operator is represented as ‘&’ and a logical operator is represented as ‘&&’. The
following are some basic differences between the two operators.
a) The logical and operator ‘&&’ expects its operands to be boolean expressions (either 1 or 0) and
returns a boolean value.
The bitwise and operator ‘&’ work on Integral (short, int, unsigned, char, bool, unsigned char, long)
values and return Integral value.
If an integral value is used as an operand for ‘&&’ which is supposed to work on boolean values, the
following rule is used in C.
…..Zero is considered as false and non-zero is considered as true.
c) The ‘&&’ operator doesn’t evaluate the second operand if the first operand becomes false. Similarly
‘||’ doesn’t evaluate the second operand when first operand becomes true. The bitwise ‘&’ and ‘|’
operators always evaluate their operands.
Inclusive OR allows both possibilities as well as either of them. So, if either A or B is True, or if both are True,
then the statement value is True whereas Exclusive OR only allows one possibility. So if either A or B is true,
then and only then is the value True. If both A and B are True, even then the statement's value will be False.
Example for Exclusive OR: At a restaurant, you are offered a coupon which entitles you to eat either a
Sandwich OR a Burger. This is an exclusive OR statement in English language. You can choose either one of
them, but not both.
**A program is nothing but the execution of sequence of one or more instructions.
Quite often, it is desirable to alter the sequence of the statements in the program depending upon certain
circumstances. (i.e., we have a number of situations where we may have to change the order of execution
of statements based on certain conditions)
Based on application, it is necessary / essential
Conditional Branching:
It includes the statements which work on checking the condition of a given expression to execute the
code. They are:
Decision making statements allow you to decide the order of execution of specific statements in your
program. You can set up a condition and tell the compiler to take a particular action if the condition is
met. In case the condition is not met, you can instruct the compiler to execute a different block of code.
Used to execute or skip some set of instructions based on given condition.
Number of decision making statements are supported in C language are as follows:
1. If
2. If-else
3. Nested if
4. Switch
5. Else-if ladder (used to test set of conditions in sequence).
“if” statement is a powerful decision making statement, and is used to control the flow of execution of
statements.
Syntax :
if (Condition or test expression)
Statement;
Rest of the program
(OR)
Example : Program: Write a program to check equivalence of two numbers. Use “if” statement.
# include<stdio.h>
# include<conio.h>
void main( )
{
int m,n;
clrscr( );
printf(“\n Enter two numbers:”);
scanf(“%d %d”, &m, &n);
if((m-n)==0)
printf(“\n two numbers are equal”);
getch();
}
Output :
Enter two numbers: 5 5
Two numbers are equal.
It is observed that the “if” statement executes only when the condition following if is true. It does nothing
when the condition is false. In if-else either True-Block or False – Block will be executed and not both.
The “else” Statement cannot be used without “if”.
Syntax :
if ( Test Expression or Condition )
{
Statements; /*true block (or) if block */
}
else
{
Statements; /* false block (or) else block */
}
It is observed that the “if” statement executes only when the condition following if is true. It does nothing
when the condition is false. In if-else either True-Block or False – Block will be executed and not both.
The “else” Statement cannot be used without “if”.
Flow chart :
Using of one if-else statement in another if-else statement is called as nested if-else control statement.
When a series of decisions are involved, we may have to use more than one if-else statement in nested
form.
Syntax :
if ( Test Condition1)
{
if ( Test Condition2)
{
Statement -1;
}
else
{
Statement -2;
}
}
else
{
if ( Test Condition3)
{
Statement -3;
}
else
{
Statement-4;
}
} /* end of outer if-else *
Flow chart :
Eg. Program: Program to select and print the largest of the three float numbers using nested “if else”
statements.
# include<stdio.h>
# include<conio.h>
main( ) {
float a,b,c;
printf(“Enter Three Values:”);
scanf(“%f%f%f”, &a, &b, &c);
printf(“\n Largest Value is:”) ;
if(a>b) {
if(a>c)
printf(“ %f ”, a);
else
printf(“ %f ”, c);
}
else {
if (b>c)
printf(“ %f ”, b);
else
printf(“ %f ”, c);
}
getch();
}
Output :
Run 1: Enter three values: 9.12 5.34 3.87
Largest Value is: 9.12
Run 2: Enter three values: 45.781 78.34 145.86
Largest Value is: 145.86
1.(4) The “else – if” Ladder :
This is another way of putting if‘s together when multiple decisions are involved. A multipath decision is
a chain of if‘s in which the statement associated with each else is an if. Hence it forms a ladder called
else–if ladder. if else-if, statement is used to execute one code from multiple conditions.
Syntax :
if (Test Condition -1)
{
Statement -1;
}
else if ( Test Condition -2)
{
Statement -2;
}
else if ( Test Condition -3)
{
Statement -3;
}
:
:
:
:
else if ( Test Condition –n)
{
Statement –n;
}
else
{
default statement;
}
Rest of the Program Statements-X;
The above construction is known as else if ladders. The conditions are evaluated from top to bottom. As
soon as a true condition is found, the statement associated with it is executed and The control is
transferred to the Rest of the Program Statement–X (skipping rest of the ladder). When all the “n”
conditions become false, then the final else containing the default statement will be executed.
Flow chart :
Eg. Program: Write a program to read three numbers and find the largest one by using “else-if” ladder.
# include<stdio.h>
# include<conio.h>
void main( )
{
int a, b, c
clrscr ( ) ;
printf(“Enter 1st number:”);
scanf(“%d”, &a);
printf(“Enter 2nd number:”);
scanf(“%d”, &b);
printf(“Enter 3rd number:”);
scanf(“%d”, &c);
if ((a>b) && (a>c))
printf(“Highest Number is: %d”, a);
else if ((b>a) && (b>c))
printf(“Highest Number is: %d”, b);
else
printf(“Highest Numbers is: %d”, c);
getch( );
}
Output :
Enter 1st number: 52
Enter 2nd number: 90
Enter 3rd number: 74
Highest Numbers is: 90
1.(5) The “switch-case” Statement :
Switch is another conditional control statement used to select one option from several options based on
given expression value; this is an alternative to the if-else-if ladder. The switch statement causes a
particular group of statements to be chosen from several available groups. The selection is based upon the
current value of an expression which is included with in the switch statement. The switch statement is a
multi-way branch statement. In a program if there is a possibility to make a choice from a number of
options, this structured selected is useful. The switch statement requires only one argument of int or char
data type, which is checked with number of case options. The switch statement evaluates expression and
then looks for its value among the case constants. If the value matches with case constant, then that
particular case statement is executed. If no one case constant not matched then default is executed. Here
switch, case and default are reserved words or keywords.
Every case statement terminates with colon “:”.
In switch each case block should end with break statement, i.e.
Syntax :
Switch (variable or expression)
{
Case Constantvalue-1:Block -1;
(Or)
Statement-1;
break;
Output :
=========
MENU
=========
[1] ADDITION
[2] SUBTRACTION
[3] MULTIPLICATION
[4] DIVISION
[5] REMAINDER
[6] LARGER OUT OF TWO
[7] EXIT
===============
Enter your choice: 6
Enter two numbers: 8 9
9 is larger than 8
Branching statements give us code which is optionally executable, depending on the outcome of certain
tests or you can say certain cases which we can define.
Looping statements are used to repetition of a section of code a number of times or until a condition has
been fulfilled.
Suppose you want to execute some code/s 10 times. You can perform it by writing that code/s only one
time and repeat the execution 10 times using loop. For example: Suppose that you have to print table of 2
then you need to write 10 lines of code, by using loop statements you can do it by 2 or 3 lines of code
only. Different Loops exists in C programming language are as follows:
The for loop works well where the number of iterations of the loop is known before the loop is entered.
The head of the loop consists of three parts separated by semicolons. The first is run before the loop is
entered. This is usually the initialization of the loop variable. The second is a test, the loop is exits when
this returns false. The third is a statement to be run every time the loop body is completed. This is usually
an increment of the loop counter. The 3 actions are
“Initialize expression”, “Test Condition expression” and “updation expression”
The expressions are separated by Semi-Colons (;).
Syntax :
for (initialize expression; test condition; updation )
{
Statement-1;
Statement-2;
}
(i)The initialization sets a loop to an initial value. This statement is executed only once.
(ii) The test condition is a relational expression that determines the number of iterations desired or it
determines when to exit from the loop. For loop continues to execute as long as conditional test is
satisfied. When the condition becomes false the control of the program exits from the body of for loop
and executes next statements after the body of the loop.
(iii) The updation (increment or decrement operations) decides how to make changes in the loop. The
body of the loop may contain either a single statement or multiple statements.
Eg. Program : Print the first five numbers starting from one together with their squares.
#include<stdio.h>
#include<conio.h>
main( )
{
int i;
clrscr( ) ;
for(i = 1; i <6; i++)
printf(“\n Number: %d it’s Square: %d”, i, i*i);
getch( );
}
Output :
Number: 1 it’s Square: 1
Number: 2 it’s Square: 4
Number: 3 it’s Square: 9
Number: 4 it’s Square: 16
Number: 5 it’s Square: 25
We can also use loop within loops. i.e. one for statement within another for statement is allowed in C. In
nested for loops one or more for statements are included in the body of the loop. * ANSI C allows up to
15 levels of nesting. Some compilers permit even more.
Syntax :
for( initialize ; test condition ; updation) /* outer loop */
{
for(initialize ; test condition ; updation) /* inner loop */
{
Body of loop;
}
}
Program : The following program is an example of nested for loop.
# include<stdio.h>
# include<conio.h>
main ( )
{
int x, i, j ;
printf(“How many lines stars (*) should be print f? :”);
scanf(“%d”, &x);
for(int i=1; i<=x; i++)
{
for (j=1; j < =i; j++)
{
printf( “*”);
}
printf( “ \n”);
}
getch( );
}
Output :
How many lines stars (*) should be print d ? : 5
*
**
***
**** *
2. (2) The “while” loop:
The while is an entry-controlled loop statement (i.e. a condition is checked before executing the body of a
loop). The test condition is evaluated and if the condition is true, then the body of the loop is executed.
The execution process is repeated until the test condition becomes false and the control is transferred out
of the loop. On exit, the program continues with the statement immediately after the body of the loop. The
body of the loop may have one or more statements. The braces are needed only if the body contains two
or more statements. It’s a good practice to use braces even if the body has only one statement. The
simplest of all the looping structures in C is.
Syntax :
Initialization Expression;
while ( Test Condition)
{
Body of the loop
Updation Expression
}
Eg. Program : To add 10 consecutive numbers starting from 1. Use the while loop.
# include<stdio.h>
# include<conio.h>
main( )
{
int a=1, Sum=0;
while(a<=10)
{
Sum = Sum + a;
a++;
}
printf(“Sum of 1 to 10 numbers is: %d”, sum);
getch( );
}
Output :
while(n>=1)
{
fact = fact*n;
n--;
}
printf(“ \n factorial of given number is %d”, fact);
getch( );
}
Output :
Enter the Number: 5 /* logic 5 * 4 * 3 * 2 * 1 = 120 */
Factorial of given number is 120
Infinitive while loop
If you pass 1 as a expression in while loop, it will run infinite number of times.
Syntax :
while(1){
//statements
}
To execute a part of program or code several times, we can use do-while loop of C language. The code
given between the do and while block will be executed until condition is true. The do-while is an exit-
controlled loop statement (i.e. A condition is checked after executing the body of a loop). Because, in do-
while, the condition is checked at the end of the loop. The do-while loop will execute at least one time
even if the condition is false initially. The do-while loop executes until the condition becomes false.
Syntax :
Initialization Expression;
do
{
Body of the loop
Updation Expression;
} while ( Test Condition);
If you pass 1 as a expression in do while loop, it will run infinite number of times. The do-while is an
exit-controlled loop statement. Because, in do-while, the condition is checked at the end of the loop. The
do-while loop will execute at least one time even if the condition is false initially. The do-while loop
executes until the condition becomes false.
Syntax :
do{
//statements
} while (1);
Ex. #include <stdio.h>
int main () {
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
Output: value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
(3) Unconditional branching is when the programmer forces the execution of a program to jump to
another part of the program. Theoretically, this can be done using a good combination of loops and if
statements. In fact, as a programmer, you should always try to avoid such unconditional branching and
use this technique only when it is very difficult to use a loop.
3. UNCONDITIONAL CONTROL STATEMENT
3. (1) The “break” Statement :
A break statement terminates the execution of the loop and the control is transferred to the statement
immediately following the loop. i.e., the break statement is used to terminate loops or to exit from a
switch.
• It can be used within for, while, do-while, or switch statement.
• The break statement is written simply as break;
• In case of inner loops, it terminates the control of inner loop only.
Syntax :
Jump-statement;
break;
Jump Statement makes the control jump to another section of the program unconditionally when
encountered. It is usually used to terminate the loop or switch-case instantly. It is also used to escape the
execution of a section of the program.
The jump statement in c break syntax can be while loop, do while loop, for loop or switch case.
The continue statement is used to bypass the remainder of the current pass through a loop. The loop does
not terminate when a continue statement is encountered. Instead, the remaining loop statements are
skipped and the computation proceeds directly to the next pass through the loop. The continue statement
can be included within a while, do-while, for statement. It is simply written as “continue”. The continue
statement tells the compiler “Skip the following Statements and continue with the next Iteration”. In
“while” and “do” loops continue causes the control to go directly to the test –condition and then to
continue the iteration process. In the case of “for” loop, the updation section of the loop is executed
before test-condition, is evaluated.
Syntax :
Jump-statement;
Continue;
The jump statement can be while, do while and for loop.
Output :
Enter an integer: 7
Enter an integer: 3
Enter an integer: 10
Enter an integer: 15
Enter an integer: 30
The sum of the positive integers entered = 65
C supports the “goto” statement to branch unconditionally from one point to another in the program.
Although it may not be essential to use the “goto” statement in a highly structured language like “C”,
there may be occasions when the use of goto is necessary. The goto requires a label in order to identify
the place where the branch is to be made. A label is any valid variable name and must be followed by a
colon (: ). The label is placed immediately before the statement where the control is to be transferred. The
label can be anywhere in the program either before or after the goto label statement.
During running of a program, when a statement likes “goto begin;” is met, the flow of control will jump
to the statement immediately following the label “begin:” this happens unconditionally. “goto” breaks the
normal sequential execution of the program. If the “label:” is before the statement “goto label;” a loop
will be formed and some statements will be executed repeatedly. Such a jump is known as a “backward
jump”. If the “label:” is placed after the “goto label;” some statements will be skipped and the jump is
known as a “forward jump”.
Program : Write a program to detect the entered number as to whether it is even or odd. Use goto
statement.
3. (4) Return Statement :
The return statement terminates the execution of a function and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return statement
can also return a value to the calling function.
Syntax :
Jump-statement:
return expression
Notes: Conditional branch is happened based on some condition like if condition in C. Transfer of control
of the program will depend on the outcome of this condition.
Uncoonditional branching occurs without any condition like goto statement.
Loops like For, while use both of these branching techniques. It employs condition checking(For
conditional branching) and once one loop is complete, control is automatically transfered to the start of
the loop(Unconditional branching).
In the case of computer programming, a data type refers to a classification that specifies the
given interpreter or compiler which type of data must be used. There are typically two major
types of data:
Type of A fundamental data type is very basic. It A derived data type is basically an
Complication is also known as a primitive data type. aggregation of the fundamental
data type.
Examples Void, Float, Integer, and Character are Structures, Unions, Arrays, and
fundamental data types. Pointers are the derived data types.
Specification of It uses Character in the form of char, The Derived Data Types make use
Elements Unsigned char, Signed char, etc., for the of pointers for storing the address
characters present in the Fundamental of the available variables.
Data Type.
Storage of Data It uses integers for the integers with no It makes use of arrays to contain a
decimal digits. We can classify it as similar data type.
unsigned and signed. It is further
classified as the int, long int, and short
int.
Use We use void when we don’t require the It is just like a structure, but the
return value. difference is that all the members
present in a union share the very
same location of memory.
Grouping of We use floats for the decimal numbers. We use a structure for grouping all
Values The classification occurs as double, float, the different types of available
and long double. items into one single type.
C was developed as a language to write the UNIX operating system cleanly. The earlier version of UNIX that
Ken Thompson wrote was in a language called B which was in turn a simplified version of a language called
BCPL (which stood for Basic Combined Programming Language). When Dennis Ritchie joined the team, he
set on to develop a better language than B which will eventually be used as a successor of B. So he named the
language C.
Unit 3
Arrays, Arrays (1-D, 2-D), Character arrays and Strings (6 lectures)
C Array
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Contiguous memory allocation is basically a method in which a single contiguous
section/part of memory is allocated to a process or file needing it. Because of this all the
available memory space resides at the same place together, which means that the freely/unused
available memory partitions are not distributed in a random fashion here and there across the
whole memory space. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc. It also has the capability to
store the collection of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly accessed by using its index
number. C array is beneficial if you have to store similar elements. For example, if we want to
store the marks of a student in 6 subjects, then we don't need to define different variables for the
marks in the different subject. Instead of that, we can define an array which can store the marks
in each subject at the contiguous memory locations. By using the array, we can access the
elements easily. Only a few lines of code are required to access the elements of the array.
Properties of Array
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element
is stored at the smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of
each element of the array with the given base address and the size of the data element.
Advantages of C Array
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantages of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed
the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
Declaration of C Array
1. data_type array_name[array_size];
Initialization of C Array
The simplest way to initialize an array is by using the index of each element. We can initialize
each element of the array by using the index. Consider the following example.
1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;
C array example
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
Output
80
60
70
85
75
We can initialize the c array at the time of declaration. Let's see the code.
1. int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the size. So it may also be written as the
following code.
1. int marks[]={20,30,40,50,60};
1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }
Output
20
30
40
50
60
In the following program, we are using bubble sort method to sort the array in ascending order.
1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }
Program to print the largest and second largest element of the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }