0% found this document useful (0 votes)
5 views

UNIT-1-1

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)
5 views

UNIT-1-1

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/ 44

Programming for Problem solving using C UNIT-1

Computer:
A computer is a machine that can be instructed to carry out sequences of arithmetic
or logical operations automatically via computer programming.

Bits and Bytes:


Bits:
The term bit is an acronym of Binary Digit. By definition, it is ―a single digit in binary
number scheme‖, meaning it can take on one of two values: 0 and 1 (a binary condition). It is
a mutually exclusive state: Something either isn‘t (‗0‘), or it is (‗1‘). It is also the basic unit of
information storage.

State 0: OFF State 1: ON


Byte:
A pattern eight bits makes up a BYTE. A BYTE represents characters (letters, numbers &
symbols).

27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0
0 0 0 0 0 0 1 1
0 0 0 0 0 1 0 0
0 0 0 0 0 1 0 1
0 0 0 0 0 1 1 0
0 0 0 0 0 1 1 1
0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 1

Page 1
Programming for Problem solving using C UNIT-1

• 8 bits are 1 byte


• 16 bits are 2 bytes = 1 halfword
• 32 bits are 4 bytes = 1 word
• 1024 bytes are 1 kilobyte
• 1024 kilobytes are 1megabyte
• 1024 mega bytes are 1gigabyte
• 1024 gigabytes are 1terabyte
• 1024 terabytes are 1 petabyte
• 1024 petabytes are 1 zettabyte.
Programming Languages:
To write a computer program, a standard programming language is used. A
programming language is composed of a set of instructions in a language understandable to
the programmer and recognizable by a computer. Programming languages can be classified
as high-level and low level.
Low-level programming languages were the first category of programming languages
to evolve. Gradually, high-level languages were developed and put to use.

Fig: Programming Languages Classification


a) Low-level Languages:
A low-level computer programming language is one that is closer to the native
language of the computer, which is 1‟s and 0‟s.
Machine Language:
Only computer can directly understand only its own machine language. Machine
language is the natural language of a particular computer. It is defined by the hardware
design of that computer. This is considered to be the First Generation Language (1GL).
Advantages:
The CPU directly understands machine instructions and hence no translation is
required. Therefore, the computer directly starts execute the machine language
instructions, and it takes less execution time.
Page 2
Programming for Problem solving using C UNIT-1

Disadvantages:
➢ Difficult to use
➢ Machine dependent
➢ Error prone
➢ Difficult to debug and modify

Assembly Language:

When symbols as letters, digits, or special characters are employed for the operation,
operand and other parts of instruction code. The representation is called an assembly
language instruction. Such representations are known as mnemonic codes; they are used
instead of binary codes. A program written with mnemonic codes forms an assembly
language program. This is considered to be a Second Generation Language (2GL).

Advantages:
➢ Changes could be made easier and faster.
➢ Easier to read and write.
➢ Error checking is provided.

Disadvantages:
➢ Machine dependent.
➢ Programming is difficult and time consuming.
➢ The programmer should know all about the logical structure of the computer.

b) High-Level Languages:
Since a computer prefers machine language while a person wants to use a natural
language special ―high level computer languages have been developed to bridge this
communication gap. A high level language like C, uses English words plus symbols and
numbers. Very first two high level languages are FORTRAN and COBOL. This is
considered to be a Third Generation Language (3GL).

Advantages:

➢ Readability Programs written in these languages are more readable than those
written in assembly and machine languages.
➢ Portability High-level programming languages can be run on different machines
with little or no change.
➢ Easy debugging error can be easily detected and removed.
➢ Ease in the development of Software Since commands of these programming
languages are closer to the English language, software can be developed with ease.

Page 3
Programming for Problem solving using C UNIT-1

Translation of high level language to machine language:

i) Procedural Languages:
Algorithmic Languages:
These are high-level languages designed for forming convenient expression of
procedures, used in the solution of wide class of problems. In this language, the programmer
must specify the steps the computer has to follow while executing a program. Some of
languages that fall in the category are C, COBOL, and FORTRAN.
Object-oriented language:
The basic philosophy of object-oriented programming is to deal with objects rather
than functions or subroutines as in strictly algorithmic languages. Objects are self-contained
modules that contain data as well as the functions needed to manipulate the data within the
same module. The difference affects the way a programmer goes about writing a program as
well as how information is represented and activated in the computer. The most important
object-oriented programming features are
• abstraction
• encapsulation and data hiding
• polymorphism
• inheritance
• reusable code
C++, JAVA, SMALLTALK, etc. are examples of object-oriented languages.
Scripting Languages:
These languages assume that a collection of useful programs, each performing a task,
already exists. It has facilities to combine these components to performing a complex task. A
scripting language may thus be thought of as a glue language, which sticks a variety of

Page 4
Programming for Problem solving using C UNIT-1

components together. One of the earliest scripting languages is the UNIX shell. Now there
are several scripting languages such as VB script and Perl.
ii) Problem-oriented languages
Problem-oriented Languages were designed to solve specific problems e.g.
MATLAB is used to design circuit diagrams, and allowed the programmer to concentrate
more on the problem rather than spending time learning the complex syntax of the language.
iii) Non-procedural Languages
Functional languages: These functional languages solve a problem by applying a set of
functions to the initial variables in specific ways to get the answer. LISP, ML, etc. are
examples of functional languages.
Logic Based Programming Language: A logic program is expressed as a set of atomic
sentences, known as fact, and horn clauses, such as if-the rules. A query is then posed. The
execution of the program now begins and the system tries to find out if the answer to the
query is true or false. Such languages include PROLOG.
Software:
A set of computer programs are called software. Computer program is a series of
instructions telling the computer what to do.
Types of software:
1. System software
2. Application software
1. System software:
• System software exists in the functioning of a computer system and includes the
operating system, assembler, interpreter, compiler, linker and loader.
• Operating system is the interface between user applications and system hardware.
• Assembler is a translator that converse assembly language code into machine
language.
• Interpreter converts source language program into executable code at once.
• Linker performs the important task of linking together several objects modules.
• The task of loading the linked object modules is performed by the loader.
System software includes three types of programs:
• Operating System: The combination of a particular hardware configuration and
system software package is known as a computer system platform. System
platforms are commonly termed as operating system (OS). Some common
operating systems are DOS, UNIX, Mac, and Windows platform.
• Language Translators: These are interpreters and compilers for programs such as
Pascal, BASIC, COBOL, C, and C++.
• Common Utility Programs: Communication tools, disk formatter, etc.
Examples: Language Translator, Operating System, Special Purpose Program, Utilities

Page 5
Programming for Problem solving using C UNIT-1

2. Application software:
Application software is written to enable the computer to solve a specific data
processing task. There are two categories of application software: pre-written software
packages and user application programs.
A number of powerful application software packages that do not require significant
programming knowledge have been developed. These are easy to learn and use compared to
programming languages.
Examples:
• Database Management Software
• Spreadsheet Software
• Word processing, Desktop Publishing (DTP), and Presentation Software
• Multimedia Software
• Data Communication Software
• Statistical and operational research Software
Algorithms:
➢ Computer Scientist ―Niklaus Wirth‟ stated that Programs = Algorithms + Data
➢ An algorithm is a part of the plan for the computer program; an algorithm is ‗an
effective procedure for solving problem in a finite number of steps‘.
➢ A sequential solution of any program that written in human language, called
algorithm.
➢ Algorithm is first step of the solution process, after the analysis of problem,
programmer writes the algorithm of that problem.

Good Qualities of algorithm:


• Inputs and outputs should be defined precisely.
• Each step in algorithm should be clear and unambiguous.
• Algorithm should be most effective among many different ways to solve a
problem.
• Algorithm should be complete or finiteness.
• Algorithm should be correctness.

Steps for algorithm:


• Identify the processes
• Identify the major decisions
• Identify the loops
• Identify the variables
Example Algorithm for Making a Tea:
1. Put the kettle in the stove.
2. Fill the kettle with water, sugar and tea powder.
3. Boil the water in the kettle.
4. Add milk to the decoction.
5. Filter the tea into cup.
6. Drink the tea.

Page 6
Programming for Problem solving using C UNIT-1

1. Example Algorithm for Addition of two numbers:


Step 1: START
Step 2: Read a, b
Step 3: Sum = a + b
Step 4: PRINT Sum
Step 5: STOP
2. Example Algorithm for Biggest of two numbers:
Step 1: START
Step 2: Read a, b
Step 3: IF a>b Then PRINT ―a is Big‖
ELSE IF a<b Then PRINT ―b is Big‖
ELSE PRINT ―both are equal‖
Step 4: STOP
3. Example Algorithm for Increment of Employee salary:
Step 1: START
Step 2: Read salary
Step 3: IF salary is greater than 5000 THEN step 4
ELSE IF salary is equal to 5000 Then step5
ELSE step 6
Step 4: Salary = Salary + (0.05*Salary) Step 5: Salary = Salary + 200
Step 6: Salary = Salary Step 7: Print Salary Step 8: STOP
4. Example Algorithm for Factorial of Number:
Step 1: START Step 1: START
Step 2: Read n Step 2: Read n
Step 3: [Initialize] i = 1, fact = 1 Step 3: [Initialize] fact = 1 Step 4:
WHILE i<=n Step 4: WHILE n>=1
BEGIN BEGIN
fact = fact * i (or) fact = fact * n
i=i+1 n=n-1
END END
Step 5: PRINT fact Step 5: PRINT fact
Step 6: STOP Step 6: STOP
5. Example Algorithm for Swapping of Two Numbers:
Step 1: START Step 1: START
Step 2: Read a, b Step 2: Read a, b
Step 3: c = a Step 3: a = a + b
Step 4: a = b (or) Step 4: b = a - b
Step 5: b = c Step 5: a = a - b
Step 6: PRINT a, b Step 6: PRINT a, b
Step 7: STOP Step 7: STOP

Page 7
Programming for Problem solving using C UNIT-1

Flowchart:
A flowchart is a pictorial representation of on algorithm. It shows the logic of the
algorithm and the flow of control. The flowchart uses symbols to represent specific actions
and arrows to indicate the flow of control.
Flowchart symbols are

1. Example Flowchart for Addition of two numbers:

Page 8
Programming for Problem solving using C UNIT-1

2. Example Flowchart for Biggest of two numbers:

3. Example Flowchart for Increment of Employee salary:

4. Example Flowchart for Factorial of Number:

Page 9
Programming for Problem solving using C UNIT-1

5. Example Flowchart for Swapping of Two Numbers:

Program development steps:


Program development contains following steps:
i. Creating the program
ii. Compiling the program
iii. Linking the program
iv. Executing the program
i) Creating the program:
In this step, the program can be written into a file through text editor. The file is saved
on the disk with and extension. Corrections to the program at later stages are done to
these editors. Once the program has written, it requires to be translated into machine
language.
ii) Compiling the program:
This step is carried out by a program or compiler. Compiler translates the source code
into object code.
Compilation of these cannot proceed successfully until and useless the source code is
error free. Compiler generates messages if it encounters some errors in the source
code. The error free source code translates in the object code and stored in a separate
code with an extension .obj.
iii) Linking the program:
The linker links all the files and functions with the object code under execution.
Ex: printf-the linker links the user programs object with the object of the printf
function. Now object code is ready for next phase.
iv) Execution the program:
The execution object code is loaded into the memory and the program execution
begins. It encounters error to till the execution phase, Even though compilation phase
is successful. These errors may be logical errors.

Page 10
Programming for Problem solving using C UNIT-1

Introduction to C Language
C is a general-purpose high level language that was originally developed by Dennis
Ritchie for the Unix operating system. It was first implemented on the Digital Equipment
Corporation PDP-11 computer in 1972. The Unix operating system and virtually all Unix
applications are written in the C language.
C has now become a widely used professional language for various reasons.
➢ Easy to learn
➢ Structured language
➢ It produces efficient programs.
➢ It can handle low-level activities.
➢ It can be compiled on a variety of computers.
Facts about C
➢ C was invented to write an operating system called UNIX.
➢ C is a successor of B language which was introduced around1970
➢ The language was formalized in 1988 by the American National Standard Institute
(ANSI).
➢ By 1973 UNIX OS almost totally written in C.
➢ Today C is the most widely used System Programming Language.
➢ Most of the state of the art software have been implemented using C

Page 11
Programming for Problem solving using C UNIT-1

Dennis Ritchie, Father of C

Born: 9 September 1941

Died: 12 October 2011

Why to use C?
C was initially used for system development work, in particular the programs that
make-up the operating system. C was adopted as a system development language because it
produces code that runs nearly as fast as code written in assembly language. Some examples
of the use of C might be:
➢ Operating Systems
➢ Language Compilers
➢ Assemblers
➢ Text Editors
➢ Print Spoolers
➢ Network Drivers
➢ Modern Programs
➢ Databases
➢ Language Interpreters
C Program File
All the C programs are written into text files with extension ".c" for example hello.c.
A TurboC Compiler in Windows operating system is used to write a C program into a file.
History of C Language
C is a general-purpose language which has been closely associated with the UNIX
operating system for which it was developed - since the system and most of the programs that
run it are written in C.
Many of the important ideas of C stem from the language BCPL, developed by
Martin Richards. The influence of BCPL on C proceeded indirectly through the language B,
which was written by Ken Thompson in 1970 at Bell Labs, for the first UNIX system on a
DECPDP-7. BCPL and B are "type less" languages whereas C provides a variety of
datatypes.
In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the publication of The C
Programming Language by Kernighan & Ritchie caused a revolution in the computing world.
In 1983, the American National Standards Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C. The resulting definition, the ANSI
standard, or "ANSI C", was completed late 1988.

Page 12
Programming for Problem solving using C UNIT-1

Structure of C:

Fig: Structure of C
1. Documentation section: The documentation section consists of a set of comment lines
giving the name of the program, the author and other details, which the programmer
would like to use later.
2. Link section: The link section provides instructions to the compiler to link functions
from the system library such as using the #include directive.
3. Definition section: The definition section defines all symbolic constants such using the
#define directive.

Page 13
Programming for Problem solving using C UNIT-1

4. Global declaration section: There are some variables that are used in more than one
function. Such variables are called global variables and are declared in the global
declaration section that is outside of all the functions. This section also declares all the
user-defined functions.
5. main ( ) function section: Every C program must have one main function section. This
section contains two parts; declaration part and executable part
1. Declaration part: The declaration part declares all the variables used in the
executable part.
2. Executable part: There is at least one statement in the executable part. These two
parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing
brace of the main function is the logical end of the program. All statements in the
declaration and executable part end with a semicolon.
6. Subprogram section: If the program is a multi-function program then the subprogram
section contains all the user-defined functions that are called in the main () function.
User-defined functions are generally placed immediately after the main () function,
although they may appear in any order.
Character set:
Character set is a set of alphabets, letters and some special characters that are valid
in C language.
Alphabets:
Uppercase: A B C .................................... X Y Z
Lowercase: a b c ....................................... x y z
Digits:
0123456789
Special Characters:
, < > . _ -
( ) ; $ : /
% [ ] # ? ~
‗ & { } ― +
^ ! * / |
White space Characters, blank space, new line, horizontal tab.
Keywords:
Keywords are predefined; reserved words used in programming that have special
meaning. Keywords are part of the syntax and they cannot be used as an identifier.
For example:
int money;
Here, int is a keyword that indicates 'money' is a variable of type integer.
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list
of all keywords allowed in ANSI C.

Page 14
Programming for Problem solving using C UNIT-1

auto double int struct


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned
Along with these keywords, C supports other numerous keywords depending upon
the compiler. All these keywords, their syntax and application will be discussed in their
respective topics.
Identifiers:
Identifiers are the names you can give to entities such as variables, functions,
structures etc. identifier names must be unique. They are created to give unique name to a
C entity to identify it during the execution of a program. For example:
int money;
double balance;
Here, money and balance are identifiers.
Also remember, identifier names must be different from keywords. You cannot use
int as an identifier because int is a keyword.
Rules for writing an identifier:
1. A valid identifier can have letters (both uppercase and lowercase letters), digits
and underscore only. For ex., a variable named ‗NUMBER‘ is not the same as the
variable named ‗number‘ and neither of them is the same as the variable named
‗Number‗. All three refer to different variables.
2. The underscore should not be used as the first character of a variable name
because several compiler-defined identifiers in the standard C library have the
underscore for beginning character, and it can conflict with system names.
3. A numeric digit should not be used as the first character of an identifier.
4. There is no rule on the length of an identifier. However, the first 31 characters of
identifiers are discriminated by the compiler. So, the first 31 letters of two
identifiers in a program should be different.
5. The identifier should not be a keyword of C.
Variable:
➢ A variable is an identifier for a memory location in which data can be stored and
subsequently recalled. All the variables have two important attributes.
➢ A data type that is established when the variable is defined, e.g., integer, real,
character. Once defined, the type of a C variable cannot be changed.
➢ A value can be changed by assigning a new value to the variable. The kind of values a
variable can assume depends on its type. For e.g., an integer variable can only take
integer values, e.g., 2, 100, -12, -14, 0, 4.

Page 15
Programming for Problem solving using C UNIT-1

Declaration of variables:
➢ Any programming language any variable used in the program must be declared before
it is used.
➢ This declaration tells the compiler what the variable name and what type of data it is.
➢ In C language a declaration of variable should be done in the declaration part of the
program. A type declaration statement is usually written at the beginning of the
program.
Syntax: data_type var1,var2,var3,………,varn;
Ex: int i, count;
float price,area;
charc;
Assigning values:
➢ Values can be assigned to variables by using the assignment operator. An assignment
statement employees that the value of the variable on the left of the equal to the value
of quantity on the right.
Syntax: data_type variable_name = constant;
Ex: int i= 20;
The main( ) Function:
All C language programs must have a main( ) function. It‗s the core of every
program. It‗s required. The main( ) function doesn‗t really have to do anything other than
be present inside your C source code. Eventually, it contains instructions that tell the
computer to carry out whatever task your program is designed to do. But it‗s not officially
required to do anything. When the operating system runs a program in C, it passes control
of the computer over to that program. This is like the captain of a huge ocean liner
handing you the wheel. Aside from any fears that may induce, the key point is that the
operating system needs to know where inside your program the control needs to be
passed. In the case of a C language program, it‗s the main() function that the operating
system is looking for.
At a minimum, the main( ) function looks like this:
main ( )
{
}
Like all C language functions, first comes the function‗s name, main, then comes a set of
parentheses, and finally comes a set of braces, also called curly braces.
If your C program contains only this line of code, you can run it. It won‗t do
anything, but that‘s perfect because the program doesn‗t tell the computer to do anything.
Even so, the operating system found the main( ) function and was able to pass control to
that function which did nothing but immediately return control right back to the operating
system. It‗s a perfect, flawless program.
The set of parentheses after a C language function name is used to contain any
arguments for the function — stuff for the function to digest. For example, in
the sqrt( ) function, the parentheses hug a value; the function then discovers the
square root of that value.

Page 16
Programming for Problem solving using C UNIT-1

The main ( ) function uses its parentheses to contain any information typed
after the program name at the command prompt. This is useful for more advanced
programming.
The braces are used for organization. They contain programming instructions
that belong to the function. Those programming instructions are how the function
carries out its task or does its thing.
The printf ( ) Function:
It is a library function. It is provided by the compiler, ready for use. In
addition to its variable, a function, including main ( ), may optionally have arguments
those are listed in the parenthesis following the function name.
In the C Programming Language, the printf function writes a formatted string
to the stdout stream.
Syntax:
The syntax for the printf function in the C Language is:
printf(“Control_String”, list_of_variables);
Ex:-
#include<stdio.h>
void main( )
{
printf(“Hello”);
}

When the printf ( ) function is executable its built-in instructions process this
argument. The result is that the string is display on the output device, usually
assumed as a display screen terminal.
The output is
Hello
➢ C uses a semicolon as a statement terminator; the semicolon is required as a signal
to the compiler to indicate that a statement is complete.
➢ All program instructions, which are also called statements, have to be written in
lowercase characters.
➢ The following statement implies the preprocessor directive: #include<stdio.h>
➢ The #include directive includes the contents of a file during compilation. In this
case the file stdio.h is added in the source program before the actual compilation
begins.

Page 17
Programming for Problem solving using C UNIT-1

The scanf ( ) statement:


In C programming, scanf ( ) is one of the commonly used function to take input
from the user. The scanf ( ) function reads formatted input from the standard input such as
keyboards.

Ex:-
#include<stdio.h>
void main( )
{
int a,b,c;
printf(―Enter a value: ‖);
scanf(―%d‖, &a):
printf(―Enter b value: ‖);
scanf(―%d‖, &b):
c = a + b;
printf(―Sum is %d ‖, c);
}
Output:
Enter a value: 56
Enter a value: 67
Sum is = 123
Escape sequence:
The \n pronounced as backslash n in the string argument of the function printf ( ).
printf ( ―Welcome\nComputer‖ );
is an example of escape sequence.
It is used print the new line character. If the program is executed, the \n does not
appear in the output. Each \n in the string argument of a prinf ( ) causes the cursor to be
placed at the beginning of the next line of output.

Sno Code meaning


1 \a Ring terminal bell (a is for alert)
2 \? Question mark
3 \b Backspace
4 \r Carriage return
5 \f Form feed
6 \t Horizontal tab
7 \v Vertical tab
8 \o ASCII null character
9 \\ Back slash
10 \‖ Double quote
11 \‗ Single quote
12 \n New line
13 \o Octal constant
14 \x Hexadecimal constant

Page 18
Programming for Problem solving using C UNIT-1

Format Modifiers:
Describes the output as well as provides a placeholder to insert the formatted string.
Here are a few examples:

Format Explanation Example


%c Display Character m
%s Display group of characters hai
%d (%i) Display an integer 10
%ld Display long decimal 51200
%o Display Octal value 12
%u Display unsigned integer 15
%x Display hexa value b
%X Display HEXA value B
%f Displays a floating-point number in fixed decimal format 10.500000
Displays a floating-point number with 1 digit after the 10.5
%.1f
decimal
Display a floating-point number in exponential (scientific 1.050000e+0
%e
notation) 1
Display a floating-point number in either fixed decimal or
exponential format depending on the size of the number 10.5
%g (will not display trailing zeros)

COMMENT:
A "comment" is a sequence of characters beginning with a forward slash, asterisk
combination (/*) that is treated as a single white-space character by the compiler and is
otherwise ignored. A comment can include any combination of characters from the
represent able character set, including newline characters, but excluding the "end
comment" delimiter (*/). Comments can occupy more than one line but cannot be nested.
Comments can appear anywhere a white-space character is allowed. Since the
compiler treats a comment as a single white-space character, you cannot include
comments within tokens. The compiler ignores the characters in the comment. Use
comments to document your code. This example is a comment accepted by the compiler:
/* Comments can contain keywords such as for and while without
generating errors. */
To use single line comment we can use // (double forward slashes)
// single line comment

Page 19
Programming for Problem solving using C UNIT-1

Data types of C:
Data types in c refer to an extensive system used for declaring variables or
functions of different types. The type of a variable determines how much space it
occupies in storage and how the bit pattern stored is interpreted.

Primitive/Basic Data Type:


Integer data types:
C offers 3 different individual data types they are int, short int, long int. the
difference between these 3 individual types are bytes required and range of values.

TYPE SIZE (bits) RANGE


short int 16 -2 to 215-1
15

int 16 -215 to 215-1


long int 32 -231 to 231-1
unsigned short int 16 0 to 216-1
unsigned int 16 0 to 216-1
unsigned long int 32 0 to 232-1
Float data types:
Like integer, float are divided into 3 different individual data types they are float,
double, long double. The differences between these 3 individual types are bytes required
and range of values.
TYPE SIZE (bits) RANGE
float 32 3.4E-38 to 3.4E+38
double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 3.4E+4932

Character data types:


Keyword char is used for declaring character type variables. For example:
char a = „m‟;
TYPE SIZE (bits) RANGE
char 8 -128 to 127
unsigned char 8 0 to 255

Page 20
Programming for Problem solving using C UNIT-1

Expression:
An expression is a combination of variables constants and operators written
according to the syntax of C language. In C every expression evaluates to a value i.e.,
every expression results in some value of a certain type that can be assigned to a variable.
Some examples of C expressions are shown in the table given below.

Algebraic Expression C Expression


axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c

Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the
left hand side. All variables used in the expression must be assigned values before
evaluation is attempted.
Example of evaluation statements are
x=a*b–cy=b/c*a
z = a – b / c + d;
The following program illustrates the effect of presence of parenthesis in expressions.
Ex:
void main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = a – b / 3 + c * 2 – 1;
y = a – b / (3 + c) * (2 – 1);
z = a – ( b / (3 + c) * 2) – 1;
printf (― x = %.2f ‖, x);
printf (― y = %.2f ‖, y);
printf (― z = %.2f ‖, z);
}
Output:
x = 10.00
y = 7.00
z = 4.00

Page 21
Programming for Problem solving using C UNIT-1

Operator Precedence:
This page lists C operators in order of precedence (highest to lowest). Their
associativity indicates in what order operators of equal precedence in an expression
are applied.

Operator Description Associativity


() Parentheses (function call) (see Note 1)
[] Brackets (array subscript)
. Member selection via object name left-to-right
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement
+- Unary plus/minus
!~ Logical negation/bitwise complement
(type) Cast (convert value to temporary value of type) right-to-left
* Dereference
& Address (of operand)
sizeof Determine size in bytes on this implementation
*/% Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to
left-to-right
> >= Relational greater than/greater than or equal to
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
right-to-left
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment
, Comma (separate expressions) left-to-right
Note 1:
Parentheses are also used to group sub-expressions to force a different
precedence; such parenthetical expressions can be nested and are evaluated from
inner to outer.
Note 2:
Postfix increment/decrement have high precedence, but the actual increment or
decrement of the operand is delayed (to be accomplished sometime before the
statement completes execution). So in the statement y = x * z++; the current
value of z is used to evaluate the expression (i.e., z++ evaluates to z) and z only
incremented after all else is done.

Page 22
Programming for Problem solving using C UNIT-1

Type Conversions:

There are two kinds of type conversion we need to talk about: automatic or implicit type
conversion and explicit type conversion.

1. Implicit Type Conversion

The operators we have looked at can deal with different types. For example we
can apply the addition operator + to an int as well as a double. It is important to understand
how operators deal with different types that appear in the same expression. There are rules
in C that govern how operators convert different types, to evaluate the results of
expressions.
For example, when a floating-point number is assigned to an integer value in C,
the decimal portion of the number gets truncated. On the other hand, when an integer
value is assigned to a floating-point variable, the decimal is assumed as .0.
This sort of implicit or automatic conversion can produce nasty bugs that are
difficult to find, especially for example when performing multiplication or division using
mixed types,
e.g. integer and floating-point values. Here is some example code illustrating some of
these effects:
Program:
#include <stdio.h>
void main( ) {
int a = 2;
double b = 3.5;
double c = a * b;
double d = a / b;
int e = a * b;
int f = a / b;
printf(" b = %.3f \n", b );
printf(" c = %.3f \n", c );
printf(" d = %.3f \n", d );
printf(" e = %d \n", e );
printf(" f = %d \n", f );
}
Output:
b = 3.500
c = 7.000
d = 0.571
e=7
f=0

Page 23
Programming for Problem solving using C UNIT-1

2. Explicit Type Conversion


Type Casting
There is a mechanism in C to perform type casting that is to force an expression to be
converted to a particular type of our choosing. We surround the desired type in brackets
and place that just before the expression to be coerced. Look at the following example
code:
#include <stdio.h>
void main()
{
int a = 2;
int b = 3;
printf("a / b = %.3f\n", a/b);
printf("a / b = %.3f\n", (double) a/b);
}

Mathematical library functions:

The <math.h> header file contains the mathematical operations like trigonometric
and other mathematic formats.

Function Return type Description


-1
acos(d) double Return the cos of d
asin(d) double Return the sin-1 of d
atan(d) double Return the tan-1 of d
atan2(d1,d2) double Return the tan-1 of d1/d2
ceil(d) double Return a value rounded upto the next higher integer
cos(d) double Return the cos of d
cosh(d) double Return the hyperbolic cos of d
exp(d) double Return e of the power of d
fabs(d) double Return absolute value of d
floor(d) double Return a value rounded downto the next lower integer
fmod(d1,d2) double Return the remainder of d1/d2 (with same sign as d1)
labs(l) long int Return the absolute value of l
log(d) double Return natural logarithm of d
log10(d) double Return natural logarithm (base 10) of d
pow(d1,d2) double Return d1 raised to the d2 power (d1d2)
sin(d) double Return the sin of d
sinh(d) double Return the hyperbolic sin of d
sqrt(d) double Return square root of d
tan(d) double Return the tan of d
tanh(d) double Return the hyperbolic tan of d

Page 24
1

Algorithm:

An algorithm is a step-by-step problem-solving procedure that can


be carried out by a computer.

Does algorithm depend on programming language? Justify your


answer.

No, an algorithm does not depend on the programming language.


Because an algorithm expresses the steps sequentially for solving a
problem only, we can express the algorithm in our natural languages like
English etc.

Ex. 1. Write the algorithm to find the sum and product of two given
numbers.

Algorithm: To find the sum and product of two given numbers:


Step 1: Read A, B
Step 2: Let Sum= A+B
Step 3: Let Product=A*B
Step 4: Print Sum, Product
Step 5: Stop.

Ex 2: Develop an algorithm to interchange the values assigned to two


variables A and B. (For example, if A=2 and B=3, after interchange,
it should be A=3 and B=2).

Algorithm: To interchange the values.

1. [Initialize the variables]


A=2
B=3
2. [Peform the operations]
TEMP = A
A=B
B = TEMP
3. [Print the result]
Print A, B
4. [Finished]
Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


2

Ex.3: Write an algorithm to find the largest number from 10 given


numbers.
Algorithm: To find the largest number from 10 given numbers.

1. [Initialize the variables]


large = 0
count = 0
2. [Increment the count]
count = count+1
3. [Enter number]
read x
4. [Perform the operations]
if (t>x) then
goto step 6
end if
5. large = x
6. if (count  10) then
goto step 2
end if
7. [Print the result]
Print large
8. [Finished]
Stop

Ex 4: Develop an algorithm to evaluate S using the relation:


S=1 + 4 + 9+ 16 + …..+ 100

Algorithm:
1. [Initialize the variables]
X=1
S=0
2. [Perform the operations]
Y = X*X
S=S + Y
X=X+1
3. [Check the condition]
If (X  100) Then
Goto step 2
End if
4. [Print the output]
Print S
5. [Finished]
Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


3

Flow-chart?

(i) A flowchart is a diagrammatic representation of algorithm to


plan the solution to the problem.

(ii) Constructed by using special geometrical symbols where each


symbol represents an activity. The activity would be
input/output of data, computation/processing of data etc.

Advantages of using flowchart:


1. Communication: They are good visual aid to understand the
program.
2. Quicker grasps of relationships.
3. Effective analysis.
4. Synthesis
5. Proper program documentation
6. Efficient coding
7. Orderly debugging & testing of programs.
8. Efficient program maintenance.

Limitations of using flowchart:


1. Complex logic
2. Alterations & Modifications
3. Reproduction
4. No uniform practice
5. Link between conditions
6. Standardization

Flowchart symbols:

Start/Stop
Ellipse

Expression
Rectangle

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


4

I/O Statements

Parallelogram

Decision

Rhombus

Connecting lines (Flow lines)

Connector with label

Ex. Draw the flowchart to find the sum and product of two given
numbers.

Flowchart: To find the sum and product of two given numbers:

Start

Read A,B

Sum=A+B

Product=A*B

Print Sum, Product

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


5

Ex: Write the algorithm and draw the flowchart to find the sum and
product of two given numbers.

Solution:
Algorithm: To find the sum and product of two given numbers:
Step 1: Read A , B
Step 2: Let Sum= A+B
Step 3: Let Product=A*B
Step 4: Print Sum, Product
Step 5: Stop.

Flowchart: To find the sum and product of two given numbers:

Start

Read A,B

Sum=A+B

Product=A*B

Print Sum, Product

Stop

Ex: What are the advantages and limitations of flowcharts when


used to solve a problem?

Solution: Flowcharts have the following advantages when used to solve a


problem:
(a) They are brief and to the point.
(b) They express clearly the logic of a given procedure.
(c) They are unambiguous as there can be only one
direction of logic at any one time.
(d) They show readily whether all eventualities are
covered.
Limitations: Complex and detailed charts can be laborious to plan and
draw and the actions to be taken in specified situations can be difficult
when many decision paths are involved.

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


6

Ex: What is meant by algorithm? Write an algorithm to find and


print the smaller number from two given numbers.

Solution: An algorithm is a logical list of procedures or steps for solving


a given problem.

Algorithm: To find the smallest number from two given numbers:


1. [Enter numbers]
Read A, B
2. [Perform the operations]
If (A<B) then
Print smallest number is A
Else
Print smallest number is B
End If
3. [Finished]
Stop

Ex: Write an algorithm to compute the arithmetic mean of n


numbers.

Solution:
Algorithm: To compute the arithmetic mean of n numbers.
1. [Enter N]
Read N
2. [Enter numbers]
For I=1 to N
Read A[I]
End For
3. [Initialize the variables]
Sum=0
4. [Perform the operations]
For I=1 to N
Sum=Sum+A[I]
End For
AM=Sum/N
5. [Print the Output]
Print Sum, AM
6. [Finished]
Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


7

Ex: What is an algorithm? What are its essential properties?


Solution:
Algorithm: An algorithm is a step-by-step problem solving procedure that
can be carried out by a computer. The essential properties of an algorithm
are:
1. It should be simple.
2. It should be clear with no ambiguity.
3. It should lead to a unique solution of the problem.
4. It should involve a finite number of steps to arrive at a solution.
It should have the capability to handle some unexpected situations
which may arise during the solution of a problem (for example,
division by zero).

Ex: What are the advantages and disadvantages of algorithm?


Solution:
Advantages of Algorithm:
1. It is a step by step solution to a given problem which is very easy
to understand.
2. It has got a definite procedure which can be exacted within a set
period of time.
3. It is easy to first develop an algorithm, then convert it into a
flowchart and then into a computer program.
4. It has got a beginning and an end within which there are definite
procedures to produce output(s) within a specified period of time.
5. It is easy to debug as every step has got its own logical sequence.
6. It is independent of programming language.

Disadvantages of Algorithm:
It is time consuming and cumbersome as an algorithm is developed first
which is converted into a flowchart and then into a computer program.

Ex: What do you meant by an algorithm? Discuss the main features


of an algorithm.

Solution:
An algorithm is a step of instructions to be followed to solve a
problem in computers.
According to D.E. Knuth, a pioneer in the computer science
discipline, an algorithm has five important features.

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


8

i) Finiteness: An algorithm terminates after a fixed number of


steps.
ii) Definiteness: Each step of the algorithm is precisely defined,
i.e. the actions to be carried out should be specified
unambiguously.
iii) Effectiveness: All the operations used in the algorithm are basic
(division, multiplication, comparison., etc.) and can be
performed exactly in fixed duration of time.
iv) Input: An algorithm has certain precise inputs, i.e. quantities
which are specified to it initially, before the execution of the
algorithm begins.
v) Output: An algorithm has one or more outputs, that is the
results of operations which have a specified relation to the
inputs.

Ex: Develop an algorithm to read a value of N and to compute and print


the value of N!

Algorithm: To read a value of N and to compute and print the value of


N!
1. [Enter number]
read N
2. [Check, if the number is negative]
if(N<0) then
stop
end if
3. [Perform the operation]
K=1
For L=2 to N
K=K*L
End For
4. [Print the result]
Print K
5. [Finished]
Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


9

Ex: Does an algorithm depend on the programming language?

Solution: No, an algorithm does not depend on the programming


language.

Ex: What is a flowchart? Why is it called a flowchart?


OR
What is a flowchart?

Solution: A flowchart is a picture or a diagram which helps us define a


procedure for solving a problem. It is called a flowchart since it shows the
logical flow of operations in various steps.

Ex: What is the purpose of a flowchart?

Solution: A flowchart is a picture or a diagram which helps us define a


procedure one step at a time, and arrange it in a logical sequence. . It is
necessary to draw a flowchart before writing a procedure because it gives
a picture of the logical flow of operations. If there is any logical error in
the procedure, we can easily identify the error just by looking at the
flowchart.

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


10

Fig. Flowchart for writing and posting a post card.

Start

Pick up a postcard

Pick up the pen

Write on the post card

Write the address

Goto the post office

Post the card

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


11

Fig: Summing of N given numbers.

Start

Read N

Put S = 0
Initialization and I = 0

Read A

Computation Add A into S


(S=S+A)

Looping
Increase I by 1
Modification (I=I+1)

is
Testing I=N
No

Write S

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


12

Flowchart: To find the biggest number of three given numbers:

Start

Read A, B, C

No Yes
Is
A>B

Yes No No Yes
Is Is
B>C A>C

Print B Print C Print A

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


13

Q.1. Draw a flowchart to find the sum of n given numbers


OR
Draw a flowchart to find the sum of n integers given as input.

Solution:

Start

Read n

Sum=0

For i=1 to n

Read x[i]

Sum=Sum + x[i]

End for

Print Sum

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


14

Q.2. Draw a flowchart to find the average, maximum and minimum values of n given
numbers.
Solution:
Start

Read n

For i=1 to n

Read x[i]

End for

Max=x[1], Min=x[1], Sum=0

For i=1 to n

No Is Yes
Max<x[i]
?
Max=x[i]

Is
Min>x[i] Yes
? Min=x[i]

No Sum=Sum+x[i]

End for

Average=Sum/n

Write Max, Min, Average

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


15

Q.3. Draw a flowchart to read and find the maximum of n given numbers.

Solution:
Start

Read n

For i=1 to n

Read x[i]

End for

Max=x[1]

For i=1 to n

If
No max<x[i] ? Yes

Max=x[i]

End for

Print Max

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


16

Q.4. Draw a flowchart to find the maximum of n given numbers.

Solution:
Start

Read n

For i=1 to n

Read x[i]

End for

Max=x[1]

For i=1 to n

If
max<x[i] ?
No Yes

Max=x[i]

End for

Print Max

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


17

Q.5: Draw a flowchart to print the maximum of n given numbers.

Solution:

Start

Read n

For i=1 to n

Read x[i]

End for

Max=x[1]

For i=1 to n

No If max<x[i] Yes
?
Max=x[i]

End for

Print Max

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


18

Q.6: Draw a flowchart to determine and print the average of 30 given numbers.

Solution:
Flowchart: To determine and print the average of 30 given numbers.
Start

Sum =0, Count =1

Read Num

Sum = Sum+Num

Count = Count+1

Is
Count 30 ?
Yes

No
Average =Sum/(Count-1)

Print Average

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


19

Q.7: Draw a flowchart to read N numbers and then to compute and print the
arithmetic mean of the numbers.
Solution: The flowchart to compute the arithmetic mean of n numbers is shown
below.
Start

Read n

For I=1 to N

Read A[I]

End For

Sum = 0

For I=1 to N

Sum=Sum+A[I]

End For

AM=Sum/N

Print AM

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH


20

Q.8: Draw a flowchart to read a value of N and to compute and print the value of N!

Solution:
Flowchart: To read a value of N and to compute and print the value of N!

Start

Read N

Is
N <0 ?
Yes No
Fact = 1
Stop

For L = 2 to N

Fact=Fact*L

End For

Print Fact

Stop

Dr. K SANDEEP, Dept of IT, DHANEKULA INST OF ENG & TECH

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy