Unti 1
Unti 1
Q) What is an Algorithm?
A set of rules that must be followed in solving a particular problem is called an algorithm.
Or
A sequential solution of any program that written in human language is called an algorithm.
1. Sequence:
Sequence means that each step of the algorithm is executed in the specified order.
The steps are executed purely sequential order.
3. Repetition:
-It involves executing one or more steps for a number of times.
-These can be implemented by while, do-while, for loops.
-These loops execute one or more steps until some condition is true.
1
Example: Algorithm to print first 10 natural numbers.
Algorithm: Step 1: set I=0,N=10.
Step 2: Repeat step3 while I<=n;
Step 3: print I.
Step 4: end.
Examples:
Write an algorithm for exchange two numbers.
Step 1: input the first number as A.
Step 2: Input the second number as B.
Step 3: Set temp=A;
Step 4: set A=B;
Step 5: set B=temp;
Step 6: print A, B.
Step 7: End.
Write an algorithm to find the larger of two numbers.
Step 1: Input first number as A.
Step 2: Input second number as B.
Step 3: if A>B
then print A.
else if A< B
then print B.
else
Print “two are equal”.
Write an algorithm to find number is even or odd.
Step 1: Input the first number as A.
Step 2: if A%2 =0
Then print “Even”.
else
print “odd”.
End.
Q. What is a Flowchart?
1. Diagrammatic (or) pictorial (or) graphical Representation of program logic involve in a problem
is called flowchart.
2. It is used to visualize the logic of the program.
3. When designing the flow chart, each step in the process is depicted by different symbols and is
associated with a short description.
4. A flow chart fallows the top-down approach in solving the problems.
2
Symbol Purpose Description
Examples: Draw a flow chart to calculate the sum of two natural numbers:
3
Draw a flow chart for finding sum of n numbers
Advantages:
• Communication: Flowcharts are better way of communicating the logic of a system to all
concerned or involved.
• Effective analysis: With the help of flowchart, problem can be analyzed in more effective way
therefore reducing cost and wastage of time.
• Proper documentation: Program flowcharts serve as a good program documentation, which is
needed for various purposes, making things more efficient.
• Efficient Coding: The flowcharts act as a guide or blueprint during the systems analysis and
program development phase.
• Proper Debugging: The flowchart helps in debugging process.
• Efficient Program Maintenance: The maintenance of operating program becomes easy with the
help of flowchart. It helps the programmer to put efforts more efficiently on that part
Disadvantages:
• Complex logic: Sometimes, the program logic is quite complicated. In that case, flowchart
becomes complex and clumsy.
• Alterations and Modifications: If alterations are required the flowchart may require re-drawing
completely. This will usually waste valuable time.
• Reproduction: As the flowchart symbols cannot be typed, reproduction of flowchart becomes a
problem.
Q) What is pseudocode?
1. It is a form of structured English that describes algorithms.
2. An ideal pseudocode must be complete, describing the entire logic of the algorithm.
3. It is basically meant for human reading.
4. Pseudocode is an outline of a program that can easily be converted into programming languages.
5. The main purpose is to enhance human understandability of the solution.
6. The keywords associated with the pseudocode are “ while—endwhile,if—endif,case—endcase”.
4
Q) What is programming language?
A programming language is a language specifically designed to express computations that can be
performed using the computer.
Programming languages usually referred as “high-level languages. These are easy for humans to
understand.
The fifth generation programming language or visual programming language, is also known as
natural language.
Provides a visual or graphical interface, called a visual programming environment, for creating
source codes.
5
Fifth generation programming allows people to interact with computers without needing any
specialized knowledge.
People can talk to computers and the voice recognition systems can convert spoken sounds
into written words.
Prolog and Mercury are the best known fifth-generation languages.
1. Requirements analysis:
In this phase, the user’s expectations are gathered to know why the program has to be built. Then,
all the gathered requirements are analyzed and documented to arrive at the scope or the objective
of the program.
6
2. Design:
The requirements documented in the previous phase act as input to the design phase. In the
design phase, a plan of actions is made before the actual development. In this phase the program
is divided into modules. We prepare alogorithms and flow charts for all modules.
3. Implementation:
In this phase, the designed algorithms are converted into program code by using any of the high-
level languages.
4.Testing:
In this phase all the modules are tested together to ensure that the overall system works well as a
whole product.
In this phase the software or program is tested using a large number of varied inputs also known
as test data, to ensure that the software or program is meet the requirements.
6.Maintenance:
Maintenance and enhancements are ongoing activities that are done to cope with new
requirements. Once when the customers starts using the developed system then the actual
problems comes up and needs to be solved from time to time. This process where the care is
taken for the developed product is known as maintenance.
UNIT – 1
CHAPTER 2: INTRODUCTION TO C
Q) History of c or background:
7
ALGOL:
The root of all modern languages is ALGOL.
ALGOL means “Algorithmic Language”.
It is the first computer language to use a block structure.
It is used for structured programming language.
BCPL:
In 1967, Martin Richards developed BCPL.
BCPL means Basic Combined Programming language.
It is used for System software.
B:
In 1970, Ken Thompson created a language called B.
It is used to create UNIX operating system.
It is type less system programming language.
C:
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell laborites.
It uses the concept of data types.
It was used for academic environments.
It is also known as “traditional c”.
K & R C:
The traditional c is popular by releasing the book “the C programming language” by Kernighan
and Ritchie in 1978.
ANSI C:
American national standards institute define standards for c in 1983. So it is known as ANSI C.
ISO C:
International standards organization approved c in 1990.It is referred as C89.
In 1999 a modified version c99 was released with character, Boolean and integer data types.
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:
This provides instructions to the compiler to link system library function.
The most common function is ‘include’ statement.
4. Global declaration section: These are some variables that are used in more than one function
Such variables are called global variables declared in this section.
5. Main ( ):
Every c program must have one main ( ) function section.
9
This section contains 2 parts
Declaration part: it is used for variable declaration
Executable part: it is contains opening logic for problem.
The main function contains opening brace for program execution starting and closing brace for
program execution ends.
All the statements in declaration and executable parts ends with a semicolon (;).
The subprogram section contains all user defined functions that are called in main () function.
1. Source code file: It contains the source code of the program with extension “.c”.
It contains main () function and may be other functions.
2. Header files: It contains all built in functions with .h extension. In C we have header files like
stdio.h, string.h, stdlib.h etc….
3. Object files: object files are generated by the compiler as a result of processing the source code
file. They contain binary code for the source code with extension .obj.
4. Executable files: Linker uses the object files to produce executable files. These files contain
extension .exe.
They are four general steps involved in the execution of a program written in ‘C’ language
irrespective of the operating system being used.
10
Once the source program is ready in a text file, next the file is submitted to the ‘C’ compiler.
The ‘C’ compilers process the source program and if the program is syntactically correct,
produce the object code.
3. Linking the program with functions in the standard ‘C’ library:
Once the object code of the program is obtained after successful compilation, the linker links
the object code with the functions in the standard library referred by the program.
4. Executing the program to get the expected output:
After the compilation of linking the functions the code should be executed.
Note: For compilation --> Alt+f9
For runnig --->ctrl+f9
To see the output screen—> Alt+f5.
Example:
#include<stdio.h> //this is link section
void main()
{
printf("Hello"); /* this is used to display the message hello */
printf("By");
}
11
Keywords in C Language
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
Identifiers refer to the names of variables, functions and arrays. These are user-defined names
and consist of a sequence of letters and digits, with a letter as a first character.
Both uppercase and lowercase letters are permitted. The underscore character is also
permitted.
Examples:
Valid identifiers: invalid identifiers:
Rol_number, money, name, DeptCode 23_money, &deptcode, auto
Unsigned char:
The unsigned char is a variation of char type.
The size of a variable of unsigned char type is also one byte.
The range of values that can be stored ina a variable of byte unsigned char is 0 to 255(0 to
unsigned int:
The size of a variable of unsigned int is also 2 bytes.
It can store only positive range of values. The range of values be stored in a variable of
unsigned int is 0 to65535(0 to
Syntax: unsigned int variablename;
Example:unsigned int ui;
short int:
The size of a variable of short int is also 2 bytes. It is similar to int.
Syntax: short int variablename;
Example:short int si;
13
long int:
The size of a variable of long int is also 4 bytes.
The range of values be stored in a variable of unsigned int is -2147483648 to 2147483647.
Syntax: long int variablename;
Example:long int li;
Unsigned Short int:
Unsigned short int is similar to unsigned int.
The range of values that can be stored in a variable of unsigned long int is 0 to 65,535 or 0 to
14
Constants
1. Integer Constant:
It must have at least one digit.
It should not contain a decimal place.
It can be positive or negative.
Use of blank space and comma is not allowed between real constants.
Example:1990, 194, -394
2. Real Constant:
It must have at least one digit.
It must have a decimal point which may be positive or negative.
Use of blank space and comma is not allowed between real constants.
Example:+194.143, -416.41
3. Character Constant:
It is a single alphabet or a digit or a special symbol enclosed in a single quote.
Maximum length of a character constant is 1.
Example:'T', '9', '$'
4. String Constant:
It is collection of characters enclosed in double quotes.
It may contain letters, digits, special characters and blank space.
Example: “ravi”, “123”, ”it is c-language”
65536 6
a : variable
65536 : address of cell
6 : value in the cell
15
Declaring & initializing C variable:
Variables should be declared in the C program before to use.
Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
Variable initialization means assigning a value to the variable.
S.No Type Syntax Example
1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;
2 Variable initialization data_type variable_name = value; int x = 50, y = 30; char flag = ‘x’, ch=’l’;
1. Input: In any programming language input means to feed some data into program. This can be
given in the form of file or from command line. C programming language provides a set of built-
in functions to read given input and feed it to the program as per requirement.
2. Output: In any programming language output means to display some data on screen, printer
or in any file. C programming language provides a set of built-in functions to output required
data.
3. In c we use printf() function for output and scanf() function for input data.
4. printf() and scanf() functions are inbuilt library functions in C programming language which are
available in C library by default. These are defined in “stdio.h”
Printf()
Printf() means print formatting.
In C programming language, printf() function is used to print the “character, string, float,
integer, octal and hexadecimal values” onto the output screen.
Syntax: printf (“format string”, argument list);
o Format string may be a collection of escape sequence or/and conversion specification
or/and string constant. The format string directs the printf function to display the entire
text enclosed within the double quotes without any change.
Escape sequence is a pair of character. The first letter is a slash followed by a character.
Escape Meaning
16
sequence
\n New line
t Tab
\b Back space
\a Bell
\o Null character
\? To print question mark
\\ To print slash
\' To print single quote
\" To print double quote
Conversion specification is also a pair of character. it is preceded by % and followed by a
quote which may be a character. The Conversion specification inscribes the printf() function
that it could print some value at that location in the text.
Conversion Specification Output
%c Character
%s string of characters
%d or %i decimal integer
%e floating point number in e-notation
%f floating point number in decimal notation
%g uses %f or %e whichever is shorter
%p Pointer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer, using lower case
%X hexadecimal integer, using upper case
%% Prints a % sign
Example:
#include <stdio.h>
int main()
{
char ch = 'A';
char str[20] = "fresh2refresh.com";
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf("Character is %c \n", ch);
printf("String is %s \n" , str);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , no);
printf("Double value is %lf \n", dbl);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}
2. SCANF()
1. It usually used input statement is scanf () function.
17
2. Syntax of scanf function is
scanf (“format string”, argument list);
3. The format string must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory.
Example: integer (%d) , float (%f) , character (%c) or string (%s).
4. The argument list contains a list of variables each proceeded by the address list and
separated by comma. The number of argument is not fixed;
Example: if i is an integer and j is a floating point number, to input these two numbers we may use
scanf (“%d%f”, &i, &j);
Example:
#include <stdio.h>
int main()
{
char ch;
char str[100];
printf("Enter any character \n");
scanf("%c", &ch);
printf("Entered character is %c \n", ch);
printf("Enter any string ( upto 100 character ) \n");
scanf("%s", &str);
printf("Entered string is %s \n", str);
}
1.Arithmetic operators:
These are used to perform mathematical calculations like addition, subtraction, multiplication, division
and modulus.
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
18
/ (Division) A/B
% (Modulus) A%B
All arithmetic operators execute from left to right.
If all operators are in one expression higher precedence operators like multiplication, division and
modulus carries first and then lower precedence operators like addition and subtraction from left to
right manner.
2. Relational operators:
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
Expression that contains relational operators is called relational expression.
Relational expressions return only true or false values.
Operators Example/Description
== x == y (x is equal to y)
!= x != y (x is not equal to y)
Example:
#include <stdio.h>
void main()
{
int m=40,n=20;
clrscr();
19
printf(“m and n are equal%d\n”,(m==n));
printf(“m and n are not equal%d\n”,(m!=n));
printf(“m is greater than n d\n”,(m>n));
printf(“m is less than n %d\n”,(m<n)); getch(); }
3. LOGICAL OPERATORS:
These operators are used to perform logical operations on the given expressions.
These are used to test two or more conditions at a time.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
Operator
s Example/Description
&& (x>5)&&(y<5)
(logical It returns true when both conditions
AND) are true
(x>=10)||(y>=10)
|| (logical It returns true when at-least one of
OR) the condition is true
!((x>5)&&(y<5))
It reverses the state of the operand
“((x>5) && (y<5))”
! (logical If “((x>5) && (y<5))” is true, logical
NOT) NOT operator makes it false
Example: #include <stdio.h>
void main()
{
int m=40,n=20;
int o=20,p=30;
clrscr();
printf(“%d”, (m>n && m !=0))
printf(“%d”, (o>p || p!=20))
getch();
}
4. BIT WISE OPERATORS:
These operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
Bitwise Negation b = 00010110
a=00000011 a|b=00010111
~a =11111100
Bitwise And
a = 00000011 Bitwise Exclusive Or
b = 00010110 a = 00000011
a&b=00000010 b = 00010110
Bitwise Or a^b=00010101
a = 00000011
20
Right Shift
a = 0000 0011 = 3
(a<<=1) = 00000110 = 6
(a<<=2) = 00011000 = 24
(a<<=3) = 11000000 = 192
Left Shift
a=11000000 =192
(a>>=1) = 01100000 = 96
(a>>=2) = 00011000 = 24
(a>>=3) = 0000 0011 = 3
21
5. Unary Operators
The operators that act upon a single operand to produce a new value are known as Unary operator.
The frequently used Unary operators in C are
1. Unary minus
The operand of Unary minus operator must have arithmetic type, and the result is the –ve of its
operand.
Example:
-(p+q)
x=-y
-10*(p+q)
1. Increment operator:
It is indicated with ++. It is used to increase the value of the variable by one. It is
classified into two types. They are:
Pre increment:
In pre-increment the value is incremented first and then the value will be assigned.
Syntax: ++operand;
Post increment:
In post-increment the value is assigned first and then the value is incremented.
Syntax: operand++;
Examples:
i) A=5; B=A++;
Now A =6, B=5.
ii) A=5; B=++A;
Now A =6, B=6.
2. Decrement operator:
It is indicated with --. It is used to decrease the value of the variable by one. It is classified into
two types. They are:
Pre decrement:
In pre-decrement the value is decremented first and then the value will be assigned.
Syntax: --operand;
Post decrement:
In post-decrement the value is assigned first and then the value is decremented.
Syntax: operand--;
Examples:
i) A=5; B=A--;
Now A =4, B=5.
Example:
22
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10;
clrscr();
printf(“ the value of a is%d\n”,a);
printf(“ the value of pre increment is%d\n”, ++a);
printf(“ the value of post increment is%d\n”, a++);
printf(“ the value of pre decrement is%d\n”, --a);
printf(“ the value of post decrement is%d\n”, a--);
}
ii)sizeof operator
It is a unary operator which is used in finding the size of data type, constant, arrays, structure etc.
Syntax: sizeof (operand);
example:
#include <stdio.h>
void main()
{
int a;
float b;
double c;
char d;
clrscr();
printf("Size of int=%d bytes\n",sizeof(a));
printf("Size of float=%d bytes\n",sizeof(b));
printf("Size of double=%d bytes\n",sizeof(c));
printf("Size of char=%d byte\n",sizeof(d));
return 0;
}
24