Chapter 1 Notes
Chapter 1 Notes
Definition of Algorithm
The word Algorithm means ” A set of finite rules or instructions to be followed in calculations or
other problem-solving operations ”
Or
” A procedure for solving a mathematical problem in a finite number of steps that frequently
involves recursive operations”.
Algorithms can be simple and complex depending on what you want to achieve.
It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one reads the
instructions and steps and executes them one by one, in the given sequence. The result thus obtained is the
new dish is cooked perfectly. Every time you use your phone, computer, laptop, or calculator you are using
Algorithms. Similarly, algorithms help to do a task in programming to get the expected output.
The Algorithm designed are language-independent, i.e. they are just plain instructions that can be
implemented in any language, and yet the output will be the same, as expected.
1. Clear and Unambiguous: Each step must be precise and lead to only one interpretation.
2. Well-Defined Inputs: Inputs should be clearly specified, though an algorithm may not require any.
3. Well-Defined Outputs: The algorithm must produce at least one well-defined output.
4. Finiteness: The algorithm must terminate after a finite number of steps.
5. Feasibility: It should be practical and executable with available resources.
6. Language Independent: The algorithm should be described in plain instructions, implementable in
any programming language.
7. Definiteness: Instructions must be precise and easy to interpret without ambiguity.
8. Effectiveness: The algorithm should use basic operations that can be manually traced.
Properties of Algorithm:
• It should terminate after a finite time.
• It should produce at least one output.
• It should take zero or more input.
• It should be deterministic means giving the same output for the same input case.
• Every step in the algorithm must be effective i.e. every step should do some work.
Advantages of Algorithms:
• It is easy to understand.
• An algorithm is a step-wise representation of a solution to a given problem.
• In an Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the
programmer to convert it into an actual program.
Disadvantages of Algorithms:
• Writing an algorithm takes a long time so it is time-consuming.
• Understanding complex logic through algorithms can be very difficult.
• Branching and Looping statements are difficult to show in Algorithms(imp).
How to Design an Algorithm?
To write an algorithm, the following things are needed as a pre-requisite:
1. The problem that is to be solved by this algorithm i.e. clear problem definition.
2. The constraints of the problem must be considered while solving the problem.
3. The input to be taken to solve the problem.
4. The output is to be expected when the problem is solved.
5. The solution to this problem is within the given constraints.
Example: Consider the example to add three numbers and print the sum.
Step 1: Fulfilling the pre-requisites
As discussed above, to write an algorithm, its prerequisites must be fulfilled.
1. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.
2. The constraints of the problem that must be considered while solving the problem: The numbers
must contain only digits and no other characters.
3. The input to be taken to solve the problem: The three numbers to be added.
4. The output to be expected when the problem is solved: The sum of the three numbers taken as the
input i.e. a single integer value.
5. The solution to this problem, in the given constraints: The solution consists of adding the 3
numbers. It can be done with the help of the ‘+’ operator, or bit-wise, or any other method.
int main()
{
return 0;
}
Flowchart symbols
Different types of boxes are used to make flowcharts flowchart Symbols. All the different kinds of boxes are
connected by arrow lines. Arrow lines are used to display the flow of control. Let’s learn about each box in
detail.
Symbol Name
Symbol Representation
Terminal/Terminator
Process
Decision
Document
Symbol Name
Symbol Representation
Data or Input/Output
Stored Data
Flow Arrow
Comment or Annotation
Predefined process
On-page connector/reference
Off-page connector/reference
Uses of Flowcharts in Computer Programming/Algorithms
The following are the uses of a flowchart:
• It is a pictorial representation of an algorithm that increases the readability of the program.
• Complex programs can be drawn in a simple way using a flowchart.
• It helps team members get an insight into the process and use this knowledge to collect data, detect
problems, develop software, etc.
• A flowchart is a basic step for designing a new process or adding extra features.
• Communication with other people becomes easy by drawing flowcharts and sharing them.
1. Terminal
This box is of an oval shape which is used to indicate the start or end of the program. Every flowchart diagram
has an oval shape that depicts the start of an algorithm and another oval shape that depicts the end of an
algorithm. For example:
2. Data
This is a parallelogram-shaped box inside which the inputs or outputs are written. This basically depicts the
information that is entering the system or algorithm and the information that is leaving the system or
algorithm. For example: if the user wants to input a from the user and display it, the flowchart for this would
be:
3. Process
This is a rectangular box inside which a programmer writes the main course of action of
the algorithm or the main logic of the program. This is the crux of the flowchart as the main processing codes
is written inside this box. For example: if the programmer wants to add 1 to the input given by the user, he/she
would make the following flowchart:
4. Decision
This is a rhombus-shaped box, control statements like if, condition like a > 0, etc are written inside this box.
There are 2 paths from this one which is “yes” and the other one is “no”. Every decision has either yes or no
as an option, similarly, this box has these as options. For example: if the user wants to add 1 to an even
number and subtract 1 if the number is odd, the flowchart would be:
5. Flow
This arrow line represents the flow of the algorithm or process. It represents the direction of the process flow.
in all the previous examples, we included arrows in every step to display the flow of the program. arrow
increases the readability of the program.
6. On-Page Reference
This circular figure is used to depict that the flowchart is in continuation with the
further steps. This figure comes into use when the space is less and the flowchart is long. Any numerical
symbol is present inside this circle and that same numerical symbol will be depicted before the continuation to
make the user understand the continuation. Below is a simple example depicting the use of On-Page
Reference
Advantages of Flowchart
• It is the most efficient way of communicating the logic of the system.
• It acts as a guide for a blueprint during the program design.
• It also helps in the debugging process.
• Using flowcharts we can easily analyze the programs.
• flowcharts are good for documentation.
Disadvantages of Flowchart
• Flowcharts are challenging to draw for large and complex programs.
• It does not contain the proper amount of details.
• Flowcharts are very difficult to reproduce.
• Flowcharts are very difficult to modify.
Question 1. Draw a flowchart to find the greatest number among the 2 numbers.
Solution:
Algorithm:
1. Start
3. Now check the condition If a > b, goto step 4, else goto step 5.
5. Print b is greater
6. Stop
FlowChart:
Question 2. Draw a flowchart to check whether the input number is odd or even
Solution:
Algorithm:
1. Start
2. Put input a
5. Print(“number is even”)
6. Stop
FlowChart:
2. Input number a
3. Now initialise c = 1
4. Now we check the condition if c <= 5, goto step 5 else, goto step 7.
5. Print a
1. Start
2. Now initialise c = 1
3. Now we check the condition if c < 11, then goto step 4 otherwise goto step 6.
4. Print c
6. Stop
FlowChart:
Flowchart to print numbers from 1 to 10
1. Start
2. Now initialise c = 1
3. Now check the condition if c < 6, then goto step 4. Otherwise goto step 6
4. Print 3 * c
6. Stop
FlowChart:
1. Documentation
This section consists of the description of the program, the name of the program, and the creation date and
time of the program. It is specified at the start of the program in the form of comments. Documentation can be
represented as:
// description, name of the program, programmer name, date, time etc.
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this will not interfere with
the given code. Basically, it gives an overview to the reader of the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program. Header files
help us to access other’s improved code into our code. A copy of these multiple files is inserted into our
program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the process of compilation. There are
multiple steps which are involved in the writing and execution of the program. Preprocessor directives start
with the ‘#’ symbol. The #define preprocessor is used to create a constant throughout the program. Whenever
this name is encountered by the compiler, it is replaced by the actual piece of defined code.
Example:
#define long long ll
4. Global Declaration
The global declaration section contains global variables, function declaration, and static variables. Variables
and functions which are declared in this scope can be used anywhere in the program.
Example:
int num = 18;
5. Main() Function
Every C program must have a main function. The main() function of the program is written in this section.
Operations like declaration and execution are performed inside the curly braces of the main program. The
return type of the main() function can be int as well as void too. void() main tells the compiler that the
program will not return any value. The int main() tells the compiler that the program will return an integer
value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is shifted to the
called function whenever they are called from the main or outside the main() function. These are specified as
per the requirements of the programmer.
Example:
int sum(int x, int y)
{
return x+y;
}
// Link
#include <stdio.h>
// Definition
#define X 20
// Global Declaration
int sum(int y);
// Main() Function
int main(void)
{
int y = 55;
printf("Sum: %d", sum(y));
return 0;
}
// Subprogram
int sum(int y)
{
return y + X;
}
Explanation of the above Program
Below is the explanation of the above program. With a description explaining the program’s meaning and use.
Sections Description
/**
* file: sum.c
* author: you
It is the comment section and is part of the description section of the code.
* description: program
to find sum.
*/
Header file which is used for standard input-output. This is the preprocessor
#include<stdio.h>
section.
#define X 20 This is the definition section. It allows the use of constant X in the code.
This is the Global declaration section includes the function declaration that can be
int sum(int y)
used anywhere in the program.
int main() main() is the first function that is executed in the C program.
{…} These curly braces mark the beginning and end of the main function.
printf(“Sum: %d”,
printf() function is used to print the sum on the screen.
sum(y));
We have used int as the return type so we have to return 0 which states that the
return 0;
given program is free from the error and it can be exited successfully.
int sum(int y)
{ This is the subprogram section. It includes the user-defined functions that are
return y + X; called in the main() function.
}
Conclusion
In this article points we learned about the structure of the C Program are mentioned below:
• The basic structure of a C program is divided into 6 parts which makes it easy to read,
modify, document, and understand in a particular format.
• Debugging is easier in a well-structured C program.
• There are 6 sections in a C Program that are Documentation, Preprocessor Section,
Definition, Global Declaration, Main() Function, and Sub Programs.
• There are certain steps while compilation and executing of C program as mentioned below:
• Creation of Program
• Compilation of the program
• Execution of the program
• Output of the program
C Programming - Basic Concepts (with Examples)
1. Character Set
A character set is a collection of characters that can be used in a C program.
• Alphabets: A-Z, a-z
• Digits: 0-9
• Special Symbols: + - * / % = < > ( ) { } [ ] , ; . : # &
• Whitespace Characters: Space, Tab (\t), Newline (\n)
• Escape Sequences: \n (newline), \t (tab), \\ (backslash), \" (double quote)
Example
#include <stdio.h>
int main() {
printf("Hello\tWorld!\n"); // \t for tab, \n for new line
return 0;
}
Output:
Hello World!
2. C Tokens
A token is the smallest meaningful unit in a C program. There are 6 types:
1. Keywords – Reserved words like int, float, if, return.
2. Identifiers – Names given to variables, functions, etc.
3. Constants – Fixed values like 10, 3.14, 'A'.
4. Strings – Sequence of characters inside "", like "Hello".
5. Operators – Symbols that perform operations (+, -, *, /).
6. Special Symbols – {}, [], (), #, ;, ,.
Example
#include <stdio.h>
int main() {
int num = 10; // Identifier: num, Constant: 10
float pi = 3.14; // Identifier: pi, Constant: 3.14
char ch = 'A'; // Identifier: ch, Constant: 'A'
return 0;
}
Output:
Number: 10
Pi: 3.14
Character: A
3. Keywords and Identifiers
Keywords
• Predefined, reserved words in C.
• Cannot be used as variable names.
• Examples:
int, float, return, if, else, while, switch, break, void.
Identifiers
• User-defined names for variables, functions, arrays, etc.
• Rules:
• Must start with a letter (A-Z, a-z) or underscore (_).
• Can contain letters, digits, and underscores.
• Case-sensitive (sum and Sum are different).
• Cannot be a keyword.
Example
#include <stdio.h>
int main() {
int age = 20; // 'age' is an identifier
float height = 5.9; // 'height' is an identifier
return 0;
}
Output:
Age: 20
Height: 5.9
4. Constants
A constant is a value that does not change during program execution.
Types of Constants
1. Integer Constants: Whole numbers (10, -25, 1000).
2. Floating-point Constants: Decimal numbers (3.14, -0.05).
3. Character Constants: Single characters ('A', '5', '\n').
4. String Constants: Sequence of characters ("Hello", "C Programming").
5. Symbolic Constants: Defined using #define.
Example
#include <stdio.h>
int main() {
const int MAX = 100; // Another way to define constants
Variable Declaration
Specifies a variable’s type and name:
int age; // Integer variable
float price; // Floating-point variable
char grade; // Character variable
Variable Initialization
Assigning a value at the time of declaration:
int age = 20; // Integer initialized
float price = 99.99; // Float initialized
char grade = 'A'; // Character initialized
Example
#include <stdio.h>
int main() {
int num = 50; // Variable declaration & initialization
float temp = 36.5;
char letter = 'B';
return 0;
}
Output:
Number: 50
Temperature: 36.5
Letter: B
Summary Table
Concept Description Example
Character
Set of valid characters in C A-Z, 0-9, +, -, \n, \t
Set
Smallest units (Keywords, Identifiers, Constants,
C Tokens int, float, +, 10, "Hello"
Operators, etc.)
Keywords Reserved words in C int, return, if, while
Identifiers User-defined names for variables & functions age, sum, calculateTotal()
#define PI 3.14, const int MAX
Constants Fixed values that do not change
= 100;
int num = 10;, float price =
Variables Named memory locations that store values
99.9;
int main() {
int num = 5;
float result = num + 3.5; // int is converted to float
Output:
Result: 8.5
B. Explicit Conversion (Type Casting)
• Done manually by the programmer using (type).
Example:
#include <stdio.h>
int main() {
float num = 5.75;
int result = (int) num; // Converting float to int
Output:
Result: 5
Operators in C
Operators are symbols used to perform operations on variables.
1. Arithmetic Operators
Used for mathematical operations.
int main() {
int a = 10, b = 5;
printf("Sum: %d\n", a + b);
printf("Product: %d\n", a * b);
return 0;
}
2. Relational Operators
Used to compare two values.
int main() {
int x = 5, y = 10;
printf("x > 2 && y < 20: %d\n", (x > 2) && (y < 20)); // 1 (true)
return 0;
}
4. Assignment Operators
Used to assign values to variables.
Example:
int num = 10;
printf("%s", (num > 0) ? "Positive" : "Negative");
7. Bitwise Operators
Used for bitwise calculations.
Input/Output Functions
Functions used for user input and output.