Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
39 views57 pages

PSPC Chapter 1

The document covers the fundamentals of computer programming, focusing on computing environments, algorithms, flowcharts, and the C programming language. It details various computing environments such as personal, time-sharing, client-server, and distributed systems, as well as types of programming languages including low, high, and middle-level languages. Additionally, it explains algorithms and flowcharts, their advantages and limitations, and provides examples of algorithms and flowcharts for common programming tasks.

Uploaded by

ajay701390
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)
39 views57 pages

PSPC Chapter 1

The document covers the fundamentals of computer programming, focusing on computing environments, algorithms, flowcharts, and the C programming language. It details various computing environments such as personal, time-sharing, client-server, and distributed systems, as well as types of programming languages including low, high, and middle-level languages. Additionally, it explains algorithms and flowcharts, their advantages and limitations, and provides examples of algorithms and flowcharts for common programming tasks.

Uploaded by

ajay701390
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/ 57

Problem Solving and Programming Through C

TOPICS
Unit-1
Introduction to Computer Programming:
Computing Environments,
Computer Languages,
Creating and Running Programs.

Algorithms and Flow charts :


Definition of Algorithms and examples,

Introduction to C Language:
C Identifiers,
Data Types,
Operators,
Variables,
Constants,
Input / Output,
Expressions,
Precedence and Associativity,
Evaluating Expressions,
Type Conversion,
Statements,
Bitwise Operators.
Computing Environments
Definition:
Computing environment is a collection of computers/machines, software and networks that
support the processing and exchange of electronic information.

Different types of computing environments


There are four types of computing environments. They are:
1. Personal computing environment
2. Time-Sharing environment
3. Client -Server environment
4. Distributed environment

Personal Computing Environment:


• A personal computer(PC) is a general purpose computer. The size and capabilities of a
personal computer makes it useful for end-users.
• In a personal computer, all the hardware components are tied together, so that it can be
used as per our need.

Time Sharing Environment


• Employees in large companies often work in a time sharing environment. In this
environment, many users are connected to one or more computers.
• These are minicomputers or central mainframes.
• The terminals used are not programmable, but now we see more microcomputers that
are used to simulate the environments terminals.
• In the time sharing environment, the output devices and auxiliary storage are shared by
all the users.
• In time sharing environment, each computer must be operated by the central computer.
• In this type of environment, computing is operated by central computer. This central
computer has many duties which keeps the computer busy.

Client Server Environment


• Client/Server is a distribute computing model, in which the client requests services
from the server.
• Client/Server usually run on separate computers connected by a network.
• A client is a process or an application that sends messages to a server through the
network.
• These messages ask the server to perform a specific task, like finding a customer
record in a database.
• Severs usually run on powerful computers, workstations or mainframes
• The administration of the installed equipment is more expensive than maintaining a
centralized system

Distributed Computing Environment


• A distributed computing environment allows smooth integration of computing
functions between different internet server's clients and provides the connection to
different servers around the world.
• Distributed Computing is used by distributed systems to solve computational problems
• In Distributed Computing, each problem is divided into several tasks, which are solved
by one or more computers.
TYPES OF LANGUAGES:
Computer languages are classified into 3 types
1) Low level languages
2) High level languages
3) Middle level languages

Low level languages:


➢ The language which is understood by the computer without any translator is
called as low level languages.
➢ These languages are also known as machine languages.
➢ Low level languages are used to develop system programs and component based
programs.
➢ These languages are implemented in 1st and 2nd generation of computer
➢ Eg: 1. binary languages, 2. assembly languages

High level languages:


➢ The language which uses English alphabets, words, simple mathematical symbols
& decimal number system, which has a language translator to translate high level
program into machine understanding program.
➢ These languages are also called as problem oriented language.
➢ High level languages are used to develop application programs & user interactive
programs.
➢ These languages are implemented in 3rd generation of the computer.
➢ Examples:
BASIC [Beginners All the purpose Symbolic Instruction Code]
COBOL[COmmon Business Oriented Language]
FORTRAN[FORmulae TRANslation]
PASCAL

Middle level Languages:


➢ The language which has both the features of low & high level languages are
called as middle level language.
➢ These languages are used to develop system programs and application programs.
➢ These languages are also implemented in 3rd generation of the computer.
➢ Eg: C language
ALGORITHM

Algorithm definition and use of algorithm in the context of software


development:

The typical meaning of an algorithm is a formally defined procedure for performing some
calculation. If a procedure is formally defined, then it must be implemented using some
programming languages. The algorithm give the logic of the program, that is , step-by-step
description of how to arrive a solution.

In general term, an algorithm provides a blueprint for writing a program to solve a


particular problem. It is considered to be an effective procedure for solving a problem in a
finite number of steps. Thus, a well-defined algorithm always provides an answer, and is
guaranteed to terminate.

Algorithms are mainly used to achieve software re-use.

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.

Key features of an algorithm:

An algorithm uses three control structures, namely sequence,decision and repetition.


1. Sequence: Sequence means that each step of the algorithm is executed in the specified
order. An algorithm to add two numbers is given in figure. The algorithm performs the steps in
a purely sequential order.

Step 1: Input the first number as A


Step 2: Input the second number as B
Step 3: Set sum=A+B
Step 4: Print sum
Step 5: End

2. Decision: Decision statements are used when the the execution of a process depends on
the outcome of some condition. The general form of the if construct can be given as:

if condition then process

A condition in this context is any statement that may evaluate either to a true value or a
false value. If the condition is true then the process is executed.

A decision statement can also be stated in the following manner.

if condition
then process1
else process2
This form is commonly known as the if-else construct. Here, if the condition is true
then process1 is executed, else process2 is executed. An algorithm to check the equality of two
numbers is shown in figure.

Step 1: Input the first number as A


Step 2: Input the second number as B
Step 3: if A==B
then print “Equal”
else
print “Not Equal”
Step 4: End

Algorithm to test the equality of two numbers

3. Repetition: Repetition, which involves executing one or more steps for a number of
times, can be implemented using constructs such as the while, do-while, and for loops. These
loops execute one or more steps until some condition is true.

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

Algorithm to print the first 10 natural numbers


FLOWCHARTS:
A flowchart is a graphical or symbolic representation of a process. It is basically used to design
and document virtually complex processes to help the viewers to visualize the logic of the
process.
When designing a flowchart, each step in the process is depicted by a 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.

1) Start and end symbols are also known as the terminal symbols and are represented as
circles, ovals, or rounded rectangles. Terminal symbols are always the first and the
last symbols in a flowchart.
2) Input / Output symbols are represented using a parallelogram and are used to get
inputs from the users or display the results to them.
3) Generic processing step, also called as activity, is represented using rectangle.
Activities include instructions such as add a to b, save the result.
4) A conditional or decision symbol is represented using a diamond. It is basically used
to depict a yes/no question or a True/False test. The two symbols coming out of it, one
from the bottom point and the other from the right point, corresponds to Yes or True,
and No or False, respectively.
5) Arrows depict the flow of control of the program.
6) Labelled connectors are represented by an identifying label inside a circle and are used
in complex or multisheet diagrams to substitute for arrow. For each label, the ‘outflow’
connector must have one or more ‘inflow’ connectors.
Advantages of flowcharts:
• Flowcharts are very good communications tools to explain the logic of a system to all
concerned. They help to analyse the problem in a more effective manner.
• They are also used for program documentation. They are even more helpful in the case
of complex programs.
• They act as a guide or blueprint for the programmers to code the solution in any
programming language.
• 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 a systematic manner.

Limitations of flowcharts:
• Drawing flowcharts is a laborious and time-consuming activity.
• Often, the flowchart of a complex, program becomes complex.
• At times, alittle bit of alteration in the solution may require complete redrawing of the
flowchart.
• There are no well-defined standards that limit the details that must be incorporated into
a flowchart.
The following flowchart is an example of a sequential execution.

Example
Draw a flowchart to find the simple interest. (Sequence)
Solution

The following flowchart is an example of a selective execution.


Example
Draw a flowchart to find bigger number among two numbers (selective)
Solution
The following are the examples of an iterative execution.
Example
Draw a flow chart to find factorial of any number.
Solution:

Example
Draw a flow chart to find biggest number among n numbers.
Solution:

Finite and Infinite loop :


In looping statements, if some set of statements are executed n times (fixed number of times),
then it is called “finite loop‟. At the same time, if some set of statements are executed again
and again without any end (infinite times), then it is called “infinite loop‟. For example , if we
are not incrementing I (index) value, then we will get endless (infinite) loop. The following is
an example of infinite loop.

Example
Draw a flow chart to print the number from 1 to ∞.
Solution
In the above example “I” value is not at all incremented, so it will create endless loop.
This is also called infinite loop.

Note: Set of statements is executed again and again without any end is called infinite
loop.

Differences between algorithm and flowchart:

ALGORITHM FLOWCHART
1. Step-by-step process 1) Pictorial representation
2. Didn’t use any symbol 2) Use symbol for processes & I/O
Example: Example:
Just like simple statements Just like maps
3. Easy to debug errors 3) Difficult to debug errors
4. Independent 4) Dependent
5. Use to solve problem with multiple 5) Use for improving process & also
solutions. show their relationships
6. No hard & fast rule to create it 6) Have some rule to create it
7. Easy to edit in process for betterment 7) Difficult to edit in process for
betterment.
Examples of Algorithms and Flowcharts:

1. Algorithm and Flowchart to print 1 to 100 numbers:

Algorithm to print 1 to 100 numbers:


Step 1: Start
Step 2: [Take Input] Declare N as integer
Step 3: N=1
Step 4: Repeat while N<=100
Print: N
Increment N with 1, i.e, N=N+1
[End of while loop]
Step 5: Exit

Flowchart to print 1 to 100 numbers:


2. Algorithm and Flowchart to print 100 to 1 numbers:

Algorithm to print 100 to 1 numbers:


Step 1: Start
Step 2: [Take Input] Declare N as integer
Step 3: N=100
Step 4: Repeat while N>0
Print: N
Increment N with 1, i.e, N=N-1
[End of while loop]
Step 5: Exit

Flowchart to print 100 to 1 numbers:


3. Algorithm and Flowchart to print even numbers from 1 to 100:

Algorithm to print even numbers from 1 to 100:


Step 1: Start
Step 2: [Take Input] Declare N as integer
Step 3: Assign N=1
Step 4: Repeat while N<=100
If N%2==0
Print: N
Increment N with 1 i.e., N=N+1
[End of while loop]
Step 5: Exit

Flowchart to print even numbers from 1 to 100:


4. Algorithm and Flowchart to print Sum of first N natural numbers:

Algorithm to print Sum of first N natural numbers:


Step 1: Start
Step 2: [Take Input] Declare N,S as integers
Step 3: Assign N=1,S=0
Step 4: Repeat while N<=100
S=S+N
Increment N with 1, i.e, N=N+1
[End of while loop]
Step 5: Print S
Step 6: Exit

Flowchart to print Sum of first N natural numbers:


5. Algorithm and Flowchart to print sum of digits of a number:

Algorithm to print sum of digits of a number:


Step 1: Start
Step 2: [Take Input] Declare N,S as integers
Step 3: Assign S=0
Step 4: Repeat while N>0
Compute: R=N%10
Compute: S=S+R
Compute: N=N/10
[End of while loop]
Step 5: Print S
Step 6: Exit

Flowchart to print sum of digits of a number:


6. Algorithm and Flowchart to find a Reverse of a given number:

Algorithm to find a Reverse of a given number:


Step 1: Start
Step 2: [Take Input] Declare R,N as integer and Read: N
Step 3: Repeat while N>0
Compute: R=N%10
Print: R
Compute: N=N/10
[End of while loop]
Step 4: Exit

Flowchart to find a Reverse of a number:


7. Algorithm and Flowchart to check whether a given number is
Palendrome number or Not:
Algorithm to find a given number is Palendrome number or Not:
Step 1: Start
Step 2: [Take Input] Declare R,X,T,N as integer and Read: N
Step 3: [Initialize] Set: X=0 and T=N
Step 4: Repeat while N>0
Compute: R=N%10
Compute: X=X*10+R
Compute: N=N/10
[End of while loop]
Step 5: Check If T==X Then
Print: N is a Palendrome Number
Else
Print: N is not a Palendrome Number
Step 6: Exit
Flowchart to find a given number is Palendrome number or Not:
8. Algorithm and Flowchart to check whether a given number is Armstrong
number or Not:
Algorithm to find a given number is Armstrong number or Not:
Step 1: Start
Step 2: [Take Input] Declare R.S,T,N as integer and Read: N
Step 3: [Initialize] Set: S=0 and T=N
Step 4: Repeat while N>0
Compute: R=N%10
Compute: S=R*R*R+S
Compute: N=N/10
[End of while loop]
Step 5: Check If T==S Then
Print: N is an Armstrong Number
Else
Print: N is not an ArmstrongNumber
Step 6: Exit

Flowchart to find a given number is Armstrong number or Not:


9. Algorithm and Flowchart to check whether a given number is Prime
number or Not:

Algorithm to find a given number is Prime Number or Not:


Step 1: Start
Step 2: Read: N[Take Input]
Step 3: set: count=0 and A=1
Step 4: Repeat while A<=N
check If N%A==0 then
compute:count=count+1
[End of If structure]
compute:A=A+1
[End of while loop]
Step 5: Check If count==2 then
print: N is prime number
Else
print: N is not prime number
Step 6: Exit.
Flowchart to find a given number is Prime Number or Not:
10. Algorithm and Flowchart to check whether a number is perfect number
or not:
Algorithm to check whether a number is perfect number or not:
Step 1: Start
Step 2: [Take Input] Read: N
Step 3: [Initialize] Set: Sum=0 and A=1
Step 4: Repeat while A<N
Check If N%A==0 Then
Compute: Sum=sum+A
[End of If structure]
Compute: A=A+1
[End of while loop]
Step 5: Check If N==sum Then
Print: N is a Perfect Number
Else
Print: N is not a Perfect Number
Step 6: Exit
Flowchart to check whether a number is perfect number or not:
11. Algorithm and Flowchart to print fibonacci series upto 100:

Algorithm to print fibonacci series upto 100:


Step 1: Start
Step 2: [Take Input] Declare A,B,C as integer
Step 3: [Initialize] Set: A=0 , B=1 and C=1
Step 4: Print: A,B
Step 5: Repeat while C<100
Print: C
Assign: A=B
Assign: B=C
Compute: C=A+B
[End of while loop]
Step 6: Exit

Flowchart to print fibonacci series upto 100:


Introduction to C-Language
C language is a middle level language, as it performs the features of High level
language (easiness) as well as low level languages (more performance)
C-language is a functional oriented language since every task performed by function.

History of C-Language:

Year Language Developed By


1960 ALGOL – 60 International Committee

CPL
1963 Cambridge University
( Combined Programming
Language )
BCPL
Martin Richards at
1967 ( Basic Combined Programming
Cambridge University
Language )
1970 B-Language Dennis Ritchie and Ken Thomson

1972 C-Language Dennis Ritchie AT & T Bell Labs

• In 1972 Dennis Ritchie has taken best features of BCPL and B- language, and also
added his features, then developed C-Language compiler.

• Initially C-Compiler is a DOS based compiler, called as traditional compiler.

• In 1973 UNIX server was developed. It provides system calls to interact with
hardware components.

• In 1979 Kernighan & Dennis Ritchie developed UNIX based compiler, named as K

& R compiler In 1987 Borland has taken the rights on DOS based compiler and

released as TURBO-C.

• Microsoft has taken rights from Borland, modified the DOS based compiler to
Windows.
• In 1990 K & R Compiler was recognized by ANSI(American National Standards
Institute) and name as ANSI-C. In the same year ANSI-C was certified by ISO and
called ISO-C.

• TURBO-C is a windows and dos OS dependent. ANSI-C is UNIX/LINUX OS

dependent.

• Turbo-C is a student version.

• ANSI-C, compiler is used for real time applications.

• ANSI-C compiler provides feature to develop following types of Applications.

1. Application programming ( CRUD Operations )

2. Network programming ( communication between systems )

3. Embedded programming ( Device Drivers )


Structure of a C-Program:

A “C-program” is basically a collection of functions that are supported by the ‘C library’. We


can continuously add our own functions to the ‘C library’.

A “C-program” may contain one (or) more sections,


Documentation section
Link Section
Definition section
Global declaration section
main() Function section
{
Declaration part
Executable part
}
Sub program section
Function 1
Function 2

Function-n
(user defined functions)
The sections contained in the ‘C’ structure are:
i. Documentation section:
It 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.
Ex:/*Program to find
1. Area of circle
2. Circumference of circle*/
Any block of comment lines must start with ‘/*’ and must ends with ‘*/’

ii. Link section:


The link section provides instructions to the compiler to link functions from the
system library (or) the user-defined-library. This is performed by the preprocessor
directive ‘include’ as follow.
#include<library-name>
Ex: #include<stdio.h>

iii. Definition section:


It defines all the symbolic constants and macros
Ex: #define PI 3.1428
#define SQR (x)(x*x)

iv. 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
all the functions.
Ex: int c;
void main()
{
---
---
}
v. main() function section:
Every “C-program” must have one main() function section. This section contains two
parts, declaration part and executable part. The declaration part declares all the
variables used in executable part. These two parts must be appear between the opening
and closing braces.

The program execution begins at opening brace and ends as the closing brace. The
closing brace of the main() function section is the logical end of the program. ALL
statements in the declaration and executable parts end with a semicolon.
Ex: main()
{
int a;
a=10;
printf(“%d”,a);
}

vi. sub program section: The sub program 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.
Ex:
void print();
void main()
{
print();
}
void print()
{
printf(“This is user-defined function”);
}
Various steps in creating and executing a C program:

Executable
Source file Compiler Object files Linker
Preprocessor file

Library files Library files

Figure: Execution process of C-program


Executing a program written in C involves a series of steps these are
i. Creating the program
ii. Compiling the program
iii. Linking the program
iv. Executing the program
i) Creating the program:
The programming process starts with creating a source file that consists of the statements of
the program written in C language. This source file usually contains ASCII characters and can
be produced with a text editor,such as Windows notepad, or in an Integrated Design
Environment. Create a text file with its name ending with a ‘C’ extension and type a C
programming that file.

In case of Turbo C package, the program can be typed using built-in editor. If the
operating system is unix, the program can be typed using Vi text editor.

ii) Compiling the program:


The source file is then processed by a special program called a compiler. The compiler
translate the source code into an object code. The object code contains the machine
instructions for the CPU and calls to the operating system Application Praogramming
Interface(API).

The compilation command under unix is $gcc filename.c

Turbo C compiler is under friendly and provides integrated program development


environment. Thus compilation can be done by selecting appropriate menu options.

The translation is done after examining each instruction for its correctness, if
everything is alright the compilation proceeds silently and the translated program is stored an
another file with name filename.obj.

iii) Linking the program:


Linking is the process of putting together other program files and functions that are required
by the program.
For example, if the program is using sqrt() function, then the object code of this
function should be brought from the math library of the system and linked to the main
program.
The compiled and linked program is called the executable code, and stored
automatically file name.exe or in UNIX file named a.out

iv) Executing the program:


In unix operating system the program can be executed with the executable file a.out, by typing
a.out at system prompt $
In Turbo C environment, the RUN option will do the compilation and executing of a
program.

During execution, the program may request for some data to be entered sometimes, the
program does not produce the desired results. Then it is necessary to correct the source
program (or) the data. In case the source program is modified, the entire process of compiling
and executing the program should be repeated.
Identifier :
A name in C program is called identifier. It may be variable name, function name, structure
name, union name etc.

Rules to define C identifiers:


Rule 1: The only allowed characters in C identifiers are:
1) a to z
2) A to Z
3) 0 to 9
4) _ (underscore)

Rule 2: If we are using any other character we will get compile time error.
Example:
1) total_number-------valid
2) Total#------------------invalid

Rule 3: identifiers are not allowed to starts with digit.


Example:
1) ABC123---------valid
2) 123ABC---------invalid

Rule 4: C identifiers are case sensitive and C language itself treated as case sensitive language.
Example:
void main()
{
int number=10;
int Number=20;
int NUMBER=20; we can differentiate with case.
int NuMbEr=30;
}

Rule 5: We can't use reserved words as identifiers.


Example:
int if=10; --------------invalid

Rule 6: It must not contain white spaces.

Rule 7: Identifier names must be unique(different).


Differences between Identifiers and Keywords:

Identifier Keyword
Identifiers are names that are given to various C take some reserved word called keyword,
program elements, such as variable, function they have predefine meaning in C
and arrays.
Identifiers consist of letters and digits. Keyword consist of only letter
Identifier’s first character must be a letter In all Keyword’s, character is letter
Identifiers Upper and lowercase letter is use. Keywords are all lowercase
Upper and lowercase are not equivalent. Uppercase and lowercase are also not
equivalent
Ex: X, sum_5,etc Ex: auto,short, long etc..

Reserved words:
In C some identifiers are reserved to associate some functionality or meaning such type of
reserved identifiers are called reserved words. There are a total of 32 keywords in C Language
which can not be used for the names of variables and functions.
Reserved words for data types: (4)
1) int
2) float
3) double
4) char

Reserved words for flow control:(12)


1) if
2) else
3) switch
4) case
5) default
6) for
7) do
8) while
9) break
10) continue
11) goto
12) return
Keywords for data type modifiers:(4)
1) long
2) short
3) signed
4) unsigned

Keywords for Storage classes:(4)


1) auto
2) extern

3) static

4) register

void return type keyword:(1)


If a method won't return anything compulsory that method should be declared with the void
return type in C.
1) void

Keywords for structures:(1)


struct

Keywords for unions:(1)


union

Other Keywords:(5)
1. Const
2. typedef

3. enum

4. sizeof

5. volatile
DATA TYPES

A data type defines a set of values and the operations that can be performed on them. Every
data type item (constant,variable etc.,) in a C-program has a data type associated with it. C
supports several different types of data, each of which may be represented differently with in
the computer’s memory.

C supports three classes of datatypes.


1. Primary ( or Basic) data types
2. User defined data types
3. Derived data types

Data types

Derived data types


Basic datatypes User defined data types

struct Arrays
char union pointers
int enum functions
float typedef .
double . .
void . .
.

1. Basic data types:


i. Integer Data types:
Integer data types represents all numeric values. Integer is a number that can not have
any decimal points. Integer number can be formed by using the digits 0 to 9 and + or –
sign. Integer data types further classified into different types. Its range and size can be
shown through the following table.

Data type size Range


7 7
signed short int 1 byte -2 to 2 -1(-128 to 127)
unsigned short int 1 byte 0 to 255
signed int 2 bytes -215 to 215 -1
(-32,768 to 32,767)
unsigned int 2 bytes 0 to 65,535
signed long int 4 bytes -231 to 231-1
(-2,147,483,648 to
2,147,483,647)
unsigned long int 4 bytes 0 to 4,294,967,295

Note: 1. signed integer data types allows + or – sign.


2. unsigned integer values allows only positive values.

ii. Floating point Data types:


Floating point data types represents the real numbers. A number does have decimal
point is called floating point numbers or real numbers. Floating data types size, range
shown in the following table

Data type Size Range


float 4 bytes 3.4e-38 to 3.4e38
double 8 bytes 1.7e-308 to 1.7e308
long double 10 bytes 1.18e-4932 to 1.18e4932

iii. Character Data types:


Character data types can be used that represents the character type of value. Character
values means a character that enclosed with in the single quotes. Character data type is
also classified into two types. These are
Data type Size Range
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 255

iv. void data type:


void or empty data type is used in the user defined functions and pointers. It occupies
zero bytes and its range is zero.

2. User Defined Data types:


C permits us to define another defined data types by using existing data types is called user
defined data types. The following are some of the user defined data types.
Structures,
unions,
bit fields,
typedef and so on.

3. Derived Data types:


Derived data types are derived by using the already existing data types are derived data types.
The following are some of the derived data types are
arrays,
pointers,
functions and so on.
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. The
data items that operators act upn are called operands.

Some operators require two operands, while others act up on only one operand. The
operators are classified into unary, binary and ternary depending on whether they operate on
one, two, (or) three operands respectively.

These operators can be categorized into the following major groups.


1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Equality operators
5. Assignment operators
6. Increment and decrement operators
7. Conditional operators
8. Bitwise operators
9. Special operators

1) Arithmetic operators
C provides all the basic arithmetic operators. They are shown in below table. These can
operate on any built-in data type allowed in C.
Arithmetic operators
Operation Operator
Multiply *
Divide /
Addition +
Subtraction -
Modulus %

A “C arithmetic statement could be of 3 types.


i. Integer Arithmetic:
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression and the operation is called integer arithmetic.
Integer arithmetic always yields an integer value.

In the below examples, if a and b are integers, then for a=14 and b=4 we have the
following results:
a-b=10
a+b=14
a*b=56
a/b=3 (decimal part truncated)
a%b=2(remainder of division)

ii. Real Arithmetic:


An arithmetic operation involving only real operands is called real arithmetic. A real
operand may assume values either in decimal (or) exponential notation.

If x,y and z are floats, then we will have:


x=6.0/7.0=0.8572
y=1.0/3.0=0.333
z=-2.0/3.0=-0.6667
The operator % cannot be used with real operands.

iii. Mixed mode Arithmetic :


When one of the operands is real and the other is integer, the expression is called a
mixed mode arithmetic expression.

If either operand is of the real type, then only the real operation is performed and the
result is always a real number. Thus 15/10.0=1.5 where 15/10=1

2) Relational operators:
Relational operators are symbols that are used to test the relationship between two
variables(or) between a variable and a constant. We often compare two quantities, and
depending on their relation takes certain decisions. These comparisons can be done
with the help of relational operators. These relationships are illustrated in table.

Operator Meaning Example


< Less than 3<5 gives 1
> Greater than 7>9 gives 0
>= Greater than or equal to 100>=100 gives 1
<= Less than or equal to 50>=100 gives 0

3) Logical operators:
Logical operators are symbols that are used to combine (or) negate expressions
containing relational operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
i. Logical AND:
Logical AND operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If expressions on both the sides (left and right side) of the
logical operator is true then the whole expression is true. The truth table of logical
AND operator is given in Table.
Truth table of Logical AND
A B A &&B
0 0 0
0 1 0
1 0 0
1 1 1
For example, (a<b)&&(b>c)
The expression to the left is (a<b) and that on the right is (b>c). The whole expression
is true only if both expressions are true, i.e, if b is greater than a and c.

ii. Logical OR:


Logical OR operator is used to simultaneously evaluate two conditions or expressions
with relational operators. If one or both the expressions on the left side and right side of
the logical operator is true then the whole expression is true. The truth table of logical
OR operator is given in Table.
Truth table of Logical OR
A B A ||B
0 0 0
0 1 1
1 0 1
1 1 1

For example, (a<b)||(b>c)


The expression to the left is (a<b) and that on the right is (b>c). The whole
expression is true if either b is greater than a or b is greater than c.

iii. Logical NOT:


The logical NOT operator takes a single expression and negates the value of the
expression. That is, logical NOT produces 0 if the expression evaluates to a non-zero
value and produces 1 if the expression produces a zero. In other words, it just reverses
the value of the expression. The truth table of logical NOT operator is given in Table.
Truth table of Logical NOT
A !A
0 1
1 0
For example:
int a=10,b;
b=!a;
Now the value of b=0.
4) Equality operators:
C language supports two kinds of equality operators to compare their operands for
strict equality or inequality. They are equal to == and not equal to != operators. The
equality operators have lower precedence than the relational operators.

Table summarizes equality operators.


Equality operators
Operator Meaning
== Return True (1) if both operands are equal, False(0) otherwise
!= Returns True (1) if operands do not have the same value, False(0)
otherwise

5) Assignment operators:
Assignment operators are used to assign the result of an expression to a variable.
The general format of assignment statement is:

Variable_name=expression;

Where expression may be as simple as a constant (or) as complex as an expression.

The operator ‘=’ is called assignment operator. The left of assignment operator must be
a variable.

Ex:
F=1.8*C+32.0;
i=10;
a=b+c;

The usual assignment operator, ‘=’, in addition ‘C’ has a set of ‘shorthand’ assignment
operators of the form

V OP = EXP;

Where V is a variable, exp is an expression and OP is a C binary arithmetic operator.


The operator OP= is known as the shorthand assignment operator.

The assignment statement V OP= exp;


is equivalent to V=V OP (exp);

Some of the commonly used shorthand assignment operators are shown in below Table.
Statement with simple assignment Statement with shorthand operator
operator
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a%b a%=b

6) Increment and decrement operators:


C allows two very useful operators not generally found in other languages. These are
the increment and decrement operators:
++ and --
The operator ++ adds 1 to the operand, while – subtracts 1. Both are unary operators
and takes the following form.
++m or m++
--m or m--
++m; is equivalent to m=m+1; ( or m+=1;)
--m; is equivalent to m=m-1; ( or m-=1;)

while ++m and m++ mean the same thing when they form statements
independently, they behave differently when they are used in expressions on the right
hand side of an assignment statement. Consider the following:
m=5;
y=++m;

In this case, the value of y and m would be 6. Suppose, if we rewrite the above
statements as
m=5;
y=m++;
then, the value of y would be 5 and m would be 6.
A prefix operator first adds 1 to the operand and then the result is assigned to the
variable on left. On the other hand, a postfix operator first assigns the value to the
variable on left and then increments the operand.

7) Conditional operator:
A ternary operator “?:” is available in C to construct conditional expressions of the
form.
exp1?exp2:exp3
where exp1, exp2, and exp3 are expressions.
The operator ?: works as follows: exp1 is evaluated first. If it is nonzer(true),
then the expression exp2 is evaluated and becomes the value of the expression. If exp1 is
false, exp3 is evaluated and its value becomes the value of the expression. Note that only
one of the expressions (either exp2 or exp3) is evaluated.

For example, consider the following statements.


A=10;
b=15;
x=(a>b)?a:b;
In this example, b will be assigned the value of x.
8) Bitwise operators:
C has a distinction of supporting special operators known as bitwise operators for
manipulation of data at bit level. These operators are used for testing the bits, or
shifting them right or left. Bitwise operators may not be applied to float or double.
Lists the bitwise operators and their meanings.

Bitwise operators
Operator Meaning
~ One’s complement(Bitwise NOT)
>> Right shift
<< Left shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR(Exclusive OR)

9) Special operators
These are used for special purpose in C language these operators are used in pointers,
structures and unions etc. Some types special operators as
i. unary operator
ii. comma operator
iii. sizeof operator
iv. member selection operator
i. unary operator: Those that operators on a single operand. The unary operators are +
+, --, _(underscore), &(address operator), *(indirection operator) , sizeof operator and
so on.

ii. Comma operator: When a no. of statement occurred in a C program having a


relationship between expressions. Then we can write all expression are statements in a
single expression using comma(,) operator. The comma operator are also used in
variable declaration statement.

iii. sizeof operator:


It is to display no. of bytes covered by a variable or an expression.
Ex:
int a,b;
b=sizeof(a);
b contains 4

iv. Member selection operator:


These operators are used in structures, unions and pointers. These are ‘.’ and ‘->’
VARIABLES
A variable can be considered as a name given to the location in memory. The term variable is
used to denote any value that is referred to a name instead of explicit value. A variable is able
to hold different values during execution of a program, whereas a constant is restricted to just
one value.

Rules for constructing variable names:


1) The name of a variable is composed of one to several characters, the first of which
must be a letter.
2) No special characters other than letters,digits and underscore can be used in variable
name. Some compilers permit underscore as the first character.
3) Commas (or) Blanks are not allowed with in a variable name.
4) Upper case and lower case letters are significant. That is the variable income is not the
same as INCOME.
5) The variable name should not be a C keyword.

1. Declaring variables:
Any variable used in the program must be declared before using it in any statement. To declare
the variables we must use the following general form.

Syntax: datatype variable_name;

Example: int a;
float b;
char c;
double d;

In the above example a,b,c and d are the names of the variables whereas int, float, char &
double are predefined data types.

It is possible to declare multiple variables by using the single declaration statement. This can
be shown through the following example.

Syntax: data_type variable_names list;

Ex: int a,b,c;

2. Assigning values to variables:

We can assign a value to a variable by using assignment statement. The expression having
assignment statement is also called assignment expression. In an assignment expression, an
assignment operator is used.

The general syntax for assigning a value to a variable:


variable=constant;
variable=variable;
variable=expression;
Ex:
a=10;
b=a;
c=a+b;

3.Initializing variables:

While declaring the variables, we can also initialize them with some value.

For example:
int emp_num=7;
float salary=5000;
char grade= ‘A’;

The initializer applies only to the variable defined immediately before it. Therefore, the
statement
int count,flag=1;
initializes the variable flag and not count.
CONSTANTS

Constants in C refer to fixed values that do not change during the execution of a program. C
supports several types of constants as shown below.

I. Numeric Constants: Numeric constants are the numeric value that can be represent either
integer or floating value. It is constants are formed by using the digits 0 to 9 + or – sign. And
decimal point. Numeric constants further it can be classified into two types these are
1. Integer constants
2. Floating point constants.

1) Integer constants: These have integer data combination of 0 to 9 without any decimal
point. These have either + or – sign. Integer constants can be represented in 3 different ways.

i. Octal constants
It can be formed by using the digits 0 to 7 only. The octal constant prefixed with zero.
Example: 012,01234...

ii. Decimal constants


It can be formed by using the 0 to 9 digits, + or – sign. Example: 1, 786...

iii. Hexadecimal constants


It can be formed by using 0 to 9 digits and A to F or a to f alphabets. The letters A to F
represents the numbers 10 to 15. Hexadecimal constant preceded with 0x.
Example: 0x123,0xff2...

2) Floating point constant: Some constants floating which have a decimal point with in it
having +ve or -ve sign is called real or float numeric constant. These constant can be
represented two different forms. These are

i. Decimal Form(Fixed values)


ii. Exponential Form

i. Decimal Form: Real constants expressed in decimal form must have atleast one digit and
one decimal point. As in the case of integers, the real constants can be either positive (or)
Negative. Commas,blanks and non-digit characters are not allowed with in a real constant.

The following are acceptable real constants :


0.0
6.1
-2000.0

ii.Exponential Form: In exponential form, a real constant is expressed as an integer number


(or) a decimal number multiplied by an integral power of 10. This simplifies the writing of
very large and very small numbers. In this representation, letter e is written instead of 10, the
power is written just to the right of e. Generally the part appearing before e is called
mantissa, whereas the part following e is called exponent.

The following are acceptable real constants in exponential form:


5.0e-12
-7e+16
6.2e13
II. Character constants:
Character constants have either a single character or a group of characters.

i. Single character constant: These have a single character with in asingle quote
for example: ‘s’, ‘a’ , ‘@’...

ii. String character constant: A string is a cobination of characters, a string constant is


enclosed with in double quotes.
Example: “hello”, “krishna”, “4867”...
INPUT-OUTPUT in C
There are three main functions of any program- it takes data as input, processes this data and
gives the output. The input operation involves movement of data from an input device
(generally keyboard) to computer memory, while in output operation the data moves from
computer memory to the output device (generally screen). The input output is performed
through a set of library functions that are supplied with every C compiler.

There are several header files that provide necessary information in support of the various
library functions. These header files are entered in the program using the #include directive at
the beginning of the program. For example if a program uses any function from, the standard
I/O library, then it should include the header file stdio.h as-

#include<stdio.h>

Similarly there are other header files like string.h, stdlib.h that should be included when certain
library functions are used.

A simple method for taking the data as input is to give the value to the variables by assignment
statement. For example-

int basic=2000;
char ch= ‘y’;

But in this way we can give only particular data to the variables. The second method is to use
the input function scanf(), which takes the input data from the keyboard. In this method we
can give any value to the variables at run time. For output, we use the function printf().

CONVERSION SPECIFICATIONS:
The functions scanf() and printf() make use of conversion specifications to specify the type
and size of data. Each conversion specification must begin with a percent sign(%). Some
conversion specification are as given below-

%c - a single character
%d - a decimal integer
%f - a floating point number
%o - an octal integer
%x - a hexadecimal integer
%s - a string
%u - an unsigned decimal integer

READING INPUT DATA:


Input data can be entered into the memory from a standard input device (key board). C
provides the scanf() library function for entering input data. This function can take all types of
values as input. The scanf() function can be written as-

scanf(“control string”, address1,address2,....);

This function should have atleast two parameters. First parameter is a control string, which
contains conversion specification characters. It should be within double quotes. The
conversion specification characters may be one or more; it depends on the number of variables
we want to input. The other parameters are addresses of variables. In the scanf() function
atleast one address should be present.
The address of a variable is found by preceding the variable name by an ampersand (&) sign. A
string variable is not preceded by & signs to get the address.

Some examples of scanf() function-


#include<stdio.h>
main()
{
int marks;
.................
scanf(“%d”,&marks);
..................
}

In this example, it contains only one conversion specification character %d, which implies that
one integer value should be entered as input.

#include<stdio.h>
main()
{
int basic;
float hra;
char grade;
......
scanf(“%d %f %c”, &basic, &hra, &grade);
......
}

Here, it contains three conversion specifications characters %d,%f and %c, means that one
integer value, one floating point value and one single character can be entered as-

1500 200.50 A

WRITING OUTPUT DATA:

Output data can be written from computer memory to the standard output device using printf()
library function. With this function all type of values can be written as output. The printf()
function can be written as-

printf(“control string”, variable1, variable 2,......);

In this function the control string contains conversion specification characters and text. It
should be enclosed within double quotes. The name of variables should not be preceded by an
ampersand(&) sign.

Some examples of printf() function-


#include<stdio.h>
void main()
{
printf(“C is excellent\n”);
}
Output:
C is excellent

Here control string has only text and no conversion specification character, hence the output is
only text.

#include<stdio.h>
main()
{
int age;
printf(“Enter your age:”);
scanf(“%d”,&age);
printf(“age=%d”,age);
}

Output:
Enter your age:45
age=45

Here the first printf also does not contain any conversion specification and is used to display a
message that tell the user to enter his age. Scanf will read the data from keyboard and store
into the address of age variable. The second printf has the conversion specification %d which
specifies the integer prints age value on the monitor.

getchar() and putchar():

• These macros getchar() and putchar() can be used for character I/O.
• getchar() reads a single character from the standard input.
• putchar() outputs one character at a time to the standard output.

#include<stdio.h>
void main()
{
char ch;
printf(“enter a character:”);
ch=getchar();
printf(“The entered character is:”);
putchar(ch);
}
Output:
Enter a character:B
The entered character is: B
PRECEDENCE AND ASSOCIATIVITY OF OPERATORS
The operators of the same precedence are evaluated either from ‘left to right’ or from ‘right to
left’, depending on level. This is known as the associativity property of an operator.
Table provides a complete list of operators, their precedence levels, and their rules of
association. The groups are listed in the order of decreasing precedence. Rank 1 indicates the
highest precedence level and 15 the lowest
RANK OPERATOR DESCRIPTION ASSOCIATIVITY
1 () Function call Left to Right
[] Array subscript
. Dot operator
-> Arrow operator
2 + Unary plus Right to Left
- Unary minus
++ Increment
-- Decrement
! Logical Not
~ One’s complement
* Indirection
& Address
(datatype) Typecast
sizeof Size in bytes

3 * Multiplication Left to Right


/ Division
% Modulus
4 + Addition Left to Right
- Subtraction
5 << Left shift Left to Right
>> Right shift
6 < Less than Left to Right
<= Less than or equal to
> Greater than
>= Greater than or equal
to
7 == Equal to Left to Right
!= Not equal to
8 & Bitwise AND Left to Right
9 ^ Bitwise XOR Left to Right
10 | Bitwise OR Left to Right
11 && Logical AND Left to Right
12 || Logical OR Left to Right
13 ?: Conditional operator Right to Left
14 = Assignment operators Right to Left
*=
/=
%=
+=
-=
&=
^=
|=

<<=
>>=
15 , Comma operator Left to Right
EXPRESSIONS
An expression is a combination of operators,constants,variables and function calls. The
expression can be arithmetic,logical, or relational.

Some examples are as-

x+y -arithmetic operation


a=b+c -uses two operators(=) and (+)
a>b -relational expression
a==b -logical expression
func(a,b) -function call

C Expression Evaluation
• In the C programming language, an expression is evaluated based on the operator
precedence and associativity. When there are multiple operators in an expression, they
are evaluated according to their precedence and associativity. The operator with higher
precedence is evaluated first and the operator with the least precedence is evaluated
last.
• An expression is evaluated based on the precedence and associativity of the operators
in that expression.
• To understand expression evaluation in c, let us consider the following simple example
expression...
10 + 4 * 3 / 2
• In the above expression, there are three operators +, * and /. Among these three
operators, both multiplication and division have the same higher precedence and
addition has lower precedence. So, according to the operator precedence both
multiplication and division are evaluated first and then the addition is evaluated. As
multiplication and division have the same precedence they are evaluated based on the
associativity. Here, the associativity of multiplication and division is left to right. So,
multiplication is performed first, then division and finally addition. So, the above
expression is evaluated in the order of * / and +. It is evaluated as follows...
• 4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
TYPE CONVERSION AND TYPE CASTING

Type conversion of typecasting of variables refers to changing a variable of one data type into
another. Type conversion is done implicitly whereas, typecasting has to be done explicitly by
the programmer.

1. Type conversion: Type conversion is done when the expression has variables of
different data types. To evaluate the expression, the data type is promoted from a lower to a
higher level where the hierarchy of datatypes (from higher to lower) can be given as: double,
float ,long , int short and char. Figure shows the conversion hierarchy of data types.

Higher level

Lower level

Figure: Conversion hierarchy of data types


Type conversion is automatically done when we assign an integer value to a floating point
variable. Consider the following code in which an integer data type is promoted to float. This
is known as promotion (when a lower level data types is promoted to a higher type).
float x;
int y=3;
x=y;
Now x=3.0, as the integer value is automatically converted into its equivalent floating point
representation.

Let us summarize how promotion is done:


• float operands are converted to double.
• char or short operands whether signed or unsigned are converted to int.
• If any one operand is double, the other operand is also converted to double. Hence,
the result is also of type double.
• If any one operand is long, the other operand is also converted to long. Hence, the
result is also of type long.
We can observe the following changes that are unavoidable when performing type
conversions
• When a float value is converted to an integer value, the fractional part is truncated.
• When a double value is converted to a float value, rounding of digits is done.
• When a long int is converted into int, the excess higher order bits are dropped. These
changes may cause incorrect results.

2. Typecasting: Typecasting is also known as forced conversion. Typecasting an arithmetic


expression tells the compiler to represent the value of the expression in a certain way. It is
done when the value of a higher data type has to be converted into the value of a lower data
type.

Syntax: (cast-type) expression;

For example, if we need to explicitly typecast an integer variable into a floating point variable,
then the code to perform type casting can be given as,

float salary=10000.00;
int sal;
sal=(int) salary;

Typecasting is also done in arithmetic operations to get correct result.


Ex: int a=500, b=70;
float res;
res=(float)a/b;
STATEMENTS
In C program, instructions are written in the form of statements. A statement is an executable
part of the program and causes the computer to carry out some action. Statements can be
categorized as-
(1) Expression statements
(2) Compound statements
(3) Selection statements (if, if...else,switch)
(4) Iterative statements (for, while, do..while)
(5) Jump statements (goto,continue,break,return)
(6) Label statements (case, default, label statements used used in goto)

(1) Expression statement:


Expression statement consists of an expression followed by a semicolon.
For example-
x=5;
x=y-z;
func(a,b);
A statement that has only a semicolon is also known as null statement.
For example-
;/*null statement*/

(2) Compound statement:


A compound statement consists of several statements enclosed within a pair of curly braces{ }.
Compound statement is also known as block of statements. Note that there is no semicolon
after the closing brace. For example-
{
int i=4,b=2,h=3;
int area,volume;
area=2*(l*b+b*h+h*i);
volume=l*b*h;
}
If any variable is to be declared inside the block then it can be declared only at the beginning
of the block. The variables that are declared inside a block can be used only inside that block.
BITWISE OPERATORS
One of C’s powerful features is a set of bit manipulation operators. These permit the
programmer to access and manipulate individual bits with in a piece of data. The various
Bitwise operators available in C are shown below table 1.

Operator Meaning
~ One’s complement(Bitwise NOT)
>> Right shift
<< Left shift
& Bitwise AND
| Bitwise OR
^ Bitwise XOR(Exclusive OR)
Table 1: Bitwise operators

These operators can operate upon ints and chars but not on floats and doubles.

1) Bitwise complement:
The operator ~ is called the one’s complement operator, or the bitwise complement
operator. It inverts the bit string representation of its argument; the 0’s becomes 1’s,
and the 1’s becomes 0’s.

For example, the declaration


int a=65;

The binary representation of a is 1000001

The expression ~a is the bitwise complement of a, and this expression has the binary
representation 0111110

2) Bitwise logical operators:


The following are the bitwise logical operators
i. Bitwise AND
ii. Bitwise OR
iii. Bitwise exclusive OR

i) Bitwise AND:
The Bitwise AND operates on two operands. While operating upon these two operands
they are compared on a bit-by-bit basis. The symbol ‘&’ represents the bitwise AND
the rules that decide the value of the resultant bits are shown below:
a b a&b
0 0 0
0 1 0
1 0 0
1 1 1
For Example:
ii) Bitwise OR:
The Bitwise OR operations are similar to the bitwise AND and the results is 1 if any of
the bit value is 1. The symbol ‘1’ represents the bitwise OR.

The rules that decide the value of the resultant bits are shown below:

a b a|b
0 0 0
0 1 1
1 0 1
1 1 1
For example:

iii) Bitwise exclusive OR:


The bitwise exclusive OR (XOR) operator is represented as ^. The OR operator returns
1, when any one of the two bits(or) both the bits are 1, whereas XOR returns 1 only
if the one of the two bits is 1.
The rules that decide the value of the resultant bits are shown below:

a b a^b
0 0 0
0 1 1
1 0 1
1 1 0

For example:

3) Shift operations:
The shift operations take binary patterns and shift the bits to the left or right, keeping
the same number of bits by dropping shifted bits off the end and filling in with zeroes
from the other end. C provides two types of shift operations, left shift and right shift.

i) Right shift operator:


It is represented by >> and it shifts each bit in the operand to the right. The
number of places the bits are shifted depends on the number following the operand.

ii) Left shift operator:


It is represented by << and it shifts each bit in the operand to the left.The
number of places the bits are shifted depends on the number following the operand.

You might also like