Unit 1
Unit 1
Introduction, Algorithms, building blocks of algorithms, Algorithmic problem-solving steps; Simple Strategies and
notation for developing algorithms: Control flow, Flow charts, Pseudo codes, Programming languages; Introduction
to C; Structure of a C Program; Compiling and Executing C Programmes, C Tokens and character set, Keywords,
Identifiers, Basic Data types, Variables, Constants, Input/ Output statements, Operators, Type conversion and Type
Casting
1.1 Introduction
Computer is an electronic device which is used to store the data, manipulate the data as per given instructions and it
gives results quickly and accurately.
Data: Data is a raw material of information.
Information: Proper collection of the data is called information.
Steps in Problem Solving:
1. Define the problem
A clear and concise problem statement is provided.
The problem definition should specify the input and output
Full knowledge about the problem is needed.
Example: To find the average of two numbers
2. Formulate the mathematical model.
Any technical problem provided could be represented mathematically
Full knowledge about the problem should be provided along with the underlying mathematical concept.
Example: Average = (Data1+Data2)/2
3. Develop an algorithm
An algorithm is the sequence of operations to be performed
It gives the precise plan for the problem
Example:
1. Start
2. Read the integers A and B from the user.
3. Calculate the sum: C = A + B.
4. Calculate the average: average = sum / 2.
5. Display the result.
4. Write the code for the problem
The algorithm developed must be converted to any Programming Language
The compiler will convert the program code to the machine code, which the computer can understand
5. Test the program.
Testing involves checking errors both syntactically and semantically
The errors are called bugs
When the compiler finds the bugs, it prevents compiling the code and reports the error
Checks the program by providing set of data for testing
1.2 Algorithms
An Algorithm is defined as a set of steps for solving a particular problem in a finite amount of time. It is a good
software engineering practice to design algorithms before we write a program.
Characteristics/Properties of Algorithm
Precision: The steps of an algorithm are clearly defined.
Uniqueness: The results of each step are uniquely defined and depend only on the input and the results of the
previous steps.
Finiteness: The algorithm stops after a finite number of instructions are executed.
Effectiveness: Every step in the algorithm should be easy to understand and can be implemented using any
programming language.
Input: The algorithm takes input data, which can be in various formats, such as numbers, text, or images.
Output: The algorithm produces output, which could be a result, a decision, or some other meaningful
information.
Generality: The algorithm applies to a set of inputs.
Advantage
It is a stepwise description of a solution, which makes easy to understand.
It is not dependent on any programming language.
It is easier for programmer to convert into an actual program.
Disadvantage
It is difficult to show branching and looping statements.
It is time consuming, algorithm needs to be developed first which is then converted to program.
Before writing the pseudocode of any algorithm the following points must be kept in mind.
Organize the sequence of tasks and write the pseudocode accordingly.
At first, establishes the main goal or the aim.
Example:
This program will print factorial of a given number N.
Use standard programming structures such as if-else, for, while, and cases the way we use them in
programming. Indent the statements if-else, for, while loops as they are indented in a program, it helps to
comprehend the decision control and execution mechanism. It also improves readability to a great extent.
Use appropriate naming conventions. The human tendency follows the approach of following what we see.
If a programmer goes through a pseudo code, his approach will be the same as per that, so the naming must
be simple and distinct.
Reserved commands or keywords must be represented in capital letters.
Example: if you are writing IF…ELSE statements then make sure IF and ELSE be in capital letters.
Check whether all the sections of a pseudo code are complete, finite, and clear to understand and comprehend.
Also, explain everything that is going to happen in the actual code.
Don’t write the pseudocode in a programming language.
It is necessary that the pseudocode is simple and easy to understand.
INPUT number
SET factorial := 1, i := 1
WHILE i <= number DO
COMPUTE factorial := factorial * i
INCREASE i by 1
END LOOP
PRINT factorial
1.3.4 Programming Language
A programming language is a type of written language that tells computers what to do.
Examples are: Python, Ruby, Java, JavaScript, C, C++, and C#.
Programming languages are used to write computer programs and computer software. A programming language is
like a set of commands that tell the computer how to do things.
Usually, the programming language uses real words for some of the commands (e.g. "if... then... else...", "and", "or"),
so that the language is easier for a human to understand. Like any normal language, many programming languages
use punctuation. To make a program, a programmer writes commands in their chosen programming language and
saves the commands to a text file. This text file is called source code. Some programming languages, such as Python
and JavaScript, can be read by the computer right away. If not, the source code has to be compiled, which means that
the computer translates the source code into another language (such as assembly language or machine language) that
a computer can read, but which is much harder for a person to read.
Computer programs must be written very carefully. If a programmer makes mistakes, then the program might then
stop working, which is called "crashing". When a program has a problem because of how the code was written, this
is called a "bug". A very small mistake can cause very serious bugs.
1.4 Introduction to C
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972.
It is a very popular language, despite being old. It was developed to overcome the problems of previous languages
such as B, BCPL, etc. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee
Characteristics of ‘C’
High-level programming language
Small size- has only 32 keywords
C makes extensive use of function calls
Well suited for structured programming
Programs written in C are efficient and fast. This is due to its variety of data type and powerful operators
The C compiler combines the capabilities of an assembly language with features of a high-level language.
A-C program is basically a collection of functions that are supported by C library. We can also create our own
function and add it to C library
Supports pointer to refer computer memory, array, structures and functions
Core language as many programming languages are based on C
C is a portable language
Structure of a C Program
Global Declaration
In C programming, a global declaration refers to the declaration of a variable or function that is accessible from any
part of the program, not just from the block or function where it was declared.
A global variable is declared outside of a function, typically at the top of the program file, and it can be used by any
function in the program.
For example
#include <stdio.h>
int count = 0; // global variable
void increment() {
count++;
}
int main() {
increment();
printf("count = %d\n", count); // prints "count = 1"
return 0;
}
Main() function
In C programming, the main() function is a special function that serves as the entry point for the program. When a C
program is executed, the operating system loads the program into memory and starts executing instructions from the
beginning of the main() function.
The main() function has a specific syntax in C:
int main() {
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
This program uses the printf() function from the stdio.h library to print the message "Hello, world!" to the console.
When the program is executed, the main() function is called, the message is printed to the console, and the program
exits with a return value of 0.
Subprograms
In C programming, subprograms refer to functions or procedures that perform a specific task or set of tasks and can
be called from other parts of the program.
Functions in C are subprograms that return a value to the caller, while procedures (also known as void functions) do
not return a value. Both functions and procedures can have parameters that are used to pass data between the caller
and the subprogram.
Here's an example of a function in C:
#include <stdio.h>
int sum(int a, int b) {
return a + b;
}
int main() {
int x = 3, y = 4;
int result = sum(x, y);
printf("The sum of %d and %d is %d\n", x, y, result);
return 0;
}
Output: The sum of 3 and 4 is 7
In this example, the sum() function takes two integer parameters and returns their sum. The main() function calls the
sum() function with the values of x and y and then prints the result to the console.
1.6 C Tokens
Tokens in C is the smallest individual element in C and is the most important element to be used in creating a program
in C. Tokens in C is the building block or the basic component for creating a program in C language.
Tokens in C language can be divided into the following categories:
Keywords
Variables
Constants
Strings
Special characters
operators
1.6.1 Keywords in C
Keywords in C can be defined as the pre-defined or the reserved words having its own importance, and each
keyword has its own functionality. Since keywords are the pre-defined words used by the compiler, so they
cannot be used as the variable names. If the keywords are used as the variable names, it means that we are
assigning a different meaning to the keyword, which is not allowed. C language supports 32 keywords given
below:
Auto double int struct break else long switch
case enum register typedef char extern return union
const float short unsigned continue for signed Void
default goto sizeof volatile do if static while
1.6.2 Identifiers in C
Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the user-defined
words. It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting letter should
be either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in
C are given below:
No other special characters except underscore could be use
No two or more successive underscores could be used
The first character of an identifier should be either an alphabet or an underscore, and then it can be followed
by any of the character, digit, or underscore.
It should not begin with any numerical digit.
In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case
sensitive.
Commas or blank spaces cannot be specified within an identifier.
Keywords cannot be represented as an identifier.
The length of the identifiers should not be more than 31 characters.
Identifiers should be written in such a way that it is meaningful, short, and easy to read.
1.6.3 Character Set in C
Any letter from English alphabet, digit or special symbol used to represent information. The character set of C can
therefore be given as:
English Alphabet: include both uppercase (A - Z) and lowercase (a - z) letters
Digits: include numerical digits from 0 – 9
Special Characters: include symbols such as
! ; “ < # = $ > % ? & @ ‘ [ ( /
) ] * ^ =+ _ , ` - { . | / } : ~
White Space Characters: The white spaces are characters that create space between words or symbols.
Character Meaning
\b Blank Space
\t Horizontal Tab
\v Vertical Return
\r Carriage Return
\f Form Feed
\n New Line
Escape Sequence in C: The purpose of the escape sequence is to represent the characters that cannot be used normally
using the keyboard. They include \a, \n, \\, \’, \”, \?, \0
1.6.4 Basic Data types
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer,
character, floating, double, etc. Each data type requires different amounts of memory and has some specific
operations which can be performed over it.
Detailed list:
1.6.5 Variables
A variable is the name of the memory location. It is used to store information. Its value can be altered and reused
several times.
Each variable has a unique identifier, its name, and a data type describing the type of data it may hold.
Syntax:
data_type variable_name;
The three components of declaring a variable
1. Variable Declaration:
The process of telling the compiler about a variable's existence and data type is known as variable declaration. It
notifies the compiler that a variable with a specific name and data type will be used in the program.
Syntax:
data_type variable_name;
3. Variable Initialization:
The process of reserving memory space for the variable to keep its contents during program execution is known as a
variable definition.
Syntax:
data_type variable_name=value;
Example:
#include <stdio.h>
void main() {
// Variable definition & Initialization
int age = 25;
float salary = 2500.5;
char initial = 'J';
}
Types of Variables in C
There are many types of variables in c:
1. local variable
2. global variable
Local Variable
A variable that is declared inside the function or block is called a local variable.
It must be declared at the start of the block.
void function1(){
int x=10;//local variable
}
Global Variable
A variable that is declared outside the function or block is called a global variable. Any function can change the value
of the global variable. It is available to all the functions.
It must be declared at the start of the block.
#include<stdio.h>
int value=20;//global variable
void main(){
int x=10;//local variable
}
1.6.6 Constants
A constant in C is a value that doesn't change as the program runs. Integers, floating-point numbers, characters, and
strings are just a few of the several types of constants that may be employed. When a constant has a value, it cannot
be changed, unlike variables. They may be utilized in various operations and computations and serve as the program's
representation of fixed values.
Integer Constants:
The digits of an integer constant can range from 0 to 9.
A decimal point should not be present in an integer constant.
Positive or negative integer constants are also possible.
You can add a suffix to a constant's name to define its type. 'U' or 'u' stands for unsigned, 'L' or 'l' for long,
or 'LL' or 'll' for long long.
Floating-Point Constants:
A decimal point, an exponent, or digits can all be found in floating-point constants.
Either exponential notation or decimal notation can be used to write them.
'E' or 'e' can be used to denote an exponent.
You can add a suffix to a constant's name to define its type. For instance, "F" or "f" stands for float and "L"
or "l" for long double.
Character Constants:
Individual characters are represented as character constants when they are in single quotes.
A single letter or an escape sequence, such as "n" for newline or "t" for tab, can be used as these characters.
String Constants:
A series of characters surrounded in double quotes is represented by string constants.
They are essentially character arrays that are closed with the null character "0".
Declaring a Constant:
There are two ways to define constant in C programming.
1. const keyword
2. #define preprocessor
1. const keyword
The const keyword is used to define constant in C programming.
const float PI=3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
void main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
}
2. #define preprocessor
The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive.
#define PI 3.14;
Now, the value of PI variable can't be changed.
#include<stdio.h>
#define PI 3.14;
void main(){
printf("The value of PI is: %f",PI);
}
1.7 Input/ Output statements
All input and output is performed with streams. A stream acts in two way. It is the source of data as well as destination
of data. There are two forms of streams Text Stream and Binary Stream.
Text Stream: It is a sequence of characters organized into lines. Each line consists of zero or more characters and
ends with the "newline" character
Binary Stream: Contains data values using their memory representation.
Streams are associated with physical device such as monitor and keyboard. Based on data flow between devices
streams are classified into input stream and output stream.
Formatting input and output
C language has standard libraries that allow input and output in a program. The stdio.h or standard input output
library in C that has methods for input and output.
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf(“control string”, variable list);
Control string takes the following format
Specifier – used to define the type and the interpretation of the value of the corresponding argument.
Examples:
scanf()
The scanf() method, in C, reads the value from the console as per the type specified and store it in the given address.
Syntax:
scanf(“control string”, variable list);
Type Specifiers:
Output:
1.8 Operators
An operator is simply a symbol that is used to perform operations.
There are following types of operators to perform different types of operations in C language.
Arithmetic Operators Unary Operators Assignment Operator
Relational Operators Conditional Operators Comma Operator
Equality Operators Bitwise Operators sizeof Operator
Logical Operators Shift Operators
with
1.8.2 Relational Operators
Relational operators assess the relationship between values by comparing them. They return either true (1) or false
(0). The relational operators in C are as follows:
int a = 5;
int b = 3;
int result = (a > 3) && (b < 5); // result = 1 as both conditions are true
Logical OR Operator (||): The logical OR operator returns true if at least one of the operands is true
int a = 5;
int b = 3;
int result = (a > 3) || (b > 5); // result = 1 as the first condition is true
Logical NOT Operator (!): The logical NOT operator negates the value of the operand.
int a = 5;
int result = !(a > 3); // result = 0
1.8.5 Unary Operator
A unary operator is an operator used to operate on a single operand.
Unary Minus (-)
The unary operator is used to change the sign of any positive value to a negative value. It means it changes the
positive number to the negative, and a negative number becomes the positive number using the unary minus operator.
int a = 2;
int b = -(a);
Increment Operator (++)
It is the unary increment operator, which is denoted by the "++" symbol. The "++" symbol represents the operand's
value is increased by 1. It can be used in two ways, as the post-increment and the pre-increment.
Pre Increment: The pre-increment operator is represented as (++a), which means the value of variable 'a' is increment
by 1 before using operand to the expression.
For example:
x = 10;
A = ++x;
The initial value of x is 10, and using the pre-increment operator (++x) increases the operand value by 1 before
assigning it to the variable 'A'.
Post Increment: The (a++) symbol represents the post-increment operator, which means the value of 'a' is incremented
by 1 after assigning the original value to the expression or another variable.
For example:
x = 10;
A = x++;
Here the initial value of the x variable is 10 and using the post-increment operator (x++) to assign increment value
of the 'x' to the variable 'A'.
#include <stdio.h>
#include <conio.h>
void main ()
{
int x, y, a, b; // declare local variable
a = 10;
x = ++a; // It shows pre increment operator
printf (" Pre Increment Operator");
// Here the value of x is increased by 1.
printf (" \n The value of x is %d.", x);
printf (" \n The value of a is %d.", a);
b = 20;
y = b++; // It shows the post increment operator
printf (" \n\n Post Increment Operator");
printf (" \n The value of y is %d.", y);
// get updated value of b
printf (" \n The value of b is %d.", b);
}
Output:
Pre Increment Operator
The value of x is 11.
The value of a is 11.