0% found this document useful (0 votes)
13 views129 pages

R18 PPS Unit I Introduction to Programming

The document outlines the syllabus for a Computer Programming course in C for B.Tech students, detailing course objectives, outcomes, and various units covering programming fundamentals, data structures, algorithms, and file handling. It includes practical lab sessions aimed at developing programming skills through exercises and projects. The syllabus also lists recommended textbooks and reference materials for further study.

Uploaded by

Vinay Vinnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views129 pages

R18 PPS Unit I Introduction to Programming

The document outlines the syllabus for a Computer Programming course in C for B.Tech students, detailing course objectives, outcomes, and various units covering programming fundamentals, data structures, algorithms, and file handling. It includes practical lab sessions aimed at developing programming skills through exercises and projects. The syllabus also lists recommended textbooks and reference materials for further study.

Uploaded by

Vinay Vinnu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

COMPUTER PROGRAMMING

IN C
1B.TECH (ALL BRANCHES) - R18
(As Per Revised Syllabus-JNTUH)

UNIT 1

Name of the Student:

Roll No: Branch: Section:

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

SREYAS INSTITUTE OF ENGINEERING & TECHNOLOGY


B.Tech. I Year Syllabus JNTU HYDERABAD

CS103ES/CS203ES: PROGRAMMING FOR PROBLEM SOLVING

B.Tech. I Year I Sem. L T P C


3 1 0 4
Course Objectives:
• To learn the fundamentals of computers.
• To understand the various steps in program development.
• To learn the syntax and semantics of PPS language.
• To learn the usage of structured programming approach in solving problems.

Course Outcomes: The student will learn


• To write algorithms and to draw flowcharts for solving problems.
• To convert the algorithms/flowcharts to C programs.
• To code and test a given logic in PPS language.
• To decompose a problem into functions and to develop modular reusable code.
• To use arrays, pointers, strings and structures to write C programs.
• Searching and sorting problems.

Unit - 1: Introduction to Programming


Introduction to components of a computer system: disks, primary and secondary memory,
processor, operating system, compilers, creating, compiling and executing a program etc.,
Number systems
Introduction to Algorithms: steps to solve logical and numerical problems. Representation of
Algorithm, Flowchart/Pseudo code with examples, Program design and structured
programming
Introduction to C Programming Language: variables (with data types and space
requirements), Syntax and Logical Errors in compilation, object and executable code ,
Operators, expressions and precedence, Expression evaluation, Storage classes (auto, extern,
static and register), type conversion, The main method and command line arguments
Bitwise operations: Bitwise AND, OR, XOR and NOT operators
Conditional Branching and Loops: Writing and evaluation of conditionals and consequent
branching with if, if-else, switch-case, ternary operator, goto, Iteration with for, while, do-
while loops
I/O: Simple input and output with scanf and printf, formatted I/O, Introduction to stdin,
stdout and stderr.
Command line arguments

Unit - II: Arrays, Strings, Structures and Pointers:


Arrays: one and two dimensional arrays, creating, accessing and manipulating elements of
arrays
Strings: Introduction to strings, handling strings as array of characters, basic string functions
available in C (strlen, strcat, strcpy, strstr etc.), arrays of strings
Structures: Defining structures, initializing structures, unions, Array of structures
6
B.Tech. I Year Syllabus JNTU HYDERABAD

Pointers: Idea of pointers, Defining pointers, Pointers to Arrays and Structures, Use of
Pointers in self-referential structures, usage of self referential structures in linked list (no
implementation)
Enumeration data type

Unit - III: Preprocessor and File handling in C:


Preprocessor: Commonly used Preprocessor commands like include, define, undef, if, ifdef,
ifndef
Files: Text and Binary files, Creating and Reading and writing text and binary files,
Appending data to existing files, Writing and reading structures using binary files, Random
access using fseek, ftell and rewind functions.

Unit - IV: Function and Dynamic Memory Allocation:


Functions: Designing structured programs, Declaring a function, Signature of a function,
Parameters and return type of a function, passing parameters to functions, call by value,
Passing arrays to functions, passing pointers to functions, idea of call by reference, Some C
standard functions and libraries
Recursion: Simple programs, such as Finding Factorial, Fibonacci series etc., Limitations of
Recursive functions
Dynamic memory allocation: Allocating and freeing memory, Allocating memory for arrays
of different data types

Unit - V: Introduction to Algorithms:


Algorithms for finding roots of a quadratic equations, finding minimum and maximum
numbers of a given set, finding if a number is prime number, etc.
Basic searching in an array of elements (linear and binary search techniques),
Basic algorithms to sort array of elements (Bubble, Insertion and Selection sort algorithms),
Basic concept of order of complexity through the example programs

TEXT BOOKS:
1. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill
2. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage
Learning, (3rd Edition)

REFERENCE BOOKS:
1. Brian W. Kernighan and Dennis M. Ritchie, The PPS Language, Prentice
2. Hall of India
3. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
4. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
5. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition

7
B.Tech. I Year Syllabus JNTU HYDERABAD

CS106ES/CS206ES: PROGRAMMING FOR PROBLEM SOLVING LAB

B.Tech. I Year I Sem. L T P C


0 0 3 1.5

[Note:The programs may be executed using any available Open Source/ Freely available IDE
Some of the Tools available are:
CodeLite: https://codelite.org/ Code::Blocks:
http://www.codeblocks.org/ DevCpp :
http://www.bloodshed.net/devcpp.html Eclipse:
http://www.eclipse.org
This list is not exhaustive and is NOT in any order of preference]

Course Objectives: The students will learn the following:


• To work with an IDE to create, edit, compile, run and debug programs
• To analyze the various steps in program development.
• To develop programs to solve basic problems by understanding basic concepts in C
like operators, control statements etc.
• To develop modular, reusable and readable C Programs using the concepts like
functions, arrays etc.
• To Write programs using the Dynamic Memory Allocation concept.
• To create, read from and write to text and binary files

Course Outcomes: The candidate is expected to be able to:


• formulate the algorithms for simple problems
• translate given algorithms to a working and correct program
• correct syntax errors as reported by the compilers
• identify and correct logical errors encountered during execution
• represent and manipulate data with arrays, strings and structures
• use pointers of different types
• create, read and write to and from simple text and binary files
• modularize the code with functions so that they can be reused

Practice sessions:
a. Write a simple program that prints the results of all the operators available in C
(including pre/ post increment , bitwise and/or/not , etc.). Read required operand
values from standard input.
b. Write a simple program that converts one given data type to another using auto
conversion and casting. Take the values form standard input.

Simple numeric problems:


a. Write a program for fiend the max and min from the three numbers.
b. Write the program for the simple, compound interest.
11
B.Tech. I Year Syllabus JNTU HYDERABAD

c. Write program that declares Class awarded for a given percentage of marks, where
mark <40%= Failed, 40% to <60% = Second class, 60% to <70%=First class, >=
70% = Distinction. Read percentage from standard input.
d. Write a program that prints a multiplication table for a given number and the number
of rows in the table. For example, for a number 5 and rows = 3, the output should be:
e. 5 x 1 = 5
f. 5 x 2 = 10
g. 5 x 3 = 15
h. Write a program that shows the binary equivalent of a given positive number between
0 to 255.

Expression Evaluation:
a. A building has 10 floors with a floor height of 3 meters each. A ball is dropped from
the top of the building. Find the time taken by the ball to reach each floor. (Use the
formula s = ut+(1/2)at^2 where u and a are the initial velocity in m/sec (= 0) and
acceleration in m/sec^2 (= 9.8 m/s^2)).
b. Write a C program, which takes two integer operands and one operator from the user,
performs the operation and then prints the result. (Consider the operators +,-,*, /, %
and use Switch Statement)
c. Write a program that finds if a given number is a prime number
d. Write a C program to find the sum of individual digits of a positive integer and test
given number is palindrome.
e. A Fibonacci sequence is defined as follows: the first and second terms in the sequence
are 0 and 1. Subsequent terms are found by adding the preceding two terms in the
sequence. Write a C program to generate the first n terms of the sequence.
f. Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user.
g. Write a C program to find the roots of a Quadratic equation.
h. Write a C program to calculate the following, where x is a fractional value.
i. 1-x/2 +x^2/4-x^3/6
j. Write a C program to read in two numbers, x and n, and then compute the sum of this
geometric progression: 1+x+x^2+x^3+………….+x^n. For example: if n is 3 and x is
5, then the program computes 1+5+25+125.

Arrays and Pointers and Functions:


a. Write a C program to find the minimum, maximum and average in an array of
integers.
b. Write a functions to compute mean, variance, Standard Deviation, sorting of n
elements in single dimension array.
c. Write a C program that uses functions to perform the following:
d. Addition of Two Matrices
e. ii. Multiplication of Two Matrices

12
B.Tech. I Year Syllabus JNTU HYDERABAD

f. iii. Transpose of a matrix with memory dynamically allocated for the new matrix as
row and column counts may not be same.
g. Write C programs that use both recursive and non-recursive functions
h. To find the factorial of a given integer.
i. ii. To find the GCD (greatest common divisor) of two given integers.
j. iii. To find x^n
k. Write a program for reading elements using pointer into array and display the values
using array.
l. Write a program for display values reverse order from array using pointer.
m. Write a program through pointer variable to sum of n elements from array.

Files:
a. Write a C program to display the contents of a file to standard output device.
b. Write a C program which copies one file to another, replacing all lowercase characters
with their uppercase equivalents.
c. Write a C program to count the number of times a character occurs in a text file. The
file name and the character are supplied as command line arguments.
d. Write a C program that does the following:
It should first create a binary file and store 10 integers, where the file name and 10
values are given in the command line. (hint: convert the strings using atoi function)
Now the program asks for an index and a value from the user and the value at that
index should be changed to the new value in the file. (hint: use fseek function)
The program should then read all 10 values and print them back.
e. Write a C program to merge two files into a third file (i.e., the contents of the firs t file
followed by those of the second are put in the third file).

Strings:
a. Write a C program to convert a Roman numeral ranging from I to L to its decimal
equivalent.
b. Write a C program that converts a number ranging from 1 to 50 to Roman equivalent
c. Write a C program that uses functions to perform the following operations:
d. To insert a sub-string in to a given main string from a given position.
e. ii. To delete n Characters from a given position in a given string.
f. Write a C program to determine if the given string is a palindrome or not (Spelled
same in both directions with or without a meaning like madam, civic, noon, abcba,
etc.)
g. Write a C program that displays the position of a character ch in the string S or – 1 if
S doesn‘t contain ch.
h. Write a C program to count the lines, words and characters in a given text.

Miscellaneous:
a. Write a menu driven C program that allows a user to enter n numbers and then choose
between finding the smallest, largest, sum, or average. The menu and all the choices

13
B.Tech. I Year Syllabus JNTU HYDERABAD

are to be functions. Use a switch statement to determine what action to take. Display
an error message if an invalid choice is entered.

b. Write a C program to construct a pyramid of numbers as follows:


1 * 1 1 *
12 ** 23 22 **
123 *** 456 333 ***
4444 **
*

Sorting and Searching:


a. Write a C program that uses non recursive function to search for a Key value in a
given
b. list of integers using linear search method.
c. Write a C program that uses non recursive function to search for a Key value in a
given
d. sorted list of integers using binary search method.
e. Write a C program that implements the Bubble sort method to sort a given list of
f. integers in ascending order.
g. Write a C program that sorts the given array of integers using selection sort in
descending order
h. Write a C program that sorts the given array of integers using insertion sort in
ascending order
i. Write a C program that sorts a given array of names

Suggested Reference Books for solving the problems:


i. Byron Gottfried, Schaum’s Outline of Programming with C, McGraw-Hill
ii. B.A. Forouzan and R.F. Gilberg C Programming and Data Structures, Cengage
Learning, (3rd Edition)
iii. Brian W. Kernighan and Dennis M. Ritchie, The PPS Language, Prentice iv.
Hall of India
v. R.G. Dromey, How to solve it by Computer, Pearson (16th Impression)
vi. Programming in C, Stephen G. Kochan, Fourth Edition, Pearson Education.
vii. Herbert Schildt, C: The Complete Reference, Mc Graw Hill, 4th Edition

14
PPS (R18) UNIT 1 Page | 1

COMPUTER PROGRAMMING IN C UNIT 1


1.1 Introduction to Computers
“A Computer is an electronic device which takes input, process it and gives the
output”.
 The information given to a computer is called “Input”.
 The information or result given by the computer is called “Output”.

Different basic parts of a Computer:


All parts of a computer are divided into the following categories.
1. Input Device
2. Output Device
3. CPU (Central Processing Unit)
4. Primary Storages
5. Auxiliary Storages

1. Input Devices:
These are the devices through which input is given to the computer.
Ex: Keyboard, Mouse, Scanner, Joystick, Light Pen, Touch Screen, etc.

2. Output Device:
These are the devices through which the output is given by the computer.
Ex: Monitor, Printer, Speakers etc.

3. Central Processing Unit(CPU):


CPU is the main part of a computer system which is responsible for all arithmetic
calculations, movement of data, and comparison among the data. It can be called as
the Heart of a computer system.
The CPU consists of CU (Control Unit) and ALU (Arithmetic Logic Unit).
CU stores the instruction set, which specifies the operations to be performed by the
computer. CU transfers the data and instructions to ALU for Arithmetic operations.

4. Primary storage:
The primary storage, also known as main memory, is a place where the programs
and data are stored temporarily during processing. The data in primary storage will
be erased when we turn off a personal computer (In case of RAM).
RAM(Random Access Memory):
It is also called the main memory. It is a place where the programs and data are
stored temporarily during processing. The data in this memory will be removed, when
we switch off the computer.
ROM (Read Only Memory):
ROM stores the data even the computer turned off. It is a permanent memory cannot
be modified, used to store BIOS (Basic Input Output System).
PPS (R18) UNIT 1 Page | 2

5. Auxiliary Storage:
Auxiliary storage, also known as secondary storage, is used for both input and
output. It is the place where the programs and data are stored permanently. When we
turn off the computer, our programs and data remain in the secondary storage, ready
for the next time we need them. It is the place where the programs and data stored
permanently.

All above are collective called as Hardware.

A Computer system consists of two major


components.
1. Hardware
2. Software

1. Hardware:
All physical equipment of a computer system is called Hardware.
2. Software:
Software is a set of programs that allows Hardware to do specific job.
Software is divided into two categories.
1. System software 2. Application Software
PPS (R18) UNIT 1 Page | 3

SYSTEM SOFTWARE:

System software manages the computer resources. It provides the interface between the
hardware and the users but does nothing to directly serve the users‟ needs. System
software consists of programs that manage the hardware resources of a computer and
perform required information processing tasks.
This can be divided into 3 parts.
i. Operating system:
The operating system provides services such as a user interface, file and database
access, and interfaces to communication systems such as internet protocols. The
primary purpose of this software is to keep the system operating in an efficient
manner while allowing the users access to the system. It is a software which interacts
with the hardware directly.

ii. S y s t e m support:
This provides system utilities such as disc format, sort programs etc and operating
services such as performance statistics of a computer and security monitors which
monitors which protect the system and data.

iii. System development software:


It consists of translators which convert high level languages into machine level
languages and debuggers, and computer assisted software engineering (CASE)
systems, which makes programs error free.

APPLICATION SOFTWARE:
It is the software which is used to solve different problems. It can be divided into two
categories.
i. General purpose ii. Application specific

i. General purpose:
The General purpose software is purchased from a software developer and can be
used for more than one application.
Examples are word processors, database management systems, and computer aided
design systems. They labeled General Purpose because they can solve a variety of
users computing problems.

ii. Application specific:


Application- specific software can be used only for its intended purpose.
A general ledger system used by accountants and a material requirements planning
system used by manufacturing organization are examples of application- specific
software.
They can be used only for the task for which they were designed; they cannot be
used for other generalized tasks.
Application software can’t be used for solving for general problems.
PPS (R18) UNIT 1 Page | 4

RELATIONSHIP BETWEEN SYSTEM SOFTWARE AND APPLICATION


SOFTWARE

 Each layer represents the connection point user


interacts with application software to do some work.
 T h e application software interacts with operating
system, which is a part of system software
directly interacts with the hardware.
 The user can directly interact with operating system
whenever needed.

COMPUTER ENVIRONMENTS
In the earlier days there was only one environment. The mainframe computer hidden in the
central computing department with the advent of mini computers and personal
computers, the environment changed.

1. PERSONAL COMPUTING ENVIRONMENT

 In this environment, all of the computer hardware components tied together in our PC.
 In this situation, we have the whole computer for ourselves. We can do whatever we
want. A typical personal computer is shown above.

2. TIME SHARING ENVIRONMENT


PPS (R18) UNIT 1 Page | 5

This type of environment can be found in large companies many users are connected to
one or more computers
 Each user will be given a terminal.
 All the resources like output devices(such as printers)and auxiliary storage devices( such
as discs) are shared.
 The example for time-sharing environment is a college lab in which a minicomputer is
shared by many students.
 The central computer has many duties: It must control the shared resources; it must
manage the shared data and printing; and it must do the computing. All of this work
tends to keep the computer busy. In fact, it is sometimes so busy that the user becomes
frustrated by the computer’s slow responses.

3. CLIENT SERVER ENVIRONMENT

 In this environment the load of central computer will be shared with different PCs
connected to it.
 The users are given PCs or workstations that some of the computational responsibility will
be shared.
 Each PC or workstation connected to central computer is called “client”.
 The central computer, which may be a powerful microcomputer, minicomputer, or central
mainframe system, is known as the server
 A Client/server computing environment splits the computing function between a central
computer and users‟ computers
PPS (R18) UNIT 1 Page | 6

4. DISTRIBUTED COMPUTING:

 A distributed computing environment provides a seamless integration of computing


functions between different servers and clients.
 The Internet provides connectivity to different servers throughout the world.
 For example, eBay uses several computers to provide its auction service. This
environment provides a reliable, scalable, and highly available network

1.3 COMPUTER LANGUAGES


 To write a program for a computer, we must use a computer language. Over the
years computer languages have evolved from machine languages to natural
languages. The computer languages are broadly divided into 3 types.

MACHINE LANGUAGES
 In this language, instructions are written in 1's and 0's as the computers are made of
two state electronic devices that they could understand only pulse that can be in any
one of the states: off or on. The off state is represented by 0; the on state is
represented by 1.
 They are called binary code also called as machine code.
 Computers are identical in design, therefore each computer has its own
machine language.
 Machine languages are usually referred to as "first generation languages/low level
languages".

ASSEMBLY LANGUAGE
 In this language the set of instructions are written in special words like
ADD,SUB,INC,HLT so on. These words are called "MNEMONICS" also called
"OPCODE" OR"PERATION CODE"
 To convert assembly language to machine code, a tool called “Assembler “is used.
 This is also called “symbolic language”, also referred to second generation
programming language, and is also “Low-level language”
PPS (R18) UNIT 1 Page | 7

{ Even today, we prefer to use assembly language for


 Initialize and test the system hardware prior to booting the Operating System.
 This assembly language code will be stored in ROM
 Direct interaction with hardware.
 In extremely high security situations where complete control over the environment.
 Maximize the use of limited resources.
}
HIGH-LEVEL LANGUAGE
Although symbolic languages greatly improved programming efficiency, they still
require programmers to concentrate on the hardware that they were using. And also it was
tedious because machine instruction had to be individually coded. The desire to improve
programmer efficiency and to change the focus from the computer to the problem being
solved led to the development of high- level language.
 In this language instructions are written in normal English.
 High- level languages are portable to many different computers, allowing the
programmer to concentrate on the application problem rather than the details of the
computer.
 High- level languages are designed to relieve the programmer from the details of the
assembly language.
 High- level languages are too to be converted into machine language. The process of
converting them is known as Compilation.
 Some high- level languages are FORTRAN, COBOL, C, C++ etc.
 To convert high level language into machine level language we use a tool called
“compiler”.
High-level languages can be classified into 3 categories
 procedure oriented languages (3rdGeneration Languages)
 problem oriented language (4thGeneration Languages)
Ex: To create various items like Text Boxes, Text labels, Radio buttons, etc.
 Natural language(5th Generation Languages)
Ex: LIP, PROLOG used to develop artificial intelligence and expert systems.

1.4 CREATING AND RUNNING PROGRAMS


It is the job of a programmer to write and run the program. This process involves four
steps.
1. W riting and editing programs
2. Compiling the program
3. Linking the program with required library modules
PPS (R18) UNIT 1 Page | 8

4. Executing the program

1. WRITING & EDITING PROGRAMS:


 The software used to write program known as a "Text Editor".A text editor helps us to
write, modify and store character data.
 Depending on the editor on our system, we could use it to write letters, create
reports, or write programs.
 After we complete the program, we save the file to disk. This file is called "Source
File"(xxxx.c) which is an input to the compiler.
 Our text editor could be a generalized word processor, but it is more often a special
editor included with the compiler.
 Some of the features are search commands to locate and replace statements, copy
and paste commands to copy or move statements from one part of a program to
another etc.
{ The main difference between text processing and program writing is that the programs
are written in lines of code, while most text processing is done with, characters and lines.
Our text editor could be a generalized word processor, but it is more often a special editor
with the compiler.
}
2. COMPILING PROGRAM:
The source code file must be translated into machine language, which is the job of a
compiler.
The c compiler has actually two separate programs.
1. Preprocessor
2. Translator
PPS (R18) UNIT 1 Page | 9

 The preprocessor reads the source code and prepares it for the translator. While
preparing the code, it scans for special instructions known as preprocessor
commands.
 These commands tell the preprocessor to look for special code libraries, make
substitutions in the code, and in other ways prepare the code for translation into
machine language. The result of the preprocessing is called the Translation Unit.
 After the preprocessor has prepared the code for compilation, the translator does the
actual work of converting the program into machine language. The translator reads
the translation unit and writes the resulting object module to a file that can then be
combined with other precompiled units to form the final program.
 An object module is the code in machine language called “Object File”(xxx.obj file)
 Even though the output of the compiler is machine language code, it is not yet ready
to run; that is, it is not yet executable because it does not have the required C and
other functions included.

3. LINKING THE PROGRM:


The object file will be linked to the necessary library filessuch as input/output processes
and mathematical library functions exist elsewhere and must be attached to our program
using a tool called as linker. After linking, the file is called "Executable File". (xxx.exe file)
4. EXECUTING PROGRAMS:
 The executable file, which is in the hard disk, will be loaded in memory for execution
by a tool is called “loader”. It locates the executable program and reads it into
memory. When everything is loaded, the program takes control and it begins
execution.
 In a typical program execution, the program reads data for processing, either from the
user or from a file. After the program processes the data, it prepares the output.
 Data output can be to the user’s monitor or to a file. When the program has finished
its job, it tells the operating system, which then removes the program from memory.
PPS (R18) UNIT 1 Page | 10

1.5 PROGRAM
DEVELOPMENT:
When we are given the assignment to develop a program, we will be given a program
requirements statement and the design of any program interfaces. Also we should receive
an overview of the complete project. Our job is to determine how to take the inputs we are
given and convert them into the outputs that have been specified. This is known as program
design.

Program development is a multistep process which consists o the following steps


1. Understand the problem
2. Develop a solution
3. W rite a program
4. Test the program

1. Understand the problem:


The first step in developing a program is to be carefully understand the given
problem. This can be done by questioning about the problem to the user.

2. Develop a solution:
Once we finally understand the problem, we use three tools in developing a solution.
i. Structured Chart
ii. Algorithm/Pseudo Code
iii. Flow Chart
i. A Structured Chart also known as a “Hierarchy Chart”, is used to design the
whole program, which shows the relationship of various units. (the functional flow

the program).
ii. Algorithm: Step by step procedure to solve a problem is called as Algorithm.
Pseudo code: English- like statements that follow a loosely defined syntax and are
used to convey the design of an algorithm. Pseudo code is part English, part
program logic. Its purpose is to describe, in precise algorithmic detail, what the
program being designed is to do. This requires defining the steps to accomplish
the task in sufficient detail so that they can be converted into a computer program.
Most of the statements in the pseudo code are easy to understand.

iii. Flowchart: Graphical representation of an algorithm is called as flowchart. A


flowchart is a program design tool in which standard graphical symbols are used
to represent the logical flow of data through function.
PPS (R18) UNIT 1 Page | 11

3. Writing a Program:
After developing a solution the program has to be written in any language.

4. Test the Program:


After writing the program, it has to be tested to check if there are any errors or not.
There are basically two kinds of testing techniques.
i. Black Box Testing
ii. White Box Testing.
 Black Box Testing is done to Test Functionality of Program..

 White Box Testing is a method of testing that tests internal structures or


workings of application.
PPS (R18) UNIT 1 Page | 12

1.6.1 ALGORITHM: (Pseudo Code)

An algorithm is a finite set of instructions that if followed accomplishes a particular task.


In addition, algorithms must fallow the below criteria:
1. Input: Zero or more quantities are externally supplied.
2. Output: At least one quantity is produced
3. Definiteness: Each instruction must be clear and unambiguous.
4. Finiteness: For all cases of algorithm is should terminate after a finite no
of steps.
5. Effectiveness: Every instruction must be very basic and easy to fallow

 Algorithms are developed during the design phase of software engineering.


 In the design phase, we first look at the problem, try to write the “pseudo code”
and move towards the programming (implementation) phase.
 The logic of a problem can be represented using an algorithm.
 Algorithm uses English like language.
 Pseudo code is a high level description of the algorithm
 It is less detailed than the program
 It will not reveal the design issues of the program

Algorithms are divided into three


categories
i. Sequence
ii. Selection
iii. Iteration

i. Sequence:
In this category all the instructions are performed one after the other.
Ex: W rite an algorithm for telephone about the conversation between two people.
Step 1: Dial the Number.
Step 2: Phone rings at the called party
Step 3: Caller waits for the response.
Step 4: Phone lifted by the called party. (Connection Activated).
Step 5: Conversation begins.
Step 6: Release the connection. ( Connection Terminated)

ii. Selection:
In the selection, instructions will be executed based on the condition.
 The selection form can be written as
if (condition) then
statement;
if (condition) then
statement1;
else
statement2;
PPS (R18) UNIT 1 Page | 13

Ex: Take the previous example.


Step 1: Dial the Number
if (busy tone) then
goto step1;
Step 2: Phone rings at the called party
Step 3: Caller waits for the response.
Step 4: Phone lifted by the called party. (Connection Activated).
Step 5: Conversation begins.
Step 6: Release the connection. ( Connection Terminated)

iii.Iteration:
In this category some of the instructions will be performed repeatedly for some number of
times. Iteration statements are written using the following format.
Repeat
Statements;
Until
Condition
 The system will be executed continuously if the condition is false
 If the condition becomes true the next step will be executed
Ex: W rite an algorithm for going to a movie with a friend condition is that , friend waits
for every two minutes
step 1:
Repeat
wait for 2 minutes
until
friend comes

step 2:
Goto movie .

{
do while
wait 2 min (friend don‟t come)
while wait for 2 min
Friend don‟t come
}
PPS (R18) UNIT 1 Page | 14

Algorithm1:
Write a algorithm for adding 2
sol:
Algorithm Pseudo code:
step 1:start step 1: start
2:read 2 numbers 2: read 2 numbers a,b
3:add the 2 numbers 3: sum<-a+b (or) sum=a+b;
4:print sum 4: Display sum
5:stop 5: stop

Algorithm 2:
Write an algorithm for finding the average of 3 numbers
sol:
step 1:start
2:read 3 numbers a, b, c
3:average<-(a +b + c)/3.0
4:print average
5:stop

Algorithm 3:
Write an algorithm to find the area of triangle
Sol:
Step 1: start
2:Read 2 numbers b, h
3:Area<-(b*h)/2.0
4: print area
5:stop

Algorithm 4:
Write an algorithm to find the area of circle
Sol:
Step 1: start
2: read radius "r";
3: Area <-(22/7.0)*r*r (or) 3.14 (r*r*)
4: print area;
5: stop
PPS (R18) UNIT 1 Page | 15

Algorithm 5:
Write an algorithm to find the given number is even or odd
Sol:
STEP1: start
2: Read number 'n'
3: if (n==0)then print "Number is neither even nor odd;
4: if (n%2==0) then print "Number is even ";
If (n%2==0) then print "Number is odd ";
5: stop;

STEP1: start
2: Read number 'n'
3: if (n==0)then
print "Number is neither even nor odd;
4: else
if (n%2==0) then
print "Number is even ";
else
print "Number is odd ";
5: stop;

Algorithm 6:
Write an algorithm to find whether a number is +ve or not
Sol:
STEP 1: Start
2: Read a number N
3: if (n=0) print “N is neither even nor odd”
else
if (n>0) then
Print “No. is Positive”
. else
Print “Number is Negative”
5: Stop

Algorithm 7:
Write a number to find the biggest of the two numbers
Sol:
STEP 1: start
2: read two numbers ;
3: if (a=b) then Print “both are same”
else
if (a>b) then
Print “a is bigger than b”
else
PPS (R18) UNIT 1 Page | 16

Print “b is bigger than a”


4:stop.

Algorithm 8:
Write an algorithm to swap given two numbers 10,20.
Sol:
STEP 1: start
2: read a <-10;
b<-20;
3: c<-a;
a<-b;
b<-c;
4: print a,b;
5: stop.

Algorithm 9:
Write an algorithm to swap two numbers without using third name(variable).
Sol:
STEP 1: start
2: read a<-10;
b<-20
3: a<-a+b;
b<-a-b;
a<-a-b;
4: print a,b;
5: stop;
PPS (R18) UNIT 1 Page | 17

{
Points from Infosys Campus Training:
Guidelines to write a Pseudo Code:
Use Good English to write the Pseudo code:
We can include variable names, comments etc wherever necessary, English phrases used should
be comprehensible but not necessary to write full sentences

Unnecessary details can be avoided:


Unnecessary details like comma, semi-colon etc can be avoided, we need to worry about any
specific syntax

Obvious things need not be emphasized:


Type of the variable can be identified from the given context, hence not necessary to explicitly
specify the datatype.

Make use of programming short hands like if, then, else, for etc:
We can use programming short hands like if, then, else, for, while, do etc as well as indicate
parameters for a pseudo code procedure instead of trying to put the same thing using English
language.

Context should be kept in mind:


We should write the pseudo code keeping the context in mind, If something is not clear with respect
to the context, don‟t use the same.

Underlying model should be clear:


It should be possible to understand the algorithm represented using pseudo code and we should be
able to analyze the same, if not the pseudo code is said to be written at a very high level.

It should be easy to understand and translate to a high level language:


Pseudo code should be easily understandable and should be able to translate it easily into a high
level language

Operators can be used:


*, =, +, -, /, %, <, <=, >, >=, [, ], and, or, not
Conventions
Use “Input” for accepting data from the user
Use “Display” for displaying data to user
Use “=” for assignment operation as well as Comparison
= Operator can be used for both assignment and comparison. When used in a conditional statement,
= must be considered for comparison.
}
PPS (R18) UNIT 1 Page | 18

1.6.2 FLOW CHART:


A Flow chart is a diagrammatic representation of the given problem.
The different symbols used for a flow chart given below.

SYMBOL OPERATION DESCRIPTION

Start/Stop Terminator: Shows the starting and ending points of


the program. A terminator has flow lines in only one
direction, either in (a stop node) or out (a start node).

Data Input/ output This represents the Input / Output of a given


Statements problem

Process Processing: Indicates an operation performed by the


computer, such as a variable assignment or
mathematical operation.

Decision Decision: The diamond indicates a decision structure.


A diamond always has two flow lines out. One flow
lineout is labeled the “yes” branch and the other is
labeled the“no” branch.

Predefined process Predefined Process: One statement denotes a group of


previously defined statements. For instance, “Calculate
m!” indicates that the program executes the necessary
commands to compute m factorial.

Document This represents the situation to produce a document


as a result or for comment a particular situation

Connector This symbol used to continue the flow chart

Summing junction This is used for connecting multiple flow lines

Flow lines These symbols represent the flow of the


execution of a given problem
PPS (R18) UNIT 1 Page | 19

The conditional symbol can be used in different forms.

1) Single alternative Decision

 If the condition is true the statements will be executed


and goes to the next instructions.
 If the condition is false the control goes directly to the
next step.

2)Two alternative Decisions

If the condition is true


then stts-1 will be executed and control
goes to the next instruction,else,i.e, the
condition is false then the stts-2 will be
executed and control goes to the next
instruction.

3) Multi alternative decisions

If the condition -1 is true,stts-1 will be


executed and control goes to the next
instruction, if condition-1, is false then
condition-2 will be checked

If the condition-2 is true,stts-2 will be


executed and goes to the next
instruction else, the condition-3 will be
checked and this will goes on..
PPS (R18) UNIT 1 Page | 20

(1) Draw flow charts for the following:-

1. Addition of two numbers 2. Average of three numbers

3. Area of a circle 4. Area of a triangle

Left for the Reader


PPS (R18) UNIT 1 Page | 21

The iteration can be specified in three different forms:-

i). Repeat-Until

Repeat
Statements – 1
Until
Condition;

Statements – 2

ii). W hile form

while (condition)
statement-1
end while

statement-2

In this stt-1 will be repeated if the condition is


true.
if it is false ,the control go to next statement,
statements-2.

iii). do-while Statement


do
Statements – 1;
while (condition)

Statements – 2;

In this statements-1 will be repeated if the condition is


true.
If it is false the flow (control)goes to the next
statements-2.

***
The difference between while and do while is do while statements will be executed at least
once without checking the condition.
PPS (R18) UNIT 1 Page | 22

iv). for loop:

In for loop, a particular variable will be initialized with a value, and then the condition will
be checked, if it is true, the body of the
statements will be executed.
After that, the initialized value will be updated,
and again control checks the condition, if it is
true, the process continues, else the control
comes out of the loop.

PRACTICE:

1) Draw a flowchart for finding the sum of „n‟ numbers starting from 1?
2) Write an algorithm to read five integers and find out if the values are in ascending order.
3) Draw a flow chart for displaying the grade of the marks of average of 4 subjects of a student.
Average Grade
>=75 A
>=60 &&<75 B
>=50 &&<60 C
<50 D
** Ensure that the user entered all of his marks in between 0 & 100 only.

4) Draw a flow chart to read ten integer values and print the sum of squares of the values.
5) Calculate the Expenditure per month of a sales person. Your algorithm should print either „dues‟
or „no dues. If the expenditure is below 5000/- then the balance(5000-exp) is his due. If the
expenditure is above Rs. 5000/- then no Due.
Hint: subtract exp from 5000 if bal is <5000 the print the due else print no dues
PPS (R18) UNIT 1 Page | 23

EX1.System Development Life


Cycle:

In this example flow chart, I have checked the


condition regarding the design errors only,
students can check the errors from coding
phase to requirements phase also, in which we
have discussed in previous section.

EX2.Find the result of the following


program

An
s:
Factorial of a Number N
PPS (R18) UNIT 1 Page | 24

1.7 Number systems


A set of values used to represent different quantities is known as “Number System".
For example, a number system can be used to represent the number of students in a class or number
of viewers watching a certain TV program etc. The digital computer represents all kinds of data and
information in binary numbers. It includes audio, graphics, video, text and numbers. The total
number of digits used in a number system is called its base or radix. The base is written after the
number as subscript such as (512)10.
Some important number systems are as follows.

 Binary number system


 Decimal number system
 Octal number system (not in syllabus)
 Hexadecimal number system
1.7.1 Binary number system
In mathematics and digital electronics, a binary number is a number expressed in the binary
numeral system or base-2 numeral system which represents numeric values using two different
symbols: typically 0 (zero) and 1 (one). The base-2system is a positional notation with a radix of 2.

 First position in a binary number represents a 0 power of the base (2). Example 20

 Last position in a binary number represents a x power of the base (2). Example 2x where x
represents the last position.

1. Example :Binary Number : 101012


Calculating Decimal Equivalent:

Step Binary Decimal Number


Number

Step 1 101012 ((1 x 24) + (0 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Step 2 101012 (16 + 0 + 4 + 0 + 1)10

Step 3 101012 2110

Note : 101012 is normally written as 10101.

1.7.2 Decimal number system


Decimal number system has only ten (10) digits from 0 to 9. Every number (value) represents
with 0,1,2,3,4,5,6, 7,8 and 9 in this number system. The base of decimal number system is 10,
because it has only 10 digits.
Example : (452)10 = (4 * 100) + (5*10) + (2*1)
PPS (R18) UNIT 1 Page | 25

1.7.3 Hexadecimal number system


In mathematics and computing, hexadecimal (also base 16, or hex) is a positional numeral
system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to
represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values
ten to fifteen. Hexadecimal numerals are widely used by computer system designers and
programmers
For Example : (2AF3)16 can be converted to decimal number as

1.7.4 Conversions
a) Decimal to Binary Conversion
As the decimal number is a weighted number, converting from decimal to binary (base 10 to base 2)
will also produce a weighted binary number with the right-hand most bit being the Least Significant
Bit or LSB, and the left-hand most bit being the Most Significant Bit or MSB, and we can represent
this as:

Representation of a Binary Number

MSB Binary Digit LSB

28 27 26 25 24 23 22 21 20

256 128 64 32 16 8 4 2 1

We saw above that in the decimal number system, the weight of each digit to the left increases by a
factor of 10. In the binary number system, the weight of each digit increases by a factor of 2 as
shown. Then the first digit has a weight of 1 ( 20 ), the second digit has a weight of 2 ( 21 ), the third
a weight of 4 ( 22 ), the fourth a weight of 8 ( 23 ) and so on.
PPS (R18) UNIT 1 Page | 26

So for example, converting a Binary to Decimal number would be:

Decimal Digit Value 256 128 64 32 16 8 4 2 1

Binary Digit Value 1 0 1 1 0 0 1 0 1

By adding together ALL the decimal number values from right to left at the positions that are
represented by a “1” gives us: (256) + (64) + (32) + (4) + (1) = 35710 or three hundred and fifty
seven as a decimal number.

b) Decimal to Hexadecimal Conversion :


Steps:
1. Divide the decimal number by 16. Treat the division as an integer division.
2. Write down the remainder (in hexadecimal).
3. Divide the result again by 16. Treat the division as an integer division.
4. Repeat step 2 and 3 until result is 0.
5. The hex value is the digit sequence of the remainders from the last to first.

Example 1

Convert the number 256 DECIMAL to HEXADECIMAL

DIVISION RESULT REMAINDER (in HEX)


256 / 16 16 0
16 / 16 1 0
1 / 16 0 1

ANSWER 100

Example 2

Convert the number 921 DECIMAL to HEXADECIMAL

DIVISION RESULT REMAINDER (in HEX)


921 / 16 57 9
57 / 16 3 9
3 / 16 0 3

ANSWER 399
PPS (R18) UNIT 1 Page | 27

Example 3

Convert the number 188 DECIMAL to HEXADECIMAL

REMAINDER
DIVISION RESULT
(in HEX)
188 / 16 11 C (12 decimal)
11 / 16 0 B (11 decimal)

ANSWER BC

Note that here the answer would not be 1112, but BC. Remember to write down the remainder in
hex, not decimal.

Example 4

Convert the number 100 DECIMAL to HEXADECIMAL

REMAINDER
DIVISION RESULT
(HEX)
100 / 16 6 4
6 / 16 0 6

ANSWER 64

Example 5

Convert the number 590 DECIMAL to HEXADECIMAL

REMAINDER
DIVISION RESULT
(HEX)
590 / 16 36 E (14 decimal)
36 / 16 2 4 (4 decimal)
2 / 16 0 2 (2 decimal)

ANSWER 24E
PPS (R18) UNIT 1 Page | 28

C) Binary to Hexadecimal Conversion:


Convert each 4 binary digits to hex digit according to this table:

Binary Hex

0000 0

0001 1

0010 2

0011 3

0100 4

0101 5

0110 6

0111 7

1000 8

1001 9

1010 A

1011 B

1100 C

1101 D

1110 E

1111 F

Example #1
Convert (01001110)2 to hex:

(0100)2 = (4)16
(1110)2 = (E)16
So
(01001110)2 = (4E)16

Example #2
Convert (0100101000000001)2 to hex:

(0100)2 = (4)16
(1010)2 = (A)16
(0000)2 = (0)16
(0001)2 = (1)16
So (0100101000000001)2 = (4A01)16
PPS (R18) UNIT 1 Page | 28

1.8 Storing Integers and Real numbers

Integer Numbers: In Computer Systems integers are stored at bit level in 8-bit,16-bit or 32 bit
register. A single bit (MSB – Most Significant Bit) is reserved for sign of the number - 0 for positive
integers and 1 for Negative integers.
Format to Store Integer Numbers (8 Bit Register )
MSB
SIGN MAGNITUDE
(1 Bit) (7 Bits)

Example: +(97)10 = (1100001)2


0 1 1 0 0 0 0 1

Real Numbers: In Computer Systems integers are stored in the following format

SIGN EXPONENT MANTISSA


(1 Bit) (3 Bits) (4 Bits)

The rules for converting a decimal number into floating point are as follows:

A. Convert the absolute value of the number to binary, perhaps with a fractional part after the
binary point. This can be done by converting the integral and fractional parts separately. The
integral part is converted with the techniques like divide by 2 etc.. The fractional part can be
converted by multiplication. This is basically the inverse of the division method: we
repeatedly multiply by 2, and harvest each one bit as it appears left of the decimal.
B. Append × 20 to the end of the binary number (which does not change its value).
C. Normalize the number. Move the binary point so that it is one bit from the left. Adjust the
exponent of two so that the value does not change.
D. Place the mantissa into the mantissa field of the number. Omit the leading one, and fill with
zeros on the right.
E. Add the bias to the exponent of two, and place it in the exponent field. The bias is 2k−1 − 1,
where k is the number of bits in the exponent field. For the eight-bit format, k = 3, so the bias
is 23−1 − 1 = 3.
F. Set the sign bit, 1 for negative, 0 for positive, according to the sign of the original number.
PPS (R18) UNIT 1 Page | 29

Example
Store 2.625 to a 8-bit floating point format.

A. The integral part is easy, (2)10 = (10)2. For the fractional part:

0.625 × 2 = 1.25 1 Generate 1 and continue with the rest.


0.25 × 2 = 0.5 0 Generate 0 and continue.
0.5 × 2 = 1.0 1 Generate 1 and nothing remains.
B. So 0.62510 = 0.1012, and 2.62510 = 10.1012.
C. Add an exponent part: 10.1012 = 10.1012 × 20.
D. Normalize: 10.1012 × 20 = 1.01012 × 21.
E. Mantissa: 0101
F. Exponent: 1 + 3 = 4 = 1002.
G. Sign bit is 0.

The result is

0 1 0 0 0 1 0 1

Represented as hex, that is 4516.


PPS (R18) UNIT 1 Page | 30

INTRODUCTION TO C PROGRAMMING
History of C Language
1958 ALGOL Too Abstract
ALGOL60 Too General
ALGOLW Also Too Abstract, & General
COBOL Commercial Purpose
PASCAL
FORTRAN Engineering & scientific Applications
1963 CPL Hard to learn& Difficult to implement.
1967 BCPL Martin Richards
Too specific Deals with specific Applications
1970 B AT & T Bell Labs
Also Too specific, only for specific requirements.
1972 C Dennis Ritchie
AT &T Bell

BCPL Basic combined programming language.


ANSI American National Standard Institute.
ISO International Organization for standardization.
ALGOL Algorithmic language

 In the strictest sense, C99 is the current standard.


 C should refer as "c99 standard".
 C99 has not caught as quickly as one might have hoped. So c89/c99 is still widely
supported, than c99.
 ANSI C Originally referred to c89 standard.
 ISO adopted c89 (with cosmetic changes) as c90 and accepted by ANSI.
 C89 Older ANSI C
 C90 Older ISO (very small difference between two)
 C94 With some technical clarifications.
 C99 Current ISOC, Current ANSI C {ANSI/ISO C}.
PPS (R18) UNIT 1 Page | 31

History of Programming Languages


Practical Applications

Right from UNIX, Windows and many Ant viruses etc developed using C.
Embedded devices, chip designing Industrial Automations products, signal
transmission.
Major Advantages
 A combination of high-level Machine level program capabilities.

Introduction to C
 C is a program language developed by "Dennis Ritchie" in 1972 at
AT&T Bell laboratories.
 C is a high-level language.
 It is also called Middle level language because it supports both
features of low-level and high-level languages.
 C is a structured program language in which a program is written as
a set modules (or) blocks (or) functions.
PPS (R18) UNIT 1 Page | 32

STUCTURE OF A C PROGRAMME

 Preprocessor directives are the command


which tells the compiler about the
predefined used in a program.
 “include” is one of the preprocessor
command which includes the header files (or)
library files into a program.
 In Global declaration section all the
variables which are to be used in the entire
program are declared.

 The main contains two sections


1. Local Declaration
2. Body of the Statement
In the local declaration section the variables that are to be used only in the main, will
be declared.
The program instructions should be written only after the local declaration
Program instructions will be called as statements which will be terminated with “;” .
Any other user defined functions can be written after main.

printf():
“printf()” is a predefined output function which is used to print the given text or the values on
the console(screen).
Syntax: printf (“Message to Print”);
printf (“Message or Format specifiers”, variable names);
scanf():
scanf() is a predefined input function which is used to take input from the keyboard.

BASIC SIMPLE PROGRAMS (SEQUENTIAL)

/*1.PROGRAM TO PRINT A MESSAGE */


#include<stdio.h>
int main()
{
printf("\nWELCOME TO SREYAS ");
return 0;
}
O/P: WELCOME TO SREYAS
=================================================================
PPS (R18) UNIT 1 Page | 33

/*2.PROGRAM TO FIND THE AREA OF A TRIANGLE */


#include<stdio.h>
int main()
{
float b,h,area;
printf("\n\nEnter the base of triangle: ");
scanf("%f",&b);
printf("\n\nEnter the height of triangle: ");
scanf("%f",&h);
area=(b*h)/2;
printf("\n\nThe area of Triange = %f", area);
return 0;
}
Enter the base of triangle: 2.5
Enter the height of triangle: 3.6
The area of Triange = 4.500000
=================================================================
/*3.PROGRAM TO FIND THE AREA OF A CIRCLE */
#include<stdio.h>
int main()
{
float r,area;
printf("\n\nEnter Radius of Circle: ");
scanf("%f",&r);
area=(22/7.0)*r*r;
printf("\n\nThe area of Circle = %f", area);
}
Enter Radius of Circle: 10
The area of Circle = 314.285706
=================================================================
/*4.PROGRAM TO FIND THE AVERAGE OF 3 NUMBERS*/
#include<stdio.h>
int main()
{
int a,b,c,sum;
float avg;
printf("\n Enter 3 integers: ");
scanf("%d%d%d",&a,&b,&c);
sum=a+b+c;
avg=sum/3.0;
printf("\nSUM = %d \t AVERAGE = %f",sum,avg);
return 0;
}
Enter 3 integers: 5 6 7
SUM = 18 AVERAGE = 6.000000
PPS (R18) UNIT 1 Page | 34

/*5.PROGRAM TO FIND THE SIMPLE INTEREST*/


#include<stdio.h>
int main()
{
float p,n,r,si;
char ch;
printf("\nEnter the Principle amount: ");
scanf("%f",&p);
printf("\nEnter the No. of years for interest: ");
scanf("%f",&n);
printf("\nEnter the Rate of Interest: ");
scanf("%f",&r);
si=(p*n*r)/100.0;
printf("\n\nSIMPLE INTEREST = %f",si);
}
Enter the Principle amount: 1000
Enter the No. of years for interest: 5
Enter the Rate of Interest: 12
SIMPLE INTEREST = 600.000000
=================================================================
/*6.PROGRAM TO SWAP THE 2 NO.S USING 3 VARIABLES */
#include<stdio.h>
int main()
{
int a,b,c;
printf("\n\nEnter 2 integers: ");
scanf("%d%d",&a,&b);
c=a;
a=b;
b=c;
printf("\n\nAfter swap a=%d \t b=%d ",a,b);
return 0;
}
O/P: Enter 2 integers: 10 25
After swap a=25 b=10
=================================================================
/*7.PROGRAM TO SWAP THE 2 NO.S USING 2 VARIABLES */
#include<stdio.h>
int main()
{
int a,b;
printf("\n\nEnter 2 integers: ");
scanf("%d%d",&a,&b);
a=a+b; b=a-b; a=a-b;
printf("\n\nAfter swap a=%d \t b=%d ",a,b);
return 0;
}
PPS (R18) UNIT 1 Page | 35

Enter 2 integers: 10 25
After swap a=25 b=10
8. Write a Program to convert the Celsius temperature into Fahrenheit Temperature.
9. Write a Program to convert the Fahrenheit temperature into Celsius Temperature.
 Left to the aspirants

C CHARACTER SET
The characters that can be used to form words numbers and expressions depend upon the
computer on which the program runs.
A set of characters is available that can be used for c.
The characters in c are grouped into following categories.
Alphabets A, B, C, D, E, F,...Y,Z
a, b, c, d, e, f,.....y, z
Digits 0, 1, 2, 3, 4,....9
special characters ~ ! @ # % ^ & * ( ) _ - + = $ 1 \ { } [ ] : ; '' <> , . ? /
White spaces Blanks space
Horizontal tab, carriage return, New line, form feed (\ f), Page Break
C tokens:
In a c program, the smallest individual units are called c tokens. C has six types of
tokens. Every c program must be written using these tokens and some syntax of c.

keywords
identifiers
constants
strings
special symbols
operators
(every c words must be either a keywords or an identifier)

Keywords:
key words are pre defined names which have fixed meaning in c language. Key words must
be written only in lower case letters. There are 32 key words available in c language.c99
adds some more key words.

ANSI C key words:


auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto size of volatile
do if static while
PPS (R18) UNIT 1 Page | 36

Identifiers:
Identifiers are the names given to the variable, functions, arrays. These are user
defined names and consist of sequence of letters and digits with a letter as a first character.
Both upper case and Lower case letters permitted.
The underscore character is also permitted.

Rules for identifiers:


 First character must be an alphabet or an underscore.
 Must contain letters, digits and ''_''only.
 Only first 31 characters are significant.
 A max 31 characters should be used.
 Some compilers allow 63 characters also key words should not be used as identifiers.
White space is not allowed.
Ex: sum sum-1, int, x, a ->valid
int, 1var, sum.123, sum123 -> invalid

Constants:
Constants in C are fixed values that do not change during the execution of a c program.

INTEGER CONSTANTS
An integer constant refers to a sequence of digits. There are three types of integer
constants.
 Decimal integers
 Octal integers
 Hexadecimal integers
Decimal integers:
It consists of digits 0 to 9 preceded by an optional –ve or +ve sign.
Ex: 123, -423, 789, +65433.
Embedded spaces, commas, non-digit characters are permitted between digits.
Ex: 15, 750, 20,000/-, $ 1000 are not valid.

Octal integers:
It consists of any combination of digits from 0 through with a leading 0 (zero)
Ex: octal integers are 037, 0, 0435
Hexadecimal integers:
[Ty pe text ] [Ty pe text ] [Ty pe text ]

PPS (R18) UNIT 1 Page | 37

It consists of digits from 0 to 9 and alphabet from A to Z, where, A=10, B=11, C=12, D=13,
E=14, F=15. They are preceded by OX or 0X
Ex: 0X2, 0X9D, 0XBC, 0X.

The largest integer values that can be stored is machine dependent.


For 16 bit machines, it is 32767. For 32 bit machines, it is 2,147,483,647.
Qualifiers can be used to store larger integers.

REAL CONSTANTS
 Real numbers consists of digits from 0 to 9 with a decimal point.
Ex: 1.24, +.24, 7.0 valid.
 A real number may also be expressed in scientific (or) exponential notation.
This is of the form “mantissa e exponent“
 Mantissa can be integer (or) a real number.
 Exponent should be an integer with an optional sign + ve or – ve.
 Ex: 0.65e4, 12e-2, 1.5e+5, 3.76 E3, -1.2E-1
 Space is not allowed in the syntax.

SINGLE CHAR CONSTANTS


A single char constant is a single char enclosed with in a pair of single quotes.
Ex: „A‟ , „ X ‟ , „ 5 ‟, „ % ‟ , „ ; ‟ , „ „.
„5‟ is not as same as 5, but „5‟ is a char constants have integer valuesknown as ASCll
values.
ASCll: American Standard Code for Information Interchange.
Ex: print f ( “ %d ”, „a‟ ) ;
o/p: 97
print f ( “ %d ” , „5‟ ) ;
o/p: 53
print f ( “ %c ” , „97‟ ) ;
o/p: a

STRING CONSTANTS
A string is a sequence of chars placed inside the double quotes.
Ex: “ program “ , “ a ” , “ 123 ”, “ 877 ”, “ Hello! “.
„X‟ != “X
a char constant ( „X‟ ) is not equivalent to the single cha string constant ( “X” ).
A single char string constant does not have an equivalent integer value, while a
char constant has an integer value.
PPS (R13) UNIT 1 P a g e | 33

/*PROGRAM TO ILLUSTRATE ABOUT ASCII CODES*/


#include<stdio.h>
int main()
{
printf("\n\nASCII VALUS ");
printf("\n\nA->%d\tB->%d...Y->%d\tZ->%d",'A','B','Y','Z');
printf("\n\na->%d\tb->%d...y->%d\tz->%d",'a','b','y','z');
printf("\n\n0->%d\t1->%d...8->%d\t9->%d",'0','1','8','9');
printf("\n\n!->%d\t@->%d...*->%d\t#->%d",'!','@','*','#');
printf("\n\n\n");
printf("\n\n65->%c\t66->%c...89->%c\t90->%c",65,66,89,90);
}
ASCII VALUS
A->65 B->66...Y->89 Z->90
a->97 b->98...y->121 z->122
0->48 1->49...8->56 9->57
!->33 @->64...*->42 #->35
65->A 66->B...89->Y 90->Z
=================================================================
/*PROGRAM TO ILLUSTRATE THE DECIMAL OCTAL HEXA DECIMAL INTS*/
#include<stdio.h>
int main()
{
int i,n,r;
printf("\nEnter Decimal int: ");
scanf("%d",&n);
printf("\nfor Decimal %d\n\nOCTAL NO.=%o \nHEXA DECIMAL=%X ",n,n,n);
}
Enter Decimal int: 99
for Decimal 99
OCTAL NO.=143
HEXA DECIMAL=63
=================================================================

Check %d %d %d “,99,099, x99


PPS (R13) UNIT 1 P a g e | 34

BACKSLASH CONSTANTS
The backslash constants are predefined which are to be used in o/p functions.
\n new line
\t horizontal line
\v vertical line
\a audible alert ( bell )
\r carriage return
\b back space
\f form feed
\‟ Single quote
\” double quote
\? Question mark
\\ back slash
\O null

VARIABLE
A variable is a data name which is used to store a value.
SYNTAX:
datatype variable1, variable2…;

ANS1 standard recognizes a length of 31 characters. However, length should not be


normally 8 characters, since only first eight characters are treated as significant by many
compilers.
Ex: Average, value, T-value, int-type, IN

DATA TYPES
C language is rich in data types. Storage representations and machine instructions to
handle constants differ from machine to machine.
Data types represent the type of data stored in the variables.
ANSIC supports three classes of data types.
1. Primary (fundamental) data types.
2. Derived data type.
3. User-defined data type.

PRIMARY DATA TYPES

int
signed unsigned
int unsigned int
short int unsigned short int
long int unsigned long int
PPS (R13) UNIT 1 P a g e | 35

Character Data Type:


character
signed character
unsigned character

Floating Point Type


float
double
long Double

void
void is a key word in C used to not to return any thing by a function.

INTEGER TYPES
These are the numbers without a decimal point.

Data types Size Range


int(or signed int) 2 bytes -32768 to 32767
unsigned int(or unsigned) 2 bytes 0 to 65535
short int
1 bytes -128 to 127
(signed short int or short)
unsigned short int 1 byte 0 to 255
-2,147,483,648 to
long int 4 bytes
2,147,483,647
unsigned long int 4 bytes 0 to 4,294,967,295

Floating Point Data Types


Floating point (Real) numbers are stored in 32 bits (on all 16 bit & 32 bit machines) with 6
digits of precision by default.
When accuracy of the float number is not sufficient, then the type double can be used.

Type Storage size Value range Precision


float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

 Float data type stores 6 digits precision.


 Double data type stores 14 digits precision.
 The number of digits stored after the decimal point is called „Precision‟
PPS (R13) UNIT 1 P a g e | 36

Character Data Types:


A single character can be defined as a character data type. Characters usually stored in one
byte. The qualifier signed or unsigned may be explicitly applied to character.

Data type Size Range


char 1 byte -128 to 127
unsigned char 1 byte 0 to 255

Assigning values to the variables:


Syn: datatype identifier=value;
Example:
int a=10;
The process of giving initial values to the variable is called "INITIALIZATION".

USER DEFINED DATA TYPES


We can write our own data types using the following key words.
Typedef and enum

typedef:(typedefinition)
This keyword is used to give another narrate to the existing data type.
SYN: typedef datatype identifier;
 Datatype represents the existing datatype.
 Identifier refers to the 'NEW ' name given to the existing datatype.
Example1:
typedef int marks;
here marks symbolizes int. This can later used to declare variable as.
marks m1,m2,m3;
Example2
typedef float units;
units u1,u2,u3;

enum:
This keyword is used to create our own datatypes.
Syntax to define a datatype.
enum identifier {value1,value2,value3,----------------};

Syntax to declare variables of enum datatype


enum identifier variable1,variable2,-------------------;
 The values given in curl bracets are called as enumeration constants.
 The variables should be assigned only one of the values given in curly
braces.
Example
enum mar_stat {single,married,divorced,widowed};
enum mar_stat person1,person2;
PPS (R13) UNIT 1 P a g e | 37

The 1st part declares the datatype and specifies its possible values.
These values are also called "Enumerators".
The second part declares variables of this.
Now we can give values to these variables.
person1= married;
person2= divorced;
Note :- we can't use the values that aren't in the original declaration.
EXAMPLE:-
person1= Bachelor;--> error.
 Internally the compiler treats the enumerators as integers from by zero by default.

We can assign our own no’s to enumerators.


We can also use those no’s in the program.
Example:
enum week{sun=2,mon,tue};
In the example Mon will be 3, tue will be 4.
Example:
enum mar_stat
{single=100,married=200,divorced=300,widowed=400};
enum mar_stat person1,person2;

We can define and declare the enumerated datatype in a single lineusing the following
Syntax
enum identifier
{value1,value2,---------}variable1,variable2,----------;
enum week
{sun,mon,tue}day1,day2;
=================================================================
/*PROGRAM TO ILLUSTRATE ABOUT THE TYPEDEF */
#include<stdio.h>
#include<conio.h>
main()
{
typedef int Marks;
Marks m1,m2,m3,total;
float percent;
printf("\n\n\tEnter the Marks for the following subjects:");
printf("\n\tCPDS:");
scanf("%d",&m1);
printf("\n\tM1:");
scanf("%d",&m2);
printf("\n\tMM:");
scanf("%d",&m3);
total=m1+m2+m3;
percent= (total/300.0)*100;
PPS (R18) UNIT 1 Page | 43

printf("\n\nThe Total Marks are: %d/300\n",total);


printf("\n\nThe Percentage is: %6.2f %",percent);
return 0;
return 0;
}
Enter the Marks for the following subjects:
CPDS:99
M1:100
MM:100
The Total Marks are: 299/300
The Percentage is: 99.67 %
=================================================================
/*PROGRAM TO ILLUSTRATE THE USERE DEFINED DATATYPE ENUM*/
#include<stdio.h>
int main()
{
enum mar_st { married,single, divorced=77,widowed};
enum mar_st kalam,sonia;
kalam=single;
sonia=widowed;
printf("\n\nI am kalam,I am %d \n\nI am sonia,I am %d", kalam,sonia);
return 0;
}
O/P:
I am kalam,I am 1
I am sonia,I am 78
=================================================================
/*PROGRAM TO ILLUSTRATE ABOUT ENUM*/
main()
{
enum week{sun,tue=5,wed,thu=99,sat}r,a=wed,v,i=sat;
r=9;
v=sun;
printf("\n\n\t i am r=%d\ta=%d\tv=%d\ti=%d",r,a,v,i);
}
i am r=9 a=6 v=0 i=100
=================================================================
PPS (R18) UNIT 1 Page | 44

OPERATORS
An operator is a symbol that performs operations on operands(data variables).
In the expression c=a+b,
+ is called the "operator"
and a,b are called "operands". C is the result.

The different types of operators are:


1. arithmetic operators
2. relations operators
3. logical operators
4. conditional operators
5. assignment operators
6. increment & decrement operators
7. bitwise operators
8. special operators

1. ARITHMETIC OPERATORS:
These operators are used to perform arithmetic calculations.
+ --> addition
- --> subtraction
* --> multiplication
/ --> division
% -->modulus (modular division)
The unary minus operator, in effect multiplies its single operand by -1, so that a no.
preceded by minus sign changes its sign.
The division operator gives quotient as the result.
The modulus operator gives reminder as the result.
Ex1: int a =14, b =4;
a-b=10 a+b= 18 a*b=56 a/b=3 (decimal part truncated)
a%b=2 (remind or)

Ex2: 6/7=0 , -6/-7=0


-6/7 or 6/-7 =0 or -1(machine dependent)
During modular division, the sign of the result is always the sign of the first operand (the
dividend)
-14/3= -2 -14/-3= -2 14/-3=2

Real Arithmetic & Mixed Arithmetic


Ex:x =6.0/7.0= 0.857143
y= 1.0/3.0= 0.333333
Ex: 15/10.0= 1.5 15/10=1.5
PPS (R18) UNIT 1 Page | 45

2. RELATIONAL OPERATORS:
These operators are used to compare two operands they are
< Less than
> Greater than
<= less than or equal to
>= greater than or equal to
== Equal to
!= not equal to
Eg: a<b, a>b, a<=b, a>=b, a==b, a!=b
 These expressions are also called "relational expressions".
 The value of a relational expressions is either one or zero
 If the specified relation is true, then it is, if it is false, the value is 0.

3. LOGICAL OPERATORS:
These operators are used to combine two or more relational expressions or
conditions together.
They are
&& logical AND
|| logical OR
! logical NOT
Ex:
1. (a>b)&& (a>c) ! (a>b)
2. if (age >55 && sal < 1000)
3. if (number <0 11 number >1000)
RELATIVE PRECEDENCE:
highest ! > >= < <= == != && lowest

4. CONDITIONAL OPERATORS:
A ternary operator pair ?: is used to check the condition.
SYNTAX:
condition? statement 1 : statement 2;

The condition will be evaluated first if it is true (non zero), then stt-1 is evaluated and
becomes the value of stt-1 if condition is false, stt-2 is evaluated and its value becomes the
value of stt-2.
Only one of the statements (1 or 2) will be evaluated
Ex: Big= (a>b) ? a:b ;
a>b ? print f ("a is Big"): print f ("b is Big")
Ex: y=1.5x+3 if x<=2
2x+5 if x>2
y= (x>2)? (2x+5):(1.5x+3);

The operators may also be nested for evaluating more complex assignments.
=================================================================
PPS (R18) UNIT 1 Page | 46

/*PROGRAM TO ILLUSTRATE THE CONDITIONAL OPERATORS


A mathematical function is defined as follows
Let the salary of an sales executive be the no. of products sold per day
and is constrained as
salary = 4*N+100 if x < 40
= 300 if x = 40
= 4*N+200 if x > 40
then the day sal of the employee can be calculated as follows
*/
#include<stdio.h>
int main()
{
float sal,n;
printf("\nEnter the no. of products sold per day: ");
scanf("%f",&n);
sal=(n==40)?300:(n<40)?(4*n+100):(4*n+200);
printf("\n\nSalary = %6.2f",sal);
return 0;
}
Enter the no. of products sold per day: 41
Salary = 364.00
=================================================================
5. ASSIGNMENT OPERATORS
This operator is used to assign a value to a variable.
This assignment operator is '='
Ex: a=10;
There are short hand operators inc. They are:
+= /=
-= %=
*=
Ex: a+=2 ---> a= a+2
a-=2 ---> a= a-2
a*=2 ---> a= a*2
a/=b ---> a= a/b
a%=b ---> a= a%b

6. INCREMENT OR DECREMENT OPERATORS


The increment operator is ++, which increases the value by 1.
The decrement operator is --, which decreases the value by 1.
Ex: int a=5;
a++ ; print f ("the value of a is %d", a)
++a ; print f ("the value of a is %d", a)
++ or -- can be placed before or after the variable.
a++ Here ++ is called as "post fix increment operator"
++a Here ++ is called as "prefix increment operator"
PPS (R18) UNIT 1 Page | 47

a-- Here -- is called as “Postfix decrement operator”


--a Here -- is called as “Prefix decrement operator”
a++ is same as a+1.
'a++' or '++a' mean the same when they form statements independently.
They behave differently when they are assigned to another variable.
(when they are used in expressions on RHS of an assignment statements)
Ex: int a=5, b;
b=a++;
In the above, first a will be assigned to b, and the value of a will be increased so, value
of a=6, b=5.
int a=5, b;
b=++a;
In the above, first value of a is increased, and then will assigned to b, so the value of
a=6, b=6.
=================================================================
/*PROGRAM TO ILLUSTRATE THE INCREMENT & DECREMENT OPERATORS */
#include<stdio.h>
int main()
{
int i=5,j=6,a,b;
printf("\n\n===========INCREMENT OPERATOR==========");
printf("\n\nInitial values: i=%d\tj=%d",i,j);
i++; j++;
printf("\n\nAfter i++ & j++");
printf("\n\ni= %d\tj= %d",i,j);
++i; ++j;
printf("\n\nAfter ++i & ++j");
printf("\n\ni= %d\tj= %d",i,j);
a=++i; b=++j;
printf("\n\nAfter a=++i & b=++j");
printf("\n\na= %d\tb= %d",a,b);
a=i++; b=j++;
printf("\n\nAfter a= i++ & b= j++");
printf("\n\na= %d\ti= %d\tb= %d\tj=%d",a,i,b,j);
printf("\n\n\nThe value of i+++j is: %d",i+++j);
printf("\n\nFinal Values i= %d\tj= %d",i,j);
printf("\n\n===========DECREMENT OPERATOR==========");
printf("\n\nInitial values: i=%d\tj=%d",i,j);
i--; j--;
printf("\n\nAfter i-- & j--");
printf("\n\ni= %d\tj= %d",i,j);
--i; --j;
printf("\n\nAfter --i & --j");
printf("\n\ni= %d\tj= %d",i,j);
a=--i; b=--j;
PPS (R18) UNIT 1 Page | 48

printf("\n\nAfter a=--i & b=--j");


printf("\n\na= %d\tb= %d",a,b);
a=i--; b=j--;
printf("\n\nAfter a= i--& b= j--");
printf("\n\na= %d\ti= %d\tb= %d\tj=%d",a,i,b,j);
printf("\n\n\nThe value of i---j is: %d",i---j);
printf("\n\nFinal Valuesi= %d\tj= %d",i,j);
return 0;
}
===========INCREMENT OPERATOR==========
Initial values: i=5 j=6
After i++ & j++
i= 6 j= 7
After ++i & ++j
i= 7 j= 8
After a=++i & b=++j
a= 8 b= 9
After a= i++ & b= j++
a= 8 i= 9 b= 9 j=10
The value of i+++j is: 19
Final Values i= 10 j= 10
===========DECREMENT OPERATOR==========
Initial values: i=10 j=10
After i-- & j--
i= 9 j= 9
After --i & --j
i= 8 j= 8
After a=--i & b=--j
a= 7 b= 7
After a= i--& b= j--
a= 7 i= 6 b= 7 j=6
The value of i---j is: 0
Final Values i= 5 j= 6
=================================================================
PPS (R18) UNIT 1 Page | 49

7. BITWISE OPERATORS
These operators are for manipulation of data at bit level.
The operators are
OPERATOR PURPOSE
& Bitwise AND
l Bitwise OR
^ Bitwise exclusive OR
(both are same ---> 0 Both are different ---> 1)
~ complement
<< left shift
>> right shift
=================================================================
/*PROGRAM TO CHECK THE BITWISE OPERATORS*/
main()
{
int x,y;
printf("\n\n\t\tPROGRAM TO CHECK THE OPERATIONS ON BITWISE
OPERATORS");
printf("\n\n\tENTER TWO NUMBERS X & Y: ");
scanf("%d%d",&x,&y);

printf("\n\n\t X<<1= %d & Y>>1= %d",x<<1,y>>1);


printf("\n\n\t SO NOW X = %d AND Y = %d ",x,y);
printf("\n\n\t OBSERVE '<<' DOUBLES THE NO. AND '>>' MAKES THE NO.
HALF\n\n");
printf("\n\n\t X & Y = %d \n\n\t X | Y = %d \n\n\t X ^ Y= %d ", x&y, x|y, x^y);
printf("\n\n\t ~X = %d", ~x);
return 0;
return 0;
}
O/P:
PROGRAM TO CHECK THE OPERATIONS ON BITWISE OPERATORS
ENTER TWO NUMBERS X & Y: 6 9
X<<1= 12 & Y>>1= 4
SO NOW X = 6 AND Y = 9
OBSERVE '<<' DOUBLES THE NO. AND '>>' MAKES THE NO. HALF
X & Y = 0
X | Y = 15
X ^ Y= 15
~X = -7
=================================================================
PPS (R18) UNIT 1 Page | 50

8. SPECIAL OPERATORS
C supports some special operators as sizeof (), comma, pointer operators (& and *) and
member selection operators (. and -->).
Comma operator can be used to link the related expressions together into a single line
Ex1: int a , b=10 , c ;
Ex2: t=a , a=b , b=t ;
Ex3: (c=ca=10 , b=is , a+b) ;
sizeof operator is used to display the size of datatype
syntax: sizeof (datatype);
Ex: sizeof(float)
print f ("%d",sizeof (float) ) ;
=================================================================
/*PROGAM TO ILLUSTRATE ABOUT THE SIZE OF DATA TYPES */
int main()
{
int i;
float j;
char ch;
printf("\n\nSize of i= %dBytes\tSize of int= %dBytes",sizeof(i),sizeof(int));
printf("\n\nSize of j= %dBytes\t Size of float= %dBytes",sizeof(j),sizeof(float));
printf("\n\nSize of ch= %dBytes\t Size of char= %dBytes",sizeof(ch),sizeof(char));
printf("\n\nSize of float=%dBytes",sizeof(float));
printf("\n\nSize of double=%dBytes",sizeof(double));
printf("\n\nSize of long double=%dBytes",sizeof(long double));
return 0;
}
O/P:
Size of i= 2Bytes Size of int= 2Bytes
Size of j= 4Bytes Size of float= 4Bytes
Size of ch= 1Bytes Size of char= 1Bytes
Size of float=4Bytes
Size of double=8Bytes
Size of long double=10Bytes
=================================================================
FORMAT SPECIFIERS:
int %d octal %o (o is alphabet not zero)
float %f . hexadecimal %ox
char %c
string %s
short int %d or % hd
long int % ld
double %f long double % ld
PPS (R18) UNIT 1 Page | 51

OPERATOR PRECEDENCE & ASSOCIATIVITY:


Precedence is used to determine the order in which the operators are to be evaluated.
Every C operator has a rank or priority or precedence. Depending on the rank, the operators
are evaluated.
Associativity is used to determine the order in which the operators are to be evaluated if the
given expression contains the operators of the same rank.
Associativity is of two types
1.left to right (L -> R )
2.right to left ( R ->L )

SUMMARY OF C OPERATORS:
=================================================================
OPERATOR DESCRIPTION ASSOCIATIVITY RANK
=================================================================
( ) functional call L -> R 1
[] array element reference
=================================================================
+ unary plus R -> L 2
- unary minus
++ increment
-- decrement
! logical NOT
~ 1‟s compliment
* pointer reference
& address of
size of size of an object
(type) typecast(conversation)
=================================================================
* multiplication L -> R 3
/ division
% modular division
=================================================================
+ addition L -> R 4
- subtraction
=================================================================
<< left shift L -> R 5
>> right shift
=================================================================
< Lessthan L -> R 6
<= Lessthan or equal to
> Greater that
>= Greater than or equal to
=================================================================
PPS (R18) UNIT 1 Page | 52

=================================================================
== equality L -> R 7
!= inequality
=================================================================
& bitwise AND L -> R 8
=================================================================
^ bit wise XOR L -> R 9
=================================================================
! bitwise OR L -> R 10
=================================================================
&& Logical AND L -> R 11
=================================================================
!! logical OR L -> R 12
=================================================================
? : conditional expression R -> L 13
=================================================================
=
*= /= %=
+= -= &= assignment operators R -> L 14
^=
=================================================================
, comma L -> R 15
=================================================================
Note: Follow the Class notes for more problems in the Precedence and Associativity.
=================================================================
/*PROGRAM TO ILLUSTRATE ABOUT THE OPERATOR'S PRECEDENCE &
ASSOCIATIVITY */
#include<stdio.h>
int main()
{
int i,j,a,b,c;
i=(2*3/4+4/4+8-2+5/8);
printf("\n\ni=%d",i);
a=3; b=5; c=8;
a+=b*=c-5;
printf("\n\na=%d",a);
a=3; b=4; c=5;
j=--a*(3+b)/2-c++*b;
printf("\n\nj=%d",j);
} i=8
a=18
j=-13
=====================================================================
ILLUSTRATION ABOUT
PPS (R18) UNIT 1 Page | 53

OPERATORS PRECEDENCE& ASSOCIATIVITY (Frequently Used)


=================================================================
OPERATOR DESCRIPTION ASSOCIATIVITY RANK
=================================================================
( ) functional call L -> R 1
[] array element reference
=================================================================
++ increment
-- decrement
! logical NOT
* pointer reference R -> L 2
& address of
size of size of an object
(type) typecast(conversation)
=================================================================
* multiplication L -> R 3
/ division
% modular division
=================================================================
+ addition L -> R 4
- subtraction
=================================================================
<< left shift L -> R 5
>> right shift
=================================================================
< Lessthan
<= Lessthan or equal to L -> R 6
> Greater that
>= Greater than or equal to
=================================================================
== equality L -> R 7
!= inequality
=================================================================
! bitwise OR L -> R 10
=================================================================
&& Logical AND L -> R 11
=================================================================
? : conditional expression R -> L 13
=================================================================
=
*= /= %=
+= -= &= assignment operators R -> L 14
^=
=================================================================
#include<stdio.h>
void main()
{
int a=9, b=12, c=3,d;

d=a – b / (3 + c) * (2 - 1);

printf("\nd=%d",d);
}
/*Ans: d=7*/

#include<stdio.h>
void main()

{
int a=9,b=12,c=3,d;

d = a -(b/(3+c)*2)-1;

printf("\nd=%d",d);
}

/*Ans: d=4*/
PPS (R18) UNIT 1 P a g e | 55
Type Conversion (or) Type Casting:
 C permits mixing of constants and variables of different types in an expression.
 The process of converting one type value to another type is called “ Type conversion”.
 There are two types of conversions
Implicit Conversion
Explicit Conversion
1. Implicit Conversion:
 C automatically converts one type of value into another. This is called “Implicit
Conversion”.
 Every Datatype in C has a conversion Rank.
 Depending on the Conversion Rank either promotion or Demotion occurs.
 Promotion occurs when a lower Rank value is converted into higher Rank.
 Demotion occurs when a higher Rank value is converted into lower Rank.
Ex: //Promotion //Demotion
int a=5; int a;
float b; float b=7.1657;
b=a; a=b;
The Value of b=5.000000 The value of a=7 only.
2. Explicit Conversion
The process of converting one type to another type of value by our self is called
“Explicit conversion”.
Syntax: (datatype) variable;
Ex: int a=5,b=2;
float c;
c=(float)a/b;
The Value of c=2.500000
Ex: int a=22, b=7;
float c=a/b;
The value of c is 3.000000 only
Statements
A statement is an action performed by a program.
There are 11 types of statements in C
1. null statement
2. expression statement
3. compound statement
4. return statement
5. labeled statement
6. switch statement
7. break statement
8. continue statement
9. goto statement
10. conditional statement
PPS (R18) UNIT 1 Page | 56
1. Null Statement:
An empty statement ending with a semicolon “;” is called a Null statement.
Ex: ;
This statement is used when we require a statement but no action is performed.

2. Expression statement:
An expression ending with ; is called “Expression statement”.
Ex: c= a + b; area=(1.0/2)*b*h; a=99;

3. Compound statement:
It is a unit/block of code that combines a group of statements.
Ex: {
---
--- // body statements;
---
}

4. Return Statement:
A return statement terminates a function;
Syntax: return value;

 main() function also returns a value


 main returns zero to the operating system which means that the program is successfully
executed.

5. Selection Statements:
It contains a decision making to see whether a condition is satisfied or not and to execute the
respective statements.
The different selection statements are
i. if statement
ii. switch statement
iii. conditional statement
iv. goto statement
The above are all called the “Decision making statements” or “Control Statements”.

i. if statement:
The different forms of if statements are
1. simple if
2. if …else
3. nested if
4. else if
PPS (R18) UNIT 1 Page | 57
a). simple if:
Syntax:
if(condition)
{
Statements block-1;
}

 If the condition is true, the statements block-1 will be executed and the control goes to
next statements.
 If the condition is false, then the control directly goes to next to the if block without
executing the inside block of statements-.
Ex: Write a program to find the biggest of the two numbers using the simple if.

=====================================================================
/* Program to find the biggest of two numbers using simple if*/
#include<stdio.h>
int main()
{
int a,b;
printf(“\nEnter two Integers:”);
scanf(“%d%d”,&a,&b);
if(a>b)
printf(“\n%d is bigger than %d”,a,b);
if(a<b)
printf(“\n%d is bigger than %d”,b,a);
if(a==b)
printf(“\n%d is equal to %d”,a,b);
}

Enter two Integers: 5 6


6 is bigger than 5

b). if … else statement:

Syntax:
if(condition)
{
True Statements Block;
}
else
{
False Statements Block
}
Statements Block – 3;
PPS (R18) UNIT 1 Page | 58
 If the condition is true, then true stt block will be executed and the control goes to the
stat-3 block;
 If the condition is false, then false statements block will be executed and then the
control goes to the Stat-3 block.
 In either case only one of the true/false block statements will be executed.
 if only one statement is there in true/false block then { } are optional for blocks.

Ex:
/*PROGRAM TO FIND THE BIGGEST OF TWO NO.S USING IF…ELSE*/
#include<stdio.h>
int main()
{
int a,b;
printf(“\nEnter two Integers:”);
scanf(“%d%d”,&a, &b);
if(a>=b)
printf(“\n%d is bigger than %d”,a, b);
else
printf(“\n%d is bigger than %d”,b, a);
}
Enter two Integers: 5 6
6 is bigger than 5
=========================================================================
c). nested if :
Syntax:
if(condition-1)
{
if(condition-2)
{
if(condition-3)
{
Statement-1;
}
}
}
 In the nested if block first the condition-1 will be checked, if it
is true, the control again checks the condition-2, if it is true,
the control again checks the condition-3,if it is also true, then
stt-1 will be executed. if either of the conditions is false then
stt-1 will not be executed.
 after that control comes out of the block and then executes any other statements

=========================================================================
PPS (R18) UNIT 1 Page | 59

/*PROGRAM TO CHECK WHETHER THE FIRST NUMBER IS BIGGER THEN THE


REMAINING OR NOT USING NESTED IF*/
#include<stdio.h>
int main()
{
int a,b,c,d;
printf("\nEnter a, b, c, d:");
scanf("%d%d%d%d",&a, &b,&c,&d);
if(a>b)
if(a>c)
if(a>d)
printf("\n%d is bigger than the other three no.s",a);
printf("\nDone\n");
return 0;
}
O/P:
Enter a, b, c, d:8 7 2 1
8 is bigger than the other three no.s
Done
Ex: Write a program to print the biggest of 3 integers
=====================================================================
/*PROGRAM TO FIND THE BIGGEST OF 3 INTEGERS*/
#include<stdio.h>
int main()
{
int a,b,c;
printf(“\n Enter 3 integers”);
scanf(“%d%d%d”,a,b,c);
if(a>b&& a>c)
printf(“\n Big=%d”,a);
else
if(b>c)
printf(“\nBig=%d”,b);
else
printf(“\nBig=%d”,c);
return 0;
}
O/P:
Enter 3 integers 8 9 6
Big = 9
=====================================================================
/*PROGRAM TO FIND THE BIGGEST OF 3 NUMBERS*/
int main()
{
int a,b,c;
printf("\nEnter 3 integers ");
PPS (R18) UNIT 1 Page | 60
scanf("%d%d%d",&a,&b,&c);
printf("\n\nUsing Conditional Operator\n\nBIG= %d",(a>=b&&a>=c)?a:(b>=c)?b:c);
}
O/P:
Enter 3 integers 8 9 6
BIG= 9
Using Conditional Operator
BIG= 9
=====================================================================
/*PROGRAM TO CHECK WHETHER THE NUMBER IS EVEN OR ODD */
#include<stdio.h>
int main()
{
int n;

printf("\n\nEnter integer: ");


scanf("%d",&n);
if(n%2==0)
printf("\n %d is EVEN",n);
else
printf("\n %d is ODD",n);
return 0;
}
Enter integer: 9 9 is ODD
=================================================================
/*PROGRAM TO CHECK WHETHER THE NUMBER IS POSITIVE OR NEAETIVE */
#include<stdio.h>
int main()
{
int n;
printf("\n\nEnter integer: ");
scanf("%d",&n);
if(n>0)
printf("\n %d is POSITIVE",n);
else
if(n==0)
printf("\n %d is NEITHER +VE NOR -VE",n);
else
printf("\n %d is NEGATIVE",n);
return 0;
}
Enter integer: 0
0 is NEITHER +VE NOR –VE
=================================================================
PPS (R18) UNIT 1 Page | 61
d). else..if ladder
PPS (R18) UNIT 1 Page | 62

/* PROGRAM TO PRINT THE GRADE OF A STUDENT */


#include<stdio.h>
int main()
{
int marks;
printf("\n\n GRADE OF A STUDENT");
printf("\n\n Enter your marks: ( 0 to 100 only)");
scanf("%d",&marks);
if(marks>=75 && marks <=100)
printf("\n\n You got GRADE A");
else
if(marks>=60)
printf("\n\n You got GRADE B");
else
if(marks>=50)
printf("\n\n Your got GRADE C");
else
if(marks>=40)
printf("\n\n You got GRADE D");
else
printf("\n\n You are failed");
}
GRADE OF A STUDENT
Enter your marks: ( 0 to 100 only)99
You got GRADE A
=================================================================
/*PROGRAM TO CALCULATE THE GROSS SALARY OF AN EMPLOYEE AS FOLLOWS
BASIC SALARY DA HRA CONVEYENCE
>=5000 110% 20% 500
>=3000 &<5000 100% 15% 400
<3000 85% 10% 300 */
#include<stdio.h>
int main()
{
float basic, da,hra,con,gross;
printf("\n\n Enter your Basic Salary: ");
scanf("%f",&basic);
if(basic>=5000)
gross=(basic+1.3*basic+500);
else
if(basic >= 3000)
gross=(basic+1.15*basic+400);
else
gross=(basic+.95*basic+400);
printf("\n\nYOUR GROSS SALARY IS: %6.2f",gross);
}
PPS (R18) UNIT 1 Page | 63

o/p: Enter your Basic Salary: 6000


YOUR GROSS SALARY IS: 14300.00
=================================================================
/*PROGRAM TO FIND THE NATURE AND ROOTS OF A QUADRATIC EQUATION
ax2+bx+c=0*/
#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c,d;
clrscr();
printf("\nEnter a,b,c in the\n\nQudratic Equation ax^2+bx^1+c=0 ");
scanf("%f%f%f",&a,&b,&c); d=b*b-
4*a*c; printf("\n\nDiscriminent =
%6.0f",d); if(d>0)
{
printf("\n\nRoots are Real and Distinct");
printf("\n\nRoot1=%f Root2=%f ",(((-b)+sqrt(d))/2*a),(((-b)-sqrt(d))/2*a));
}
else
if(d==0)
{
printf("\n\nRoots are Equal");
printf("\n\n Root1=%f Root2=%f ",((-b)/2*a),((-b)/2*a));
}
else
{
printf("\n\nRoots are Imaginary");
printf("\n\nRoot1=%6.3f+%6.3fi",(-b/(2*a)),(sqrt(-d)/(2*a)));

printf("\n\nRoot2=%6.3f-%6.3fi",(-b/(2*a)),(sqrt(-d)/(2*a)));
}
return 0;
}
Enter a,b,c in the
Qudratic Equation ax^2+bx^1+c=0 5 6 8
Discriminent = -124
Roots are Imaginary
Root1= -0.600+ 1.114i
Root2= -0.600- 1.114i
PPS (R18) UNIT 1 Page | 64
The switch Statement:
When one of the many alternatives is to be selected, we can use if statement to control
the (situation) selection. However, the complexity of such programs increases dramatically,
when the number of alternatives increases, then the programs becomes difficult to read and
follow. C has a built in multi-way decision statement known as "switch"
 The switch statement tests the values of a variable (expression) against a list of case

values and when a match is found, a block of statements associated with that case will be
executed.
 The expression is an integer or character.Value-1, value-2 are constants or constant
expressions and they are known as case labels. Each of these values should be unique.
 No need of the braces around these blocks.
 The switch tests the values of given variable against a list of case values, when a match is
found a block of statements associated with it will be executed.

Syn:
switch(variable) //value
{
case value-1:
stt-1;
case value-2:
stt-2;
:
:
default:
Default stt;
}
PPS (R18) UNIT 1 Page | 65

Ex:/* PROGRAM TO ILLUSTRATE ABOUT SWITCH WITH SIMPLE PROGRAM*/


#include<stdio.h>
int main()
{
int i;
printf(“\nEnter an integer (1 or 2 or 3): ”);
scanf(“%d”,&i);
switch(i)
{
case 1:
printf(“\n I am in Case-1”);
case 2:
printf(“\n I am in Case-2”);
case 3:
printf(“\n I am in case-3);
default:
printf(“\n I am in Default”);
}
}
o/p:
Enter an integer (1 or 2 or 3): 3
I am in case-3
I am in Default
=====================================================================
/*PROGRAM TO PERFORM THE ARITHMATIC OPERATIONS BASED ON THE USER'S
CHOICE */
#include<stdio.h>
int main()
{
int i;
float a,b;
clrscr();

printf("\nEnter any no.s a & b: ");


scanf("%f%f",&a,&b);
printf("\n\n 1. ADDITION\n\n 2. SUBTRACTION\n\n 3. MULTIPLICATION\n\n
4. DIVISION ");
printf("\n\n Enter your option: ");
scanf("%d",&i);
switch(i)
{
case 1:
printf("\n\n%f + %f = %f",a,b,a+b);
break;
case 2:
printf("\n\n%f - %f = %f",a,b,a-b);
break;
PPS (R18) UNIT 1 Page | 66

case 3:
printf("\n\n%f * %f = %f",a,b,a*b);
break;
case 4:
if(b!=0)
printf("\n\n%f / %f = %f",a,b,a/b);
else
printf("\nDivision is not possible with zero");
break;
default :
printf("\n Enter correct option");
scanf("%d",&i);
}
return 0;
}
Enter any no.s a & b: 45 15
1. ADDITION
2. SUBTRACTION
3. MULTIPLICATION
4. DIVISION
Enter your option: 4
45.000000 / 15.000000 = 3.000000
PPS (R18) UNIT 1 Page | 67

THE ABOVE PROGRAM WITH ANOTHER VERSION


=====================================================================
/*PROGRAM TO PERFORM THE ARITHMATIC OPERATIONS BASED ON THE USER'S
CHOICE WITH LABELS AND LOCAL VARIABLES – VERSION 2*/
#include<stdio.h>
int main()
{
int i;
float a,b;
printf("\nEnter any no.s a & b: ");
scanf("%f%f",&a,&b);
printf("\n\n 1. ADDITION\n\n 2. SUBTRACTION\n\n 3. MULTIPLICATION\n\n
4. DIVISION\n\n 5. MODULAR DIVISION\n\n 6. QUIT");
printf("\n\n Enter your option: ");
scanf("%d",&i);
ravi: /*label*/
switch(i)
{
case 1:
printf("\n\n%f + %f = %f",a,b,a+b);
break;
case 2:
printf("\n\n%f - %f = %f",a,b,a-b);
break;
case 3:
printf("\n\n%f * %f = %f",a,b,a*b);
break;
case 4:
krishna :
if(b!=0)
printf("\n\n%f / %f = %f",a,b,a/b);
else
{
printf("\nDivision is not possible with zero");
printf("\nEnter correct no.");
scanf("%f",&b);
goto krishna;
}
break;
case 5:
{
int c,d; /*local variables in this block*/
c=(int)a;
d=(int)b;
printf("\n\nMODULAR DIV OF %d %d = %d",c,d,c%d);
break;
PPS (R18) UNIT 1 Page | 68
}
case 6:
exit();
default :
printf("\n Enter correct option");
scanf("%d",&i);
goto ravi;
}
return 0;
}
Enter any no.s a & b: 45 0
1. ADDITION
2. SUBTRACTION
3. MULTIPLICATION
4. DIVISION
5. MODULAR DIVISION
6. QUIT
Enter your option: 4
Division is not possible with zero
Enter correct no.15
45.000000 / 15.000000 = 3.000000
Note: You don‟t need to write this much big code for division. You write simply.
This is to explain about labels and local block variables.
====================================================================
/*PROGRAM TO FIND THE CELSICUS/FAHRENHEIT TEMPERATURE */
#include<stdio.h>
int main()
{
float temp,ctemp;
int i;

printf("\nEnter Temperature: ");


scanf("%f",&temp);
printf("\n 1. Celsius to Fahrenheit\n 2. Fahrenheit to Celsius ");
printf("\n\n Enter your option: ");
scanf("%d",&i);
switch(i)
{
case 1:
ctemp=(9*temp/5)+32;
printf("\n\nEquivalent Fahrenheit Temperature is: %f",ctemp);
break;
case 2:
ctemp=(temp-32)*5/9;
printf("\n\nEquivalent Celsius Temperature is: %f",ctemp);
}
PPS (R18) UNIT 1 Page | 69

return 0;
}
Enter Temperature: 32
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Enter your option: 2
Equivalent Celsius Temperature is: 0.000000
====================================================================
goto statement
 C supports go to statement branch unconditionally from one point to another point in the
program. Although it may not be essential to use the go to statement in a highly
structured language like C, there may be occasions to use goto.
 goto breaks the normal sequential execution of the program .
syntax:
goto label;
…….
…….
label:
{
stts;
}
label:
{
stts;
}
…….
…….
goto label;
/*PROGRAM TO ILLUSTRATE ABOUT GOTO STATEMENT*/
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("\ti=%d",i);
if(i==5)
goto SRYS;
}
printf("\nThis stt won't be executed");
SRYS:
printf("\n This is a labeled Stt for goto");
printf("\n Completed");
}
O/P:
i=1 i=2 i=3 i=4 i=5
PPS (R18) UNIT 1 Page | 70

This is a labeled Stt for goto


Completed
=================================================================
break statement:
C break(key word) statement is used to terminate any type of loop such as while loop,
do while loop and for loop. C break statement terminates the loop body immediately and
passes control to the next statement after the loop.
Terminates the current loop(inner most loop)
=================================================================
/*PROGRAM TO ILLUSTRATE ABOUT THE BREAK STATEMENT*/
int main()
{
int i;
for(i=1;i<=5;i++)
{
printf("\ti=%d",i);
if(i==3)
break;
}
printf("\n Completed");
}
i=1 i=2 i=3
Completed
=====================================================================
continue statement:
C continue statement is used to skip over the rest of the current iteration in program. After
continue statement, the control returns to the top of the loop.
=====================================================================
/*PROGRAM TO ILLUSTRATE ABOUT THE CONTINUE STATEMENT IN C*/
int main()
{
int i;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
printf("\ni=%d",i);
}
printf("\n Completed");
}
o/p: i=1 i=2
i=4 i=5
Completed
exit():
exit function is used to come out from the execution of the program where ever it is.
Note: As “for loop” already been explained in the algorithms &simple programs,
I have taken for loop for goto, break and continue programs.
PPS (R18) UNIT 1 Page | 71

Decision making and looping:


In looping the sequence of the loop are executed until some conditions for termination of
the loop are satisfied. A program loop consists of two parts body and the Head. The head of
the statement decides the no. of times for which the instructions present in the body of the
statements are to be executed
 Based on the positions of the condition in the loop, a control structure can be
classified into two types
1. Entry control loop
2. Exit control loop
 In the entry control loop, the conditions are tested before start of the loop execution.
 In the exit control loop, the conditions are tested at the end of the body of the loop

A looping consists of 4 steps.


1. Setting & Initialization of a counter
2. Execution of statement in the loop
3. Test a specified condition for the execution of the loop
4. Increasing /decreasing the counter
The test may be either to determine whether the loop has been repeated the satisfied
no. of times or to determine whether a particular condition has been met
C provides 3 different statements for looping
1. While statement
2. do while statement
3. for statement

1. While statement
The test condition is evaluated and if condition is
true ,then the body of the loop is executed .After the
execution of the body ,the test-condition are again
evaluated ,and if it true ,the body is executed once again.
This process continues till the test condition becomes
false and the control is transformed out of the loop.
The body of the loop may have one or more
statements .the braces are needed only if the body
contains two more statements
=====================================================================
/*program to find the average of n numbers using while*/
#include<stdio.h>
main()
{
int i=1,n;
float x,sum=0;

printf("\n\n\tEnter n: ");
PPS (R18) UNIT 1 Page | 72

scanf("%d",&n);
while(i<=n)
{
printf("\n\n\t Enter x%d: ",i);
scanf("%f",&x);
sum+=x;
i++;
}
printf("\n\n\tThe sum is: %2.3f",sum);
printf("\n\tThe Avg is: %2.4f ",sum/n);
}
O/P: Enter n: 4
Enter x1: 1.2 Enter x2: 3.4 Enter x3: 5.6 Enter x4: 7.8
The sum is: 18.000
The Avg is: 4.5000
=====================================================================
The do-while statement:
 The do stt is an exit control loop.
 The do stt first executes the body of the loop, then it will
check the condition given in while stt.
 If the condition in while stt is true, then once again the body of
the loop will be executed.
 This process will continue till the condition becomes false,
then the loop will be terminated and control goes to the stt
that appears immediately after the while stt.

====================================================================
Ex: Program to calculate the average of n numbers.
/*program to find the average of n numbers using do-while*/
#include<stdio.h>
main()
{
int i=1,n;
float x,sum=0;
printf("\n\n\tEnter n: ");
scanf("%d",&n);
do
{
printf("\n\n\t Enter x%d: ",i);
scanf("%f",&x);
PPS (R18) UNIT 1 Page | 73

sum+=x;
i++;
}while(i<=n);
printf("\n\n\tThe sum is: %2.3f",sum);
printf("\n\tThe Average is: %2.4f ",sum/n);
}
o/p: Enter n: 5
Enter x1: 1.2 Enter x2: 2.3 Enter x3: 3.4 Enter x4: 4.5
Enter x5: 5.6
The sum is: 17.000
The Average is: 3.4000
=====================================================================
for statement:
The for loop is another entry control loop
format:
The for loop follows three things
1. Initialization
2. Condition checking
3. Increasing/Decrementing
1. Initialization
Sets the loop counter to an initial value.
2. Condition checking:
The value of the control variable is tested using the test condition. If the condition is
true the body of the loop will be executed, else the loop will be terminated and execution
continues with the stt that immediately follows the loop.
3. Increment/Decrement:
After the body of the loop executed, the value of the control variable either
incremented or decremented and again the condition will be tested.
=====================================================================
/*PROGRAM TO PRINT THE FACTORIAL OF A NO.*/
#include<stdio.h>
int main()
{ int i,n,fact=1;
printf("\nEnter No: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
fact*=i;
printf("\n%d! = %d",n,fact);
}
Enter No: 10
10! = 24320
=================================================================
PPS (R18) UNIT 1 Page | 74

PERFECT NUMBER:
a perfect number is a positive integer that is the sum of its proper positive divisors, that is,
the sum of the positive divisors excluding the number itself. Equivalently, a perfect number is a
number that is half the sum of all of its positive divisors (including itself), or s(n) = 2n.

The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and
1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors:
(1 + 2 + 3 + 6 ) / 2 = 6.
The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers
496 and 8128 (sequence A000396 in OEIS).
These first four perfect numbers were the only ones known to early Greek mathematics.
Here are the first few perfect numbers:
6,
28,
496,
8128,
33550336,
8589869056,
====================================================================================
PALINDROMIC NUMBER:
A palindrome number or numeral palindrome is a 'symmetrical' number like 16461 that remains
the same when its digits are reversed. The term palindromic is derived from palindrome, which
refers to a word like rotor that remains unchanged under reversal of its letters. The first
palindrome numbers (in decimal) are:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171,
181, 191, … (sequence A002113 in OEIS).
Palindromic numbers receive most attention in the realm of recreational mathematics. A typical
problem asks for numbers that possess a certain property and are palindromic. For instance,

The palindromic primes are 2, 3, 5, 7, 11, 101, 131, 151, (A002385) etc.
The palindromic square numbers are 0, 1, 4, 9, 121, 484, 676, 10201, 12321,(A002779) etc.
====================================================================================
ARMSTRONG NUMBER:
An Armstrong number is a number that is equal to the sum of each of the individual digits that
make up the number raised to the power of the number of digits the number has.
Armstrong numberAlso known as narcissistic numbers, Armstrong numbers are the sum of their
own digits to the power of the number of digits. As that is a slightly brief wording,
Let me give an example:
153 is an Armstrong number because 153 = 1^3 + 5^3 + 3^3.
370 is an Armstrong number because 370 = 3^3 + 7^3 + 0^3.
1634 is an Armstrong number because 1634 = 1^4 + 6^4 + 3^4 + 4^4.
PPS (R18) UNIT 1 Page | 75

/*PROGRAM TO FIND THE PERCENTAGE OF A STUDENT*/


#include<stdio.h>
int main()
{
int marks,i,n,max,sum=0;
float per;

printf("\n How many no. of subjects you want to enter? ");


scanf("%d",&n);
printf("\n Enter Maximum marks for each subject: ");
scanf("%d",&max);

for(i=1;i<=n;i++)
{
printf("\nEnter subject %d marks: ",i);
scanf("%d",&marks);
sum+=marks;
}
per=(sum*100)/(n*max);

printf("\nTOTAL = %d \/ %d \t PERCENTAGE= %f",sum,(n*max),per);


return 0;
}
How many no. of subjects you want to enter? 4
Enter Maximum marks for each subject: 75
Enter subject 1 marks: 75
Enter subject 2 marks: 74
Enter subject 3 marks: 72
Enter subject 4 marks: 73
TOTAL = 294 / 300 PERCENTAGE= 98.000000
=================================================================
/*PROGRAM TO FIND THE SUM AND AVERAGE OF N NUMBERS ENTERED BY THE USER*/
#include<stdio.h>
int main()
{
int i,n;
float x,sum=0,avg;
printf("\n\nHow many no's you want to add? ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter x: ");
scanf("%f",&x);
sum+=x;
}
PPS (R18) UNIT 1 Page | 76

avg=sum/n;
printf("\n\nSum= %6.4f\n\nAverage= %6.4f",sum,avg);
return 0;
}
How many no's you want to add? 4
Enter x: 22.36 Enter x: 33.45 Enter x: 45.89 Enter x: 65.78
Sum= 167.4800 Average= 41.8700
=================================================================
/*PROGRAM TO FIND THE SUM OF THE DIGITS OF THE GIVEN NUMBER*/
#include<stdio.h>
int main()
{
int n,sum=0,r;

printf("\nEnter a number: ");


scanf("%d",&n);
while(n>0)
{
r=n%10;
sum+=r;
n=n/10;
}
printf("\n Sum of the digits of given no. is: %d",sum);
return 0;
}
Enter a number: 12345
Sum of the digits of given no. is: 15
=================================================================
PPS (R18) UNIT 1 Page | 77

/*PROGRAM TO FIND THE SUM OF THE EVEN AND ODD DIGITS OF THE GIVEN
NUMBER*/
#include<stdio.h>
int main()
{
int n,esum=0,osum=0,r;

printf("\nEnter a number: ");


scanf("%d",&n);
while(n>0)
{
r=n%10;
if(r%2==0)
esum+=r;
else
osum+=r;
n=n/10;
}
printf("\n Sum of the even digits of given no. is: %d",esum);
printf("\n Sum of the odd digits of given no. is: %d",osum);
return 0;
}
Enter a number: 13254
Sum of the even digits of given no. is: 6
Sum of the odd digits of given no. is: 9
=================================================================
/*PROGRAM TO FIND THE PRODUCT OF N NUMBERS ENTERED BY THE USER*/
#include<stdio.h>
int main()
{
int i,n;
float x,prod=1;

printf("\n\nHow many no's you want to add? ");


scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\nEnter x: ");
scanf("%f",&x);
prod*=x;
}
printf("\n\nPRODUCT = %6.4f",prod);
return 0;
}
PPS (R18) UNIT 1 Page | 78

How many no's you want for product? 4


Enter x: 2.3
Enter x: 3.4
Enter x: 5.6
Enter x: 7.8
PRODUCT = 341.5776
=================================================================
/*PROGRAM TO FIND X POWER N*/
#include<stdio.h>
int main()
{
int i,n;
float x,pow=1;

printf("\n\nEnter x: ");
scanf("%f",&x);
printf("\n\Eneter n ");
scanf("%d",&n);

for(i=1;i<=n;i++)
pow*=x;

printf("\n\n%f^%d = %6.4f",x,n,pow);
return 0;
}
Enter x: 5.6
Eneter n 3
5.600000^3 = 175.6160
=================================================================
/*PROGRAM TO PRINT THE MULTIPLICATION TABLE*/
#include<stdio.h>
int main()
{
int i,n;

printf("\nEnter No.for multiplication table: ");


scanf("%d",&n);
for(i=1;i<=15;i++)
printf("\n%d * %d = %d",n,i,n*i);
return 0;
}
Enter No.for multiplication table: 11
PPS (R18) UNIT 1 Page | 79

11 * 1 = 11
11 * 2 = 22
11 * 3 = 33
11 * 4 = 44
11 * 5 = 55
11 * 6 = 66
11 * 7 = 77
11 * 8 = 88
11 * 9 = 99
11 * 10 = 110
11 * 11 = 121
11 * 12 = 132
11 * 13 = 143
11 * 14 = 154
11 * 15 = 165

=================================================================
/*PROGRAM TO PRINT THE FIRST N FIBONACCI NUMBERS*/
#include<stdio.h>
int main()
{
int n1=0,n2=1,count,n,fib;

printf("\nHow many Fibonacci terms you need? ");


scanf("%d",&n);
if(n>=1)
printf("\n0");
if(n>=2)
printf("\t1");
if(n>=3)
for(count=1;count<=n-2;count++)
{
fib=n1+n2;
printf("\t%d",fib);
n1=n2;
n2=fib;
}

return 0;
}
How many Fibonacci terms you need? 10

0 1 1 2 3 5 8 13 21 34
=================================================================
PPS (R18) UNIT 1 Page | 80

/*PROGRAM TO FIND THE GCD/HCF and LCM OF TWO NUMBERS*/


#include<stdio.h>
int main()
{
long int n1,n2,a,b;

printf("\n\n\t==============================");
printf("\n\n\t GCD/HCF & LCM OF TWO NUMBERS");
printf("\n\n\t==============================");
printf("\n\n\tENTER TWO NUMBERS: ");
scanf("%ld %ld",&n1,&n2);
a=n1;b=n2;
while(n1!=n2)
{
if(n1>n2)
n1=n1-n2;
else
n2=n2-n1;
}
printf("\n\n\tGCD/HCF OF TWO NUMBERS IS: %ld",n1);
printf("\n\n\t LCM OF TWO NUMBERS IS: %ld",(a*b)/n1);
return 0;
}
==============================
GCD/HCF & LCM OF TWO NUMBERS
==============================
ENTER TWO NUMBERS: 49 56
GCD/HCF OF TWO NUMBERS IS: 7
LCM OF TWO NUMBERS IS: 392
=================================================================
/*PROGRAM TO PRINT THE REVERS OF A GIVEN NUMBER*/
#include<stdio.h>
int main()
{
long n,rev=0,r;

printf("\nEnter a number: ");


scanf("%ld",&n);

while(n>0)
{
r=n%10;
rev=rev*10+r;
n=n/10;
}
PPS (R18) UNIT 1 Page | 81

printf("\n Reverse of given numbers is %ld",rev);


return 0;
}
Enter a number: 1234 Reverse of given numbers is 4321
=================================================================
/*PROGRAM TO PRINT WHETHER THE NO. IS PALINDROME OR NOT*/
#include<stdio.h>
int main()
{
long n,m,rev=0,r;

printf("\nEnter a number: ");


scanf("%ld",&n);
m=n;
while(n>0)
{ r=n%10;
rev=rev*10+r;
n=n/10;
}
if(m==rev)
printf("\nNUMBER IS PALINDROME");
else
printf("\nNOT A PALINDROME");
return 0;
}
Enter a number: 15951
NUMBER IS PALINDROME
=================================================================
/*PROGRAM TO CHECK WHETHER THE NO. IS PRIME OR NOT*/
int main()
{
int i,n;
printf("\n\nEnter a no: ");
scanf("%d",&n);
for(i=2;i<n;i++)
if(n%i==0)
{ printf("\n%d is NOT PRIME \t Factor is %d",n,i);
exit(0);
}
printf("\n%d is PRIME",n);
return 0;
}
Enter a no: 97
97 is PRIME
=================================================================
PPS (R18) UNIT 1 Page | 82

/*PROGRAM TO CHECK WHETHER THE NO.IS ARMSTRONG OR NOT


EXAMPLE ARMSTRONG NO.S
1 2 3 ... 9 153 370 371 407 1634 8208 9474 54748 */
#include<stdio.h>
#include<math.h>
int main()
{
int n, r, arm,sum=0,power=0;
printf("\n\tPROGRAM TO CHECK A NUMBER ARMSTRONG OR NOT");
printf("\n\tEnter No. ");
scanf("%d",&n);
arm=n;
while(n!=0)
{
power++;
n/=10;
}
printf("\nNo. of Digits=%d",power);
n=arm; /*with the above while loop n becomes zero, so again assign arm to n*/
while(n!=0)
{
r=n%10;
sum+=pow(r,power);
n=n/10;
}
if(sum==arm)
printf("\n\n\t%d IS AN ARMSTRONG NO.",arm);
else
printf("\n\n\t%d IS NOT AN ARMSTRONG NO.", arm);
return 0;
}

PROGRAM TO CHECK A NUMBER ARMSTRONG OR NOT


Enter No. 9474
No. of Digits=4
9474 IS AN ARMSTRONG NO.
One more output:
Enter No. 001
No. of Digits=1
1 IS AN ARMSTRONG NO.
=====================================================================
PPS (R18) UNIT 1 Page | 83

/* PROGRAM TO CHECK WHETHER THE NO.IS PERFECT OR NOT


EXAMPLE PERFECT NO.S 6 28 496 8128*/
#include<stdio.h>
int main()
{
long int n,i=1,perfect=0;

printf("\nEnter a number: ");


scanf("%ld",&n);
while(i<n)
{
if(n%i==0)
perfect+=i;
i++;
}
if(perfect==n)
printf("\n%ld is perfect",n);
else
printf("\n%ld is not perfect",n);
return 0;
}
Enter a number: 28
28 is perfect
=====================================================================
/*PROGRAM TO PRINT NUMBER IN THE FORMAT RIGHT ANGLED SHAPE*/
main()
{
int i,j,n;

printf("\n\n\tPROGRAM TO PRINT 1 'S IN TRIANGLE");


printf("\n\n\t ENTER NO. OF ROWS: ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{ for(j=1; j<=i; j++)
{printf("1"); }
printf("\n");
}
return 0;
}
PROGRAM TO PRINT 1 'S IN TRIANGLE
ENTER NO. OF ROWS: 6
1
11
111
1111
11111
111111
PPS (R18) UNIT 1 Page | 84

/*PROGRAM TO PRINT STARS IN THE FORMAT RIGHT ANGLED SHAPE*/


int main()
{
int i,j,n;

printf("\n\n\tPROGRAM TO PRINT * 'S IN TRIANGLE");


printf("\n\n\t ENTER NO. OF ROWS: ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf(" *");
}
printf("\n");
}
}
PROGRAM TO PRINT 1 'S IN TRIANGLE
ENTER NO. OF ROWS: 6
*
* *
* * *
* * * *
* * * * *
* * * * * *
=====================================================================
/*PROGRAM TO PRINT NUMBER IN THE FORMAT RIGHT ANGLED SHAPE-
VERSION 2 */
main()
{
int i,s=0,n;

printf("\n\n\n\t");
printf("\n\n\tPROGRAM TO PRINT 1 'S IN TRIANGLE");
printf("\n\n\tENTER NO. OF ROWS:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
s=s*10+1;
printf("\t%d\n",s);
}
return 0;
return 0;
}
PPS (R18) UNIT 1 Page | 85

/*THIS LOGIC WORKS ONLY FOR 5 ROWS AS WE TOOK VARIABE s AS JUST


INT(IT’S MAX RANGE IS 32767)*/
OUTPUT:
PROGRAM TO PRINT 1 'S IN TRIANGLE
ENTER NO. OF ROWS: 6
1
11
111
1111
=====================================================================
/*PROGRAM TO PRINT NUMBERS IN THE RIGHT ANGLED SHAPE FORMAT*/
main()
{
int i,j,n;

printf("\n\n\tPROGRAM TO PRINT NUMBERS IN TRIANGLE");


printf("\n\n\t ENTER NO. OF ROWS: ");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
for(j=1; j<=i; j++)
{
printf("%d",j);
}
printf("\n");
}
return 0;
return 0;
}
OUTPUT:
PROGRAM TO PRINT NUMBERS IN TRIANGLE
ENTER NO. OF ROWS: 6
1
12
123
1234
12345
123456
=====================================================================
/*PROGRAM TO PRINT NUMBERS IN THE RIGHT ANGLED SHAPE FORMAT*/
/*THIS LOGIC WORKS ONLY FOR 5 ROWS IF WE TAKE JUST INT*/
main()
{
int i,s=0,n;
PPS (R18) UNIT 1 Page | 86

printf("\n\n\n\t");
printf("\n\n\tENTER NO. OF ROWS:");
scanf("%d",&n);
for(i=1; i<=n; i++)
{
s=s*10+1;
printf("\t%d\n",s);
}
return 0;
}
PROGRAM TO PRINT NUMBERS IN TRIANGLE
ENTER NO. OF ROWS: 6
1
12
123
1234
12345
=====================================================================
/* PROGRAM TO PRINT NUMBERS IN THE FORMAT
1
2 3
4 5 6
7 8 9 10 */
#include<stdio.h>
int main()
{
inti,j,k,n=1;

printf("\n\n\n\t PROGRAM TO PRINT NUMBERS IN TRIANGLE FORMAT\n");


for( i=1 ; i<5 ; i++)
{
for( k=4-i ; k>0 ; k--)
{
printf(" ");
}
for( j=1 ; j<=i ; j++)
{
printf(" %d",n);
n++;
}
printf("\n");
}
return 0;
}
PPS (R18) UNIT 1 Page | 87

OUTPUT:
PROGRAM TO PRINT NUMBERS IN TRIANGLE FORMAT
1
2 3
4 5 6
7 8 9 10
=====================================================================
/* PROGRAM TO PRINT STARS THE FORMAT
*
* *
* * *
* * * *
* * * * * */

#include<stdio.h>
int main()
{
int i,j,k,n=1;

printf("\n\n\n\t PROGRAM TO PRINT NUMBERS IN TRIANGLE FORMAT\n");


for( i=1 ; i<6 ; i++)
{
for( k=6-i ; k>0 ; k--)
{
printf(" ");
}
for( j=1 ; j<=i ; j++)
{
printf(" *");
n++;
}
printf("\n");
}
return 0;
}OUTPUT:
PROGRAM TO PRINT NUMBERS IN TRIANGLE FORMAT
*
* *
* * *
* * * *
* * * * *
=====================================================================
PPS (R18) UNIT 1 Page | 88

/*PROGRAM TO PRINT PASCAL TRIANGE UP TO DESIRED ROWS*/


#include<stdio.h>
main()
{
int b,p,q,r,x;
printf("\n\n\t\tPROGRAM TO PRINT PASCAL TRIANGE UP TO DESIRED
ROWS");
printf("\n\n\t\tENTER THE NO. OF ROWS: ");
scanf("%d",&r);
printf("\n\n\t\tPASTRIANGLE\n\n");
b=1; q=0;
while(q<r)
{
for(p=30-3*q;p>0;p--)
printf(" ");
for(x=0;x<=q;x++)
{
if(x==0||q==0)
b=1;
else
b=(b*(q-x+1)/x);
printf("%6d",b);
}
printf("\n");
q++;

}
return 0;
return 0;
}
OUTPUT:
PROGRAM TO PRINT PASCAL TRIANGE UP TO DESIRED ROWS
ENTER THE NO. OF ROWS: 9
PASCAL TRIANGLE
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
=====================================================================
PPS (R18) UNIT 1 Page | 85

/*PROGRAM TO FIND THE EXP X*/

#include<stdio.h>
#include<math.h>
int main()
{
float pow = 1.0,nr=1.0,dr = 1.0,x,sum=1.0;
int i = 1,n;

printf("\n\n\t\t===================================================");
printf("\n\n\t\tPROGRAM TO FIND THE SUM OF THE EXP X SERIES ");
printf("\n\n\t\t====================================================");
printf("\n\n\t\t ENTER THE x: ");
scanf("%f",&x);
printf("\n\n\t\t ENTER THE NUMBER OF TERMS: ");
scanf("%d",&n);
while(i<n)
{
dr*=pow;
nr=nr*x;
sum = sum+(nr/dr);
pow++;
i++;
}
printf("\n\n\t\t THE SUM OF EXP X SERIES IS..: %0.6f",sum);
printf("\n\n\t\t=============================================");
return 0;
}
OUTPUT:
==============================================
PROGRAM TO FIND THE SUM OF THE EXP X SERIES
==============================================
ENTER THE x: 1

ENTER THE NUMBER OF TERMS: 20

THE SUM OF EXP X SERIES IS..: 2.718282


===============================================

=====================================================================
PPS (R18) UNIT 1 Page | 89

/*PROGRAM TO FIND THE SUM OF THE SINE SERIES*/

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

int main()
{
float pwr=1.0,nr,dr=1.0,x1,sum,x;
int i=2,n,s=1;

printf("\n\n\t==============================================");
printf("\n\n\t PROGRAM TO FIND THE SUM OF THE SINE SERIES ");
printf("\n\n\t==============================================");

printf("\n\n\tENTER THE ANGE: ");


scanf("%f",&x);
x1 = 3.142*(x/180.0);
nr=x1;
sum=x1;
printf("\n\n\tENTER THE NO. OF TERMS: ");
scanf("%d",&n);
while(i<=n)
{
pwr+=2;
dr*=pwr*(pwr-1);
nr=nr*x1*x1;
s*=-1;
sum+=(nr/dr)*s;
i++;
}
printf("\n\n\tTHE SUM OF SINE SERIES IS : %f",sum);
printf("\n\n\t==============================================");
getch ();
}
OUTPUT:
========================================================
PROGRAM TO FIND THE SUM OF THE SINE SERIES
========================================================
ENTER THE ANGE: 90
ENTER THE NO. OF TERMS: 10
THE SUM OF SINE SERIES IS : 1.00000
=========================================================
PPS (R18) UNIT 1 Page | 90

ADDITIONAL PROGRAMS
/*PROGRAM TO PRINT THE SUMOF COSINE SERIES*/

#include<stdio.h>
#include<math.h>
int main()
{
float pow = 2.0,nr,x,dr = 1.0,x1,sum;
int i = 1,n,s = -1;

printf("\n\n\t==============================================");
printf("\n\n\t PROGRAM TO FIND THE SUM OF THE COS SERIES ");
printf("\n\n\t==============================================");
printf("\n\n\t ENTER THE ANGLE: ");
scanf("%f",&x);
x1 = 3.142*(x/180.0);
sum = 1.0;
nr = x1*x1;
printf("\n\n\t ENTER THE NUMBER OF TERMS: ");
scanf("%d",&n);
while(i<=n)
{
dr = dr*pow*(pow-1.0);
sum = sum+(nr/(dr*s));
s = s*(-1);
pow = pow+2.0;
nr =nr*x1*x1;
i++;
}
printf("\n\n\t THE SUM OF THE COS SERIES IS: %0.6f",sum);
printf("\n\n\t==============================================");
return 0;
}
OUTPUT:
========================================================
PROGRAM TO FIND THE SUM OF THE COS SERIES
========================================================
ENTER THE ANGLE: 90
ENTER THE NUMBER OF TERMS: 10
THE SUM OF THE COS SERIES IS: -0.000204
========================================================
=====================================================================
PPS (R18) UNIT 1 Page | 91

/* PROGRAM PRINT ALL THE PRIME NUMBRS BELOW N, N SUPPLIED BY THE


USER */
#include <stdio.h>

int main()
{
int n,i,j,check;

printf("\n\n\t========================================");
printf("\n\tPRIME NO. SERIES");
printf("\n\t========================================");

printf("\n\n\n\tENTER THE VALUE OF N: ");


scanf("%d",&n);
printf("\n\n\tTHE PRIME NO. SERIES B/W 1 TO %d : \n\n",n);

for(i = 2; i <= n; i++)


{
check = 0;
/*THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.*/

for(j = i-1; j > 1 ; j--)


if(i%j == 0)
{
check++; /* INCREMENT CHECK IF NO. IS NOT A PRIME NO.*/
break;
}
if(check == 0)
printf("\t%d\t",i);
}
return 0;
}

OUTPUT:
========================================
PRIME NO. SERIES
========================================
ENTER THE VALUE OF N: 100
THE PRIME NO. SERIES B/W 1 TO 100 :

2 3 5 7 11 13 17 19 23 29 31 37 41
43 47 53 59 61 67 71 73 79 83 89 97
=====================================================================
PPS (R18) UNIT 1 Page | 92

/*PROGRAM TO PRINT THE PERFECT NUMBERS BELOW GIVEN RANGE*/


#include<stdio.h>
int main()
{
int i,n,s;

printf("\n\t=======================================================");
printf(" \n\tPROGRAM TO PRINT THE PERFECT NUMBERS BELOW N, N ENTERED BY
THE USER");
printf("\n\t=======================================================");
for(n=1;n<=32766;n++)
{
i=1;s=0;
while(i<n)
{
if(n%i==0)
s=s+i; i++;
}
if(s==n)
{
i=1;
printf("\n\n\t%d is a perfect number",n);
printf("\n\tFactors of %d are :\n\t",n);
while(i<n)
{
if(n%i==0)
printf("%d\t",i);
i++;
}
}
}
return 0;
}
OUTPUT:
======================================================================
PROGRAM TO PRINT THE PERFECT NUMBERS BELOW N, N ENTERED BY THE USER
=====================================================================
6 is a perfect number
Factors of 6 are :
1 2 3
28 is a perfect number
Factors of 28 are :
1 2 4 7 14
PPS (R18) UNIT 1 Page | 93

496 is a perfect number


Factors of 496 are :
1 2 4 8 16 31 62 124 248
8128 is a perfect number
Factors of 8128 are :
1 2 4 8 16 32 64 127 254 508
1016 2032 4064
=====================================================================
/*PROGRAM TO FIND THE GCD/HCF & LCM OF TWO NUMBERS-VERSION 2 */
#include<stdio.h>
int main()
{
int x,y,m,i;

printf("\n\n\t===========================================");
printf("\n\n\tPROGRAM TO FIND THE GCD/HCF OF TWO NUMBERS");
printf("\n\n\t===========================================");
printf("\n\n\tENTER TWO NUMBERS: ");
scanf("%d%d",&x,&y);
m=x;
for(i=m;i>=1;i--)
{
if(x%i==0&&y%i==0)
{
printf("\n\n\tGCD/HCF of two numbers is : %d",i) ;
break;
}
}
return 0;
}

OUTPUT:
=============================================
PROGRAM TO FIND THE GCD/HCF OF TWO NUMBERS
=============================================
ENTER TWO NUMBERS: 248 1024
GCD/HCF of two numbers is : 8
====================================================================
PPS (R18) UNIT 1 Page | 94

/* PROGRAM TO FIND THE LCM OF TWO NUMBERS*/


#include<stdio.h>
#include<conio.h>
int main()
{
int x,y,i;

printf("\n\t==============================================");
printf("\n\t\tPROGRAM TO FIND THE LCM OF TWO NUMBERS");
printf("\n\t==============================================");
printf("\n\n\tEnter Two Numbers = ");
scanf("%d%d",&x,&y);
for(i=1;;i++)
{
if(i%x==0&&i%y==0)
{
printf("\n\n\tLCM is %d\n",i);
printf("\n\n\t===========================================");
break;
}
}
return 0;
}
OUTPUT:
===================================================
PROGRAM TO FIND THE LCM OF TWO NUMBERS
===================================================
Enter Two Numbers = 48 64
LCM is 192
===================================================
PPS (R18) UNIT 1 Page | 95

SUMMARY OF ALL PROGRAMS FROM UNIT 1


1) PROGRAM TO PRINT A MESSAGE
2) PROGRAM TO FIND THE AREA OF A TRIANGLE
3) PROGRAM TO FIND THE AREA OF A CIRCLE
4) PROGRAM TO FIND THE AVERAGE OF 3 NUMBERS
5) PROGRAM TO FIND THE SIMPLE INTEREST
6) PROGRAM TO SWAP THE 2 NO.S USING 3 VARIABLES
7) PROGRAM TO SWAP THE 2 NO.S USING 2 VARIABLES
8) WRITE A PROGRAM TO CONVERT THE CELSIUS TEMPERATURE INTO
FAHRENHEIT TEMPERATURE.
9) WRITE A PROGRAM TO CONVERT THE FAHRENHEIT TEMPERATURE INTO
CELSIUS TEMPERATURE.
10) PROGRAM TO ILLUSTRATE ABOUT ASCII CODES
11) PROGRAM TO ILLUSTRATE THE DECIMAL OCTAL HEXA DECIMAL INTS
12) PROGRAM TO ILLUSTRATE ABOUT THE TYPEDEF
13) PROGRAM TO ILLUSTRATE THE USERE DEFINED DATATYPE ENUM
14) PROGRAM TO ILLUSTRATE ABOUT ENUM
15) PROGRAM TO ILLUSTRATE THE CONDITIONAL OPERATORS USING THE
FOLLOWING DATA
i). A mathematical function is defined as follows
y =1.5x+3 if x<=2
=2x+5 if x>2
(Hint: y= (x>2)? (2x+5):(1.5x+3);)
ii). Let the salary of an sales executive be the no. of products sold per day and
is constrained as
Salary = 4*N+100 if x < 40
= 300 if x = 40
= 4*N+200 if x > 40
16) PROGRAM TO ILLUSTRATE THE INCREMENT & DECREMENT OPERATORS
17) PROGRAM TO CHECK THE BITWISE OPERATORS
18) PROGAM TO ILLUSTRATE ABOUT THE SIZE OF DATA TYPES
19) PROGRAM TO ILLUSTRATE ABOUT THE OPERATOR'S PRECEDENCE &
ASSOCIATIVITY
20) PROGRAM TO FIND THE BIGGEST OF TWO NUMBERS USING SIMPLE IF
21) PROGRAM TO FIND THE BIGGEST OF TWO NO.S USING IF…ELSE
22) PROGRAM TO FIND THE BIGGEST OF 3 NUMBERS
23) PROGRAM TO CHECK WHETHER THE NUMBER IS POSITIVE OR NEAETIVE
24) PROGRAM TO CHECK WHETHER THE NUMBER IS EVEN OR ODD
25) PROGRAM TO PRINT THE GRADE OF A STUDENT
26) PROGRAM TO CALCULATE THE GROSS SALARY OF AN EMPLOYEE AS FOLLOWS
PPS (R18) UNIT 1 Page | 96

BASIC SALARY DA HRA CONVEYENCE


>=5000 110% 20% 500
>=3000 &<5000 100% 15% 400
<3000 85% 10% 300
27) PROGRAM TO FIND THE NATURE AND ROOTS OF A QUADRATIC EQUATION
ax2+bx+c=0
28) PROGRAM TO ILLUSTRATE ABOUT SWITCH WITH SIMPLE PROGRAM
29) PROGRAM TO PERFORM THE ARITHMATIC OPERATIONS BASED ON THE USER'S
CHOICE WITH LABELS AND LOCAL VARIABLES – VERSION 2
30) PROGRAM TO FIND THE CELSICUS/FAHRENHEIT TEMPERATURE(switch)
31) PROGRAM TO ILLUSTRATE ABOUT GOTO STATEMENT
32) PROGRAM TO ILLUSTRATE ABOUT THE BREAK STATEMENT
33) PROGRAM TO ILLUSTRATE ABOUT THE CONTINUE STATEMENT IN C
34) PROGRAM TO FIND THE AVERAGE OF N NUMBERS USING WHILE
35) PROGRAM TO FIND THE AVERAGE OF N NUMBERS USING DO-WHILE
36) PROGRAM TO CALCULATE THE AVERAGE OF N NUMBERS.
37) PROGRAM TO PRINT THE FACTORIAL OF A NO.
38) PROGRAM TO FIND THE PERCENTAGE OF A STUDENT
39) PROGRAM TO FIND THE SUM AND AVERAGE OF N NUMBERS ENTERED BY THE
USER
40) PROGRAM TO FIND THE SUM OF THE DIGITS OF THE GIVEN NUMBER
41) PROGRAM TO FIND THE SUM OF THE EVEN AND ODD DIGITS OF THE GIVEN
NUMBER
42) PROGRAM TO FIND X POWER N
43) PROGRAM TO FIND THE PRODUCT OF N NUMBERS ENTERED BY THE USER
44) PROGRAM TO PRINT THE MULTIPLICATION TABLE
45) PROGRAM TO PRINT THE FIRST N FIBONACCI NUMBERS
46) PROGRAM TO FIND THE GCD/HCF and LCM OF TWO NUMBERS
47) PROGRAM TO PRINT THE REVERS OF A GIVEN NUMBER
48) PROGRAM TO PRINT WHETHER THE NO. IS PALINDROME OR NOT
49) PROGRAM TO CHECK WHETHER THE NO. IS PRIME OR NOT
50) PROGRAM TO CHECK WHETHER THE NO.IS ARMSTRONG OR NOT
( EXAMPLE ARMSTRONG NO.S
1 2 3 ... 9 153 370 371 407 1634 8208 9474 54748 )
51) PROGRAM TO CHECK WHETHER THE NO.IS PERFECT OR NOT
(EXAMPLE PERFECT NO.S 6 28 496 8128).
PPS (R18) UNIT 1 Page | 97

52) PROGRAM TO PRINT NUMBER IN


THE FORMAT RIGHT ANGLED
SHAPE
1
11
111
1111
11111
53) PROGRAM TO PRINT NUMBERS IN
THE RIGHT ANGLED SHAPE
FORMAT
1
12
123
1234
12345

54) PROGRAM TO PRINT NUMBERS IN


THE FORMAT
1
2 3
4 5 6
7 8 9 10
55)PROGRAM TO PRINT STARS THE
FORMAT
*
* *
* * *
* * * *
* * * * *
56) PROGRAM TO PRINT STARS THE
FORMAT
*
*
* *
* * *
* * * *
PPS (R18) UNIT 1 Page | 98

57) PROGRAM TO PRINT PASCAL TRIANGE UP TO DESIRED ROWS


PASCAL TRIANGLE
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
58) PROGRAM TO FIND THE EXP X
59) PROGRAM TO FIND THE SUM OF THE SINE SERIES
60) PROGRAM TO PRINT THE SUMOF COSINE SERIES
61) PROGRAM PRINT ALL THE PRIME NUMBRS BELOW N, N SUPPLIED BY THE USER
62) PROGRAM TO PRINT THE PERFECT NUMBERS BELOW GIVEN RANGE
63) PROGRAM TO FIND THE GCD/HCF & LCM OF TWO NUMBERS.
=====================================================================

List of Maclaurin series of some common functions (for the advanced learners)
Exponential function:

Natural logarithm:

Finite geometric series:

Infinite geometric series:

Variants of the infinite geometric series:


PPS (R18) UNIT 1 Page | 99

Square root:

Binomial series (includes the square root for α = 1/2 and the infinite geometric series for α = −1):

with generalized binomial coefficients

Trigonometric functions:

where the Bs are Bernoulli numbers.


PPS (R18) UNIT 1 Page | 100

Hyperbolic functions:

Lambert's W function:

The numbers Bk appearing in the summation expansions of tan(x) and tanh(x) are the Bernoulli
numbers. The Ek in the expansion of sec(x) are Euler numbers.

===========================ALL THE BEST ============================


PPS (R18) UNIT 1 Page | 101

ASSIGNMENT / UNIVERSITY QUESTIONS


June-2012, JUN2011 and MAY,DEC 2010 (4 sets from each year)
SECTION-1
MAY 2012
1) a) Explain and specify the interactions between various components that support the basic
functionality of a computer.
b) Draw the flow chart to check whether a given number is perfect or not.
c) Describe various categories of computing environments.

JUN 2011& MAY&DEC 2010


2) Define Algorithm? What are the characteristics that any algorithm should satisfy?
3) What is an algorithm? Write an algorithm to find out if a given number is a prime.
4) Explain and specify the interactions between various components that support the basic
functionality of a computer?
5) Differentiate between compiler and interpreter?
6) Draw a flow chart to read ten positive integers and print how many are multiples of 7.
7) Write an algorithm to find out all the factors of a given positive integer.
8) What is a flow chart? Draw a flow chart to read ten integers and print the sum of squares of
all ten values.
9) Explain the functions of the following:
i. Preprocessor ii. Compiler iii. Linker.
10) Draw a flowchart for finding maximum of given three integers?
11) Draw a flowchart to find maximum and minimum of the given three input numbers.
12) List the activities involved in each phase of waterfall system development lifecycle model?
13) Given the 3 sides of triangle a, b and c as input, Draw a flowchart to test whether it is
isosceles, equilateral or not. It should also validate whether the input forms a triangle or not.
(Ex. 10, 3, 3 is not a triangle)
14) A utility company charges its customers based on their monthly utilization in terms of units
as follows:
Description charge
First 100 units Rs.10 per unit
Next 200 units Rs. 9 per unit
Next 200 units Rs.8 per unit
Next units Rs.7 per unit
Write flowchart that reads monthly units of a customer and output the charge amount
15) List and explain the functions of various parts of computer hardware.
16) JNTU university gives grades based on the percentage of marks obtained in the examinations
as follows:
Percentage of marks Grade
75 and above Distinction
60 and above but below 75 First
50 and above but below 60 Second
40 and above but below 50 Third
below 40 Fail
Write a flowchart that inputs the percentage marks and output the division
PPS (R18) UNIT 1 Page | 102

SECTION-2
PART A
Write minimal C expressions for the following:
A1) 2x4 + 3x3 - 4x2 + 7x -10
A2) x3 - 4x2 + 7x -12
A3) 5a4 +3a3-4a2+6a+12
A4) i). abcbccaab−− ii). 1235abbc+ iii). 2234abccab--
A5) Digit at the 10's place of the given positive integer x
(for example, digit at the 10's place in 3458 is 5)
A6) Maximum of the values of three variables a, b and c
A7) Minimum of the values of three variables a, b and c.
A8) If a > b then the value of expression is a-b, otherwise b-a
A9) Add x to y, and then decrement x
A10) Increment x, and then add to z
A11) True if the given positive integer x is odd, false otherwise
A12) True if the given positive integer x is even and is also a multiple of 7, false
Otherwise.
A13) True if the given character variable c represents a numeral (that is '0'...'9'),
false otherwise.
A14) True if the given positive integer x is a multiple of both 17 and 11, false
otherwise.
A15) True if 25 > a ≥ 10, false otherwise
A16) True if 5 <x < 10, otherwise false
A17) True if x is exactly divisible by 5 but not divisible by 3, otherwise false.
A18) True if 5 <= a <= 10, false otherwise
A19) True if the value of character variable c is in uppercase, otherwise false
A20) Absolute value of (a-b)
A21) Absolute value of variable x.
A22) True if x/y >3 without zero divide, false otherwise
A23) If x<y then -1 else if x = = y then 0 else 1(use ternary operator)
A24) Subtract x from y and then increment x.
A25) Remainder when unsigned integer variable x is divided by 8, using bitwise
operators.
A26) Divide the integer variable x by 16 using bit-wise operators
NOTE:
 FOR THE ABOVE QUESTIONS IN SECTION A, NO NEED TO WRITE THE
ENTIRE PROGRAM EVEN IN THE EXAM JUST WRITE THE LOGIC WITH C
SYNTAX.
PPS (R18) UNIT 1 Page | 103

PART B
B1) What is the difference between the following c-words?
i) amount and “amount” ii) 200 and 200.0
B2) What is the difference between the following C-words?
i) 253 and 0253 ii) „r‟ and „\r‟
B3) What is the difference between the following C-words?
i) count and int ii) 526 and “526”
B4) What is the difference between the following C-words?
i) 5 and „5‟ ii) if and ++

PART C
C1) An integer is divisible by 9 if the sum of its digit is also divisible by 9. Write
a C program that prompts the user to input an integer. The program should
then output the number and a message stating whether the number is divisible
by 9.
(June2012)
C2) What is type conversion? Explain briefly about implicit and explicit type of
conversions. (June2012)
C3) Write C- language program that reads a number from input and determine
whether it is a prime or not.
C4) Write a complete C Program to print all the prime numbers between 1 and n.
Where „n‟ is the value supplied by the user.
C5) Write C-program for determining whether the given integer at input is perfect
number or not.
C6) Write a C-program that reads the given n observations at input and computes
average of n observations and find the number of observations above average
value
C7) Write a complete C program that reads a value in the range 1 to 12 and print
the name of that month and the next month: Print error for any other input
value. (For example, print “May followed by June” if the input is 5. Note that
December is followed by January).
C8) Write C-program that reverses the decimal digits of integer value at input.
For example, for input 5379, the program need to output 9735
C9) Write a complete C Program to read ten integers and find:
(i) The number of even integers and their sum, and
(ii) The number of odd integers and their sum.
C10) Explain the structure of a C program?
C11) List the basic data types, their sizes and range of values supported by „C‟
language?
PPS (R18) UNIT 1 Page | 104

C12) Describe the purpose of commonly used conversion characters in scanf()


function?
C13) Explain the only ternary operator available in „C‟ with illustrative example?
C14) Differentiate between if-else-if ladder and switch statement?
C15) What is the implicit type conversion hierarchy that is applied while evaluating
expressions?
C16) What do you mean by operator precedence and Associativity? How one can
override the precedence defined by C language? Give illustrative examples?
C17) What is an identifier? What are the naming rules for identifiers in C?
C18) What are the bitwise operators in C? Explain the same with examples.
C19) List different categories of C operators based on their functionality? Give
examples?

Wait and See:


Questions Specified Below are mandatory for the Assignment. Remaining left for your
interest. But you should be able to answer them.
 The Questions 1, 2, 4, 5, 6, 13, 16 (In Italics) from Section 1
 Any 15 Questions from Part-A in Section 2
 All 4 Question from Part-B in Section 2
 Any 10 Questions from Part-C in Section 2

Note: The students have to submit the above assignment within 10 days.

* * *
PPS (R18) UNIT 1 Page | 105

PROGRAMS FOR RECORD


LAB 1
1.1) PROGRAM TO ILLUSTRATE ABOUT ASCII CODES
1.2) PROGRAM TO ILLUSTRATE THE INCREMENT & DECREMENT OPERATORS
1.3) PROGRAM TO CHECK THE BITWISE OPERATORS

LAB2
2.1) PROGRAM TO CALCULATE THE GROSS SALARY OF AN EMPLOYEE AS
FOLLOWS
BASIC SALARY DA HRA CONVEYENCE
>=5000 110% 20% 500
>=3000 &<5000 100% 15% 400
<3000 85% 10% 300
2.2) PROGRAM TO FIND THE NATURE AND ROOTS OF A QUADRATIC EQUATION
ax2+bx+c=0.

LAB 3
3.1) PROGRAM TO FIND THE SUM OF THE EVEN AND ODD DIGITS OF THE GIVEN
NUMBER
3.2) PROGRAM TO PRINT THE FIRST N FIBONACCI NUMBERS
3.3) PROGRAM TO FIND THE GCD/HCF and LCM OF TWO NUMBERS

LAB 4
4.1) PROGRAM TO CHECK WHETHER THE NO. IS PRIME OR NOT
4.2) PROGRAM TO CHECK WHETHER THE NO.IS ARMSTRONG OR NOT
( EXAMPLE ARMSTRONG NO.S
0 1 2 3 ... 9 153 370 371 407 1634 8208 9474 54748 )
4.3) PROGRAM TO CHECK WHETHER THE NO.IS PERFECT OR NOT
(EXAMPLE PERFECT NO.S 6 28 496 8128).

LAB 5
5.1) PROGRAM TO PRINT NUMBERS IN THE FORMAT
1
2 3
4 5 6
7 8 9 10
5.2) PROGRAM TO FIND THE EXP X
5.3) PROGRAM TO FIND THE SUM OF THE SINE SERIES
PPS (R18) UNIT 1 Page | 106

NOTE:
 Flow chart is mandatory for each and every program in the record; however for
LAB 1 flow charts are not required.
 Write the dates, Roll No and page numbers on each and every record sheet.
 Draw the flow chart and write the output of the program on the left hand side
and write the program on the right hand side of the record sheet.
 Draw the flow charts neatly with pencil only.
 Write index also with the dates in which you have done the programs.(later)
 You can enquire for the old records for the reference only from your lab
programmer, otherwise your faculty.

==================================================================
PPS (R18) UNIT 1 Page | 107

I BTECH-CPDS-MID1-UNIT1:: 2009-10
1. Which of the following is not an input device [ ]
a) Plotter b) scanner c) keyboard d) mouse
2. How many times the body of the following loop executed?
x=5; y=50; while (y! =0) {y/=x ;} [ ]
a) 4 b) 1 c) 3 d) 2
3. The parallelogram is used to represent type of statements in flow charts [ ]
a) input/output b) Functions c) decision d) processing
4. Which of the following is not a translator program [ ]
a) Linker b) assembler c) interpreter d) compiler
5. Which of following loop executes the body of the loop at least once [ ]
a) while b) for c)do..while d) compiler
6. The hardware along with the read-only software that resides on this hardware is
combinly called as
7. In flowcharts, decisions are represented by using symbol
8. acts as an interface between the computer hardware and user of the computer.
9. In menu driven programs loop statement is used
KEY
1.B 2.C 3.A 4.B 5.C 6.ROM 7. RHOMBOS 8. Operating System
9. SWITCH
I BTECH-CPDS-MID1-UNIT1::2010-11
1. What will be sum of the binary numbers 1111 and 1101 [ ]
a) 101000 b) 100010 c) 11110 d) 11100
2. Which one of the following is known as the language of the computer [ ]
a) Programming Language b) High Level Language
c) Machine Language d) Assembly Language
3. What type of errors are checked during compilation [ ]
a) Logical errors b) divide by zero errors c) run-time errors d) syntax errors
4. Which one of the following numeric value is used to represent base of the binary number [ ]
a) 8 b) 10 c) 2 d) 16
5. What will be the binary value of B [ ]
a) 1001 b) 1011 c) 1100 d) 1101
6. Which of the following is not a translator program [ ]
a) Linker b) Assembler c) Compiler d) Interpreter
7. The process of repeating a group of statements in an algorithm is known as
8. is very similar to the while loop except that the test occurs at the end of the loop
body.
9. ALU stands for
10. translates the high level language source code into low-level language.
11. The output of the assembler in the form of sequence of 0’s and 1’s is called

KEY
1.A 2.C 3.D 4.C 5.B 6.A 7.LOOP 8.DO-WHILE 9.Arithmatic
Logic Unit 10. Translator 11.Binary Code or Machine Code.
PPS (R18) UNIT 1 Page | 108

I BTECH-CPDS-MID1-UNIT1::2011-12
1. Which one of the following is not a translator program [ ]
(A)Assembler (B) Interpreter (C) Linker (D) Compiler
2. What will be sum of the binary numbers 1111 and 11001 [ ]
(A) 111100 (B) 100010 (C) 11110 (D) 101000
3. Which one of the following is known as the language of the computer [ ]
(A) Programming language (B) Machine language
(C) High level language (D) Assembly level language
4. is used to compile your c program
5. The while loop repeats a statement until the test at the top proves
6. The transfers control to a statement within its body
7. The process of repeating a group of statements in an algorithm is known as
8. Extend the term CPU
9. Monitor, keyboard, mouse and printers are
KEY
1.C 2.D 3.B 4. Compiler 5. Fails6. Conditional Statement Of A Loop
7. LOOP 8. Central Processing Unit 9. Input and Output Devices
I BTECH-CPDS-MID1-UNIT1 ::2009-10
1. Which of the following is the correct order of operators for the evaluation for the expression
z = x + y * z/4 % 2-1 [ ]
a)* / % + - = b) - % ? * + = c) / * % - + = d) * / % - + =
2. How many times the body of the following loop executed? x=5; y=50; while(y! = 0) {y/=x;}[ ]
a) 4 b) 1 c) 3 d) 2
3. Which of the following statement is syntactically correct [ ]
a) printf(“%d”, &a); b) scanf(“%d”, a); c) scanf(“%d”, #a); d) scanf(“%d”, &a);
4. Which of the following is the correct syntax of for loop [ ]
a) for(i=o, i<10, i++) b) for(i=0; i++; i<=10)
c) for(i=0; i<10; i++) d) for(i=0, i++, i<=10)
5. Which of the following loop executes the body of the loop at least once [ ]
a) while b) for c) do..while d) all of the above
6. Which of the following is used inside a loop to terminate the current iteration and start with the next
generation [ ]
a) break b) continue c) goto d) return
Fill in the Blanks
7. is the largest value that an unsigned short int type varible can store
8. logical operator is true only when both operands are true
9. The order of evaluation can be changed by using in an expression
10. A for loop with no test condition is called as loop
11. Execution of a C program begins at
12. loop in C is both counter controlled and pretest loop
13. In menu driven programs statement is used
KEY
1). A 2). C 3). D 4). C 5). C 6). B
7). 255 8). && 9). ( ) 10). Infinite 11). Main 12). For
13). Switch
=====================================================================
PPS (R18) UNIT 1 Page | 109

I BTECH-CPDS-MID1-UNIT1::2010-11
Choose the correct alternative:
1. What will be sum of the binary numbers 1111 and 1101 [ ]
a) 101000 b) 100010 c) 11110 d) 11100
2. Consider the following program segment. i=6720; j=4; [ ]
While ((i%j)==0)
{ i=i/j; j=j+1;
} then, On termination j will have the value
a) 4 b) 8 c) 9 d) 6720
3. Which of the following is/are syntactically correct [ ]
a)for( ); b)for(;); c)for(,); d)for(;;);
4. #include<stdio.h> [ ]
main( )
{
int i=1,j=2;
Switch(i)
{
Case 1: printf(“GOOD”);
break;
case j: printf(“BAD”);
break;
}
}
a) GOOD b) BAD c) GOOD BAD d)Compiler Error
5. What type of errors are checked during compilation [ ]
a) Logical errors b) divide by zero errors c) run-time errors d) syntax errors
6. Which one of the following numeric value is used to represent base of the binary number[ ]
a) 8 b) 10 c) 2 d) 16
7. What will be the binary value of B [ ]
a) 1001 b) 1011 c) 1100 d) 1101
8. The program fragment [ ]
int a=5,b=2;
printf(“%d”,a+++++b);
a) prints 7 b) prints 8 c) prints 9 d) none of the above

Fill in the Blanks


9. The # symbol is known as
10. are identifiers reserved by the C language for special use
11. The of an operator gives the order in which operators are applied in expression
12. is very similar to the while loop except that the test occurs at the end of the loop body.
13. The size of long double variable is .
14. The of an operator gives the order in which expressions involving operators of the
same precedence are evaluated.
15. The output of the assembler in the form of sequence of 0‟s and 1‟s is called .
PPS (R18) UNIT 1 Page | 110

KEY
1)D 2) C 3)D 4) D 5) D 6) C 7) B 8) D
9) preprocessor 10) keywords 11) precedence 12) do-while 13) 10
14) associativity 15) binary code or machine code
====================================================================
I BTECH-CPDS-MID1-UNIT1 ::2011-12
Choose the correct alternative
1. Which of the following is syntactically correct [ ]
(A) for(;); (B)for(); (C) for(,); (D) for(;;);
2. Find out the output for the following [ ]
#include<stdio.h>
main() { int c=--2; printf(“c=%d”,c); }
(A) -2 (B) 0 (C) 2 (D) None
3. Identify the result [ ]
vdoid main()
{ int i=5;
Printf(“%d”,i+++++i);}
(A) 5 (B) 6 (C) 10 (D) Compiler error
4. What will be the ASCll Octal value of A [ ]
(A) 100 (B) 101 (C)110 (D) 111
5. a<<1 is equal to [ ]
(A) multiplying by 2 (B) dividing by 2 (C) added 2 (D) None
6. Consider the following and find the output [ ]
Main()
{ int a=0;int b=30;char x=1;
If (a,b,x)
Printf(“Hello”);
}
(A) Compiler error (B) abxHello (C) Hello (D)None
7. What will be sum of the binary numbers 1111 and 11001 [ ]
(A) 111100 (B) 100010 (C) 11110 (D) 101000
8. Find the output [ ]
int main()
{char a[]=”12345\0”;
int i=strlen(a);
printf(“here in 3 %d\n”,++i);}
(A) here in 3 (B) here in 3 6 (C) 6 (D) 3

Fill in the Blanks


9. Short Integer size is bytes
10. The while loop repeats a statement until the test at the top proves
11. The statement transfers control to a statement within its body
PPS (R18) UNIT 1 Page | 111
12. The is a unconditional branching statement used to transfer control of the program
from one statement to another
13. The process of repeating a group of statements in an algorithm is known as

KEY
1). D 2). D 3). D4) .B5).A6). C7). D 8).B 9). 1byte 10). fails 11). Loop
12). goto 13). loop
PPS R18 UNIT 1 P a g e | 16

COMMANG LINE ARGUMENTS:


C allows a program to obtain the command line arguments provided when the executable is called,
using two optional parameters of "main()" named "argc (argument count)" and "argv (argument
vector)".

The "argc" variable gives the count of the number of command-line parameters provided to the
program. This count includes the name of the program itself, so it will always have a value of at least
one. The "argv" variable is a pointer to the first element of an array of strings, with each element
containing one of the command-line arguments

/*PROGRAM TO ILLUSTRATE ABOUT COMMAND LINE ARGUMENTS*/


void main(int argc, char* argv[])
{
int i;
clrscr();
printf("\nNo. of arguments are: %d",argc);
printf("\n Name of the Program is: %s",argv[0]);

for(i=0;i<argc;i++)
{
printf("\n Argument no. argv[%d] : %s",i,argv[i]);
}
getch();
}

Note:
Assume that this c program is save with name ”CMDLINE.C”
To execute this with arguments
Go to command prompt
c:\Users\Ravikrishna> cd\
c:> cd turboc2
c:\turboc2\>cd u3
c:\turboc2\u3> cmdline How are You?
Then the output will be as follows
No. of arguments are: 4
Name of the Program is: C:\TURBOC2\U3\CMDLINE.EXE
Argument no. argv[0] : C:\TURBOC2\U3\CMDLINE.EXE
Argument no. argv[1] : How
Argument no. argv[2] : are
Argument no. argv[3] : you?
SCOPE:
The place where a variable has to be declared.
It is of two types.
 Local scope
 Global scope

STORAGE CLASSES
Along with a data type of a variable, we can also use other keywords called as
“storage classes”.
 Using storage classes, we can determine the scope, visibility, and life time of
variables

VISIBILITY:
The area up to which a variable can be accessed.
It can be up to a block or a function or entire program.

LIFETIME:
It is the duration of time of a variable exists in memory.

Storage classes are of 4 types:


 Automatic Variables.
 External Variables.
 Static Variables.
 Register Variables.
PPS (R18) UNIT 1 P a g e | 13

1. AUTOMATIC VARIABLES:

 These are declared inside a function or a block.


 These variables will be created when a function execution begins and destroyed
when a function execution ends.

Scope : Local
Visibility : Inside a block (or) a function.
Life time : Till the fun execution ends.
Default value: Garbage value.
 An automatic variable can be declared using the keyword “auto”.
Ex: auto int a;
 If no storage class is specified for a variable then by default it will be treated as
automatic variable.

/*PROGRAM TO ILLUSTRATE /*PROGRAM TO ILLUSTRATE


ABOUT STORAGE CLASSES AUTO ABOUT STORAGE CLASSES AUTO
INT*/ INT*/
#include<stdio.h> #include<stdio.h>
void main() void main()
{ {
auto int i=1; auto int i=1;
{ clrscr();
{ {
{ int i=2;
printf("\ti=%d",i); {
} auto int i=3;
printf("\ti=%d",i); printf("\ti=%d",i);
} }
printf("\ti=%d",i); printf("\ti=%d",i);
} }
getch(); printf("\ti=%d",i);
} getch();
}
O/P: O/P:
i=1 i=1 i=1 i=3 i=2 i=1
PPS R18 UNIT I

2. EXTERNAL VAIRABLES:

These are the variables which are declared outside above all the functions.
 These are also known as global variables
 These variables can be accessed anywhere in the program and in other programs
also

Scope : Global
Visibility : Thorough out the program
Life time : Till the program execution ends
Default value : 0

/*PROGRAM TO ILLUSTRATE ABOUT STORAGE CLASSES EXTERN INT*/


#include<stdio.h>
int x=21;
void main()
{
extern int y;
clrscr();
printf("x=%d y=%d",x,y);
show();
getch();
}
int y=30;
show()
{
printf("\nIn show y=%d",y);
}
O/P:
x=21 y=30
In show y=30
 The external declaration tells the compiler that the variable is declared
somewhere else in the program.
 We can also use external declaration in the other programs to access the variable
.
PPS R18 UNIT I

/*PROGRAM TO ILLUSTRATE ABOUT STORAGE CLASSES EXTERN INT */


#include<stdio.h>
void main()
{
extern int a;
clrscr();
printf("\na=%d",a);
show();
getch();
}
int a;
show()
{
int b;
a++;
printf("\nIn show a=%d b=%d",a,b);
}
O/P:
a=0
Observe that In function show a=1 & b=523
Default value of a is 0 and value of b is garbage
PPS R18 UNIT I

STATIC VAIRABLES:

It is a variable which stores its value thorough out the program.


The variable can be declared as local or global.
A local static variable will be created and initialized only once when the fun is executed for the
first time.
Scope : Local
Visibility : Inside a block or a fun
Life time : Till the program execution ends
Default value : 0

NOTE: The difference between a global static variable and a normal global variable is
normal global variable is a global variable can be accessed in the other programs where as
global static variable can be accessed only in a single program, in which it is declared.
PPS R18 UNIT I
REGISTER VARIABLES:
 These variables will be stored in a special place called registers of CPU.
 As the size of the registers is limited, only few values can be stored.
 Some computers stores only integers and character variables in the registers.

Scope : Local
Visibility : Inside a block/a fun
Life time : Till the function execution ends.
Default value : Garbage value.

/*PROGRAM TO ILLUSTRATE ABOUT STORAGE CLASSES REGISTER INT*/


#include<stdio.h>
void main()
{
register int i=1;
clrscr();
printf("\nRegister int i=%d",i);
getch();
}
O/P:
Register int i=1

The following Table tells the summary of Storage Classes:

AUTO EXTERN STATIC REGISTER

SCOPE Local Global Local/Global Local

Thorough out Inside a block or a Inside a block / a


Inside a block (or)
VISIBILITY the program fun function
a function
Till the program Till the program
Till the function / Till the function /
LIFE TIME execution ends execution ends
block execution ends block execution ends.

DEFAULT Garbage value 0 0


Garbage value.
VALUE
Basics of Formatted Input/output in C

Concepts

 I/O is essentially done one character (or byte) at a time


 stream -- a sequence of characters flowing from one place to
another
o input stream: data flows from input device (keyboard, file,
etc) into memory
o output stream: data flows from memory to output device
(monitor, file, printer, etc)
 Standard I/O streams (with built-in meaning)
o stdin: standard input stream (default is keyboard)
o stdout: standard output stream (defaults to monitor)
o stderr: standard error stream
 stdio.h -- contains basic I/O functions
o scanf: reads from standard input (stdin)
o printf: writes to standard output (stdout)
 Formatted I/O -- refers to the conversion of data to and from a
stream of characters, for printing (or reading) in plain text
format

Conversion Specifiers
A conversion specifier is a symbol that is used as a placeholder in a formatting
string. For integer output (for example), %d is the specifier that holds the place
for integers.

Here are some commonly used conversion specifiers (not a comprehensive list):

%d int (signed decimal integer)


%u unsigned decimal integer
%f floating point values (fixed notation) - float, double
%s string
%c character
The basic format of a printf function call is:
printf (format_string, list_of_expressions);
where:

 format_string is the layout of what's being printed


 list_of_expressions is a comma-separated list of variables or expressions
yielding results to be inserted into the output

To read data in from standard input (keyboard), we call the scanf function. The
basic form of a call to scanf is:
scanf(format_string, list_of_variable_addresses);

You might also like