Professional Documents
Culture Documents
Vignan CP UNIT-1 Part-1
Vignan CP UNIT-1 Part-1
COMPUTER PROGRAMMING
2
UNIT-1
INTRODUCTION:
DEFINITION OF COMPUTER: Computer is an Electro-Mechanical device, which accepts
data as its input from its user process it by doing some kind of manipulations and produce the
output in a desired format, which can capable to store large volume of information.
“COMPUTER” was originally a job title: it was used to describe those human beings
(predominantly Women) whose job it was to perform the repetitive calculations required to
compute such things as navigational tables, tide charts, & planetary positions.
1. Calculator works with numeric data. 1. Computer works with alphanumeric data.
3. Input in the form of pressing or touching 3. Input may be in several forms, like:
punch
CPU
CU ALU
Memory Unit
1. System Software
2. Application Software
HARDWARE:
The physical components of the computer are called Hardware. Those components can
be seen and touched.
1. Low level language: These are basically two types, they are
a.)Machine Language
b.)Assembly Language
2. High level language: A set of languages developed which are very close to our native
languages, are called high-level languages. High level languages were designed to provide high
level control structures.
1. Execution of machine language program is faster than the assembly language program,
because there is no conversion in machine language.
2. Reading and writing the assembly language programs are easy for programmers; it is
difficult in machine language.
3. Machine instructions are difficult to remember where as mnemonics are easy to
remember.
4. Introduction of data to program is easier in assembly language, while it is difficult in
machine language.
It is a robust language with rich set of built-in functions and operators that can be used to
write any complex program.
The C compiler combines the capabilities of an assembly language with features of a
high-level language.
Programs Written in C are efficient and fast. This is due to its variety of data type and
powerful operators.
C is highly portable this means that programs once written can be run on another
machines with little or no modification.
Another important feature of C program is its ability to extend itself.
A C program is basically a collection of functions that are supported by C library. We
can also create our own function and add it to C library.
C language is the most widely used language in operating systems and embedded system
development today.
ALGORITHM:
Definition:
6
or
An Algorithm is defined as ‘a finite steps that provide a chain of actions for solving a
definite nature of problem’.
Properties of Algorithm:
1. Input
2. Output
3. Finiteness
4. Definiteness
5. Effectiveness
6. Generality
1. Input: An Algorithm can take some precise input during its execution, zero or more inputs.
3. Finiteness: An Algorithm must terminate after a fixed number of steps. It means Algorithm
have an end.
4. Definiteness: Each step in an Algorithm must be definite i.e; it must have a meaning towards
the solution.
5. Effectiveness: All the operations used in the Algorithm can be performed exactly in a fixed
duration of time.
6. Generality: Algorithm should be complete in itself so that it can be used to solve all
problems of a given type for any input data.
Write an Algorithm for finding the largest number amongst the 3 numbers.
Step1: START
Step2: Read the values for a, b, c
Step3:if a>b and a>c then
Step4: Display the result as ‘a’ is biggest or largest number
Step5: otherwise, if b>c then
Step6: Display the result as ‘b’ is largest number
Step7: otherwise, display the result as ‘c’ is largest number
Step8: STOP
7
FLOW CHART:
By representing the various steps in the form of a diagram called as flow chart.
or
A completed flow chart enables you to organize your problem into a plan of actions.
Limitations:
Advantages:
Start/stop. It comes
Oval (or) Egg shaped terminal
twice in a flow chart.
Depends on the
Diamond Decision
condition
Start
Read a, b, c
If b>c Print a
False True
Print c Print b
Stop
Executable part;
}
It starts with two forward slashes (i.e //) and is automatically terminated with the end –
of the line. The first line of our program is a single line comment.
or
/* This is
an example*/
2. Header Files: A C program depends upon some header files for function definition that are
used in the program. Each header file by default has a extension ‘.h’. The file should be included
by #include directive.
a.)stdio.h
#include<stdio.h> or #include “stdio.h”
Ex: printf (), scanf (), put (), get ()
b.)math.h
#include<math.h>
Ex: pow (), absc (), cos (), sin (), sqrt (), sqr ()
c.)conio.h
#include<conio.h>
10
d.)string.h
#include<string.h>
Ex: strlen (), strcmp ()
3. Global Declaration:
In this section global variables are declared before main(). These functions can be accessed by
the all used defined functions including main(). If a user defined function or a variable is not
declared in this section it will not accessed by the remaining functions.
4. Main function: Every program written in C language must contain the main() function.
Empty parentheses after main are necessary. The execution of program always begins main().
5. Declaration Part: The declaration part declares all variables that are used in the execution
part. Initialization of variables is also done in the section. Provides initial value to the variables.
Variables are declared by using data types.
6. Executable Part: This part contains the statements following the declaration of the variables.
This part contains a set of statements or single statement. These statements enclosed between
braces.
7. User-Defined Functions: The functions defined by the user are called user-defined functions.
These functions are generally defined after the main function. This portion is not compulsory.
[return-type] function_name([argument_list])
Programming Rules:
1. All statements should be written in lower case letters. Upper case letters are only used
for symbolic constants. Either in upper case or lower case will contain different ASCII
values. The ASCII carries 7 bits for represent each character.
2. Blank spaces may be inserted between the words. This improves the readability of the
statements. It is not used while declaring a variable, keyword, constant and functions.
11
3. Every statement in C must be ended with semicolon (;). In the function definition must
not ended with semicolon.
4. The opening and closing braces should be balanced i.e; for ex: if opening braces four
then closing braces should also be four.
Sample program:
#include<stdio.h>
void main()
{
printf(“Hello World\n”);
}
Output:
Hello World
1. Creating the Program: The program should be written in ‘C’ editor. The file name
does not necessarily include the extension ‘.c’. The default extension is ‘.c’.
2. Compiling the Program: The source program statements should be translated into the
object program, which is suitable for execution by the computer. The translation is done
after correcting each statement. If there is no error, compilation proceeds and translated
program is stored in another file with the same file name with extension ‘.obj’. If errors
are there the programmer should correct them.
a.)Interpreters: An Interpreter reads only one line of a source program at a time and
converts it to the object codes. The disadvantage is that it consumes more time for
converting a source program to an object program.
b.)Compilers: A Compiler reads the entire program and converts it to the object code. It
consumes little time for converting a source program to an object program.
12
3. Linking the Program: Linking is also an essential process. It puts together all other
program files and functions that are required by the program.
Ex:- The user is using the pow() function, then the object code of this function should be
brought from math.h library of the system and linked to the main() program.
4. Executing the Program: After the compilation, the executable object code will be
loaded in the computer’s main memory and the program is executed.
Let us see how to save the source code in a file, how to compile and how to run it.
System Ready
Source program
Compile Source
C Compiler Program
No
Object code
System Library Link with System
Library
Executable object code
Execute object
Input data
Code
No Errors
Correct output
Stop
C TOKENS:
In a passage of text, individual words and punctuation marks are called Tokens.
Similarly, in a C program the smallest individual units are known as C Tokens.
14
C Tokens
Constants Strings
-15.5, 100 “ABC”, year
Identifiers: Identifiers are names of variables, functions and arrays. They are user-defined
names, consisting of sequence of letters & digits. Lower case letters preferred. Upper case also
permitted. ( _ ) symbol can be used as an identifier. In general ‘_’ used as a link between 2
words in long identifiers.
Variables: A variable is a data name that may be used to store a data value. A variable name
can be chosen by the programmer in a meaningful way so as to reflect its function or nature in
the program.
Valid Ex:- Average height counter_1 sum1
Invalid Ex:- 123 (area) % 25th
Rules for defining variables:
1. They must begin with a character without spaces but underscore is permitted.
2. ANSI C recognizes the maximum length of a variable up to 31 characters.
3. The variable should not be a keyword.
4. The variable names may be a combination of upper and lower characters.
5. The variable name should not start with a digit.
Keywords:
C Character Set
As every language contains a set of characters used to construct words, statements etc., C
language also has a set of characters which include alphabets, digits and special symbols. C
language supports a total of 256 characters.
Every C program contains statements. These statements are constructed using words and these
words are constructed using characters from C character set. C language character set contains
the following set of characters...
1. Alphabets
2. Digits
3. Special Symbols
Alphabets
C language supports all the alphabets from english language. Lower and upper case letters
together supports 52 alphabets.
Digits
C language supports 10 digits which are used to construct numerical values in C language.
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports rich set of special symbols that include symbols to perform mathematical
operations, to check conditions, white spaces, back spaces and other special symbols.
16
Special Symbols - ~ @ # $ % ^ & * ( ) _ - + = { } [ ] ; : ' " / ? . > , < \ | tab newline space NULL
bell backspace vertical tab etc.,
Every character in C language has its equivalent ASCII (American Standard Code for
Information Interchange) value.
Constants:
The constants in C are applicable to the values which do not change during the execution
of a program. There are several types of constants in C.
C Constants
Integer constants: An integer constant refers to a sequence of digits. There are 3 types of
integer, namely
Decimal integer
Octal integer
Hexa decimal
Included spaces, commas, and non-digit characters are not permitted between digits.
Octal Integers: An Octal integer constant consists of any combination of digits from the
set 0 through 7, which leading 0.
Real Constants: Integer numbers are inadequate to represent quantities that vary continuously,
such as distances, heights, temperatures, prices and so on. These quantities are represented by
numbers containing fractional parts like 17.548; such numbers are called real or floating point
constants.
These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part. It is possible to omit digits before the decimal point or
digits after the decimal point.
-0.000000368 -3.68E-7
Single character constants: A single character constant contains a single character enclosed
within a pair of single quote marks.
Ex:- 1 Write a C program for printing ASCII values for corresponding characters.
#include<stdio.h>
void main()
{
printf(“%d”,’a’);
}
Output: 97
#include<stdio.h>
void main()
{
printf(“%c”,97);
}
18
Output: a
String constants: A string constant is a sequence of characters enclosed in double quotes. The
characters may be letters, numbers, special characters and blank space.
Remember that a character constant (eg:- x) is not equivalent to the single character
string constant. Further, a single character string constant does not have an equivalent integer
value while a character constant has an integer value.
#include<stdio.h>
void main()
{
printf(“%s”,”well done”);
}
C supports some special backslash character constants that are used in output functions.
Each one of them represents one character, although they consist of two characters. The
characters combinations are known as Escape sequences.
Constant Meaning
\a Audible alert
\b back space
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\’ single quote
\” double quote
\? Question mark
\\ Back slash
\0 null
#include<stdio.h>
19
void main()
{
printf(“welcome to C\n”);
printf(“Backslash\tConstants”);
printf(“\nThank you”);
}
Output: welcome to C
Backslash Constants
Thank you
We often use certain unique constants in a program. These constants may appear
repeatedly in a number of places in the program. One example of such a constant is 3.142,
representing the value of the mathematical constant “pi”.
In any case if you want to change the value of pi, we have to search throughout the
program, if any value is left, the program may produce wrong result. To avoid this disadvantage
C provides to define symbolic constants.
Syntax:
#define PASS_MARK 40
#define PI 3.142
1. Symbolic names have the same form as variable names. (symbolic names are written in
CAPITALS to visually distinguish them from the normal variable names which are
written in lower case letters.)
2. No blank space between # and define is permitted.
3. # must be the first character in the line.
4. A blank space is required between #define and symbolic name and between the symbolic
name and the constant.
5. #define statements must not end with a semicolon.
1. Primary data types: Primary data types are divided into sub parts.
a. Integer data type: C offers three different integer data types they are
short int
int
long int
short int: short int represents fairly small integer values and requires half the
amount of storage as a regular int number uses. The size of the short int occupies
1 byte. If we use 8 bits length, the size of the short int value is limited to the
range -128 to +127. The control string is used for it is %d.
int: Integers are whole numbers with a range of values supported by a particular
machine. The size of the integer occupies 2 bytes. If we use 16 bits length, the
size of the integer value is limited to the range -32768 to +32767. A signed
integer uses one bit for sign and 15 bits for the magnitude of the number, control
string is %d.
long int: The storage capacity is 4 bytes, 32 bit word length can store an integer
ranging from -2,147,483,648 to 2,147,483,647 the control string is used for it is
%ld.
Type Modifiers -
A type modifier alter the meaning of the base data type to yield a new type. There are four types
of modifiers in C they are
21
signed
unsigned
short
long
C has 3 classes of integer storage, namely short int, int, long int, in both signed and unsigned
forms. We are already discussed about signed forms.
unsigned short int: unsigned integers use all the bits for the magnitude of the
number and are always positive. Unsigned short integer occupies 1 byte, 8 bits.
Its ranging from 0 to 255. The control string is %u.
unsigned int: Unsigned integers occupy 2 bytes and its range will be from 0 to
65,535.
unsigned long int: Unsigned long integers to increase the range of values. It
occupies 4 bytes the rage is 0 to 4,294,967,295.
b. Floating point data type: Floating point numbers are stored in 32 bits, with 6 bits of
precision. Floating point numbers are defined in C by the keyword float. The accuracy
provided by a float number is not sufficient. Its range is 3.4E-38 to 3.4E+38
double: A double data type number uses 64 bits giving a precision of 14 digits.
These are known as double precision numbers.
long double: To extend the precision further, we may use long double which uses
80 bits
c. Character data type: A single character can be defined as a character (char) type
data. Characters are usually stored in 8 bits of internal storage. The qualifier signed char
(or) unsigned char.
unsigned char: unsigned char have values between 0 to 255
signed char: signed char have values from -128 to 127
Ex:- Write a C program for displaying numbers using different data types.
#include<stdio.h>
void main()
{
float x,p;
double y,q;
unsigned int k;
int m=54321;
long int n=1234567890;
x=1.234567890000;
y=9.87654321;
k=54321; Output: m=-11215
p=q=1.0; n=1234567890
printf(“m=%d\n”,m); x=1.234567880630
printf(“n=%ld\n”,n); x=1.234568
y=9.876543210000
y=9.876543
k=54321,p=1.000000,q=1.000000000000
22
printf(“x=%.12lf\n”,x);
printf(“x=%f\n”,x);
printf(“y=%.12lf\n”,y);
printf(“y=%lf\n”,y);
printf(“k=%u,p=%f,q=%.12lf\n”,k,p,q); }
Size in Control
Data Type Keywords Range
bytes bits String
char (or)signed
signed character 1 8 -128 to +127 %c
char
3.4E-4932 to
long double long double 10 80 %lf
3.4E+4932
1byte=8bits.
C Scopes:
• Scope of the variable is the visibility of the variable in the block.
• Visibility means accessibility (or) area of the program we can access the variable.
• There are Two types:
Local variable: The local variables are defined within the body of the function or the block.
The variable defined is local to that function or block only. Other function cannot access these
variables. The compiler shows errors in case others functions try to access the variables.
#include<stdio.h>
main()
{
int b=10, c=5;
printf(“In main() b=%d c=%d”,b,c);
fun();
}
fun()
{
int b=20,c=10;
printf(“\n In fun() b=%d c=%d, b,c);
}
Global variables: Global variables are defined outside the main() function. Multiple functions
can use them.
#include<stdio.h>
int b=20,c=10;
main()
{
printf(“\n In main() b=%d c=%d”,b,c);
fun();
}
fun()
{
printf(“In fun() b=%d c=%d”,b,c);
}
24
b) These variables can accessed only by b) These variables can be accessed by all
the function in which they are declared. the functions in the programs.
c) Default value for local variable is c) Default value for global variable is
garbage value. zero.