Download as pdf or txt
Download as pdf or txt
You are on page 1of 337

Problem Solving Using Computers

Subject Code: CS1002


1. E. Balagurusamy, Programming in ANSI C, 8th Edition, McGraw Hill Publication, 2019.
2. Y. P. Kanetkar, Let us C, 19th Edition, BPB Publication, 2022.
3. B. Gottfried, Programming with C, fourth Edition, 2018

Dr. Sandeep Singh


Associate Professor
Room No. 216, Faculty Block 5, 2nd Floor, Academic Block-2,
School of Computer and Communication Engineering
MANIPAL UNIVERSITY JAIPUR, INDIA
Contact: sandeep.singh@jaipur.manipal.edu, +91-9899123541

Educational Qualification
B.Tech.[1998]:IET Lucknow, Lucknow University
M.Tech.[2009]:School of IT, JNU New Delhi
Ph.D [2019]: The NorthCap University, Gurugram

Exp.:
(i) Sep 1999-Aug 2003, UPTEC Computer Consultancy Ltd. Allahabad
(ii) Sep 2003 - Nov 2005 Dronacharya College of Engineering, Gurugram
(iii) Dec 2005 - Aug 2007 Dept. of CSE, ITM Gurugram
(iv) Jul-2009 – Jun 2015, Dept. of CSE, ITM University, Gurugram
(v) Jul-2015 - Aug 2023, Dept. of CSE, The NorthCap University, Gurugram
(vi) Sep 2023 - Dept. of CCE, MUJ, Jaipur
Syllabus
Digital computer fundamentals: Algorithms and flowcharts, the von
Neumann architecture, programs, assembly language, high level
programming languages; Imperative programming (Using C): data
types, variables, Storage Classes, enumerated data types, operators,
expressions, statements, control structures, functions, arrays and pointers,
recursion, records (structures), files, input/output, some standard library
functions and some elementary data structures.
TEXT BOOKS
1. TE. Balagurusamy, Programming in ANSI C, 8th Edition, McGraw Hill Publication,
2019.
2. Y. P. Kanetkar, Let us C, 19th Edition, BPB Publication, 2022.

REFERENCE BOOKS

1. B. W. Kernighan, D. M. Ritchie, The C Programing Language, 2nd Edition,


Prentice Hall of India, 2014.
• B. Gottfired, Schaums Outline Series: Programming with C, 4th Edition, McGraw
Hill Publication, 2018.
Course Objectives
The aim of this course is to provide problem solving using
computers that focuses on basic computer fundamentals,
number system and programming in C fundamentals
language.
Using C language students will learn to write set of
instructions to create a program so that desire output can
be generated by computer and the same will be helpful in
many of other languages understanding.
Course Outcomes
At the end of the course, students will be able to:
[CS1002.1]. Understand algorithm development, elements of programming
languages and designing flow charts.
[CS1002.2]. Apply the basic programming concepts such as tokens, data
types, operators and control statements for implementing programs.
[CS1002.3]. Describe and analyze the concepts of array data type (1D and
2D), functions, structure and union.
[CS1002.4]. Illustrate the concept of pointers and file handling.
[CS1002.5]. Creating algorithms or pseudo code to solve real life problems
using programing constructs.
These course outcomes ensure that students gain a comprehensive
understanding of computer programming principles, data manipulation, and
problem-solving techniques, while also mastering the use of essential
programming constructs and libraries.
Evaluation Scheme
Why PSUC is so Important?
Example:
(i) It is fundamental to begin in Computer Science
discipline & in each examination (Private or Gov.
Job at least 10 question)
(ii) PSUC lets you know how exactly Information is
executed at the micro level. The Algorithms,
flowcharts, Analysis, timing analysis, trade offs can
be best analysed at all higher level of course.
(iii) Real life example: Computer System with Digital
communication World, with many of applications is
one of the perfect example, like banking, ATM, Face-
book, ATM, Banks, Corporate Sectors, Defence
Secret, etc…
Fundamentals and How to Start
▪How many of you have age 18-22? Its Importance, you
can do any think… general observation in this age people
has a maximum potential.
▪Belief in your self: I am powerful I can do what we can
think and what we need to do.
▪If something is hard it means it will require more hard
work and I am ready for the same
▪If you have a complain, first you talk with concerned
teacher, he/she may be perfect solution provider.
▪Refer a Standard Text and Reference Book, request do
not compromise with the same.
▪Always keep your Syllabus in front of you.
Thank You
Problem Solving Using Computers
Subject Code: CS1002
First Module:
Digital computer fundamentals: Algorithms and flowcharts, the von
Neumann architecture, programs, assembly language, high level
programming languages.
Digital computer
• A digital computer is a digital system that performs various
computational tasks and represented by variables with the limited
number of discrete values.

• The discrete values are internally processed with limited number of


discrete states. The decimal digits 0,1,2,…,9 provide 10 discrete
values. Mostly all discrete values are available in the form of
American Standard Code for Information Interchange (ASCII)

• Where the first electronic digital computers developed in 1940. From


here the term digital computer emerged because of many restrictions
with other discrete values.
Functional Units of Computer System
It is divided in two modules in general:
• Hardware: A hardware of the computer system consists of all electronic
components such as electronic circuits, display units, storage media
(magnetic and optical (a class of data storage systems that use light to
read or write data to an underlying optical media-CD, DVD)),
electromechanical devices and communication facilities.

• Software: It consists of the instructions and data that the computer


manipulates to perform various data-processing tasks. Where sequence of
instruction is called a program.
Von Neumann Architecture
• Von-Neumann computer architecture design was proposed in 1945. It
was later known as Von-Neumann architecture.

• Historically there have been 2 types of Computers:

1. Fixed Program Computers – Their function is very specific and they


couldn’t be reprogrammed, e.g. Calculators.

2. Stored Program Computers – These can be programmed to carry out


many different tasks, applications are stored on them, hence the name
is.
Von Neumann architecture… Cont’d
• Modern computers are based on a
stored-program concept introduced by
John Von Neumann.

• In this stored-program concept,


programs and data are stored in a
separate storage unit called memories
and are treated the same.

• This novel idea meant that a computer


built with this architecture would be
much easier to reprogram.
Von Neumann architecture is also known as ISA (Instruction set architecture)
computer and is having three basic units: Central Processing Unit (CPU), Main
Memory Unit and Input/Output Unit.

1. Central Processing Unit-


The central processing unit is defined as an electric circuit used for the executing the
instruction of computer program. It has following major components:
1.Control Unit(CU)
2.Arithmetic and Logic Unit(ALU)
3.variety of Registers

• Control Unit – A control unit (CU) handles all processor control signals. It directs all
input and output flow, fetches code for instructions, and controls how data moves
around the system.

• Arithmetic and Logic Unit (ALU) – The arithmetic logic unit is that part of the CPU that
handles all the calculations the CPU may need, e.g. Addition, Subtraction, Comparisons.
It performs Logical Operations, Bit Shifting Operations, and Arithmetic operations.
Basic CPU structure, illustrating ALU
Registers
1.Registers – Registers refer to high-speed storage areas in the CPU. The data
processed by the CPU are fetched from the registers. There are different types of
registers used in architecture :-Accumulator: Stores the results of calculations
made by ALU. It holds the intermediate of arithmetic and logical operatoins.it act
as a temporary storage location or device.
2.Program Counter (PC): Keeps track of the memory location of the next
instructions to be dealt with. The PC then passes this next address to the Memory
Address Register (MAR).
3.Memory Address Register (MAR): It stores the memory locations of instructions
that need to be fetched from memory or stored in memory.
4.Memory Data Register (MDR): It stores instructions fetched from memory or
any data that is to be transferred to, and stored in, memory.
5.Current Instruction Register (CIR): It stores the most recently fetched
instructions while it is waiting to be coded and executed.
6.Instruction Buffer Register (IBR): The instruction that is not to be executed
immediately is placed in the instruction buffer register IBR.
Input and Output Unit
• Input: Computer accept coded information through input unit. The most
common device is Keyboard. Whenever key is pressed, the corresponding
letter or digit is automatically translated into its corresponding binary code
and transmitted over a cable to either memory or the processor.

• Output: The output unit is the counterpart of the input unit. Its function is
to send processed results to the outside world. The most familiar device is a
printer. Some units, such as graphical displays, provide both an input and
output function.
Memory
• The function of the memory unit is to store programs and data. There are two
classes of storage, called as Primary and Secondary.

• Primary storage is a fast memory. The memory contains large number of


semiconductor storage cells, each cell capable of one bit of information. These
cells are rarely used as an individual cell instead are processed in group of fixed
size, called words.

• To provide an easy access of any word in memory, a distinguished address is


associated with each word location. Addresses are numbers that identify
successive locations. The typical word lengths range from 16 to 64 bits.

• Memory in which any location can be accessed in short and fixed amount of time
after specifying address is called Random Access Memory (RAM). CPU is known as
RAM because CPU can access any locations at any point of time.
Memory Con’d
• The smaller and fasted unit is called Cache. The largest and slowest unit
is referred to as main memory.

• Although primary storage is essentials and expensive. But in addition to


the same cheaper memory is available as a secondary memory storage,
where large amount of data and many programs may be stored.

• A wide range of secondary storage are available in the form of magnetic


disks, tapes and opticals disks (CD-ROMS).
Memory unit

➢The computer memory is measured in terms of bits, bytes and


words.

➢A bit is a binary digit either 0 or 1.

➢A byte is unit of memory and is defined as sequence of 8 bits.

➢The word can be defined as a sequence of 16/32/64 bits or 2/4/8


bytes respectively depending on the machine architecture
3
Primary storage: RAM & ROM
• RAM stands for Random Access Memory
➢ Read and write memory
➢ Information typed by the user are stored in this memory
➢ Any memory location can be accessed directly without scanning it
sequentially (random access memory)
➢ During power failure the information stored in it will be erased → volatile
memory
• ROM stands for Read Only Memory
➢Permanent memory and non volatile
➢Contents in locations in ROM can not be changed
➢Stores mainly stored program and basic input output system programs
4
Secondary memory

➢Main memory is volatile and limited


➢ Hence it is essential for other types of storage devices where programs and
data can be stored when they are no longer being processed

➢Installed within the computer at the factory or added later as needed

5
Secondary memory
➢Non-volatile memory

➢Made up of magnetic material

➢Stores large amount of information for long time

➢Low speed

➢Holds programs not currently being executed

6
Cache memory
➢ High speed memory placed between CPU and main memory
➢ Stores data and instructions currently to be executed
➢ More costlier but less capacity than main memory
➢ Users can not access this memory

7
Buses – Data is transmitted from one part of a computer to
another, connecting all major internal components to the CPU
and memory.

Types:
• Data Bus: It carries data among the memory unit, the I/O devices, and
the processor.
• Address Bus: It carries the address of data (not the actual data)
between memory and processor.
• Control Bus: It carries control commands from the CPU (and status
signals from other devices) in order to control and coordinate all the
activities within the computer.
High level Programming Languages
▪ In computer science, a high-level programming language is
a programming language with strong abstraction from the
details of the computer.

▪ In contrast to low-level programming languages, it may


use natural language elements, be easier to use, or may
automate (or even hide entirely) significant areas of computing
systems (e.g. memory management), making the process of
developing a program simpler and more understandable than
when using a lower-level language.

▪ The amount of abstraction defines how "high-level" a


programming language is provided.
Difference between High Level and Low level languages

• Both High level language and low level language are the
programming languages’s types.
• The main difference between high level language and low
level language is that programmers can easily understand or
interpret or compile the high level language in comparison of
machine.
• On the other hand, Machine can easily understand the low
level language in comparison of human beings. Examples of
high level languages are C, C++, Java, Python, etc.
Difference between High Level and Low-level language
High Level Language Low-level language
1. It is programmer friendly language. It is a machine friendly language.

2. High level language is less memory efficient. Low level language is high memory efficient.

3. It is easy to understand. It is tough to understand.

4. Debugging is easy. Debugging is complex comparatively.

5. It is simple to maintain. It is complex to maintain comparatively.

6. It is portable. It is non-portable.

7. It can run on any platform. It is machine-dependent.

It needs compiler or interpreter for


8. It needs assembler for translation.
translation.

9. It is used widely for programming. It is not commonly used now-a-days in programming.


Compiler
• A Translator (compiler) is a program that reads a program written in
one language, the source language, - and translate it into an
equivalent program in another language, the target language.

• In computing, a compiler is a computer


program that translates computer code written in one programming
language (the source language) into another language
(the target language).

• The name "compiler" is primarily used for programs that


translate source code from a high-level programming language to
a low-level programming language (e.g. assembly language, object
code, or machine code) to create an executable program
Assembly Language
Assembly Language is a low-level programming language. It helps in
understanding the programming language of machine code.
• Machine code is a series of instructions that provide
the necessary information to a user’s CPU to carry out a
particular task (add, subtract, compare values, etc.).

• In computers, there is an assembler that helps in


converting the assembly code into machine code
executable.

• It establishes with the help of compiling high-level


language source code like C and C++.

• It mainly depends on the system architecture, whether


it is an operating system or computer architecture to
add assembler?
Introduction to Computing
Objectives
To learn and appreciate the following concepts

✓Problem solving basics


✓Logic and its importance in problem solving
✓Various computational problems and its classification
✓Computer Organization and operating system
✓Different types of languages
✓History of C, Typical C program development environment.

2
Introduction to problem solving

3
Skill set required for Software Engineers

4
What is a problem?
• A problem is a puzzle that requires logical thought or mathematics to solve
• A puzzle could be a set of questions on a scenario which consists of
description of reality and a set of constraints about the scenario
• Eg: Scenario- Infosys Mysore campus has a library. The librarian issues book
only to Infosys employees.
Description of reality: There is a library in Infosys Mysore campus . There is a
librarian in the library
Constraints: librarian issues book only to Infosys employees.
Questions about the scenario: How many books are there in the library? How
many books can be issues to an employee?
Does the librarian issue book to himself? Etc.

5
Logic
• A method of human thought that involves thinking in a linear, step by
step manner about how a problem can be solved
• Logic is a language for reasoning. It is a collection of rules we use when
doing reasoning.
Eg: John’s mother has four children.
First child is April
Second child is May
Third child is June
What is the name of fourth child?

6
Importance of logic in problem solving
• Solution for any problem(eg: summation of two numbers) requires three
things.
Input: Input values(Eg: 3 and 2)
Process: Process of summation
Output: Output after process (Eg: sum of
numbers,5)

• The process part(Eg: summation) of the solution requires logic( How to


sum) or in other words based on the logic, process is developed.

7
Importance of logic in problem solving
• For solving a problem, there may be multiple valid logics, some may be
simple and some may be complex.
Eg: To determine whether the number is prime or not.

Logic 1- divide the number by all the numbers starting from 2 to one less
than the number and if for all the division operations, the reminder is non
zero, the number is prime. Else the number is not prime.
Logic 2 – same as logic 1 but divide the number from 2 to number/2
Logic 3 - same as logic 1 but divide the number from 2 to square root of
the number

8
Types of problems

9
Computational Problems
• Definition: Computation is a process of evolution from one state to
another in accordance with some rules.

10
Broad applications of Computational Problem

11
Classification of computational problems

12
Computer Organization

13
Central Processing Unit
➢Data and instructions are processed in CPU

➢ Consists of two functional units


▪ Control Unit (CU)
▪ Arithmetic and Logic Unit (ALU)

14
Arithmetic and Logical unit
▪ Performs arithmetic and logical operations:
• Example:
• arithmetic(+,-,*,/ etc..) and
• logical (AND, OR, NOT, <,= etc..) operations

15
Control unit
• Controls the order in which your program instructions are executed.
• Functions of CU:
▪ Fetches data and instructions to main memory
▪ Interprets these instructions
▪ Controls the transfer of data and instructions to and from main memory
▪ Controls input and output devices.
▪ Overall supervision of computer system

16
Memory unit
➢Storage device where the data and instructions fed by the user are stored

➢An ordered sequence of storage cells, each capable of holding a piece of information

➢Each cell has its own unique address

➢The information held can be input data, computed values, or your program

instructions.

17
Memory unit
The computer starts using the memory from the moment the computer is switched on, till the time
it is switched off. The list of steps are—
1. Turn the computer on.
2. The computer loads data from ROM. It makes sure that all the major components of the
computer are functioning properly. The computer loads the BIOS from ROM. The BIOS provides the
most basic information about storage devices, boot sequence, security, plug and play capability and
other items.
3. The computer loads the OS from the hard drive into the system’s RAM. CPU has immediate access
to the OS as the critical parts of the OS are maintained in RAM as long as the computer is on. This
enhances the performance and functionality of the overall system.
4. Now the system is ready for use.
5. When you load or open an application it is loaded in the RAM. Since the CPU looks for
information in the RAM, any data and instructions that are required for processing (read, write or
update) is brought into RAM. To conserve RAM usage, many applications load only the essential
parts of the program initially and then load other pieces as needed. Any files that are opened for
use in that application are also loaded into RAM.
18
Memory unit
6. The CPU requests the data it needs from RAM, processes it and writes new data back to RAM in a
continuous cycle. The shuffling of data between the CPU and RAM happens millions of times every
second.
7. When you save a file and close the application, the file is written to the secondary memory as
specified by you. The application and any accompanying files usually get deleted from RAM to make
space for new data.
8. If the files are not saved to a storage device before being closed, they are lost.

The memory unit is the part of the computer that holds data and instructions for processing. Although it
is closely associated with the CPU, in actual fact it is separate from it. Memory associated with the CPU is
also called primary storage, primary memory, main storage, internal storage and main memory. When
we load software from a floppy disk, hard disk or CD-ROM, it is stored in the memory unit.

19
Memory unit
➢The computer memory is measured in terms of bits, bytes and words.

➢A bit is a binary digit either 0 or 1.

➢A byte is unit of memory and is defined as sequence of 8 bits.

➢The word can be defined as a sequence of 16/32/64 bits or 2/4/8 bytes


respectively depending on the machine architecture

20
Computer memory classifications
• Main memory-Primary storage
• Secondary memory-Auxiliary storage
• Cache memory

21
Main memory
➢Memory where the data and instructions, currently being executed are
stored
➢ Located outside CPU
➢ High speed
➢ Data and instructions stored get erased when the power goes off
➢Also referred as primary / temporary memory
➢ Semiconductor memory
➢ Measured in terms of megabytes and gigabytes

22
Primary storage: RAM & ROM
• RAM stands for Random Access Memory
➢ Read and write memory
➢ Information typed by the user are stored in this memory
➢ Any memory location can be accessed directly without scanning it sequentially
(random access memory)
➢ During power failure the information stored in it will be erased → volatile
memory
• ROM stands for Read Only Memory
➢Permanent memory and non volatile
➢Contents in locations in ROM can not be changed
➢Stores mainly stored program and basic input output system programs

23
Secondary memory

➢Main memory is volatile and limited


➢ Hence it is essential for other types of storage devices where programs and data
can be stored when they are no longer being processed

➢Installed within the computer at the factory or added later as needed

24
Secondary memory
➢Non-volatile memory

➢Made up of magnetic material

➢Stores large amount of information for long time

➢Low speed

➢Holds programs not currently being executed

25
Cache memory
➢ High speed memory placed between CPU and main memory
➢ Stores data and instructions currently to be executed
➢ More costlier but less capacity than main memory
➢ Users can not access this memory

26
Computer languages
Operating System
➢OS is an integrated collection of programs which make the computer
operational and help in executing user programs.

➢ It acts as an interface between the man and machine.

➢ It manages the system resources like memory, processors, input-output


devices and files.

➢Windows, Linux, DOS

2
Computer Languages
• Machine Language- The only programming language available in earlier days
• Consists of only 0’s and 1’s; e.g.:- 10101011
• Symbolic language or Assembly language-
• symbols or mnemonics are used to represent instructions
• hardware specific
• e.g. ADD X,Y; Add the contents of y to x
• High-level languages- English like language using which the programmer can write
programs to solve a problem.
• more concerned with the problem specification
• not oriented towards the details of computer
• e.g.: C, C++, C#, Fortran, BASIC, Pascal etc.

3
Language Translator
• Compiler : Program that translates entire high level language program
into machine language at a time. e.g.:- C, C++ compilers.
• Interpreter : Program which translates one statement of a high level
language program into machine language at a time and executes it.
e.g.:- Basic Interpreters, Java Interpreters.
• Assembler : Program which translates an assembly language program
into machine language.
e.g.:- TASM(Turbo ASseMbler), MASM(Macro ASseMbler).

4
History of C
➢The C language was evolved by Dennis Ritchie at Bell Laboratories and
was originally implemented on a DEC PDP(Digital Equipment
Corporation-Programmed Data Processor)-11 computer in 1972.
➢C initially became widely known as the development language of the
UNIX operating system.
➢Today, virtually all new major operating systems are written in C and/or
C++.
➢C is available for most computers.
➢C is mostly hardware independent.

5
Typical C program development environment

6
Typical C program development environment
➢C programs typically go through six phases to be executed. These are:
edit, preprocess, compile, link, load and execute
➢ Phase 1 : creating a program
➢Phases 2 and 3: Preprocessing and Compiling a C Program
➢Phase 4: Linking
➢Phase 5: Loading
➢Phase 6: Execution

7
Structure of C Program,
Character Set, Tokens
C Character set

➢Character set is a Letters → ‘a’, ‘b’, ‘c’,………..’z’ Or ‘A’, ‘B’, ‘C’,……….’Z’


set of valid
characters that a
language can
recognize.
Digits → 0, 1, 2,……………………9

➢C character set
consists of letters,
digits, special Special characters → ;, ?, >, <, &,{, }, [, ]……
characters, white
spaces.
White spaces → New line (\n), Tab(\t), Vertical
Tab(\v) etc.

2
C Tokens
Tokens

✓A token is a group of Special


characters that Keywords Identifiers Operators Strings Constants
Symbols
logically belong
together. Break Variable + “hello” 123 ;
✓The programmer
writes a program by Int Constant * “123” 21.3 ?
using tokens.
✓C uses the following Function
float % “s” ‘A’ >
name
types of tokens.
Array
‘g’ &
name

“hello” {

3
Simple C program

4
5
Hello world program

6
Structure of C program
#incude<stdio.h>

void main()
{
printf(“I love programming\n”); /*new line*/

printf(“You can learn it easily ”); /*add comment*/

printf(“easily\n”);
}

7
Input: Scanf()
#incude<stdio.h>

Scanf() is used to obtain void main()


the value from the user {
int num;
It is included in stdio.h
printf(“Enter a number = ”);

scanf(“%d”, &num);
Eg: scanf(“%d”, &integer1);
printf(“The number is = %d”, num);
}

8
Data Types and its Storage Requirements and its Range
Format
Specifier

%c

%c

%d

%u
%h

%hu
%ld

%lu
%f

%lf

%Lf
9
Character Meaning
Group

%c Read a single character

%d Read a decimal integer

%f Read a floating point number

%g Read a short int number

%h Read a short int number

%i Read a decimal or hexadecimal or octal number


10
C Program Essentials: Format Specifiers
Format specifier Description
%d or %i It is used to print the signed integer value where signed integer means that
the variable can hold both positive and negative values.
%u It is used to print the unsigned integer value where the unsigned integer
means that the variable can hold only positive value.
%o It is used to print the octal unsigned integer where octal integer value
always starts with a 0 value.
%x It is used to print the hexadecimal unsigned integer where the hexadecimal
integer value always starts with a 0x value. In this, alphabetical characters
are printed in small letters such as a, b, c, etc.
%X It is used to print the hexadecimal unsigned integer, but %X prints the
alphabetical characters in uppercase such as A, B, C, etc.
%f It is used for printing the decimal floating-point values. By default, it prints
the 6 values after '.'.
11
C Program Essentials: Format Specifiers
Format specifier Description
%f It is used for printing the decimal floating-point values. By default, it prints
the 6 values after '.'.
%e/%E It is used for scientific notation. It is also known as Mantissa or Exponent.
%g It is used to print the decimal floating-point values, and it uses the fixed
precision, i.e., the value after the decimal in input would be exactly the
same as the value in the output.
%p It is used to print the address in a hexadecimal form.
%c It is used to print the unsigned character.
%s It is used to print the strings.
%ld It is used to print the long-signed integer value.

12
Output: Printf()

C provides the printf() to display the data on the monitor.

It is included in stdio.h

Examples are:
• Printf(“programming is an art”;
• Printf(“%d”, number);
• Printf(“%f%f”, p,q);

13
#include <stdio.h>
Adding two int main( void )
integers {
int sum; /* variable in which sum will be stored */
int integer1; /* first number to be input by user */
int integer2; /* second number to be input by user */
printf( "Enter first integer\n" );
scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer\n" );
scanf( "%d", &integer2 ); /* read an integer */
sum = integer1 + integer2; /* assign total to sum */
printf( "Sum is %d\n", sum ); /* print sum */
return 0; /* indicate that program ended successfully */
} /* end function main */
14
Syntax and Logical errors

Syntax errors: violation of programming


language rules (grammar).
• Detected by the compiler
• Eg: printf (“hello world”) // semicolon missing

Logical errors: errors in meaning:


• Programs are syntactically correct but don’t produce the
expected output
• User observes output of running program

15
C Compiler:
• For Window, you need to install MinGW for GCC or you can use Turbo C
compiler.
• The most frequently used and free available compiler is the GNU C/C++
compiler for Linux
• For MAC, the easiest way to obtain GCC is to download the Xcode
development environment from Apple's web site and follow the simple
installation instructions.
What to do when a C program produces different results in two different
compilers? → Your program must follow C standard i.e. ISO/IEC
9899:2011 (also known as C11)

16
Compilation Process
• The compilation is a process of converting the source code into object
code.
• The compilation process can be divided into four steps, i.e., Pre-
processing, Compiling, Assembling, and Linking.

The extension of the object file in DOS is '.obj,' and in UNIX, the extension is
'o'.

17
Compilation Process Example

18
Thank You!!

19
A program for Finding an Even and Odd
#include<stdio.h>
main()
{
int a,x;
printf("Enter a number\n");
scanf("%d",&a);
x=a%2;
if(x==0)
printf("Number a=%d is even\n",a);
else
printf("Number a=%d is odd\n",a);
}
20
Swap of Two Numbers, Using Two Variables
#include<stdio.h>
main()
{
int a=5, b=6;
printf("Swap of Numbers\n");
a=a+b; printf("a=%d\n",a);
b=a-b; printf("b=%d\n",b);
a=a-b; printf("a=%d\n",a);
///b=c;
printf("Final a=%d and b=%d",a,b);
}
21
Interest Calculation Program
#include<stdio.h>
#define PERIOD 10
#define PRINCIPAL 5000.00
void main()
{
int year;
float amount, value, Inrate;
amount=PRINCIPAL;
inrate=0.11;
year=0;
while(year<=PERIOD)
{
printf("year=%2d and amount=%8.2f\n",year, amount);
value=amount=amount+inrate*amount;
year=year+1;
amount=value;
}
}
22
Subroutine Call Program
#include<stdio.h>
main()
{
int a, b, c;
a=5; b=6;
c=mul(a,b);
printf("multplcaton of a=%d and b=%d is = %d",a,b,c);
}
int mul(int x,int y)
{
int p;
{
p=x*y;
return p;
}
} 23
Keywords
Constants(integer, real, character, string)
Literals
Variables
Keywords

These are some reserved words in C which have


predefined meaning to compiler called keywords.

Keywords are not to be used as variable and


constant names.

All keywords have fixed meanings and these


meanings cannot be changed.

2
Compiler specific keywords (32)

Some commonly used keywords are given below:

3
Constants

Constants are data values that cannot be changed


during the execution of a program. Like variables,
constants have a type. In this section, we discuss
Boolean, character, integer, real, complex, and string
constants.

Topics discussed in this section:


Constant Representation
Coding Constants

4
Note
A character constant is enclosed in single quotes.

Use single quotes for character constants.


Use double quotes for string constants.

5
Examples of Constant

Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program", "c in javatpoint"


etc.

6
Examples of Integer Constants

7
Examples of Real Constants

8
Examples of String Constants

9
Null Characters and Null Strings?

Characters and Strings its definitions are defined, but \0 is an explicit


representation where as in “” is an implicit representation?
10
Symbolic Names for Control
Characters

11
Two ways to define constant

1. const keyword
2. #define preprocessor

12
EXAMPLE PROGRAM

13
Literals
Literals are the constant values assigned to the constant
variables. We can say that the literals represent the fixed
values that cannot be modified.

For example, const int =10; is a constant integer


expression in which 10 is an integer literal.

There are four types of literals that exist in C programming:


◼ Integer literal

◼ Float literal

◼ Character literal

◼ String literal
14
Variables
A variable is a container (storage area) to hold data
Variables are data storage locations in the
computer’s memory.
To indicate the storage area, each variable should be
given a unique name (identifier).
Example: float f=20.8; Here, f is variable

15
Variables

Variables are the symbolic names for storing computational data.

Variable: a symbolic name for a memory location

In C variables have to be declared before they are used Ex:


int x;

A variable may take different values at different times


during execution.

Declarations reserve storage for the variable.

Value is assigned to the variable by initialization or assignment


16
Variable declarations

Data type Variable name;

Which data types Which variable names


are possible in C ? are allowed in C ?

17
Variable Names- Identifiers

Symbolic names can be used in C for various data items


used by a programmer.

A symbolic name is generally known as an identifier. An


identifier is a name for a variable, constant, function, etc.

The identifier is a sequence of characters taken from C


character set.
18
Variable names
Rules for valid variable names (identifiers) :

Name must begin with a letter or underscore ( _ ) and can


be followed by any combination of letters, underscores, or
digits.

Key words cannot be used as a variable name.

C is case-sensitive: sum, Sum, and SUM each refer to


a different variable.
Examples:
Sum
Variable names can be as long as you want, although _difference
only the first 63 (or 31) characters might be
a
significant.
J5x7
Number_of_moves
Choice of meaningful variable names can increase the 3val
readability of a program int
19
Declaring variables
• C imposes to declare variables before their usage.
• Advantages of variable declarations:

Putting all the variables in one place makes it easier for a reader
to understand the program.

Thinking about which variables to declare encourages the


programmer to do some planning before writing a program.

The obligation to declare all variables helps prevent bugs


of misspelled variable names.

Compiler knows the amount of memory needed for storing


the variable.

Compiler can verify that operations done on a variable are


allowed by its type.
20
Using and Displaying Variables
#include <stdio.h>
int main ()
{
int sum;
sum = 50 + 25;
printf("The sum of 50 and 25 is%d”,sum);
return 0;
}

Variable sum declared of type int


Variable sum assigned expression 50+25
Value of variable sum is printed

21
Variables - Examples

int a; // declaring a variable of type int

int sum, a1, a2; // declaring 3 variables

int x = 7; // declaring and initializing a variable

a = 5; // assigning to variable a the value 5

a1 = a; // assigning to variable a1 the value of a

L-value R-value

a1=a1+1; // assigning to variable a1 the value of a1+1


// (increasing value of a1 with 1)

22
Data types
Comes under the category

2
Primary (built-in or Basic)Data types

INTEGER CHARACTER

SIGNED TYPE UNSIGNED TYPE


INT UNSIGNED INT SIGNED CHARACTER
SHORT INT UNSIGNED SHORT INT UNSIGNED CHARACTER
LONG INT UNSIGNED LONG INT

FLOATING POINT TYPE VOID


FLOATING POINT TYPE
FLOAT VOID
DOUBLE
LONG DOUBLE

3
Data types
Basic data types: int, float, double, char, and void.

int: can be used to store integer numbers (values with no


decimal places).

float: can be used for storing floating-point numbers


(values containing decimal places).

double: the same as type float, and roughly twice the


size of float.

char: can be used to store a single character, such as


the letter a, the digit character 6, or a semicolon.

void: is used to denote nothing or empty.

4
Integer Types

The basic integer type is int


• The size of an int depends on the machine and
on PCs it is normally 16 or 32 or 64 bits.
modifiers (type specifiers)
• short: typically uses less bits
• long: typically uses more bits
• Signed: both negative and positive numbers
• Unsigned: only positive numbers
5
SIZE AND RANGE OF VALUES FOR A 16-BIT
MACHINE (INTEGER TYPE)

Type Size (bits) Range

short int or
signed short int 8 -128 to 127
short
unsigned int
8 0 to 255

int or signed int 16 -32,768 to 32,767


Integer
unsigned int 16 0 to 65,535
long int or
-2,147,483,648 to
signed long int 32
Long 2,147,483,647

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

6
The character type char

A char variable can be used to store a single character.

A character constant is formed by enclosing the character within a


pair of single quotation marks. Valid examples: 'a’ .

Character zero ( ‘0’ ) is not the same as the number (integer


constant) 0.

The character constant ‘\n’—the newline character—is a valid


character constant. It is called as an escape character.

There are other escape sequences like, \t for tab, \v for vertical tab, \n
for new line etc.

7
Character Types

Character type char is related to the integer type.

Modifiers(type specifiers) unsigned and signed can be used


• char →1 byte (-128 to 127)
• signed char →1 byte (-128 to 127)
• unsigned char →1 byte (0 to 255)

ASCII (American Standard Code for Information Interchange ) is


the dominant encoding scheme for characters.
• Examples
• ' ' encoded as 32 '+' encoded as 43
• 'A' encoded as 65 …………………….'Z' encoded as 90
• 'a' encoded as 97 ……………………. 'z' encoded as 122
• ‘0’ encoded as 48 ……………………..’9’ encoded as 57
8
Assigning values to char
char letter; /* declare variable letter of type char */

letter = ‘A'; /* OK */

letter = A; /* NO! Compiler thinks A is a variable */

letter = “A"; /* NO! Compiler thinks “A" is a string */

letter = 65; /* ok because characters are internally stored


as numeric values (ASCII code) */

9
Floating-Point Types

Floating-point types represent real numbers


• Integer part
• Fractional part

The number 108.1517 breaks down into the following parts


• 108 - integer part
• 1517 - fractional part

Floating-point constants can also be expressed in scientific notation. The value 1.7e4
represents the value 1.7 × 104.

The value before the letter e is known as the mantissa, whereas the value that follows
e is called the exponent.

There are three floating-point type specifiers


• float
• double
• long double
10
SIZE AND RANGE OF VALUES FOR 16-BIT MACHINE
(FLOATING POINT TYPE)

Type Size

32 bits
Single Precision Float
4 bytes

64 bits
Double Precision double 8 bytes

Long Double 80 bits


long double
Precision 10 bytes

11
void
➢2 uses of void are
▪To specify the return type of a function when it is not
returning any value.
▪To indicate an empty argument list to a function.

12
Summary of Memory Used

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

13
Summary of Memory Used
Data Types Memory Size Range
short int 2 byte −32,768 to 32,767
signed short int 2 byte −32,768 to 32,767
unsigned short 2 byte 0 to 65,535
int
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

14
Important
You can always check the size of a variable using
the sizeof() operator.
#include <stdio.h>
int main() {
short a;
long b;
long long c;
long double d;

printf("size of short = %d bytes\n", sizeof(a));


printf("size of long = %d bytes\n", sizeof(b));
printf("size of long long = %d bytes\n", sizeof(c));
printf("size of long double= %d bytes\n", sizeof(d));
return 0;
}

15
Best Practices for Programming
Naming Variables According to Standards

Prefix Data Type Example

✓i int and unsigned int iTotalMarks


✓f float fAverageMarks
✓d double dSalary
✓l long and unsigned long lFactorial
✓c signed char and unsigned char cChoice
✓ai Array of integers aiStudentId
✓af Array of float afQuantity
✓ad Array of double adAmount
✓al Array of long integers alSample
✓ac Array of characters acEmpName
16
Example: Using data types
#include <stdio.h>
int main ()

{
int integerVar = 100;
float floatingVar = 331.79;
double doubleVar = 144368.4411;
char charVar = 'W';
printf(“%d\n”, integerVar);
printf(“%f\n”,floatingVar);
printf(“%lf\n”,doubleVar);
printf(“%c\n”,charVar);
return 0;
}

17
Operators: Arithmetic,
Relational, Logical,
Assignment
Operators
The different operators are:

Arithmetic Relational Logical

Increment and
Bitwise Assignment
Decrement

Conditional

2
Arithmetic Operators
The binary arithmetic operators are +, -, *, / and the modulus
operator %.

The / operator when used with integers truncates any


fractional part i.e. E.g. 5/2 = 2 and not 2.5

Therefore % operator produces the remainder when 5 is


divided by 2 i.e. 1

The % operator cannot be applied to float or double

E.g. x % y wherein % is the operator and x, y are operands

3
The unary minus operator

#include <stdio.h>
int main ()
{
int a = 25;
int b = -2;
printf(“%d\n”,-a); Output ?
printf(“%d\n”,-b);
return 0;
}

4
The unary minus operator

#include <stdio.h>
int main ()
{
int a = 25;
int b = -2;
printf(“%d\n”,-a); Output:
printf(“%d\n”,-b);
-25
return 0;
} 2

5
Working with arithmetic expressions

• Basic arithmetic operators: +, -, *, /, %


• Precedence: One operator can have a higher priority, or
precedence, over another operator. The operators within C are
grouped hierarchically according to their precedence (i.e., order
of evaluation)

6
Working with arithmetic expressions

• Operations with a higher precedence are carried out before


operations having a lower precedence.
High priority operators * / % …
Low priority operators + - …

Example: * has a higher precedence than +


a + b * c → a+(b*c)

• If necessary, you can always use parentheses in an


expression to force the terms to be evaluated in any desired
order.

7
Working with arithmetic expressions

• Associativity: Expressions containing operators of the same


precedence are evaluated either from left to right or from right
to left, depending on the operator. This is known as the
associative property of an operator

Example: + has a left to right associativity

For both the precedence group described above, associativity


is “left to right”.

8
Summary of Operators

9
Working with arithmetic expressions

#include <stdio.h>
int main ()
Output:
{ 300
int a = 100; 102
int b = 2;
int c = 25;
int d = 4;
int result;
result = a * b + c * d; //Precedence
printf(“%d\n”,result);
result = a = (b + c * d);//Associativity
printf(“%d\n”,result);
return 0;
} 10
Increment and Decrement Operators
• ++ and -- operator as prefix and postfix
• If you use the ++ operator as a prefix like: ++var, the value of var is incremented by 1;
then it returns the value.
• If you use the ++ operator as a postfix like: var++, the original value of var is returned
first; then var is incremented by 1.

#include <stdio.h> Output:


int main() { 5
6
int var1 = 5, var2 = 5;
// 5 is displayed, Then, var1 is increased to 6.
printf("%d\n", var1++);
// var2 is increased to 6 , Then, it is displayed.
printf("%d\n", ++var2);
return 0;
} 11
Increment and Decrement Operators
#include <stdio.h>
int main()
{
int a = 10, b = 100; Output:
++a = 11
float c = 10.5, d = 100.5; --b = 99
++c = 11.500000
printf("++a = %d \n", ++a); --d = 99.500000
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);

return 0;
}

12
Increment and Decrement Operators: Example
• What will be the output of the following C code?

#include <stdio.h>
int main()
{
Output:
int a = 1, b = 1, c; a = 2, b = 1, c=2

c = a++ + b;
printf(“a=%d, b=%d, c=%d", a, b,c);
}

13
Increment and Decrement operators

Prefix Mode Postfix Mode


Ex: Ex:
m=5; m=5;

y=++m; Prefix Mode y=m++; Postfix Mode

Here y continues to be 5. Only m


In this case, the value of y and m
changes to 6.
would be 6.
Postfix operator ++ appears after
Prefix operator ++ appears before the variable
the variable.

14
Increment and Decrement operators

Don’ts:
Attempting to use the increment or decrement operator
on an expression other than a modifiable variable name
or reference.
Example:
++(5) is a syntax error

++(x + 1) is a syntax error

15
Relational operators
Operator Meaning
== Is equal to

!= Is not equal to

< Is less than

<= Is less or equal

> Is greater than

>= Is greater or equal

The relational operators have lower precedence than all


arithmetic operators:
a < b + c is evaluated as a < (b + c)

ATTENTION !
the “is equal to” operator == and the “assignment” operator =

ATTENTION !
When comparing floating-point values, Only < and >
comparisons make sense !
16
Relational operators
➢ An expression such as a < b containing a relational operator is called a
relational expression.

➢ The value of a relational expression is one, if the specified relation is true and
zero if the relation is false.
E.g.:
10 < 20 is TRUE
20 < 10 is FALSE
➢ A simple relational expression contains only one relational operator and takes
the following form.

ae1 relational operator ae2

ae1 & ae2 are arithmetic expressions, which may be simple


constants, variables or combinations of them.
17
Relational operators
The arithmetic expressions will be evaluated first & then the results
will be compared. That is, arithmetic operators have a higher priority
over relational operators. > >= < <= all have the same precedence
and below them are the next precedence equality operators i.e. == and
!=
Suppose that i, j and k are integer variables whose values
are 1, 2 and 3 respectively.

Expression Interpretation Value


i<j true 1
(i+j)>=k true 1
(j+k)>(i+5) false 0
k!=3 false 0
j==2 true 1

18
Logical operators
Truth Table
op-1 op-2 value of expression
op-1&&op-2 op-1||op-2
Non-zero Non-zero 1 1
Non-zero 0 0 1
0 Non-zero 0 1
0 0 0 0

Operator Symbol Example


AND && expression1 && expression2
OR || expression1 || expression2
NOT ! !expression1

The result of logical operators is always either 0 (FALSE) or 1 (TRUE)

19
Logical operators
Expressions Evaluates As

(5 == 5)&&(6 != 2) True (1) because both operands are true

(5 > 1) || (6 < 1) True (1) because one operand is true

(2 == 1)&&(5 ==5) False (0) because one operand is false

! (5 == 4) True (1) because the operand is false

!(FALSE) = TRUE
!(TRUE) = FALSE

20
Logical operators
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10, result;
Output
result = (a == b) && (c > b);
printf("(a == b) && (c > b) is %d \n", result); (a == b) && (c > b) is 1
result = (a == b) && (c < b); (a == b) && (c < b) is 0
printf("(a == b) && (c < b) is %d \n", result); (a == b) || (c < b) is 1
result = (a == b) || (c < b); (a != b) || (c < b) is 0
printf("(a == b) || (c < b) is %d \n", result); !(a != b) is 1
result = (a != b) || (c < b); !(a == b) is 0
printf("(a != b) || (c < b) is %d \n", result);
result = !(a != b);
printf("!(a != b) is %d \n", result);
result = !(a == b);
printf("!(a == b) is %d \n", result);
return 0;
}
21
The assignment operators
• The C language permits you to join the arithmetic operators
with the assignment operator using the following general
format: op=, where op is an arithmetic operator, including +,
–, *, /, and %.

• Example:
count += 10;
• Equivalent to:
count=count+10;

• Example: precedence of op=:


a /= b + c
• Equivalent to:
a = a / (b + c) 22
Bitwise operators
• In arithmetic-logic unit (which is within the CPU),
mathematical operations like: addition, subtraction,
multiplication and division are done in bit-level.

Operators Meaning of operators


& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise complement
<< Shift left
>> Shift right

23
Bitwise Operators Examples
12 = 00001100 (In Binary) 12 = 00001100 (In Binary)
25 = 00011001 (In Binary) 25 = 00011001 (In Binary)
Bit Operation of 12 and 25
Bitwise OR Operation of 12 and 25
00001100
00001100
& 00011001 | 00011001
______ ________
00001000 = 8 (In decimal) 00011101 = 29 (In decimal)

12 = 00001100 (In Binary) 35 = 00100011 (In Binary)


25 = 00011001 (In Binary)
Bitwise complement Operation of 35
Bitwise XOR Operation of 12 and 25 ~ 00100011
00001100 ________
^ 00011001 11011100 = 220 (In decimal)
________
00010101 = 21 (In decimal)

Bitwise complement of any number N is -(N+1) 24


Conditional Operator

The conditional operator is also known as a ternary operator. The


conditional statements are the decision-making statements which depends
upon the output of the expression. It is represented by two symbols, i.e., '?'
and ‘:’.

• Syntax of a conditional operator


Expression1? expression2: expression3;

25
Conditional Operator

#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));
return 0;
}

26
Conditional Operator
#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}

27
Thank You!!

28
Bitwise, Conditional,
Comma, Size-of
Bitwise Operators

Bitwise Logical Operators

Bitwise Shift Operators

Ones Complement operator

2
Bitwise Logical operators

&(AND),|(OR),^(EXOR)
op1 op2 & | ^

1 1 1 1 0
These are binary operators
and require two integer 1 0 0 1 1
operands.
0 1 0 1 1
These work on their operands bit
by bit starting from LSB (rightmost 0 0 0 0 0
bit).

3
Example
Suppose x = 10, y = 15
z = x & y sets z=10 like this
0000000000001010  x
0000000000001111  y
0000000000001010  z = x & y

Same way |,^ according to the table are computed.

4
Bitwise Shift operators

<< ,>>

These are used to move bit patterns either to the left


or right.

They are used in the following form

• op<<n or op>>n
• Here, op is the operand to be shifted and n is number of
positions to shift.

5
Bitwise Shift operator: <<
<< causes all the bits in the operand
op to be shifted to the left by n
positions.

The leftmost n bits in the original bit


pattern will be lost and the rightmost n
bits that are vacated are filled with 0’s

6
Bitwise Shift operator: >>

>> causes all the bits in operand op


to be shifted to the right by n
positions.

The rightmost n bits will be lost and


the left most vacated bits are filled
with 0’s if number is unsigned integer

7
Examples
Suppose X is an unsigned integer whose bit pattern is 0000
0000 0000 1011

✓x<<1 0000 0000 0001 0110 Add ZEROS

✓x>>1 Add ZEROS 0000 0000 0000 0101

8
Examples
▪Suppose X is an unsigned integer whose bit pattern is
0000 0000 0000 1011 whose equivalent value in
decimal number system is 11.
✓x<<3 0000 0000 0101 1000 Add ZEROS = 88
✓x>>2 Add Z EROS 0000 0000 0000 0010 =2

Note:
✓x=y<<1; same as x=y*2 (Multiplication)
✓x=y>>1; same as x=y/2 (Division)

9
Bitwise Shift operators

Op and n can be constants or variables.

There are 2 restrictions on the value of n

• n cannot be –ve
• n should not be greater than number of bits used
to represent Op.(E.g.: suppose op is int and size is 2
bytes then n cannot be greater than 16).

10
Bitwise complement operator
▪The complement operator(~) is an unary
operator and inverts all the bits represented
by its operand.

▪Suppose x=1001100010001111
~x=0110011101110000 (complement)

▪Also called as 1’s complement operator.

11
Bitwise Operator Examples
#include <stdio.h> Output:
6
int main() 31
{ 6
int a=6, b=14; // variable declarations -9
int x=23,y=10; // variable declarations
int m=12, n=10; // variable declarations
int k=8;
printf("The output of the Bitwise AND operator a&b is %d",a&b);
printf("The output of the Bitwise OR operator x|y is %d",x|y);
printf("The output of the Bitwise ExOR operator m^n is %d",m^n);
printf("The output of the Bitwise Comp operator k is %d",~k);
return 0;
}

12
Bitwise Operator Examples
// C Program to demonstrate use of bitwise operators
#include <stdio.h>
int main() Output:
{
// a = 5(00000101), b = 9(00001001) a = 5, b = 9
unsigned char a = 5, b = 9; a&b = 1
// The result is 00000001 a|b = 13
printf("a = %d, b = %d\n", a, b); a^b = 12
printf("a&b = %d\n", a & b);
~a = -6
// The result is 00001101 b<<1 = 18
printf("a|b = %d\n", a | b);
b>>1 = 4
// The result is 00001100
printf("a^b = %d\n", a ^ b);

// The result is 11111010


printf("~a = %d\n", a = ~a);

// The result is 00010010


printf("b<<1 = %d\n", b << 1);

// The result is 00000100


printf("b>>1 = %d\n", b >> 1);

return 0;
13
}
Important::
The bitwise operators should not be used in place of logical
operators. The result of logical operators (&&, || and !) is either 0 or 1,
but bitwise operators return an integer value. Also, the logical operators
consider any non-zero operand as 1. For example:

int main()
{ Output:
int x = 2, y = 5; False True
(x & y) ? printf("True ") : printf("False ");
(x && y) ? printf("True ") : printf("False ");
return 0;
}

14
Important::

The & operator can be used to quickly check if a number is odd or


even. The value of expression (x & 1) would be non-zero only if x is odd,
otherwise the value would be zero.

The ~ operator should be used carefully. The result of ~ operator on a


small number can be a big number if the result is stored in an unsigned
variable. And the result may be a negative number if the result is stored
in a signed variable

int main()
{ Output:
unsigned int x = 1; Signed Result -2
printf("Signed Result %d \n", ~x); Unsigned Result 4294967294d
printf("Unsigned Result %ud \n", ~x);
return 0;
}

15
Sizeof Operator:
• When sizeof() is used with the data types such as int, float, char… etc it
simply returns the amount of memory is allocated to that data types.

• When sizeof() is used with the expression, it returns size of the


expression.
int main()
{
int a = 0;
double d = 10.21;
printf("%lu", sizeof(a + d));
return 0;
}
Output: ??

16
Comma (,) operator
▪ The comma operator is a binary operator that evaluates its first operand and
discards the result, it then evaluates the second operand and returns this value
(and type).

int i = (5, 10); // Value of i will be assigned as 10

▪ The comma operator has the lowest precedence of any C operator.


▪ The comma operator is used basically to separate expressions.
i = 0, j = 10; // in initialization [ l → r ]
▪ The meaning of the comma operator in the general expression e1, e2 is
“evaluate the sub expression e1, then evaluate e2; the value of the expression is
the value of e2”.

17
Comma (,) operator
▪ The comma operator is a binary operator that evaluates its first operand and
discards the result, it then evaluates the second operand and returns this value
(and type).

int main()
{
int x = 10;
int y = 15; Output??
printf("%d", (x, y));
return 0;
}

18
Comma (,) operator
int main()
{
int x = 10; Output:
int y = (x++, ++x); 12
printf("%d", y);
return 0;
}

int main()
{
Output:
int x = 10, y;
x = 11
y = (x++, printf("x = %d\n", x), ++x, printf("x = %d\n", x), x++);
x = 12
printf("y = %d\n", y);
y = 12
printf("x = %d\n", x);
x = 13
return 0;
}

19
Comma (,) operator

• The following expression in the code:


a = 2, 3, 4;
is evaluated as:
(((a = 2), 3), 4);
• This is because the reason that assignment operator has high precedence
over the comma operator.
• Check the output for following:
1. int a = 4, 3; //Error
2. int a; //4 will be assigned
a = 4,3;
3. int a =(4, 3); //3 will be assigned

20
The conditional operator (? :)

condition ? expression1 : expression2

• condition is an expression that is evaluated first.


• If the result of the evaluation of condition is TRUE (nonzero), then
expression1 is evaluated and the result of the evaluation becomes the
result of the operation.
• If condition is FALSE (zero), then expression2 is evaluated and its result
becomes the result of the operation.

maxValue = ( a > b ) ? a : b;

Equivalent to:

if ( a > b )
maxValue = a;
else
maxValue = b; 21
Operator precedence
and associativity
Summary of Operators

Detailed
Precedence
Table

2
Example:
Show all the steps how the following expression is evaluated. Consider
the initial values of i=8, j=5.

2*((i/5)+(4*(j-3))%(i+j-2))

3
Example solution:

2*((i/5)+(4*(j-3))%(i+j-2)) i→8, j→5

2*((8/5)+(4*(5-3))%(8+5-2))
2*(1+(4*2)%11)
2*(1+8%11)
2*(1+8)
2*9
18

4
Operator precedence & Associativity
Ex: (x==10 + 15 && y < 10)
Assume x=20 and y=5

Evaluation:
+ (x==25 && y< 10)
< (x==25 && true)
== (False && true)
&& (False)

5
Tutorial Problems
Suppose that a=2, b=3 and c=6, What is the answer for the following:
(a==5)
(a * b > =c)
(b+4 > a *c)
((b=2)==a)

• Evaluate the following:


1. ( (5 == 5) && (3 > 6) )
2. ( (5 == 5) || (3 > 6) )
3. 7==5 ? 4 : 3
4. 7==5+2 ? 4 : 3
5. 5>3 ? a : b
6. K = (num > 5 ? (num <= 10 ? 100 : 200) : 500); where num =30
• In b=6.6/a+(2*a+(3*c)/a*d)/(2/n); which operation will be performed
first.
• If a is an integer variable, a=5/2; will return a value??
• The expression, a=7/22*(3.14+2)*3/5; evaluates to??
• If a is an Integer, the expression a = 30 * 1000 + 2768; evaluates to??
6
Type conversion
Type Conversions in Expressions

C permits mixing of constants and variables of different types in an


expression

C automatically converts any intermediate values to the proper type


so that the expression can be evaluated without losing any
signification

This automatic conversion is known as Implicit Type Conversion

1/25/2024 2
Implicit Type Conversions
Done by the compiler on its own, without any external trigger from the user.

Generally takes place when in an expression more than one data type is
present

All the data types of the variables are upgraded to the data type of the
variable with largest data type.

bool -> char -> short int -> int -> unsigned int -> long ->
unsigned -> long long -> float -> double -> long double

•It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long long is implicitly
converted to float).

1/25/2024 3
Implicit Type Conversions in Expressions
The following are the sequence of rules that are applied while evaluating
expressions
Lower Type Operands Higher Type Operands
Short or Char int
One operand is Long double, the other will be Result is also long double
converted to long double
One operand is double, the other will be Result is also double
converted to double
One operand is float, the other will be converted Result is also float
to float
One operand is unsigned Long int, the other will Result is also unsigned long int
be converted to unsigned long int

1/25/2024 4
Implicit Type Conversions in Expressions
Lower Type Operands Higher Type Operands

One operand is Long int, and the other is a) Result will be long int
unsigned int then
a) If unsigned int can be converted to long int
the unsigned int operand will be converted
b) Else both operands will be converted to b) Result will be unsigned long int
unsigned long int
One operand is Long int, the other will be Result is also long int
converted to long int

One operand is unsigned Long int, the other Result is also unsigned long int
will be converted to unsigned long int

1/25/2024 5
Implicit Type Conversions in Expressions

The final result of an expression is converted to the type of the


variable on the left of the assignment sign before assigning the
value to it

However the following changes are introduced during the final


assignment

• Float to int causes truncation of the fractional part


• Double to float caused rounding of digits
• Long int to int causes dropping of the excess higher order bits

1/25/2024 6
Implicit Type Conversion Example

int main()
{
int x = 10; // integer x
char y = 'a'; // character c

x = x + y;

float z = x + 1.0;

printf("x = %d, z = %f", x, z);


return 0;
}

Output:
x = 107, z = 108.000000

1/25/2024 7
Explicit Type Conversions

There are instances when we want to force a type


conversion in a way that is different from the
automatic conversion
• E.g ratio=57/67
• Since 57 and 67 are integers in the program , the decimal part of the
result of the division would be lost and ratio would represent a wrong
figure

This problem can be solved by converting locally as


one of the variables to the floating point as shown
below:
• ratio= (float) 57/67

1/25/2024 8
Type Conversions in Expressions

The operator (float) The division is performed


converts the 57 to floating in floating point mode,
point then using the rule thus retaining the
of automatic conversion fractional part of result

The process of such a local The general form of a cast


conversion is known as is
explicit conversion or • (type-name) expression
casting a value

1/25/2024 9
The Type Cast Operator
int a =150;
float f; f = (float) a / 100; // type cast operator
• The type cast operator has the effect of converting the value of the variable ‘a’ to type
float for the purpose of evaluation of the expression.
• This operator does NOT permanently affect the value of the variable ‘a’;
• The type cast operator has a higher precedence than all the arithmetic operators
except the unary minus and unary plus.
• Examples of the use of type cast operator:

(int) 29.55 + (int) 21.99 results in 29 + 21

(float) 6 / (float) 4 results in 1.5

(float) 6 / 4 results in 1.5

1/25/2024 10
Type Conversions in Expressions

Example Action
x=(int) 7.5 7.5 is converted to integer by
truncation
a=(int) 21.3/(int)4.5 Evaluated as 21/4 and the result
would be 5
b=(double)sum/n Division is done in floating point mode
y=(int)(a+b) The result of a+b is converted to
integer
z=(int)a+b a is converted to integer and then
added to b
p=cos((double)x) Converts x to double before using it

1/25/2024 11
Integer and Floating-Point Conversions
Assign an integer value to a floating variable: does not cause any
change in the value of the number; the value is simply converted
by the system and stored in the floating format.

Assign a floating-point value to an integer variable: the decimal


portion of the number gets truncated.

Integer arithmetic (division):

• int divided to int => result is integer division


• int divided to float or float divided to int => result is real division (floating-point)

1/25/2024 12
Integer and Floating-Point Conversions
#include <stdio.h>
int main ()
{ float f1 = 123.125, f2;
int i1, i2 = -150;
i1 = f1; // float to integer conversion
printf(“float assigned to int produces”);
printf(“%d\n”,i1);
f2 = i2; // integer to float conversion
printf(“integer assigned to float produces”);
123
printf(“%f\n”,f2);
i1 = i2 / 100; // integer divided by integer -150.0
printf(“integer divided by 100 produces”);
printf(“%d\n”,i1);
f1 = i2 / 100.0; // integer divided by a float -1
printf(“integer divided by 100.0 produces”);
printf(“%f\n”,f1);
return 0;
-1.5
}

1/25/2024 13
 All input and output is performed with streams, which
are sequences of bytes.
 In input operations, the bytes flow from a device (e.g.,
a keyboard, a disk drive, a network connection) to main
memory.
 In output operations, bytes flow from main memory to
a device (e.g., a display screen, a printer, a disk drive, a
network connection, and so on).
 When program execution begins, three streams are
connected to the program automatically.
 Normally, the standard input stream is connected to the
keyboard and the standard output stream is connected
to the screen.
 Operating systems often allow these streams to be
redirected to other devices.
 A third stream, the standard error stream, is connected
to the screen.
 Error messages are output to the standard error stream.
 Precise output formatting is accomplished with
printf.
 Every printf call contains a format control string
that describes the output format.
 The format control string consists of conversion
specifiers, flags, field widths, precisions and literal
characters.
 Together with the percent sign (%), these form
conversion specifications.
Printf can perform the following formatting capabilities:
◦ Rounding floating-point values to an indicated number of decimal
places.
◦ Aligning a column of numbers with decimal points appearing one
above the other.
◦ Right justification and left justification of outputs.
◦ Inserting literal characters at precise locations in a line of output.
◦ Representing floating-point numbers in exponential format.
◦ Representing unsigned integers in octal and hexadecimal format
◦ Displaying all types of data with fixed-size field widths and
precisions.
 The printf function has the form
 printf(“Format Specifier”, var1, var2, …., varn);
Format Specifier describes the output format.
 Each conversion specification begins with a percent
sign and ends with a conversion specifier.
 There can be many conversion specifications in one
format control string.
 An integer is a whole number, such as 776, 0 or –52,
that contains no decimal point.
 Integer values are displayed in one of several formats.
 A floating-point value contains a decimal point as in
33.5, 0.0 or -657.983.
 The conversion specifiers e and E display floating-point
values in exponential notation—the computer
equivalent of scientific notation used in mathematics.
 For example, the value 150.4582 is represented in
scientific notation as::
1.504582  102
 and is represented in exponential notation as
1.504582E+02

 This notation indicates that 1.504582 is multiplied


by 10 raised to the second power (E+02).
 The E stands for “exponent.”
 Values displayed with e, E and f show six digits of precision to the
right of the decimal point by default (e.g., 1.04592); other precisions
can be specified explicitly.
 Conversion specifiers e and E print lowercase e and uppercase E,
respectively, preceding the exponent, and print exactly one digit to
the left of the decimal point.
 Conversion specifier g (or G) prints in either e (E) or f format with
no trailing zeros (1.234000 is printed as 1.234).
 Values are printed with e (E) if, after conversion to exponential
notation, the value’s exponent is less than -4, or the exponent is
greater than or equal to the specified precision (six significant
digits by default for g and G). Otherwise, conversion specifier f is
used to print the value.
 At least one decimal digit is required for the decimal point to be
output.
 0.0000875, 8750000.0, 8.75, 87.50 and 875
are printed as …. with conversion specifier g??
8.75e-05
8.75e+06
8.75, 87.5
875

 0.0000875 uses e notation because, when it’s


converted to exponential notation, its exponent (-5) is
less than -4.
 The value 8750000.0 uses e notation because its
exponent (6) is equal to the default precision.
 The difference between g and G is identical to the
difference between e and E when the value is printed in
exponential notation—lowercase g causes a lowercase e to
be output, and uppercase G causes an uppercase E to be
output.
 The %E, %e and %g conversion specifiers cause the value to be
rounded in the output and the conversion specifier %f does
not.
 With some compilers, the exponent in the outputs will be
shown with two digits to the right of the + sign.
 The c and s conversion specifiers are used to print
individual characters and strings, respectively.
 Conversion specifier c requires a char argument.
 Conversion specifier s requires a pointer to char as
an argument.
 Conversion specifier s causes characters to be printed
until a terminating null ('\0') character is
encountered.
 The exact size of a field in which data is printed is specified
by a field width.
 If the field width is larger than the data being printed, the
data will normally be right justified within that field.
 An integer representing the field width is inserted between
the percent sign (%) and the conversion specifier (e.g.,
%4d).
 The field width is increased to print values wider than the
field and that the minus sign for a negative value uses one
character position in the field width.
 Field widths can be used with all conversion specifiers.
 Function printf also enables you to specify the precision
with which data is printed.
 Precision has different meanings for different data types.
 When used with integer conversion specifiers, precision
indicates the minimum number of digits to be printed.
 If the printed value contains fewer digits than the
specified precision and the precision value has a leading
zero or decimal point, zeros are prefixed to the printed
value until the total number of digits is equivalent to the
precision.
 If neither a zero nor a decimal point is present in the
precision value, spaces are inserted instead.
 The default precision for integers is 1.
 When used with floating-point conversion specifiers e, E
and f, the precision is the number of digits to appear after
the decimal point.
 When used with conversion specifiers g and G, the
precision is the maximum number of significant digits to be
printed.
 When used with conversion specifier s, the precision is the
maximum number of characters to be written from the
string.
 To use precision, place a decimal point (.), followed by an
integer representing the precision between the percent sign
and the conversion specifier.
When a floating-point value is printed with a precision smaller than the original
number of decimal places in the value, the value is rounded.
 The field width and the precision can be combined
by placing the field width, followed by a decimal
point, followed by a precision between the percent sign
and the conversion specifier, as in the statement
 printf( "%9.3f", 123.456789 );
which displays 123.457 with three digits to the right
of the decimal point right justified in a nine-digit field.
 It’s possible to specify the field width and the precision
using integer expressions in the argument list following
the format control string.
 To use this feature, insert an asterisk (*) in place of the
field width or precision (or both).
 The matching int argument in the argument list is
evaluated and used in place of the asterisk.
 A field width’s value may be either positive or negative
(which causes the output to be left justified in the field
as described in the next section).
 The statement
 printf( "%*.*f", 7, 2, 98.736 );
uses 7 for the field width, 2 for the precision and
outputs the value 98.74 right justified.
 Most literal characters to be printed in a printf statement
can simply be included in the format control string.
 However, there are several “problem” characters, such as
the quotation mark (") that delimits the format control string
itself.
 Various control characters, such as newline and tab, must be
represented by escape sequences.
 An escape sequence is represented by a backslash (\),
followed by a particular escape character.
 Figure 9.16 lists the escape sequences and the actions they
cause.
 Precise input formatting can be accomplished with
scanf.
 Every scanf statement contains a format control
string that describes the format of the data to be input.
 The format control string consists of conversion
specifiers and literal characters.
 Function scanf has the following input formatting
capabilities:
◦ Inputting all types of data.
◦ Inputting specific characters from an input stream.
◦ Skipping specific characters in the input stream.
 Function scanf is written in the following form:
 scanf( format-control-string, other-arguments );
format-control-string describes the formats of the input, and other-arguments are
pointers to variables in which the input will be stored.
 Conversion specifier %i is capable of inputting decimal,
octal and hexadecimal integers.
 When inputting floating-point numbers, any of the
floating-point conversion specifiers e, E, f, g or G can
be used.
 Figure 9.19 reads three floating-point numbers, one
with each of the three types of floating conversion
specifiers, and displays all three numbers with
conversion specifier f.
 The program output confirms the fact that floating-
point values are imprecise—this is highlighted by the
third value printed.
 Characters and strings are input using the conversion specifiers c and s,
respectively. The program inputs the first character of the string with %c
and stores it in the character variable x, then inputs the remainder of the
string with %s and stores it in character array y.
 A sequence of characters can be input using a scan set.
 A scan set is a set of characters enclosed in square brackets,
[], and preceded by a percent sign in the format control
string.
 A scan set scans the characters in the input stream, looking
only for those characters that match characters contained in
the scan set.
 Each time a character is matched, it’s stored in the scan
set’s corresponding argument—a pointer to a character
array.
 The scan set stops inputting characters when a character
that is not contained in the scan set is encountered.
 If the first character in the input stream does not match
a character in the scan set, only the null character is
stored in the array.
 The scan set can also be used to scan for characters not contained
in the scan set by using an inverted scan set. For this, place a caret
(^) in the square brackets before the scan characters.
 When a character contained in the inverted scan set is
encountered, input terminates.
 A field width can be used in a scanf conversion
specifier to read a specific number of characters from
the input stream.
 Often it’s necessary to skip certain characters in the
input stream.
 For example, a date could be entered as
 11-10-1999
 Each number in the date needs to be stored, but the
dashes that separate the numbers can be discarded.
 To eliminate unnecessary characters, include them in
the format control string of scanf (white-space
characters—such as space, newline and tab—skip all
leading white-space).
 For example, to skip the dashes in the input, use the
statement
 scanf( "%d-%d-%d", &month, &day, &year );
 Although, this scanf does eliminate the dashes in the
preceding input, it’s possible that the date could be
entered as
 10/11/1999
 In this case, the preceding scanf would not eliminate
the unnecessary characters.
 For this reason, scanf provides the assignment
suppression character *.
 The assignment suppression character enables scanf to
read any type of data from the input and discard it without
assigning it to a variable.
 Figure 9.24 uses the assignment suppression character in
the %c conversion specifier to indicate that a character
appearing in the input stream should be read and discarded.
 Only the month, day and year are stored.
 The argument lists for each scanf call do not contain
variables for the conversion specifiers that use the
assignment suppression character.
 The corresponding characters are simply discarded.
Input and Output Statements
(Formatted and Unformatted)
Input and output In C language
• C programming language has standard libraries that allow input and output in a
program.
• The studio.h or standard input-output library in C that has methods for input and
output.
• Input output built-in functions in C falls into two categories:
1. Formatted input output (I/O) functions and
2. Unformatted input output (I/O) functions.

• printf() and scanf() are examples for formatted input and output functions and
getch(), getchar(), gets(), puts(), putchar() etc. are examples of unformatted input
output functions.
• Unformatted I/O functions are used only for character data type or character
array/string and cannot be used for any other datatype.
Printf and Scanf function
• The standard input-output header file, named stdio.h contains the
definition of the functions printf() and scanf(),
• which are used to display output on screen and to take input from
user respectively.
• Format can be a simple constant string, but you can specify %s, %d,
%c, %f, etc., to print or read strings, integer, character, or float
respectively.
• There are many other formatting options available that can be used
based on requirements.
getchar ( ) ;

• This function provides for getting exactly one character from the
keyboard until and unless the enter key is pressed. This function is
declared in stdio.h

• Example:

char ch;
ch = getchar ( ) ;
putchar (char) ;

• This function provides for printing exactly one character to the


screen. This function is declared in stdio.h.
• Example:

char ch;
ch = getchar ( ) ; /* input a character from kbd*/
putchar (ch) ; /* display it on the screen */
gets() & puts() Functions
• The gets() function reads a group of characters or strings from the
keyboard by the user and these characters get stored in a character
array. This function allows us to write space-separated texts or strings
• It reads data until either a terminating newline or EOF (end of file)
occurs.
• It is declared in stdio.h header file
• The puts() function writes the string str and a trailing newline to
stdout.
• str → This is the pointer to an array of chars where the C string is
stored. (Ignore if you are not able to understand this now.)
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
Difference between scanf and gets()
• The main difference between these two functions is that scanf() stops
reading characters when it encounters a space,
• but gets() reads space as a character too. If you enter the name as
Sanjay Kumar using scanf() it will only read and store Sanjay and will
leave the part after space.
• But gets() function will read it completely.
getch()
• It reads a single character from the keyboard by the user but doesn’t
display that character on the console screen and immediately
returned without pressing enter key.
• This function is declared in conio.h(header file) and is also used for
hold the screen. int main()
{
printf("Enter any
character: ");

// Reads a character but


// not displays
getch();

return 0;
}

Output::Enter any character:


getche()
• getche() function reads a single character from the keyboard by the
user and displays it on the console screen and immediately returns
without pressing the enter key. This function is declared in conio.h.
putch()
• putch() function is used to display a single character which is given by
the user and that character prints at the current cursor location. This
function is declared in conio.h(header file)
Input/Output in C
getc ( *file ) ;

• This function is similar to getchar( ) except the input can be from the
keyboard or a file.
• Example:
char ch;
ch = getc (stdin) ; /* input from keyboard */
ch = getc (fileptr) ; /* input from a file */
Input/Output in C
putc ( char, *file ) ;

• This function is similar to putchar ( ) except the output can be to the


screen or a file.
• Example:
char ch;
ch = getc (stdin) ; /* input from keyboard */
putc (ch, stdout) ; /* output to the screen */
putc (ch, outfileptr) ; /*output to a file */
Decision Making,
Branching
if, if-else
Control Structures
➢A control structure refers to the order of executing the program
statements.
➢The following three approaches can be chosen depending on the problem
statement:

✓Sequential (Serial)
▪ In a Sequential approach, all the statements are executed in the same
order as it is written.

✓Selectional (Decision Making and Branching)


▪ In a Selectional approach, based on some conditions, different set of
statements are executed.

✓Iterational (Repetition)
▪ In an Iterational approach certain statements are executed repeatedly.

CSE 1001 Department of CSE 2


2/13/2024
Different forms of if statement
1. Simple if statement.

2. if…else statement.

3. Nested if…else statement.

4. else if ladder
5. Jump Statements:
break
continue
goto
return

2/13/2024 CSE 1001 Department of CSE 4


Simple if Statement
General form of the simplest if statement:

if (test Expression)
{ If expression is true
statement-block; (non-zero), executes
} statement.
next_statement; It gives you the choice
of executing
statement or skipping
it.

2/13/2024 CSE 1001 Department of CSE 5


if Statement- explanation
➢ (test Expression) is first evaluated.

➢ If TRUE (non-zero), the ‘if’ statement block is executed.

➢ If FALSE (zero) the next statement following the if statement block is


executed.

➢ So, during the execution, based on some condition, some


code will not be executed (skipped).

For example: bonus = 0;


if (hours > 70){
bonus = 10000;
}
salary= salary + bonus;

2/13/2024 CSE 1001 Department of CSE 6


Flow chart of simple if
Entry

2/13/2024 CSE 1001 Department of CSE 7


Find out whether a number is even or odd.
#include <stdio.h>
int main()
{
int x;
printf(“input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
{
printf(“It is an even number\n”);
}
if ((x%2) == 1)
{
printf(“It is an odd number\n”);
}
return 0;
2/13/2024 CSE 1001 Department of CSE 8

}
Example - if
// Program to calculate the absolute value of an integer

int main ()
{
int number;
printf(“Type in your number: “);
scanf(“%d”,&number);
if ( number < 0 )
number = -number;
printf(“The absolute value is”);
printf(“%d”,number);
return 0;
}

2/13/2024 CSE 1001 Department of CSE 9


The if-else statement

if (test expression )
{
statement _block1 if-else
} statement:
else enables you to
{ choose between
statement _block2 two statements
}
Next_statement

2/13/2024 CSE 1001 Department of CSE 10


if-else statement
Explanation:
1.First ,the (test expression) is evaluated.

2.If it evaluates to non-zero (TRUE), statement_1 is executed,


otherwise, if it evaluates to zero (FALSE), statement_2 is executed.

3.They are mutually exclusive, meaning, either statement_1 is


executed or statement_2, but not both.

4.If the statements_ 1 and statements_ 2 take the form of block ,


they must be put in curly braces.

Example: if(job_code == 1)
rate = 7.00;
else
rate = 10.00;
prinf(“%d”,rate);

2/13/2024 CSE 1001 Department of CSE 11


The if-else statement

yes no
expression

Program statement 1 Program statement 2

Next _statement

2/13/2024 CSE 1001 Department of CSE 12


Find out whether a number is even or odd.
#include <stdio.h>
int main()
{
int x;
printf(“Input an integer\n”);
scanf(“%d”,&x);
if ((x % 2) == 0)
{
printf(“It is an even number\n”);
}
else
{
printf(“It is an odd number\n”);
return 0;
2/13/2024 } CSE 1001 Department of CSE 13
WAP to find largest of 2 numbers

#include<stdio.h>
int main()
{
int a, b;
printf(“Enter 2 numbers\n”);
scanf(“%d %d”,&a,&b);
if(a > b)
a;
printf(“Large is %d“,a);
else
else
cout<<"large is "<<fb;
printf(“Large is %d“,b);
return 0;
}

2/13/2024 CSE 1001 Department of CSE 14


Attention on if-else syntax !
if ( expression )
program
statement 1
In C++, the ; is
else
part (end) of a
program statement !
statement 2
if ( remainder == 0 )
prinf("The number is even.\n“);
else
printf(“The number is odd.\n“);

Syntactically OK (void
statement on if) but a
semantic error !
if ( x == 0 );
printf(“The number is zero.\n“);

2/13/2024 CSE 1001 Department of CSE 15


Example: determine if a year is a leap
year
#include<stdio.h> A leap year is
int main() exactly divisible
{ by 4 except for
int year;
century years
printf(“Enter the year“);
(years ending
scanf(“%d”,&year);
if(year%4 == 0) with 00). The
{ century year is
if( year%100 == 0) a leap year only
{ if it is perfectly
if ( year%400 == 0) divisible by 400.
printf("%d is a leap year",year);
else
printf("%d is not a leap year",year);
} else printf("%d is a leap year",year);
} else printf("%d is not a leap year",year);
return 0;
} 2/13/2024 CSE 1001 Department of CSE 16
Testing for character ranges
Output:
enter a
#include<stdio.h> character:
int main() C
{ uppercase char
char ch; special char
printf(“enter a character\n”);
scanf(“%c”,&ch); enter a
if (ch >= 'a' && ch <= 'z') character:
printf(“lowercase char\n“); j
if (ch >= ‘A' && ch <= ‘Z') lowercase char
special char
printf(“uppercase char\n“);
if (ch >= ‘0' && ch <= ‘9')
enter a
printf(“digit char\n“); character:
else 5
printf(“ special char\n”); digit char
return 0;
}
2/13/2024 CSE 1001 Department of CSE 17
Testing for ranges

? if (x >= 5 && x <= 10)

range“);
printf(“in

? if (5 <= x <= 10)


printf(“in range“);

2/13/2024 CSE 1001 Department of CSE 18


Testing for ranges

YES if (x >= 5 && x <= 10)


printf(“in range“);

NO ! if (5 <= x <= 10)


printf(“in range“);

Syntactically correct, but semantically an error !!!

Because the order of evaluation for the <= operator is left-to-right, the
test expression is interpreted as follows:
(5<= x) <= 10
The subexpression 5 <= x either has the value 1 (for true) or 0 (for
false). Either value is less than 10, so the whole expression is always
true, regardless of x !

2/13/2024 CSE 1001 Department of CSE 19


Decision Making,
Branching
nested if-else, if-else ladder
Nested if-else Statement

2/13/2024 CSE 1001 Department of CSE 2


If-else nesting -Explanation
1. The if-else constructs can be nested (placed one within another)
to any depth.
2. In this nested form, expression_1 is evaluated.
➢ If it is zero (FALSE-F), statement_4 is executed and the entire
nested if statement is terminated;
➢ If not (TRUE-T), control goes to the second if (within the first if)
and expression_2 is evaluated. If it is zero, statement_3 is executed;
➢ If not, control goes to the third if (within the second if) and
expression_3 is evaluated.
➢ If it is zero, statement_2 is executed;
➢ If not, statement_1 is executed. The statement_1 (inner most)
will only be executed if all the if statement is true.

2/13/2024 CSE 1001 Department of CSE 3


Smallest among three numbers
if (a < b)
#include <stdio.h>
{ if (a < c)
int main() { smallest = a; }
{ else
int a, b, c, smallest; { smallest = c; }
}
else
printf(“Enter a, b & c\n“);
{ if (b < c)
scanf(“%d %d %d, &a,&b,&c); { smallest = b; }
else
{ smallest = c; }
}
printf(“Smallest is %d“,smallest);
return 0;
}
2/13/2024 CSE 1001 Department of CSE 4
Nested if statements

if (number > 5)
if (number < 10)
printf(“1111\n“);
else printf(“2222\n“);
Rule: an else
goes with the
if (number > 5) {
most recent if,
if (number < 10)
unless braces
printf(“1111\n“);
indicate
}
otherwise
else printf(“2222\n“);

2/13/2024 CSE 1001 Department of CSE 5


The else-if ladder
if (Expression_1 )
{
statement _block1
}
else if (Expression_2)
{
statement _block2
}
…….
else if (Expression_n)
{
statement _blockn
}
else
{
last_statement
}

Next_statement
2/13/2024 CSE 1001 Department of CSE 6
else if ladder -Explanation
▪ expression_1 is first evaluated. If it is TRUE, statement_1 is
executed and the whole statement terminated and the
next_statement is executed.
▪ On the other hand, if expression_1 is FALSE, control passes to the
else if part and expression_2 is evaluated.
▪ If it is TRUE, statement_2 is executed and the whole system is
terminated.
▪ If it is False, other else if parts (if any) are tested in a similar way.
▪ Finally, if expression_n is True, statement_n is executed; if not,
last_statement is executed.
▪ Note that only one of the statements will be executed others will be
skipped.
▪ The statement_n’s could also be a block of statement and must be
put in curly braces.

2/13/2024 CSE 1001 Department of CSE 7


else-if ladder Flow of control

True False
Condition-1

True False
statement-1 Condition-2

True False

statement-2 Condition-3

True False
statement-3
Condition-n

statement-n

default statement

next statement

2/13/2024 CSE 1001 Department of CSE 8


Testing for character ranges
#include<stdio.h>
int main()
{
char ch;
printf(“enter a character\n”);
scanf(“%c”,&ch);
if (ch >= 'a' && ch <= 'z')
printf(“lowercase char\n“);
else if (ch >= ‘A' && ch <= ‘Z')
printf(“uppercase char\n“);
else if (ch >= ‘0' && ch <= ‘9')
printf(“digit char\n“);
else
printf(“ special char\n”);
return 0;
}
2/13/2024 CSE 1001 Department of CSE 9
WAP using else-if ladder to calculate grade for the
marks entered
int main() {
char cgrade;
int imarks;
printf("enter marks“);
For inputs
scanf(“%d”,&imarks); imarks= 46
if(imarks>79) grade = D
if(imarks>79)
imarks= 64
cgradecgrade
= 'A'; = 'A'; grade = B
else ifelse if (imarks>59)
(imarks>59)
cgradecgrade
= 'B'; = 'B';
else if (imarks>49)
else cgrade
if (imarks>49)
= 'C';
else if (imarks>39) cgrade = 'C';
else cgrade
if (imarks>39)
= 'D';
else cgrade = 'D';
else cgrade = 'F';
cgrade = 'F';
printf(“Grade :%c\n”,cgrade);
2/13/2024 return 0; CSE 1001 Department of CSE 10

}
Example: else-if
// Program to implement the sign function

#include <stdio.h>
int main ( )
{
int number, sign;
printf("Please type in a number: “);
scanf(“%d”,&number);
if ( number < 0 )
sign = -1;
else if ( number == 0 )
sign = 0;
else // Must be positive
sign = 1;
printf(“Sign = %d“,sign);
return 0;
}
2/13/2024 CSE 1001 Department of CSE 11
Example – multiple choices
/* Program to evaluate simple expressions of the form number operator number */
#include <stdio.h>
int main ( )
{
float value1, value2,result;
char operator;
printf("Type in your expression.\n“);
scanf(“%f %c %f”, &value1,&operator,&value2);
if ( operator == '+' )
{result=value1+value2;
printf(“%f”,result);}
else if ( operator == '-' )
{result=value1-value2;
printf(“%f”,result);}
else if ( operator == '*' )
{result=value1*value2;
printf(“%f”,result);}
else if ( operator == '/' )
{result=value1/value2;
printf(“%f”,result);}
else
printf("Unknown operator.\n“);
2/13/2024 return 0; CSE 1001 Department of CSE 12
}
Problem…

2/13/2024 CSE 1001 Department of CSE 13


Find the roots of Quadratic equation using if-else statement

else if (disc==0)
#include<stdio.h> {
#include<math.h> printf(“Real & equal roots“);
int main() re=-b / (2*a);
{
float a,b,c,root1,root2,re,im, disc; printf(“Root1 and root2 are
scanf(“%f %f %f”,&a,&b,&c); %.21f”,re);
disc=b*b-4*a*c; }

if (disc<0) else /*disc > 0 */


{ {
printf("imaginary roots\n“); printf(“Real & distinct roots“);
re= - b / (2*a); printf(“Roots are“);
im = pow(fabs(disc),0.5)/(2*a);
printf(“root1=%.21f+%.21fi and root1=(-b + sqrt(disc))/(2*a);
root2 =%.21f-%.2fi”, re,im,re,im); root2=(-b - sqrt(disc))/(2*a);
} printf(“Root1 = %.21f and root2
=%.21f”,root1,root2);
}
return 0;
}
2/13/2024 CSE 1001 Department of CSE 14
Decision Making,
Branching
Switch and Break
The switch Statement

➢Switch is multiple–branching statement where based on a


condition, the control is transferred to one of the many possible
points.

➢ Enables the program to execute different statements based on


an expression that can have more than two values. Also called
multiple choice statements.

➢The expression provided in the switch should result in a constant


value otherwise it would not be valid.

2/13/2024 2
The switch statement
switch ( expression )
{ The expression is
case value1: successively compared
program statement against the values value1,
program statement value2, ..., valuen. If a case is
... found whose value is equal
break; to the value of expression,
case value2: the program statements that
program statement follow the case are
program statement executed.
...
break;
case value n: The switch test expression must be one
program statement with an integer value (including type
program statement char) (No float !).
...
break; The case values must be integer-type
default: constants or integer constant
program statement expressions (You can't use a variable for
program statement a case label !)
...
}
2/13/2024 3
switch- control flow

2/13/2024 4
switch- example 1
#include<stdio.h>
int main()
{
int choice;
printf(“Enter your choice: 1-yes, 2-no\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“YESSSSSSS……”);
break;
case 2: printf(“NOOOOOO……”);
break;
default: printf(“DEFAULT CASE…….”);
} printf(“The choice is %d”,choice);
return 0;
}
2/13/2024 5
switch- example 2
scanf(“%d”,&mark);

case 50:
switch (mark)
grade=‘C’
{
break;
case 100: case 40:
case 90: grade=‘D’
case 80: grade=‘A’; break;
break;
default: grade=‘F’;
case 70: break;
case 60: }
printf(“%c”,grade);
grade=‘B’;
break;

2/13/2024 6
An Example – switch case
char ch;
scanf)(“%c”,&ch);

switch(ch)
{
case ‘a’ : printf(“Vowel”);
break;
case ‘e’ : printf(“Vowel”);
break;
case ‘i’ : printf(“Vowel”);
break;
case ‘o’ : printf(“Vowel”);
break;
case ‘u’ : printf(“Vowel”);
break;
default: printf(“Not a Vowel”); }

2/13/2024 7
An Example – switch case
char ch;
scanf(“%c”,&ch);

switch(ch)
{
case ‘a’:
case ‘e’:
case ‘i’ :
case ‘o’ :
case ‘u’ : printf(“Vowel”);
break;
default: printf(“Not a Vowel”); }

2/13/2024 8
Example - switch
/* Program to evaluate simple expressions case ‘*':
of the form value operator value */ result=value1*value2;
#include <stdio.h> printf(“%f”,result);
int main (void) break;
{ float value1, value2; case ‘/':
char operator; if ( value2 == 0 )
float result; printf(“Division by
printf("Type in your expression.\n“); zero.\n“);
scanf(“%f %c %f”, else result=value1 / value2;
&value1,&operator,&value2); printf(“%f”,result);
switch (operator) break;
{case '+': default;
result=value1+value2; printf(“Unknown Operator”);
printf(“%f”,result);
}
break;
return 0;
case '-':
result=value1-value2; }
printf(“%f”,result);
break;
2/13/2024 9
What is the output of the following code snippet?

int iNum = 2;
switch(iNum)
{
case 1:
printf(“ONE”);
break;
case 2:
printf(“TWO”);
break;
case 3:
printf(“THREE”);
break;
default:
printf(“INVALID”);
break;
}

2/13/2024 10
What is the output of the following code snippet?

iNum = 2;
switch(iNum)
{
default:
printf(“INVALID”);
case 1:
printf(“ONE”);
case 2:
printf(“TWO”);
break;
case 3:
printf(“THREE”;)
}

2/13/2024 11
What is the output of the following code snippet?

switch (iDepartmentCode)
{
case 110 : printf(“HRD ”);
case 115 : printf(“IVS ”);
case 125 : printf(“E&R ”);
case 135 : printf(“CCD ”);
IVS E&R CCD
}

Assume iDepartmentCode is 115


find the output ?

2/13/2024 12
What is the output of the following code snippet?
int iNum = 2;
switch(iNum)
{
case 1.5:
printf(“ONE AND HALF”);
break;
case 2:
printf(“TWO”);
case ‘A’ :
printf(“A character”);
}

2/13/2024 13
Check Validity:
• switch(1+2+23)
• switch(1*2+3%4)
• switch(a*b+c*d)
• switch(a+b+c)

Important Points:
• Duplicate case values are not allowed
• Nesting of switch statements is allowed

2/13/2024 14
int main()
{
int x = 1;
switch (x)
{
x = x + 1;
case 1: printf("Choice is 1");
break;
case 2: printf("Choice is 2");
break;
default: printf("Choice other than 1 and 2");
break;
}
return 0;
}

Output:: Choice is 1
2/13/2024 15
int main()
{
int x = 1;
switch (x)
{
case 2: printf("Choice is 1");
break;
case 1+1: printf("Choice is 2");
break;
}
return 0;
}

Output::

Compiler Error: duplicate case value

2/13/2024 16
Decision Making,
Branching
Switch and Break
(Cont..)
Problem: Find the roots of Quadratic equation using switch statement
#include<stdio.h>
int main()
{
Int d;
float a,b,c,root1,root2,re,im, disc;
printf(“Enter the values of a, b & c:“);
scanf(“%f %f %f”,&a,&b,&c);
disc=b*b-4*a*c;
printf("\nDiscriminant= %f“,disc);

if(disc<0) d=1;
if(disc==0) d=2;
if(disc>0) d=3;
switch(d)
{
case 1:
printf("imaginary roots\n“);
re= - b / (2*a);
im = pow(fabs(disc),0.5)/(2*a);
printf(“root1=%.21f+%.21fi and root2 =%.21f-%.2fi”, re,im,re,im);
break;

2/13/2024 2
case 2:
printf(“Real & equal roots“);
re=-b / (2*a);
printf(“Root1 and root2 are %.21f”,re);
break;
case 3:
printf(“Real & distinct roots“);
printf(“Roots are“);
root1=(-b + sqrt(disc))/(2*a);
root2=(-b - sqrt(disc))/(2*a);
printf(“Root1 = %.21f and root2 =%.21f”,root1,root2);
break;
} // end of switch
return 0;
} //End of Program

2/13/2024 3
Some guidelines for writing switch case statements

(1) Order the cases alphabetically or numerically – improves


readability.
(2) Put the normal cases first ; put the exceptional cases later.
(3) Order cases by frequency:-put the most frequently executed
cases first and the least frequently used cases later.
(4) Use default case to detect errors and unexpected cases [user
friendly messages].

2/13/2024 4
Flow of control in various control structures

2/13/2024 5
Loop Control Structures
Controlling the program flow
• Forms of controlling the program
flow:
– Executing a sequence of statements
– Using a test to decide between
alternative sequences (branching) Statement1
Statement2
– Repeating a sequence of statements Statement3
(until some condition is met) Statement4
(looping) Statement5
Statement6
Statement7
Statement8

2/13/2024 2
Program Looping
• A set of statements that executes repetitively for a number of
times.
• Simple example: displaying a message 100 times:
printf(hello !\n”);
printf(hello !\n”)
printf(hello !\n”)

Repeat 100 times
printf(hello !\n”)
printf(hello !\n”)
printf(hello !\n”)

Program looping: enables you to develop concise programs containing


repetitive processes that could otherwise require many lines of code !

2/13/2024 3
The need for program looping

Example problem: computing triangular numbers.


(The n-th triangular number is the sum of the integers from 1 through
n)
#include <stdio.h>
int main (void)
{
int triangularNumber;
triangularNumber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;
printf(“The eighth triangular number is
%d“,triangularNumber);
return 0;
}

What if we have to compute the 200-th (1000-th, etc) triangular number ?

We have 3 different statements for looping.


2/13/2024 4
Iterative (loop) control structures
➢ Three kinds of loop control structures:
✓while
✓do while
✓for

2/13/2024 5
Iterative (loop) control structures
➢ Each loop control structure will have
✓ Program loop: body of loop.
✓ control statement → tests certain conditions & then directs repeated
execution of statements within the body of loop.

➢ Two types: Based on position of control statement.

1) Entry controlled loop: control is tested before the start of the loop. If
false, body will not be executed.

2) Exit controlled loop: test is performed at the end of the body. i.e. body
of loop executed at least once.

2/13/2024 6
Entry Controlled & Exit controlled loops
Entry
Entry

Test False
Body of
Condition
The loop

True

Body of
True
The loop Test
Condition

False

2/13/2024 7
Example – 200th triangular number
Statement before triangularNumber = 0
loop

init_expression n=1

no
loop_condition n<=200

yes
triangularNumber =
Statement(s) triangularNumber + n

loop_expression n=n+1

Statement after loop Print triangularNumber

2/13/2024 8
The ‘for’ loop
for ( init_expression; loop_condition; loop_expression )
{ program statement(s)
}

1 init_expression

no
5 2 loop_condition

yes

3 Program statement

4 Loop expression

Next Statement

2/13/2024 9
How for works
• The execution of a for statement proceeds as follows:
1. The initial expression is evaluated first. This expression usually sets a
variable that will be used inside the loop, generally referred to as an index
variable, to some initial value.
2. The looping condition is evaluated. If the condition is not satisfied (the
expression is false – has value 0), the loop is immediately terminated.
Execution continues with the program statement that immediately
follows the loop.
3. The program statement that constitutes the body of the loop is executed.
4. The looping expression is evaluated. This expression is generally used to
change the value of the index variable
5. Return to step 2.

2/13/2024 10
The for statement
sum = 0;

no

1 2 5 4
for ( n = 1; n yes
<= 200; n = n + 1 )
{ sum = sum + n; }

Next Statement
for ( init_expression; loop_condition; loop_expression )
{ program statement(s)
}

2/13/2024 11
Finding sum of natural numbers up to 100

#include <stdio.h>
int main()
{
int n;
int sum;
sum=0; //initialize sum

for(n = 1; n <=100; n=n + 1)


{
sum=sum + n;
}
printf(“%d”,sum);
return 0;
}
2/13/2024 12
Infinite loops
• It’s the task of the programmer to design correctly the algorithms so
that loops end at some moment !
// Program to count 1+2+3+4+5
#include <stdio.h>
int main()
{ What is wrong here ?
int i, n = 5, sum =0; Does the loop end?
for ( i = 1; i <= n; n = n + 1 )
{
sum = sum + i;
printf(“%d”,sum);
}
return 0;
}

2/13/2024 13
Example – for with a body of 2 statements

// Program to generate a table of triangular numbers

#include <stdio.h>
int main()
{
int n, triangularNumber=0;

printf(“TABLE OF TRIANGULAR NUMBERS\n\n“);


printf(“Sum from 1 to n\n“);

for ( n = 1; n <= 10; n++ )


{
triangularNumber += n;
printf(“The %d th triangular number is
%d\n”,n,triangularNumber);
}
return 0;
}

2/13/2024 14
for loop variants
• Multiple expressions (comma between…)
for(i=0 , j=10 ; i<j ; i++ , j--)

• Omitting fields (semicolon have to be still…)


i=0;
for( ; i<10 ; i++ )

• Declaring variables
for(int i=0 ; i=10 ; i++ )

2/13/2024 15
while-loop
General format:

while (test expression) Note: braces optional if


{ only one statement.
body of the loop
}

✓Entry controlled loop statement.


✓Test condition is evaluated & if it is true, then body of the loop is executed.
✓This is repeated until the test condition becomes false, & control transferred out
of the loop.
✓Body of loop is not executed if the condition is false at the very first attempt.
✓While loop can be nested.

2/13/2024 16
The while statement

while ( expression )
program statement Loop with the
test in the
beginning !
statement before loop Body might
never be
executed !

3 1 Loop_expression 4
No
yes
2 statement (s)

Next statement

2/13/2024 17
Finding sum of natural numbers up to 100

#include <stdio.h> #include <stdio.h>


int main() int main()
{
{
int n;
int n; int sum;
int sum; sum=0; //initialize
sum=0; //initialize sum sum
n=1;
while (n < 100)
for(n = 1; n < 100; n=n + 1) {
{ sum= sum + n;
sum=sum + n; n = n + 1;
} }
printf(“%d”,sum);
printf(“%d”,sum);
return 0;
return 0; }
}

2/13/2024 18
Program to reverse the digits of a number
#include <stdio.h>
int main()
{
int number, rev=0, right_digit;

printf(“Enter your number.\n“);


scanf(“%d”,&number);

while ( number != 0 )
{
right_digit = number % 10;
rev=rev*10 + right_digit;
number = number / 10;
}
printf(“The reversed number is %d“, rev);
return 0;
}
2/13/2024 19
The do – while statement
General form:
do
{
body of the loop
}
while(test condition);

✓Exit controlled loop. At the end of the loop, the test condition is evaluated.
✓After do statement, program executes the body of the Loop.
✓Then, the condition is tested, if it is true, body of the loop is executed once again
& this process continues as long as the condition is true.
✓Body of the loop is executed at least once.
✓do-while loop can be nested.

2/13/2024 1
The do statement
do
program
statement
while ( loop_expression );
Loop with the
test at the end !
Body is
executed at least
once !
3 1 Statement(s)

yes
loop_expression
2
No

Next statement 4

2/13/2024 2
Example: Finding sum of natural numbers
up to 100
#include <stdio.h> #include <stdio.h>
int main() int main()
{
{
int n;
int n; int sum =0;
int sum=0;
n=1;
n=1; while (n<=100)
do {
do
{ sum=sum+n;
{sum = sum + n;
n = n +1;
sum
n = n= +1;
sum + counter; }
} counter
while (n= <counter
=100); +1;}} printf(“%d”,sum);
} while (counter < 100); return 0;
printf(“%d”,sum); }
return 0;
2/13/2024 } 3
Program to reverse the digits of a number

#include <stdio.h>
#include <stdio.h> int main()
int main()
{
{
int number, rev=0, right_digit;
int number, rev=0, right_digit;
printf(“Enter your number.\n“);
printf(“Enter your number.\n“);
scanf(“%d”,&number);
scanf(“%d”,&number);
do
while ( number != 0 )
{
{
right_digit = number % 10;
right_digit = number % 10;
rev=rev*10 + right_digit;
rev=rev*10 + right_digit;
number = number / 10;
number = number / 10;
}
}
while ( number != 0 );
printf(“The reversed number is %d“, rev);
printf(“The reversed number is %d“,rev);
return 0;
return 0;
}
}
2/13/2024 4
Which loop to choose ?
• Criteria: category of looping
• Entry-controlled loop -> for, while
• Exit-controlledloop -> do

• Criteria: Number of repetitions:


• Indefinite loops ->while
• Counting loops -> for

• You can actually rewrite any while as a for and vice versa !

2/13/2024 5
Faculty of Engineering (FOE)
Problem-Solving Using Computers Lab
|CS 1031 | 1 Credit | 0 0 2 1
Session: Jan-May 2024

Lab Experiments

Week Topics Session Outcome

1 Algorithms and Flow Charts Describe the flowcharts and design of an algorithm

Use Unix commands to manage files and develop


2 Working with Linux Commands
programs,including multi-module programs

3 Formula-based CPrograms Understand the fundamentals of C programming.

Choose the decision-making statements to solve the


4 Control Structures: if statement
problem.

Choose the decision-making statements to solve the


5 Control Structures: Switch
problem.

6 Control Structures: Loops Choose the loop statements to solve theproblem

7 Control Structures: Nested Loops Choose the loop statements to solve the problem

8 1-D Array Implement different Operations on 1-D arrays.

9 2-D Arrays Implement different Operations on 2-D arrays

10 Strings Implementation of different Operations on strings

11 Functions Use functions to solve the given Problem


Understand and apply the concept of pointers in
12 Pointers
programming

Understand and apply the concept of Structure in


13 Structures
programming
Lab 1. Algorithms and Flowcharts

1. To multiply to numbers.
2. To divide two numbers.
3. To check whether the given number is even or odd.
4. To swap two numbers.
5. To check whether the given number is lesser than 10 or not.
6. To convert Fahrenheit to Celsius.
7. To check the greater number in the given two numbers.
8. To calculate simple interest.
9. To check whether the given number is prime or not.
10. To calculate area of the given rectangle.

Lab 2. Working with Linux Commands

22. clear Clear terminal


23. ps Display the processes in terminal
24. man Access manual for all Linux commands
25. grep Search for a specific string in an output
26. echo Display active processes on the terminal
27. sort sort the file content
28. cal View Calendar in terminal
29. df Check the details of the file system
wc Check the lines, word count, and characters in a
30.
file using different options
Lab 3. Formula based C Programs
1. Write a program to convert the time in seconds to hours, minutes, and seconds. (1 hr
=3600 sec).
2. Write a program to find the sum of the digits of a four-digit number (ex.
1234 sum=10)(without using a loop).
3. Write a program to convert the temperature given in Fahrenheit to
Centigrade andCentigrade to Fahrenheit. Hint: C=5/9(F-32)).
4. Write a program for converting distance in mm to cm, inch, feet
(1 cm =10mm,1inch=2.5cm, 1 feet =12 inches).
5. Write a program to find out the distance between two points e.g. (x1, y1) and (x2, y2).
Hint: Distance=√(x2-x1)2+ (y2-y1)2
6. Write a program to evaluate the area of the circle Area = Pi * R2
7. Write a program to interchange the values of two variables using a third variable.
8. Write a program to interchange the values of two variables without using a third variable.

Lab 4. Control Structures: If statement


1. Write a program to check whether the given number is odd or even.
2. Write a program to check whether a given year is a leap year or not.
3. Write a program to find the roots of a quadratic equation.
a. Hint: root = -b +/- sqrt(b2-4ac)/2a
4. Write a program to find the total no. of days for a given number of
months countingfrom January month.
a. Example: m=3, days=31+ (28 0r 29) + 31.
5. Write a program to take two numbers as an input and find whether
one number is amultiple of the other or not.
6. Write a program that returns a letter grade based on a quiz score. The
input will be theinteger score from a ten-point quiz.
a. The letter grades are assigned by:
b. 9-10“A”7-8“B”5-6“C”3-4“D”<3“F”
7. Write a program that takes three sides of a triangle input and calculates its
area, if theseconditions are satisfied a+b>c, b+c>a, a+c>b, calculate
area=(a+b+c)/2
8. Write a program to check whether the given character is a vowel, consonant, or digit.

Lab 5. Control Structures: Switch


1. Write a program to program to calculate an area of a circle, a rectangle, or a triangle
depending on the user’s choice.
2. Write a program to remove all the break statements from Ex-1 (with switch-case construct)
and try to execute the program with a few inputs. Observe the difference.
3. Write a program to program to input the number of week’s days (1-7) and translate to its
equivalent name of the day of the week (e.g., 1 to Sunday, 2 to Monday)
4. Write a program to design a calculator that performs addition, subtraction, minus, and
division operation. This program inputs two operands and an operator and then displays the
calculated results.
5. Write a program to calculate a bill for internet browsing. The conditions are given below:
Minimum Rs. 200 for up to 100 calls.
Plus, Rs. 0.60 per call for the next 50 calls. Plus, Rs. 0.50 per call for the next 50 calls.
Plus, Rs. 0.40 per call for any call beyond 200 calls
6. Write a program to calculate an amount of a telephone bill for the following criteria. (Without
Loop)
Calls charge per call (Rs.)
1-150 0
151-250 .9
251-400 1.2
401 onwards 1.5

7. Write a program to calculate the amount of an electricity bill for the followingcriteria.
(Without Loop)
Units charge per unit (Rs.)
First, 1-100 up to 0
Next, 101-200 up to 1.5
Next, 201-400 up to 2.5
401 onwards 3.5

8. Write a program to calculate the discount in rupees for the following criterion. (Without Loop)
Cost price discount
>=800 25%
500-800 20%
<500 no discount (0%)

Lab 6. Control Structures: Loops

1. Write a program to take N as input and print the odd numbers in descending order.
2. Write a program to print the Fibonacci number.
Hint: (Fibonacci series is 0, 1, 1, 2, 3, 5, 8,)
3. Write a program to find whether the given number is prime or not.
4. Write a program to convert the decimal number into
binary todecimal. Ex: 1101 = 1*2 3 + 1 * 2 2 + 0 *
2 1+ 1* 2 0 =13
5. Write a program to reverse a given number
Ex: 1234 reverse=4*10 3 +3 * 10 2 + 2 * 10 1 + 1 * 10 0 =4321
6. Write a program to find the sum of n terms of the sin series sin(x) = x - x3 + x5 – x7
7. Write a program to check whether a given integer no. is palindrome or not.
8. Write a program to check whether the given number is Armstrong or not. An
Armstrong number of three digits is an integer such that the sum of the cubes of
its digits is equal to the number itself. For example, 371 is an Armstrong
number since 33 + 73 + 13 = 371.

Lab 7. Control Structures: Nested Loops


1. Write a program to print different patterns using nestedloops.
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5 5

5 5 5 5 5
4 4 4 4
3 3 3
2 2
1

1
2 4
3 5 7
6 8 10 12
9 11 13 15 17

5. Write a program to generate the multiplication table for n numbers up to k terms (nested
loops).
6. Write a program to print the Fibonacci numbers that fall in the given range.
7. Write a program to print the Nth the prime number.
8. Write a program to print the Nth the Armstrong number.

Lab 8. 1-D Array


1. Write a program to find the largest and smallest element in an array.
2. Write a program to find the sum of odd index numbers in an array.
3. Write a program to print the subarray that lies between the two indexes.
4. Write a program to find the number of positive numbers, negative numbers, oddnumbers,
even numbers, and the number of 0 of an array.
5. Write a program to reverse an array with an auxiliary array.
6. Write a program to check whether an array is sorted or not.
7. Write a program to arrange the elements of an array in ascending order by a simple sorting
method. (Selection sort/bubble sort)
8. Write a program to take an array of 10 elements. Split it into the middle and store theelements
in two different arrays. E.g.- Initial array:

58 24 13 15 63 9 8 81 1 78
After splitting:

58 24 13 15 63

9 8 81 1 78

Lab 9. 2-D Arrays


1. Write a program to take 3 student marks in 5 subjects. Print the total marks of eachstudent
and the average marks of each subject.
2. Write a program for searching for an element in the matrix and counting the number of
occurrences of that element.
3. Write a program to multiply two matrices.
4. Write a program to check if the given matrix is a magic square or not.
5. Write a program to find whether a given matrix is symmetric or not.
Hint: A = AT
6. Write a program to find the trace and norm of a given square matrix.
Hint: Trace = sum of principal diagonal elements
Norm = sort (sum of squares of the individual elements of an array)

Lab 10. Strings

1. Write a program to change all lower-case letters into upper case in a sentence.
2. Write a program to find the last occurrence of a particular character.
3. Write a program to concatenate/length/copy two strings using the library function.
4. Write a program to count the number of words in a sentence.
5. Write a program to reverse a string.
6. Write a program to find the string length of a string without using the predefined function.
7. Write a program to find the substring of a given string.
8. Write a program to check if the given string is a palindrome or not.

Lab 11. Functions


1. Write a program to find the factorial of a number using a function. (Ex: 5! =5*4*3*2*1. Use
a function Fact to evaluate factorial & print the result).
2. Write a program to find the maximum of a given set of numbers using functions. (Use a
function Max and return the result to the main function)
3. Write a program to find the GCD of two numbers recursively. (Ex: GCD of 9, 24 is 3)
4. Write a program to check whether the given number is prime or not. Using this function
generates first n prime numbers using the above function.
5. Write a function to generate the nth Fibonacci term using recursion. Print first N Fibonacci
terms using this function. Hint: (Fibonacci series is 0, 1, 1, 2, 3, 5, 8,)
6. Write a program to check if the given string is a palindrome or not, using the stringhandling
function.
7. Write a function Sort for sorting a list of names which will use a function compare to
compare two names. (Selection /bubble Sort may be used).
Lab 12. Pointers
1. Write a program to access two integers using pointers and add them.
2. Write a program to find out the greatest and the smallest among the three numbers usingpointers.
3. Write a program to determine the length of a character string using a pointer.
4. Write a program to compute the sum of all elements stored in an array using a pointer.
5. Write a program to determine whether a substring (string 1) is in the main string or not.If present,
return the pointer of the first occurrence.

Lab 13. Structures

1. Write a program to define a structure personal that would contain the person’s name, date of
joining, and salary. Using this structure write a program to read this information for one person
from the keyboard and print the same on the screen.
2. Write a program to create an array of student structures to store the roll no., name, and marks in
3 subjects. Input the details of N students into the array and display roll no., name, and total
marks of each student in decreasing order of total marks.
3. Write a program to create an array of employee structures to store emp-no, name, basic salary,
and HRA. Input the details of N employees and display emp-no, name, basic, HRA, and net
salary. Display the details of all employees whose net salary is more than the average net salary
of all employees.
4. Write a program to create a structure named Date having day, month, and year as its elements.
Store the current date in the structure. Now add 45 days to the current date and display the final
date.

Lab 14. End-term Exam

You might also like