PGDCA 113 Intro Progm-Notes
PGDCA 113 Intro Progm-Notes
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 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.
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.
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) −
Decision Annotation
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.
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.
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.
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.
double
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;
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;
return 0;
}
When the above code is compiled and executed, it produces the following result −
value of area : 50
8. Operators:
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 −
== 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 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
&& Called Logical AND operator. If both the operands are non-zero, (A && B) is
then the condition becomes true. false.
! 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 −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
& Binary AND Operator copies a bit to the result if it exists in (A & B) = 12, i.e.,
both operands. 0000 1100
^ 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
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
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;
}
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);
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 );
}
}
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.
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;
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;
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.
int c;
return 0;
}
$./a.out
Enter a value : this is test
You entered: t
char str[100];
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'.
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};
Live Demo
#include <stdio.h>
int main () {
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.
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) {
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 () {
return 0;
}
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
#include <stdio.h>
int main () {
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 −
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 );
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...
Questions
Small question:
1. What is Debugging?
2. What is an algorithm?
9. Define Keywords.
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.