0% found this document useful (0 votes)
81 views

PGDCA 113 Intro Progm-Notes

The document discusses algorithms and their design. It defines an algorithm as a set of steps to solve a problem using a finite amount of time and space. Algorithm design aims to create efficient solutions using minimum time and space. Key aspects of algorithm development are problem definition, modeling, specifying, designing, testing, analyzing, implementing, and documenting algorithms. Characteristics of algorithms include unique names, defined inputs/outputs, unambiguous ordered operations, and halting in finite time. Pseudocode and flowcharts help describe algorithms at a high level without a specific programming language. Binary search is more efficient than linear search, with runtime of O(log n), by dividing the search space in half at each step.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
81 views

PGDCA 113 Intro Progm-Notes

The document discusses algorithms and their design. It defines an algorithm as a set of steps to solve a problem using a finite amount of time and space. Algorithm design aims to create efficient solutions using minimum time and space. Key aspects of algorithm development are problem definition, modeling, specifying, designing, testing, analyzing, implementing, and documenting algorithms. Characteristics of algorithms include unique names, defined inputs/outputs, unambiguous ordered operations, and halting in finite time. Pseudocode and flowcharts help describe algorithms at a high level without a specific programming language. Binary search is more efficient than linear search, with runtime of O(log n), by dividing the search space in half at each step.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Unit-1

Algorithm
An algorithm is a set of steps of operations to solve a problem performing calculation, data
processing, and automated reasoning tasks. An algorithm is an efficient method that can be
expressed within finite amount of time and space.
An algorithm is the best way to represent the solution of a particular problem in a very simple
and efficient way. If we have an algorithm for a specific problem, then we can implement it in
any programming language, meaning that the algorithm is independent from any
programming languages.

Algorithm Design
The important aspects of algorithm design include creating an efficient algorithm to solve a
problem in an efficient way using minimum time and space.
To solve a problem, different approaches can be followed. Some of them can be efficient with
respect to time consumption, whereas other approaches may be memory efficient. However, one
has to keep in mind that both time consumption and memory usage cannot be optimized
simultaneously. If we require an algorithm to run in lesser time, we have to invest in more
memory and if we require an algorithm to run with lesser memory, we need to have more time.

Problem Development Steps


The following steps are involved in solving computational problems.

 Problem definition
 Development of a model
 Specification of an Algorithm
 Designing an Algorithm
 Checking the correctness of an Algorithm
 Analysis of an Algorithm
 Implementation of an Algorithm
 Program testing
 Documentation

Characteristics of Algorithms
The main characteristics of algorithms are as follows −
 Algorithms must have a unique name
 Algorithms should have explicitly defined set of inputs and outputs
 Algorithms are well-ordered with unambiguous operations
 Algorithms halt in a finite amount of time. Algorithms should not run for infinity, i.e., an
algorithm must end at some point
Pseudocode
Pseudocode gives a high-level description of an algorithm without the ambiguity associated
with plain text but also without the need to know the syntax of a particular programming
language.
The running time can be estimated in a more general manner by using Pseudocode to represent
the algorithm as a set of fundamental operations which can then be counted.

Difference between Algorithm and Pseudocode


An algorithm is a formal definition with some specific characteristics that describes a process,
which could be executed by a Turing-complete computer machine to perform a specific task.
Generally, the word "algorithm" can be used to describe any high level task in computer
science.
On the other hand, pseudocode is an informal and (often rudimentary) human readable
description of an algorithm leaving many granular details of it. Writing a pseudocode has no
restriction of styles and its only objective is to describe the high level steps of algorithm in a
much realistic manner in natural language.
For example, following is an algorithm for Insertion Sort.
Algorithm: Insertion-Sort
Input: A list L of integers of length n
Output: A sorted list L1 containing those integers present in L
Step 1: Keep a sorted list L1 which starts off empty
Step 2: Perform Step 3 for each element in the original list L
Step 3: Insert it into the correct position in the sorted list L1.
Step 4: Return the sorted list
Step 5: Stop
Here is a pseudocode which describes how the high level abstract process mentioned above in
the algorithm Insertion-Sort could be described in a more realistic way.
for i <- 1 to length(A)
x <- A[i]
j <- i
while j > 0 and A[j-1] > x
A[j] <- A[j-1]
j <- j - 1
A[j] <- x

Algorithm flowchart:
A flowchart is a blueprint that pictorially represents the algorithm and its
steps. The steps of a flowchart do not have a specific size and shape rather it
is designed in different shapes and sizes
The boxes in different shapes and interconnected with arrows, are logically
making a flow chart. A flow-chart represents the general steps in a process.

Benefits of Flowchart
Let us now discuss the benefits of a flowchart.

Simplify the Logic


As it provides the pictorial representation of the steps; therefore, it simplifies
the logic and subsequent steps.

Makes Communication Better


Because of having easily understandable pictorial logic and steps, it is a
better and simple way of representation.

Effective Analysis
Once the flow-chart is prepared, it becomes very simple to analyze the
problem in an effective way.

Useful in Coding
The flow-chart also helps in coding process efficiently, as it gives directions
on what to do, when to do, and where to do. It makes the work easier.

Proper Testing
Further, flowchart also helps in finding the error (if any) in program

Applicable Documentation
Last but not the least, a flowchart also helps in preparing the proper
document (once the codes are written).

Flow-Chart Symbols
The following table illustrates the symbols along with their names (used in a
flow-chart) −

Name Symbol Name Symbol


Flow Line Magnetic Disk

Terminal Communication Link

Processing Offline Storage

Decision Annotation

Connector Flow line

Document Off-Page Connector


Sample of Flow Chart

Testing and debugging


Both Testing and Debugging are the most important steps or practices during the
development and after the development of any software or application developed in any
programming language. Now on the basis of features and method of practice we can
distinguish between Testing and Debugging.
Following are the important differences between Testing and Debugging.

Sr. Key Testing Debugging


No.

1 Definition Technically Testing is a process to On other hand Debugging is


check if the application is working the activity performed by
same as it was supposed to do, developers to fix the bug found
and not working as it was not in the system.
supposed to do.
Sr. Key Testing Debugging
No.

2 Objective Main objective of Testing is to find On other hand the main


bugs and errors in an application objective of Debugging is to
which get missed during the unit find the exact root cause at
testing by the developer. code level to fix the errors and
bugs found during the testing.

3 Perform As Testing is mainly to find out the While on other hand


errors and bugs is mainly Debugging is to find the
performed by the testers. Also if missing or de-faulty code in an
testing is at developer end known application hence major
as unit testing then it is performed performed by the developers
by the Developer. only.

4 Knowledge As Testing covers the functional On other hand Debugging is to


Required and behavioural flow of an find the error at code level so
application so only functional technical and code level
knowledge is required for the tester knowledge is required for the
to perform the testing. developer to perform
debugging.

5 Automation Testing can be manual or made On other hand Debugging can't


automated with the help of different be get automated it is always
tools. be the manual.

6 Level Testing on basis of level of On other hand no such level of


performing is at different level i.e., Debugging is possible.
unit testing, integration testing,
system testing, etc.

Algorithm for search


a. Linear search
Linear search is a very simple search algorithm. In this type of search, a sequential
search is made over all items one by one. Every item is checked and if a match is
found then that particular item is returned, otherwise the search continues till the end of
the data collection.
Algorithm
Linear Search ( Array A, Value x)

Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
b. binary search
Binary search is a fast search algorithm with run-time complexity of Ο(log n). This
search algorithm works on the principle of divide and conquer. For this algorithm to
work properly, the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the
collection. If a match occurs, then the index of item is returned. If the middle item is
greater than the item, then the item is searched in the sub-array to the left of the middle
item. Otherwise, the item is searched for in the sub-array to the right of the middle item.
This process continues on the sub-array as well until the size of the subarray reduces
to zero.

How Binary Search Works?


For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example. The following is our sorted
array and let us assume that we need to search the location of value 31 using binary
search.

First, we shall determine half of the array by using this formula −


mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

Now we compare the value stored at location 4, with the value being searched, i.e. 31.
We find that the value at location 4 is 27, which is not a match. As the value is greater
than 27 and we have a sorted array, so we also know that the target value must be in
the upper portion of the array.

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value
31.

The value stored at location 7 is not a match, rather it is more than what we are looking
for. So, the value must be in the lower part from this location.

Hence, we calculate the mid again. This time it is 5.


We compare the value stored at location 5 with our target value. We find that it is a
match.

We conclude that the target value 31 is stored at location 5.


Binary search halves the searchable items and thus reduces the count of comparisons
to be made to very less numbers.
Sorting algorithm
Sorting refers to arranging data in a particular format. Sorting algorithm
specifies the way to arrange data in a particular order. Most common orders
are in numerical or lexicographical order.
The importance of sorting lies in the fact that data searching can be
optimized to a very high level, if data is stored in a sorted manner. Sorting is
also used to represent data in more readable formats. Following are some of
the examples of sorting in real-life scenarios −
 Telephone Directory − The telephone directory stores the telephone
numbers of people sorted by their names, so that the names can be
searched easily.
 Dictionary − The dictionary stores words in an alphabetical order so
that searching of any word becomes easy.

In-place Sorting and Not-in-place Sorting


Sorting algorithms may require some extra space for comparison and
temporary storage of few data elements. These algorithms do not require any
extra space and sorting is said to happen in-place, or for example, within the
array itself. This is called in-place sorting. Bubble sort is an example of in-
place sorting.
However, in some sorting algorithms, the program requires space which is
more than or equal to the elements being sorted. Sorting which uses equal or
more space is called not-in-place sorting. Merge-sort is an example of not-
in-place sorting.

Stable and Not Stable Sorting


If a sorting algorithm, after sorting the contents, does not change the
sequence of similar content in which they appear, it is called stable sorting.
If a sorting algorithm, after sorting the contents, changes the sequence of
similar content in which they appear, it is called unstable sorting.

Stability of an algorithm matters when we wish to maintain the sequence of


original elements, like in a tuple for example.
Merging algorithm
Merge sort is a sorting technique based on divide and conquer technique.
With worst-case time complexity being Ο(n log n), it is one of the most
respected algorithms.
Merge sort first divides the array into equal halves and then combines them
in a sorted manner.

How Merge Sort Works?


To understand merge sort, we take an unsorted array as the following −
We know that merge sort first divides the whole array iteratively into equal
halves unless the atomic values are achieved. We see here that an array of 8
items is divided into two arrays of size 4.

This does not change the sequence of appearance of items in the original.
Now we divide these two arrays into halves.

We further divide these arrays and we achieve atomic value which can no
more be divided.

Now, we combine them in exactly the same manner as they were broken
down. Please note the color codes given to these lists.
We first compare the element for each list and then combine them into
another list in a sorted manner. We see that 14 and 33 are in sorted
positions. We compare 27 and 10 and in the target list of 2 values we put 10
first, followed by 27. We change the order of 19 and 35 whereas 42 and 44
are placed sequentially.

In the next iteration of the combining phase, we compare lists of two data
values, and merge them into a list of found data values placing all in a sorted
order.

After the final merging, the list should look like this −
Now we should learn some programming aspects of merge sorting.

Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be
divided. By definition, if it is only one element in the list, it is sorted. Then,
merge sort combines the smaller sorted lists keeping the new list sorted too.
Step 1 − if it is only one element in the list it is already
sorted, return.
Step 2 − divide the list recursively into two halves until
it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted
order.

Analysis of Algorithm
Algorithm analysis is an important part of computational complexity theory, which
provides theoretical estimation for the required resources of an algorithm to solve a
specific computational problem. Most algorithms are designed to work with inputs of
arbitrary length. Analysis of algorithms is the determination of the amount of time and
space resources required to execute it.
Usually, the efficiency or running time of an algorithm is stated as a function relating
the input length to the number of steps, known as time complexity, or volume of
memory, known as space complexity.

The Need for Analysis


In this chapter, we will discuss the need for analysis of algorithms and how to choose a
better algorithm for a particular problem as one computational problem can be solved
by different algorithms.
By considering an algorithm for a specific problem, we can begin to develop pattern
recognition so that similar types of problems can be solved by the help of this
algorithm.
Algorithms are often quite different from one another, though the objective of these
algorithms are the same. For example, we know that a set of numbers can be sorted
using different algorithms. Number of comparisons performed by one algorithm may
vary with others for the same input. Hence, time complexity of those algorithms may
differ. At the same time, we need to calculate the memory space required by each
algorithm.
Analysis of algorithm is the process of analyzing the problem-solving capability of the
algorithm in terms of the time and size required (the size of memory for storage while
implementation). However, the main concern of analysis of algorithms is the required
time or performance. Generally, we perform the following types of analysis −
 Worst-case − The maximum number of steps taken on any instance of size a.
 Best-case − The minimum number of steps taken on any instance of size a.
 Average case − An average number of steps taken on any instance of size a.
 Amortized − A sequence of operations applied to the input of size a averaged
over time.
To solve a problem, we need to consider time as well as space complexity as the
program may run on a system where memory is limited but adequate space is
available or may be vice-versa. In this context, if we compare bubble sort and merge
sort. Bubble sort does not require additional memory, but merge sort requires
additional space. Though time complexity of bubble sort is higher compared to merge
sort, we may need to apply bubble sort if the program needs to run in an environment,
where memory is very limited.
Unit-2 to 5
1.Explain the Applications of C Programming
C was initially used for system development work, particularly the programs that make-up the
operating system. C was adopted as a system development language because it produces code
that runs nearly as fast as the code written in assembly language. Some examples of the use of C
are -
 Operating Systems
 Language Compilers
 Assemblers
 Text Editors
 Print Spoolers
 Network Drivers
 Modern Programs
 Databases
 Language Interpreters
 Utilities

2.How will you Compile and Execute C Program


Let us see how to save the source code in a file, and how to compile and run it. Following are
the simple steps −
 Open a text editor and add the above-mentioned code.
 Save the file as hello.c
 Open a command prompt and go to the directory where you have saved the file.
 Type gcc hello.c and press enter to compile your code.
 If there are no errors in your code, the command prompt will take you to the next line
and would generate a.out executable file.
 Now, type a.out to execute your program.
 You will see the output "Hello World" printed on the screen.

3.Explain the following a) Tokens, b)semicolon c)comments d) keywords

Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a
constant, a string literal, or a symbol. For example, the following C statement consists of five
tokens −
printf("Hello, World! \n");
The individual tokens are −

printf
(
"Hello, World! \n"
)
;

Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must
be ended with a semicolon. It indicates the end of one logical entity.
Given below are two different statements −
printf("Hello, World! \n");
return 0;

Comments
Comments are like helping text in your C program and they are ignored by the compiler. They
start with /* and terminate with the characters */ as shown below −
/* my first program in C */
You cannot have comments within comments and they do not occur within a string or character
literals.
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.

auto else long switch

break enum register typedef

case extern return union

char float short unsigned


const for signed void

continue goto sizeof volatile

default if static while

do int struct _Packed

double

4.  Differences between High-Level and Low-Level programming languages −

High-Level Language Low-level language

It can be considered as a programmer-friendly language. It is considered as a machine-


friendly language.

It requires a compiler/interpreter to be translated into It requires an assembler that would


machine code. translate instructions.

It can be ported from one location to another. It is not portable.

It is easy to understand. It is difficult to understand.

It is easy to debug. It is difficult to debug.


It is less memory efficient, i.e., it consumes more memory It consumes less memory.
in comparison to low-level languages.

5. Explain how to define a variable in C -language .


variable
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C is
case-sensitive. Based on the basic types explained in the previous chapter, there will be the
following basic variable types −

Sr.No. Type & Description

1 char
Typically a single octet(one byte). It is an integer type.

2 int
The most natural size of integer for the machine.

3 float
A single-precision floating point value.

4 double
A double-precision floating point value.

5 void
Represents the absence of type.

C programming language also allows to define various other types of variables, which we will
cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this
chapter, let us study only basic variable types.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable.
A variable definition specifies a data type and contains a list of one or more variables of that
type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated by
commas.
6. Explain how to define constants in C
Constants
Constants refer to fixed values that the program may not alter during its execution. These fixed
values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a
character constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after
their definition.
Defining Constants
There are two simple ways in C to define constants −
 Using #define preprocessor.
 Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant −
#define identifier value
The following example explains it in detail −

Live Demo

#include <stdio.h>

#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'

int main() {
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −

Live Demo

#include <stdio.h>

int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;

area = LENGTH * WIDTH;


printf("value of area : %d", area);
printf("%c", NEWLINE);

return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50

7. Special features of C programming languages


C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie
to develop the UNIX operating system at Bell Labs. C was originally first implemented on the
DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description
of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs
have been written in C. C has now become a widely used professional language for various
reasons −
 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms
Facts about C
 C was invented to write an operating system called UNIX.
 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard Institute
(ANSI).
 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art software have been implemented using C.
 Today's most popular Linux OS and RDBMS MySQL have been written in C.

8. Operators:

Operato Description Example


r

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B =


200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an integer B%A=0


division.
++ Increment operator increases the integer value by one. A++ = 11

-- Decrement operator decreases the integer value by one. A-- = 9

An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of operators

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
We will, in this chapter, look into the way each operator works.
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds
10 and variable B holds 20 then −

Operato Description Example


r

== Checks if the values of two operands are equal or not. If yes, then (A == B) is
the condition becomes true. not true.

!= Checks if the values of two operands are equal or not. If the (A != B) is


values are not equal, then the condition becomes true. true.

> Checks if the value of left operand is greater than the value of (A > B) is not
right operand. If yes, then the condition becomes true. true.

< Checks if the value of left operand is less than the value of right (A < B) is
operand. If yes, then the condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to the (A >= B) is
value of right operand. If yes, then the condition becomes true. not true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand. If yes, then the condition becomes true. true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume
variable A holds 1 and variable B holds 0, then −
Show Examples

Operato Description Example


r

&& Called Logical AND operator. If both the operands are non-zero, (A && B) is
then the condition becomes true. false.

|| Called Logical OR Operator. If any of the two operands is non- (A || B) is


zero, then the condition becomes true. true.

! Called Logical NOT Operator. It is used to reverse the logical state !(A && B)
of its operand. If a condition is true, then Logical NOT operator is true.
will make it false.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^
is as follows −

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −


A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60 and
variable 'B' holds 13, then −
Show Examples

Operato Description Example


r

& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12, i.e.,
both operands. 0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61, i.e.,


0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) = 49, i.e.,
but not both. 0011 0001

~ Binary One's Complement Operator is unary and has the (~A ) = ~(60), i.e,.
effect of 'flipping' bits. -0111101

<< Binary Left Shift Operator. The left operands value is moved A << 2 = 240 i.e.,
left by the number of bits specified by the right operand. 1111 0000

>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15 i.e.,
right by the number of bits specified by the right operand. 0000 1111

Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples

Operato Description Example


r

= Simple assignment operator. Assigns values from right C = A + B will assign


side operands to left side operand the value of A + B to C

+= Add AND assignment operator. It adds the right operand C += A is equivalent to


to the left operand and assign the result to the left
operand. C=C+A

-= Subtract AND assignment operator. It subtracts the right


C -= A is equivalent to
operand from the left operand and assigns the result to
C=C-A
the left operand.

*= Multiply AND assignment operator. It multiplies the


C *= A is equivalent to
right operand with the left operand and assigns the result
C=C*A
to the left operand.

/= Divide AND assignment operator. It divides the left


C /= A is equivalent to
operand with the right operand and assigns the result to
C=C/A
the left operand.

%= Modulus AND assignment operator. It takes modulus


C %= A is equivalent
using two operands and assigns the result to the left
to C = C % A
operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C =


C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C =


C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C =


C&2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C =


C^2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C
|2

Expression of unary,binary,ternary operators:


An expression is a combination of operators and operands which reduces to a single value. An
operation is performed on a data item which is called an operand. An operator indicates an
operation to be performed on data.
For example, z = 3+2*1
z=5

 Primary expressions − It is an operand which can be a name, a constant or any


parenthesized expression. Example − c = a+ (5*b);
 Postfix expressions − In a postfix expression, the operator will be after the operand.
Example − ab+
 Prefix expressions − n a prefix expression, the operator is before the operand. Example
− +ab
 Unary expression − It contains one operator and one operand. Example − a++, --b
 Binary expression − t contains two operands and one operator. Example − a+b, c-d
 Ternary expression − It contains three operands and one operator. For Example, Exp1?
Exp2 − Exp3. If Exp1 is true, Exp2 is executed. Otherwise, Exp3 is executed.
Example
Given below is the C program explaining the different types of expressions in C language −

 Live Demo

#include<stdio.h>
int main(){
   int a,b,c,d,z;
   int p,q,r,s,t,u,v;
   printf("enter the values of a,b,c,d:\n");
   scanf("%d%d%d%d",&a,&b,&c,&d);
   r=a++;
   s=--b;
   t=a+b;
   u=c-d;
   v=a+(5*b);
   z = (5>3) ? 1:0;
   printf("unaryexpression=%d\nunary expression=%d\n Binary
   expression=%d\nBinary expression=%d\nPrimary expression=%d\nTernary expression=%d\
n",r,s,t,u,v,z);
}
Output
You will see the following output −
enter the values of a,b,c,d:
2346
unary expression=2
unary expression=2
Binary expression=5
Binary expression=-2
Primary expression=13
Ternary expression=1
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Show Examples

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right


Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right


Control statement:
C provides two sytles of flow control:
 Branching
 Looping
Branching is deciding what actions to take and looping is deciding how many times to take a certain
action.

Branching:
Branching is so called because the program chooses to follow one branch or another.

if statement
This is the most simple form of the branching statements.
It takes an expression in parenthesis and an statement or block of statements. if the expression is true
then the statement or block of statements gets executed otherwise these statements are skipped.
NOTE: Expression will be assumed to be true if its evaulated values is non-zero.
if statements take the following form:
Show Example

if (expression)
statement;

or

if (expression)
{
Block of statements;
}

or

if (expression)
{
Block of statements;
}
else
{
Block of statements;
}

or

if (expression)
{
Block of statements;
}
else if(expression)
{
Block of statements;
}
else
{
Block of statements;
}

switch statement:
The switch statement is much like a nested if .. else statement. Its mostly a matter of
preference which you use, switch statement can be slightly more efficient and easier to
read.
Show Example

switch( expression )
{
case constant-expression1: statements1;
[case constant-expression2: statements2;]
[case constant-expression3: statements3;]
[default : statements4;]
}

Looping
Loops provide a way to repeat commands and control how many times they are repeated. C provides a
number of looping way.

while loop
The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If
statement, if the test condition is true: the statments get executed. The difference is that after the
statements have been executed, the test condition is checked again. If it is still true the statements get
executed again.This cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows:
Show Example

while ( expression )
{
Single statement
or
Block of statements;
}

for loop
for loop is similar to while, it's just written differently. for statements are often used to proccess lists such
a range of numbers:
Basic syntax of for loop is as follows:
Show Example
for( expression1; expression2; expression3)
{
Single statement
or
Block of statements;
}

In the above syntax:

 expression1 - Initialisese variables.


 expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
 expression3 - expression3 is the modifier which may be simple increment of a variable.

do...while loop
do ... while is just like a while loop except that the test condition is checked at the end of the loop rather
than the start. This has the effect that the content of the loop are always executed at least once.
Basic syntax of do...while loop is as follows:
Show Example

do
{
Single statement
or
Block of statements;
}while(expression);

break and continue statements


C provides two commands to control how we loop:

 break -- exit form loop or switch.


 continue -- skip 1 iteration of loop.

You already have seen example of using break statement. Here is an example showing usage
of continue statement.

#include

main()
{
int i;
int j = 10;

for( i = 0; i <= j; i ++ )
{
if( i == 5 )
{
continue;
}
printf("Hello %d\n", i );
}
}

This will produce following output:

Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10

Console input-output:
The Standard Files
C programming treats all the devices as files. So devices such as the display are addressed in the same
way as files and the following three files are automatically opened when a program executes to provide
access to the keyboard and screen.

Standard File File Pointer Device

Standard input stdin Keyboard

Standard output stdout Screen

Standard error stderr Your screen

The file pointers are the means to access the file for reading and writing purpose. This section explains
how to read values from the screen and how to print the result on the screen.

printf() function
This is one of the most frequently used functions in C for output. ( we will discuss what
is function in subsequent chapter. ).
Try following program to understand printf() function.
#include <stdio.h>

main()
{
int dec = 5;
char str[] = "abc";
char ch = 's';
float pi = 3.14;

printf("%d %s %f %c\n", dec, str, pi, ch);


}

The output of the above would be:

5 abc 3.140000 c

scanf() function
This is the function which can be used to to read an input from the command line.
Try following program to understand scanf() function.

#include <stdio.h>

main()
{
int x;
int args;

printf("Enter an integer: ");


if (( args = scanf("%d", &x)) == 0) {
printf("Error: not an integer\n");
} else {
printf("Read in %d\n", x);
}
}

Here %d is being used to read an integer value and we are passing &x to store the vale read input. Here
&indicates the address of variavle x.

The getchar() and putchar() Functions


The int getchar(void) function reads the next available character from the screen and
returns it as an integer. This function reads only single character at a time. You can
use this method in the loop in case you want to read more than one character from the
screen.
The int putchar(int c) function puts the passed character on the screen and returns
the same character. This function puts only single character at a time. You can use this
method in the loop in case you want to display more than one character on the screen.
Check the following example −
#include <stdio.h>
int main( ) {

int c;

printf( "Enter a value :");


c = getchar( );

printf( "\nYou entered: ");


putchar( c );

return 0;
}
$./a.out
Enter a value : this is test
You entered: t

The gets() and puts() Functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to
by s until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline
to stdout.
NOTE: Though it has been deprecated to use gets() function, Instead of using gets,
you want to use fgets().
#include <stdio.h>
int main( ) {

char str[100];

printf( "Enter a value :");


gets( str );

printf( "\nYou entered: ");


puts( str );

return 0;
}

When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads the
complete line till end, and displays it as follows −
$./a.out
Enter a value : this is test
You entered: this is test

Array:
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the
same type. An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.

All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.

Declaring Arrays
To declare an array in C, a programmer specifies the type of the elements and the
number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer constant
greater than zero and type can be any valid C data type. For example, to declare a 10-
element array called balance of type double, use this statement −
double balance[10];
Here balance is a variable array which is sufficient to hold up to 10 double numbers.

Initializing Arrays
You can initialize an array in C either one by one or using a single statement as follows

double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};
The number of values between braces { } cannot be larger than the number of
elements that we declare for the array between square brackets [ ].

Multi-dimensional array:
C programming language allows multidimensional arrays. Here is the general form of a multidimensional
array declaration −
type name[size1][size2]...[sizeN];
For example, the following declaration creates a three dimensional integer array −
int threedim[5][10][4];

Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in
essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you
would write something as follows −
type arrayName [ x ][ y ];
Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional
array can be considered as a table which will have x number of rows and y number of columns. A two-
dimensional array a, which contains three rows and four columns can be shown as follows −

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the
name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.

Initializing Two-Dimensional Arrays


Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an
array with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};

The nested braces, which indicate the intended row, are optional. The following initialization is equivalent
to the previous example −
int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing Two-Dimensional Array Elements


An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column
index of the array. For example −
int val = a[2][3];
The above statement will take the 4th element from the 3rd row of the array. You can verify it in the
above figure. Let us check the following program where we have used a nested loop to handle a two-
dimensional array −

Live Demo

#include <stdio.h>
int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {

for ( j = 0; j < 2; j++ ) {


printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}

When the above code is compiled and executed, it produces the following result −
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

Function:
A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.

Defining a Function
The general form of a function definition in C programming language is as follows −
return_type function_name( parameter list ) {
body of the function
}

A function definition in C programming consists of a function header and a function body. Here are all
the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the value the
function returns. Some functions perform the desired operations without returning a value. In this
case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the parameter
list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you pass a value to
the parameter. This value is referred to as actual parameter or argument. The parameter list
refers to the type, order, and number of the parameters of a function. Parameters are optional;
that is, a function may contain no parameters.
 Function Body − The function body contains a collection of statements that define what the
function does.

Example
Given below is the source code for a function called max(). This function takes two parameters num1
and num2 and returns the maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual
body of the function can be defined separately.
A function declaration has the following parts −
return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows −
int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the following is
also a valid declaration −
int max(int, int);
Function declaration is required when you define a function in one source file and you call that function
in another file. In such case, you should declare the function at the top of the file calling the function.

Calling a Function
While creating a C function, you give a definition of what the function has to do. To use a function, you
will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called function. A called
function performs a defined task and when its return statement is executed or when its function-ending
closing brace is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name, and if
the function returns a value, then you can store the returned value. For example −

Live Demo
#include <stdio.h>

/* function declaration */
int max(int num1, int num2);

int main () {

/* local variable definition */


int a = 100;
int b = 200;
int ret;

/* calling a function to get max value */


ret = max(a, b);

printf( "Max value is : %d\n", ret );

return 0;
}

/* function returning the max between two numbers */


int max(int num1, int num2) {

/* local variable declaration */


int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

We have kept max() along with main() and compiled the source code. While running the final executable,
it would produce the following result −
Max value is : 200

What are Pointers?


A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address. The general form of a pointer
variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is
the name of the pointer variable. The asterisk * used to declare a pointer is the same
asterisk used for multiplication. However, in this statement the asterisk is being used to
designate a variable as a pointer. Take a look at some of the valid pointer declarations

int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or
otherwise, is the same, a long hexadecimal number that represents a memory address.
The only difference between pointers of different data types is the data type of the
variable or constant that the pointer points to.

How to Use Pointers?


There are a few important operations, which we will do with the help of pointers very
frequently. (a) We define a pointer variable, (b) assign the address of a variable to a
pointer and (c) finally access the value at the address available in the pointer variable.
This is done by using unary operator * that returns the value of the variable located at
the address specified by its operand. The following example makes use of these
operations −
Live Demo

#include <stdio.h>

int main () {

int var = 20; /* actual variable declaration */


int *ip; /* pointer variable declaration */

ip = &var; /* store address of var in pointer variable*/

printf("Address of var variable: %x\n", &var );

/* address stored in pointer variable */


printf("Address stored in ip variable: %x\n", ip );

/* access the value using the pointer */


printf("Value of *ip variable: %d\n", *ip );

return 0;
}

When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

File handling:
A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming
language provides access on high level functions as well as low level (OS level) calls to handle file on
your storage devices. This chapter will take you through the important calls for file management.

Opening Files
You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an
object of the type FILE, which contains all the information necessary to control the stream. The prototype
of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can have one of
the following values −

Sr.No Mode & Description


.

1
r
Opens an existing text file for reading purpose.

2
w
Opens a text file for writing. If it does not exist, then a new file is created. Here
your program will start writing content from the beginning of the file.

3
a
Opens a text file for writing in appending mode. If it does not exist, then a new file
is created. Here your program will start appending content in the existing file
content.

4
r+
Opens a text file for both reading and writing.

5
w+
Opens a text file for both reading and writing. It first truncates the file to zero
length if it exists, otherwise creates a file if it does not exist.

6
a+
Opens a text file for both reading and writing. It creates the file if it does not exist.
The reading will start from the beginning but writing can only be appended.

If you are going to handle binary files, then you will use following access modes instead of the above
mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This
function actually flushes any data still pending in the buffer to the file, closes the file, and releases any
memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by
character, or in the form of a fixed length string.

Writing a File
Following is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp.
It returns the written character written on success otherwise EOF if there is an error. You can use the
following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative
value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE
*fp,const char *format, ...) function as well to write a string into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this
directory on your machine.
#include <stdio.h>

main() {
FILE *fp;

fp = fopen("/tmp/test.txt", "w+");
fprintf(fp, "This is testing for fprintf...\n");
fputs("This is testing for fputs...\n", fp);
fclose(fp);
}

When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes
two lines using two different functions. Let us read this file in the next section.

Reading a File
Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the
character read, or in case of any error, it returns EOF. The following function allows to read a string from
a stream −
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the
read string into the buffer buf, appending a null character to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the
maximum number of characters, then it returns only the characters read up to that point including the
new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read
strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>

main() {

FILE *fp;
char buff[255];

fp = fopen("/tmp/test.txt", "r");
fscanf(fp, "%s", buff);
printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);


printf("3: %s\n", buff );
fclose(fp);

When the above code is compiled and executed, it reads the file created in the previous section and
produces the following result −
1 : This
2: is testing for fprintf...

3: This is testing for fputs...


Let's see a little more in detail about what happened here. First, fscanf() read just This because after
that, it encountered a space, second call is for fgets() which reads the remaining line till it encountered
end of line. Finally, the last call fgets() reads the second line completely.

Questions
Small question:

1. What is Debugging?
2. What is an algorithm?

3. How to Use Pointers?

4. How will you Compile and Execute C Program?


5. Define Operators.
6. What are Tokens in C?

7. What is statement terminator in C program?

8. What are Comments?

9. Define Keywords.

10. What is Operators Precedence in C?


11.What is break and continue statements?

Brief questions
1. What are Flow Chart Symbols? And explain the guidelines for developing flowchart with
example.
2. How to design a Program and explain in detail briefly?
3. Explain briefly the types of Errors in C Language with example.
4. Write all the Steps to Development of Program briefly.
5. What is variable and Explain how to define a variable in C -language.
6. Explain briefly the built-in operators and any four types of operators with example.

7. Explain briefly about Control statement in C programming.


8. Explain briefly about Console input-output with example.

9. Define Function and explain briefly about the function in C programming.

You might also like