UNIT-1-1
UNIT-1-1
Computer:
A computer is a machine that can be instructed to carry out sequences of arithmetic
or logical operations automatically via computer programming.
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
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
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.
Page 6
Programming for Problem solving using C UNIT-1
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
Page 8
Programming for Problem solving using C UNIT-1
Page 9
Programming for Problem solving using C UNIT-1
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
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
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
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.
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:
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.
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.
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.
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.
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
The <math.h> header file contains the mathematical operations like trigonometric
and other mathematic formats.
Page 24
1
Algorithm:
Ex. 1. Write the algorithm to find the sum and product of two given
numbers.
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
Flow-chart?
Flowchart symbols:
Start/Stop
Ellipse
Expression
Rectangle
I/O Statements
Parallelogram
Decision
Rhombus
Ex. Draw the flowchart to find the sum and product of two given
numbers.
Start
Read A,B
Sum=A+B
Product=A*B
Stop
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.
Start
Read A,B
Sum=A+B
Product=A*B
Stop
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
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.
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.
Start
Pick up a postcard
Stop
Start
Read N
Put S = 0
Initialization and I = 0
Read A
Looping
Increase I by 1
Modification (I=I+1)
is
Testing I=N
No
Write S
Stop
Start
Read A, B, C
No Yes
Is
A>B
Yes No No Yes
Is Is
B>C A>C
Stop
Solution:
Start
Read n
Sum=0
For i=1 to n
Read x[i]
Sum=Sum + x[i]
End for
Print Sum
Stop
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
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
Stop
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
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
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
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
Read Num
Sum = Sum+Num
Count = Count+1
Is
Count 30 ?
Yes
No
Average =Sum/(Count-1)
Print Average
Stop
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
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