C
C
ALGORITHM:
An algorithm is a step-by-step description of how to arrive at a solution. An algorithm
provides a blueprint for writing a program to solve a particular problem. Once we have an
idea or a blueprint of a solution, we can implement it in any high-level language, such as C,
C++, JAVA, and so on.
Characteristics of Algorithm:
1. Be precise
2. Be unambiguous
3. It looks like normal English.
4. Not even a single instruction must be repeated infinitely
5. After the algorithm gets terminated, the desired result must be obtained.
1
UNIT-I
3. Repetition: Repetition involves executing one or more steps for a number of times.
This can be implemented using constructs such as while, do-while, and for loops.
These loops execute one or more steps until some condition is true.
Algorithm to first 10 natural numbers
Step 1: [initialize] Set I=1, N=10
Step 2: Repeat steps 3 and 4 while I<=N
Step 3: print I
Step 4: set I=I+1
Step 5: End
FLOWCHARTS:
A flowchart is a graphical representation of a process.
2
UNIT-I
When designing a flowchart, each step in the process is shown by different symbol and is
associated with a short description. The symbols in the flowchart are linked together with
arrows to show the flow of logic in the process.
Significance of flowcharts:
A flowchart is a graphical representation of the process.
It is usually drawn in the early stage of the programming.
Once a flow chart is drawn, programmers can understand the logic of the problem.
Once a flow chart is drawn, it becomes easy for the programmers to write the program
in any high-level language.
A flowchart follows top-down approach in solving problems.
They act as a guide or blueprint for the programmers to code the solution in any
programming language. They direct the programmers to go from the starting point of
the program to the ending point without missing any step.
They can be used to debug programs that have error(s). They help the programmers to
easily detect, locate and remove mistakes in the program in systematic manner.
Limitations:
Drawing flowchart is laborious and time consuming activity.
Often, the flowchart of a complex program becomes complex and clumsy.
At times, a little bit of alteration in the solution may require complete re-drawing of
the flowchart.
3
UNIT-I
4
UNIT-I
PROGRAMMING LANGUAGES:
Language is the communication media, Human languages (eg. Telugu, English, Hindi etc) are
used to establish communication between person to person where as computer languages are
used to establish the communication between the person and machine. The computer
languages are divided into the following:
Computer Languages
5
UNIT-I
6
UNIT-I
Advantages Disadvantages
Advantages Disadvantages
1. The code is machine independent. 1. Code may not be optimized.
2. It is easy to learn and use the 2. The code is less efficient.
language. 3. It is difficult to write a code that
3. There are few errors. controls the CPU, memory and
4. It is easy to document and understand registers.
the code.
5. It is easy to maintain the code.
6. It is easy to detect and correct errors.
7
UNIT-I
8
UNIT-I
Unstructured Programming:
In unstructured programming, programmers write small and simple programs consisting only
of one main program. Here, main() consists of statements that modify the data that is global
throughout the whole program. Though this technique is simple, it is not good for writing
large programs. For example, if we need to perform a particular task multiple times in a
program, then we need to copy the same sequence of statements at different locations within
the program. This led to the idea of writing functions or procedures. The new technique of
using procedures came to be known as procedural programming.
Structured Programming:
The concept of structured programming also referred to as modular programming. Structured
programming employs a top-down approach in which the overall program structure is broken
down into separate modules. This allows the code to be efficiently loaded into the memory
and to be reused in other programs. Modules are coded separately, and once a module is
written and tested individually, it is then integrated with the other modules to form the overall
program structure. In structured programming, the program flow follows a simple sequence
and usually avoids the use of goto statement. Besides sequential flow, structured
programming also supports selection and repetition. Selection allows for choosing any one of
a number of statements to execute based on the current status of the program. Selection
statements contain keywords such as if, then, endif, and switch. In repetition, a selected
statement remains active until the program reaches a certain point. It includes keywords such
as repeat, for, and do until.
Advantages:
1. The goal of structured programming is to write correct programs that are easy to
understand and modify.
2. A structured program can be written in less time than an unstructured program.
Modules or procedures written for one program can be reused in other programs as
well.
3. A structured program is easy to debug. This is because each procedure is allowed to
perform just one task and therefore, every procedure can be checked individually for
any error.
4. Every procedure in a structured program has meaningful names and has clear
documentation of a task to be performed. This is clearly understood by another
programmer.
9
UNIT-I
Object-oriented programming:
Unstructured and structured programming paradigms are task-based. The object-
oriented paradigm is both task-based and data-based. All the relevant data and tasks
are grouped together in entities known as objects. The major objective of object-
oriented approach is to eliminate some of the defect encountered in the procedural
approach. OOP treats data as critical element in the program development and does
not allow it to flow freely around the system.
SHAPE
10
UNIT-I
1. BASIC:
BASIC (Beginners All-purpose symbolic Instruction Code) is a general purpose high-
level programming language developed in the 1964 by John G.Kemeny and Thomas.
In 1960s, programming was done only by scientists and mathematicians. BASIC was
specially designed to enable students in fields other than science and mathematics to
use computers. It was easy to learn and was very powerful language that was used for
wide range of applications. In 1970s BASIC was widely used in microcomputers.
2. FORTRAN:
FORTRAN (Formulas Translation) is one of the oldest general purpose programming
languages. It was developed in 1957 at IBM by John Backus. The development of
FORTRAN was remarkable development in the field of programming languages. It is
a machine independent, simple language suitable for a wide variety of applications
that combined a form of English shorthand with algebraic equation. It is extensively
used in areas such as weather prediction, finite element analysis. It is also used in
programming video games, air traffic control system.
3. Pascal:
Pascal is a procedural programming language developed in the late 1960s. It is a small
and efficient language specifically designed to encourage good programming. The
structure and syntax of Pascal is similar to that of C. Pascal provided many features
that were lacking in other languages. Pascal contains built-in data types, user-defined
data types, and defined set of data structures.
4. C
C is a high-level general-purpose programming language that was developed in 1970s
by Dennis Ritchie at Bell Labs. C is considered as a powerful and flexible
programming language that can be used for wide range of applications varying from
business programs to engineering. It is relatively small requires less memory. It is
easy to understand. It is easily portable.
5. C++
C++ is a general-purpose programming language developed by Bjarne Stroustrup
starting in 1979 at Bell Labs. Like C, C++ is an intermediate-level language because
it comprises both high-level and low-level language features. It is a powerful
language implemented on a wide variety of hardware and operating system platforms.
It is a superset of the C language. It is an object oriented programming. It allows the
programmers to reuse the existing code. In C++ it is easy to write, debug and modify
a code.
11
UNIT-I
6. JAVA
Java is a general-purpose object-oriented programming language released by Sun
Microsystems in 1995. It is a powerful language than C++ and other high-level
languages. Programs written in Java are robust, secure, and reliable. Java was used in
Internet applications (games, chatting), Desktop publishing (Viewing images in 3D),
Embedded system applications, Intranet applications and other e-business solutions.
Java program follow write once, run anywhere (WORA). Java source code files (with
.java extension) are compiled into a bytecode (with a .class extension), which can then
be executed by a Java interpreter.
7. LISP
LISP (List processing), is one of the oldest programming language still widely used
by programmers all over the world. List processing (Lisp) allows programs to easily
manipulate non-numeric data such as symbols and strings of text. LISP’s ability to
manipulate symbolic expressions rather than numbers makes it convenient for
artificial intelligence applications and for simulation of games.
Organizational Policies: Organizations have policies that dictate which computer hardware
and software they should use. For example, many organizations have Java as the default
programming language.
Suitability: The programming language must be able to work on the platform being used.
Availability of programmers: The choice of programming language also depends on the
programmer’s experience and expertise. If a new language that is new to the programmer is
chosen, then it would demand more investment in terms of time and money because either the
programmer will have to be trained in the language or some new programmer having a sound
knowledge of that language would be hired. In both cases, extra time and money will be
required.
Reliability: Some programming languages have built-in features that support the
development of the software that is reliable and less prone to crash. A reliable code can
withstand even in stress conditions.
Development costs: Development cost should be considered while choosing a programming
language.
Speed of development: Speed of development is a factor that not only includes the time it
takes to write a code but also considers the time taken to find a solution to the problem.
Object orientation: In some situations, object-oriented programming to code a solution is far
more beneficial than coding with a traditional language. This is because it not only speeds up
the development process because of the existing code that can be reused.
Elasticity: The elasticity of the language makes easy to add new features to the existing
program.
Performance: The performance of a language is to be considered.
12
UNIT-I
Speed requirements: Different languages take different times to execute. The time to
execute a code also depends on whether the language in which it is written is compiled,
assembled or interpreted.
GUI requirements: Some languages have a in-built support for GUI, whereas others either
do not have or have very little support for GUI. If a program that needs GUI, then the code
will be very lengthy and complex.
PSEUDOCODE
Pseudocode is a form of structured English that describes algorithms. It allows designers to
focus on the logic of the algorithm without getting stuck down by the details of language
syntax. The pseudocode purpose is to enhance human to understand the solution. This helps
even non-programmers to understand the logic of the designed solution. There are no
standards defined for writing a pseudocode.
Keywords used while writing pesudocode
For looping and selection, the designer must include the keywords Do while…EndDO; Do
until … EndDo; Case … EndCase; If … EndIf;
Parts of Pseudocodes:
1. If-Then: If the condition is true the statements in the Then clause executes.
Syntax:
If condition Then
Statements
End If
13
UNIT-I
3. Case Type: To make a decision from number of choices we use Case type.
Syntax:
CASE expression OF
Case 1: statement 1
Case 2: statement 2
------
Case n: statement n
Others:
Default statement
End Case
While: The statements of a loop will execute as long as the condition is true.
Syntax:
While condition
Statement
End while
Ex: while i<=10
Print i
Increment i
End while
Examples:
Calculating the price of a product adding sales tax to its original price.
1. Read the price of the product.
2. Read the sales tax rate
3. Calculate sales tax= price of
the item × sales tax rate.
4. Calculate total price= price of
the product + sales tax.
5. Print total price.
6. End
Variables: price of the product, sales
tax rate, sales tax, total price
14
UNIT-I
15
UNIT-I
HISTORY OF C
The root of modern language is ALGOL, introduced in the early 1960’s. It was first computer
language to use a block structure. Although it never became popular in USA, it was widely
used in Europe. ALGOL gave the concept of structured programming.
FEATURES OF C
1. Simple: C is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library functions, data types etc.
2. Portable: This feature refers to use of C language program on different platforms
without any change in configuration.
3. Structured Programming Language: C is a structured programming language in the
sense that we can break the program into parts using functions. So, it is easy to
understand and modify.
4. Speed: The compilation and execution time of C language is fast.
5. Extensible: C language is extensible because it can easily adopt new features
6. Case Sensitive: C is a case sensitive, that is it can differentiate the character is either
upper case or lower case.
16
UNIT-I
7. Pointer: C provides the feature of pointers. We can directly interact with the memory
by using the pointers.
8. Recursion: In C, we can call the function within the function.
9. Rich Library: C provides a lot of in-built functions that makes the development fast.
10. Memory Management: It supports the feature of dynamic memory allocation.
STRUCTURE OF C PROGRAM
Documentation Section
Link Section
Definition Section
Global Declaration Section
main( ) Function Section
{
Declaration Part
Executable Part
}
Subprogram section
Function-1
Function-2
.
.
. (User-defined funtions)
.
Funtion-n
The documentation section consist of a set of comments lines.
The link section provides instructions to the compiler to link functions from the
system library.
The definition section defines all symbolic constants.
The global declaration section contains variables that can be used in more than one
function and we call these variables as global variables.
Every C program must have one main() function section. This section contains two
parts declaration and executable part. The program execution begins at the opening
brace and ends at the closing brace. The closing brace is the logical end of the
program. All the statements in the declaration and executable parts end with
semicolon (;).
Subprogram section contains all the user-defined functions that are called in the main
function.
FIRST C PROGRAM
#include <stdio.h>
#include <conio.h>
main()
{
printf("Hello C Language");
getch();
}
17
UNIT-I
#include <stdio.h> includes the standard input output library functions. The printf() and
scanf() functions are defined in stdio.h .
#include <conio.h> includes the console input output library functions. The getch()
function is defined in conio.h file.
CHARACTER SET
A character set denotes any alphabet, digit or special symbol used to represent information.
Alphabets A, B, ….., Y, Z
a,b ……, y, z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols ~‘!@#%^&*()_-+=|\{}
[]:;"'<>,.?/
COMMENTS
Comments are like helping text in your C program and they are ignored by the compiler.
There are two types of comments.
1. Single Line Comments
2. Multi Line Comments
Single line comments are represented by double slash //.
Example: // printing information
Multi line comments are represented by slash asterisk /*…*/. It occupies of many lines of
code.
Example:
/*
Code
To be commented
*/
C TOKENS
The smallest individual units in a program are known as tokens. C has the
following tokens.
Keywords
18
UNIT-I
Identifiers
Constants
Strings
Special symbols
Operators
KEYWORDS
The following list shows the reserved words in C. These reserved words may not be used as
constants or variables or any other identifier names. There are 32 keywords.
IDENTIFIERS
Identifier refers to the name of variables, functions and arrays. These are the 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 in
identifiers.
Rules for identifiers:
1. First character must be an alphabet (or underscore).
2. Must consist of only letters, digits, or underscore.
3. Cannot use a keyword.
4. Must not contain white space
5. Only first 31 characters are significant.
CONSTANTS
Constants in C refer to fixed values that do not change during the execution of a program. C
supports types of constants as explained below:
CONSTANTS
Integer Constants:
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer
Decimal integer: It consists of a set of digits, 0-9. It may be either positive or negative.
Ex: 3445, 123, -123, -56, 0
19
UNIT-I
Octal integer: It consists of any combination of digits from the set 0 to 7 with a leading
0. Octal values have sign
Ex: 034, 037, 0551
Hexadecimal integer: It consists of a set of digits 0 to 9 and alphabets A to F to represent
the values of 10 to 15. Each Hexadecimal value begins with 0x.
Ex: 0x20xF5, 0x2, 0x9F
Real Constants:
A real constant refers to numbers containing fractional parts like 17.4. Such numbers are
called real (or floating point) constants.
A real number may also be expressed in exponential notation.
Ex: 2.1565e2
String Constants:
A string constant is a sequence of characters enclosed between double quotes. The characters
may be alphabets, digits, special characters and blank spaces.
Ex: “Ashwika”, “2016”, “ MAY1”
20
UNIT-I
int a;
float b;
char c;
From above a, b, c are variables and int, float, char are data types.
Rules for defining variables:
o A variable can have alphabets, digits and underscore.
o A variable name can start with alphabet and underscore only. It can't start with digit.
o No white space is allowed within variable name.
o A variable name must not be any reserved word or keyword e.g. int, float etc.
DATA TYPES
Data types specify what type of data we enter into our programs. C language has some
predefined set of data types. These data types have different storage capacities.
C language supports data types like
Primary data types: These are fundamental data types in C namely integer (int), floating
(float), character (char) and void
Derived data types: Derived data
types are like arrays, unions,
structures and pointers.
User-Defined data types: User-
Defined data types like Typedef,
Enum.
Integer type:
Integers are used to store whole numbers.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
Floating type:
Floating types are used to store real numbers.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
21
UNIT-I
Character type:
Character types are used to store characters value.
Size and range of Integer type on 16-bit machine
Type Size(bytes) Range
Void type:
Void type means no value.
I/O STATEMENTS IN C
C programming language provides many of the built-in functions to read given input and
write data on screen, printer or in any file.
These built-in functions are available in “stdio.h” and “conio.h” header files.
The I/O functions are classified into 2 categories as shown below:
I/O FUNCTIONS
Scanf(): It is a formatted input function which is used to accept data from the user (keyboard)
at run time. The given data is transferred to the memory and is stored in the specified
variables.
Syntax: scanf (“format-string”, &varl , &var2... &var-n);
Printf(): The printf ( ) function is a formatted output function that is used to display the
given information on the standard output device. It is used to print numbers, characters and
strings or combination of the above along with appropriate message.
The syntax of this function can be anyone of the following: #include<stdio.h>
Syntax-1: printf (“format-string”); Syntax-2: printf #include<conio.h>
(“format-string”, values-list); main()
{
In the above syntax, the 'values-list' can be variables, int x;
constants, or expressions separated by commas. The 'format- printf(" Enter the value ");
string' is a string constant that contains the following: scanf("%d",&x);
printf(" The value of x is %d ",x);
char i;
22 i=getchar();
putchar(i);
getch();
}
UNIT-I
Getchar (): This is an unformatted I/O function which is used to accept a character from the
keyboard and stores in a variable.
Syntax: variable=getchar();
Putchar (): This is an unformatted I/O function which is used to print a character on the
standard output device. i.e. monitor.
Syntax: putchar(arg)
#include<stdio.h>
Gets(): This is an unformatted I/O function which is used to
#include<conio.h>
accept a string from the keyboard and stores in a variable. It main()
reads characters until Enter is pressed. It stores null character {
‘\0’ at the end of the string.
Syntax: gets(variable); char a[8];
gets(a);
Puts(): This is an unformatted I/O function which is used to puts(a);
getch();
print a string on the monitor.
}
Syntax: puts(variable);
OPERATORS
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
C operators can be classified into following types,
1. Arithmetic operators
2. Relation operators
3. Logical operators
4. Assignment operators
5. Increment and decrement operators
6. Conditional operators
7. Bitwise operators
8. Special operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division (which returns quotient value)
23
UNIT-I
Integer Arithmetic:
When both the operands in a single arithmetic expression are integers, the expression is
called an integer expression, and the operation is called integer arithmetic.
Example:
a=14 and b =4
a-b=10, a+b=18, a*b=56, a/b=3(decimal part truncated), a%b=2 (remainder of integer
division)
Real Arithmetic: An arithmetic operation involving only real operands is called real
arithmetic.
Example:
X=6.0/7.0 = 0.857143
Mixed-mode Arithmetic:
When one of the operands is real and the other is integer, the expression is called a mixed-
mode arithmetic expression.
Example:
15/10.0=1.5
2. Relational operators: The relational operators are used to compare two values and
gives either true (1) or false (0) result. The following are the relational operators.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
Example:
#include<stdio.h>
#include<conio.h>
main()
24
UNIT-I
{
int a,b;
a=20,b=3;
printf(" \n a>b %d ",a>b);
printf(" \n a<b %d ",a<b);
printf(" \n a==b %d ",a==b);
printf(" \n a<=b %d ",a<=b);
printf(" \n a>=b %d ",a>=b);
printf("\n a!=b %d ",a!=b);
getch(); }
3. Logical operators: These are used to combine two or more relational expressions and
give the result either true or false.
Operator Meaning
&& Logical and
|| Logical or
! Logical not
Truth table for AND Truth table for OR Truth table for NOT
P Q P&& P Q P||Q P Not P
Q
T T T T T T T F
T F F T F T F T
F T F F T T
F F F F F F
25
UNIT-I
The increment operator '++' and decrement operator ‘- -‘has different meaning depending
on the position it is used. It means this operator is used again two ways. They are pre-
increment, post-increment and pre-decrement, post-decrement.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int a=1,b=2;
printf(" \n Post increment of a is %d ",a++);
printf(" \n post decrement of b is %d ",b--);
printf(" \n pre increment of a is %d ",++a);
printf(" \n pre decrement of b is %d ",--b);
getch();
}
6. Conditional operators:
It is also known as Ternary Operator. The general form of conditional operator is as
follows:
Syntax: (Exp1)? Exp2: Exp3;
Working: Exp1 is evaluated first, if it is true Exp2 will be executed. If Exp1 is false Exp3
will be executed.
Example:
#include<stdio.h>
#include<conio.h>
main()
{
int a=120, b=23;
(a>b)? printf("hi"):printf("hello");
getch();
}
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR (Exclusive OR)
~ 1’s complement
>> Right shift
<< Left shift
26
UNIT-I
8. Special operators:
The following are the special operators used in ‘C’ language.
Comma operator (,)
Sizeof operator : This operator returns the size of an operand
Pointer operator ( & and *)
Member selection operators (. And ->)
The sizeof Operator:
The sizeof is a compile time operator and, when used with an operand, it returns the number
of bytes the operand occupies. The operand may be a variable, a constant or a data type
qualifier.
Examples: m=sizeof(sum);
n=sizeof(int);
TYPE CONVERSION
Type conversion in C can be classified into the following two types:
1. Implicit type conversion.
2. Explicit type conversion.
When the type conversion is performed automatically by the compiler without programmer’s
intervention, such type of conversion is known as implicit type conversion or type
promotion.
The compiler converts all operands into the data type of the largest operand.
The type conversion performed by the programmer by posing the data type of the expression
of specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression;
Typecasting: When a value is converted from one data type to another data type then it is
called type casting.
27
UNIT-I
int a=25;
float x, y;
x = a/ 4;
y = (float) a /4;
printf("x = %f',x);
printf(''y = %f' ,y);
}
Output:
X=6.0000
Y=6.25000
28