University of Maiduguri
Department of Computer Science
Course Code: CSC 102
Course Title: Introduction to Problem
Solving
Introduction
Computer Science is the study of problems, problem-solving, and the solutions that
come out of this problem-solving process.
• Given a problem, the goal is to develop an algorithm to solve the problem.
• An algorithm is a step-by-step list of instructions to solve the problem.
Problem Solving is the sequential process of analysing information related to a given
situation and generating appropriate response options. In solving a problem, there
are some well-defined steps to be followed. Problem Solving is the sequential process
of analyzing information related to a given situation and generating appropriate
response options. Computer based problem solving is a systematic process of
designing, implementing and using programming tools during the problem solving
stage. Computer-Based Problem Solving Process is a work intended to offer a
systematic treatment to the theory and practice of designing, implementing, and using
software tools during the problem solving process.
Problem Solving Steps:
Basically, there are six (6) steps that you should follow in order to solve a problem:
1. Understand the Problem
2. Formulate a Model
3. Develop an Algorithm
4. Write the Program
5. Test the Program
6. Evaluate the Solution
STEP 1: Understand the Problem:
First step to solving any problem is to make sure that you understand the problem that
you are trying to solve. To clarify what is being asked by identifying required outputs,
available inputs and any constraints. Restate the problem in your own words to ensure
you have captured its essence.
STEP 2: Formulate a Model:
Represent the real-world problem in a simplified form, such as a mathematical
expression, a set of data structures, including only the elements necessary to solve it.
STEP 3: Develop an Algorithm:
Create a step-by-step plan or write pseudocode that transforms the input model into
the correct output. Ensure each step logically follows the previous one and leads you
toward the solution. An algorithm is a precise sequence of instructions for solving a
problem.
Two commonly used representations for an algorithm are by using:
• Pseudocode: this is a simple and concise sequence of English-like instructions
to solve a problem.
• Flow chart: This is a diagram that represents a set of instructions. Flowcharts
normally use standard symbols to represent the different types of instructions.
In other word, a flowchart is a graphical representation of various logical steps of a
program. These expressions use several shapes, including the geometric ones, to show
the step-by-step process with arrows while establishing a data flow.
STEP 4: Write the Program:
Translate your algorithm into code using the chosen programming language. Use
clear variable names, consistent indentation and comments to keep the code readable
and maintainable.
STEP 5: Test the Program:
Run the code with a variety of test cases, covering normal scenarios, boundary values
and invalid inputs. Verify that the program behaves as expected and correct any
errors. Running a program is the process of telling the computer to evaluate the
compiled instructions.
STEP 6: Evaluate the Solution:
Assess the final program for correctness and performance. Confirm it meets all
requirements and consider any improvements or optimizations before finalizing your
work.
Road Example
Imagine that you have the following image above, which is a map of a road leading
to the building shown in the picture.
There is a car and trees.
• The car cannot cross the trees.
• The road is divided into squares to calculate the steps of the car.
• Each square is considered as one step.
How can the car arrive at the building?
Different Solutions
• As we can see that Solution A and Solution B are both correct solutions to the
same problem, but there are differences in the complexity and efficiency of
the solutions.
• The cost of Solution A is 10 steps while Solution B is 8 steps, so we consider
Solution B as a better solution based on the number of steps.
• Reducing the number of steps in the previous example means reducing the
amount of fuel needed by the vehicle and speeding up the arrival time.
Algorithm
The term algorithm originally referred to any computation performed via a set of rules
applied to numbers written in decimal form. The word is derived from the phonetic
pronunciation of the last name of Abu Ja'far Mohammed ibn Musa al- Khowarizmi,
who was an Arabic mathematician who invented a set of rules for performing the four
basic arithmetic operations (addition, subtraction, multiplication, and division) on
decimal numbers.
An algorithm is a representation of a solution to a problem. If a problem can be
defined as a difference between a desired situation and the current situation in which
one is, then a problem solution is a procedure, or method, for transforming the current
situation to the desired one. We solve many such trivial problems every day without
even thinking about it, for example making breakfast, travelling to the workplace etc.
An algorithm is an effective step-by-step procedure for solving a problem in a finite
number of steps. In other words, it is a finite set of well-defined instructions or step-
by-step description of the procedure written in human readable language for solving
a given problem. An algorithm itself is division of a problem into small steps which
are ordered in sequence and easily understandable. Algorithms are very important to
the way computers process information because a computer program is basically an
algorithm that tells computer what specific tasks to perform in what specific order to
accomplish a specific task. The same problem can be solved with different methods.
So, for solving the same problem, different algorithms can be designed. In these
algorithms, number of steps, time and efforts may vary.
Algorithms
• An algorithm is a set of obvious, logical, and sequential steps that solve a
specific problem.
• To put it simply, the algorithm is like a recipe for preparing a specific food.
• Following the steps of the algorithm will end up solving the problem.
An algorithm must:
• Be lucid (clear), precise and unambiguous.
• Give the correct solution in all cases, and eventually end.
What is pseudocode?
• It is English that looks like code
• But it is not actual code (only looks a little similar).
• Think of pseudocode as a way of expressing your algorithm.
What is a flowchart?
• A graphical representation of the sequence of operations in an information
system or program.
Now, we express our algorithms in many ways:
• Pseudocode: this is not “real code”, but a slightly more formal way of writing
the algorithmic steps as an example, maybe the programmer does not know
the language he/she will use. Therefore, they just write pseudocode during
Problem-Solving Phase.
• Flowchart: this is a graphical representation of the algorithm
• Actual code: this is during the Implementation Phase Python, Java, C++, C,
etc
Importance of Algorithm
1. Algorithms Define Efficiency: At their core, algorithms are step-by-step sets
of instructions designed to solve specific problems. They are like recipes for
computers, telling them how to perform tasks efficiently and accurately.
Without algorithms, computers would be lost in a sea of data, unable to make
sense of it.
2. Universal Problem Solvers: Algorithms are universal problem solvers. From
search engines finding relevant web pages to GPS systems finding the fastest
route, algorithms work tirelessly behind the scenes, tackling a staggering
variety of problems.
3. Complexity Management: In a world flooded with data, algorithms help us
manage complexity. They sift through vast datasets, making sense of
information and distilling it into actionable insights. This ability is invaluable
in fields like data science, where algorithms analyze data to make predictions
and decisions.
4. Time and Resource Savings: Algorithms save time and resources. They enable
automation, reducing the need for manual labor. Think of algorithms in
manufacturing, optimizing production processes and saving both time and
money.
5. Innovation Catalysts: Algorithms drive innovation, they power everything
from recommendation systems on streaming platforms to the development of
new drugs in healthcare. By solving problems more efficiently, algorithms
open doors to new possibilities and discoveries.
Exploring Real-World Applications of Algorithms
1. Web Search Engines: Search engines like Google utilize complex algorithms
to retrieve and rank web pages, ensuring that you find the most relevant results
for your queries quickly. These algorithms consider factors like keywords,
user behavior, and page authority.
2. GPS Navigation: GPS algorithms calculate the fastest or shortest route to your
destination, taking into account traffic conditions, road closures, and real-time
data. They optimize your travel experience by minimizing travel time and fuel
consumption.
3. Social Media Feeds: Algorithms power social media platforms by curating
your feed to show you content you're likely to engage with. They analyze your
preferences, interactions, and user data to personalize your social media
experience.
4. E-commerce Recommendations: When you shop online, algorithms suggest
products based on your past purchases, browsing history, and the behavior of
other shoppers with similar preferences. These recommendations algorithms
enhance user experience and boost sales.
5. Medical Diagnosis: In healthcare, algorithms assist doctors in diagnosing
diseases and predicting patient outcomes. Machine learning algorithms
analyze medical data to identify patterns and make predictions about patient
health.
6. Finance and Stock Trading: Algorithmic trading uses mathematical models
and algorithms to make rapid, data-driven decisions in financial markets.
These algorithms execute trades at optimal times and prices, often faster than
human traders.
7. Manufacturing and Supply Chain: Algorithms optimize production schedules,
manage inventory, and streamline supply chain logistics. They ensure
products are manufactured efficiently and delivered to consumers on time.
8. Natural Language Processing: Algorithms for natural language processing
enable chatbots, virtual assistants, and automatic translation services. They
help bridge language barriers and improve communication.
9. Image and Video Processing: Image recognition algorithms are used in
security systems, autonomous vehicles, and even in sorting and quality control
in manufacturing. Video compression algorithms enable efficient streaming
and storage of multimedia content.
10. Weather Forecasting: Meteorologists rely on sophisticated algorithms to
process vast amounts of atmospheric data and generate accurate weather
forecasts. These forecasts are crucial for disaster preparedness and everyday
planning.
Analyzing the Time and Space Complexity of Algorithms
When it comes to evaluating the efficiency and performance of algorithms, analyzing
their time and space complexity is paramount. These analyses provide crucial insights
into how algorithms behave under different conditions and help in making informed
decisions about algorithm selection. Here's why analyzing time and space complexity
is essential:
1. Performance Prediction: Time complexity analysis allows us to predict how
long an algorithm will take to run as the input size grows. This prediction is
invaluable in choosing the most efficient algorithm for a particular task. It
helps avoid unexpected slowdowns when dealing with larger datasets.
2. Resource Management: Space complexity analysis helps us understand how
much memory an algorithm requires. In memory-constrained environments or
when dealing with massive datasets, this analysis is crucial to ensure an
algorithm doesn't cause memory overflow or excessive resource usage.
3. Comparative Evaluation: Time and space complexity analyses enable us to
compare different algorithms objectively. By quantifying their performance
characteristics, we can select the algorithm that best suits the specific
requirements of a problem.
4. Algorithm Optimization: Understanding the bottlenecks in an algorithm's time
or space complexity allows for optimization. We can identify which parts of
the algorithm consume the most resources and focus on improving those areas
for efficiency gains.
5. Scalability Assessment: Time and space complexity analyses are essential for
assessing how well an algorithm scales with input size. This information is
critical when designing systems that need to handle increasing amounts of
data or users.
6. Algorithm Design: Time and space complexity considerations often guide
algorithm design decisions. They influence the choice of data structures,
algorithms, and optimization techniques used in implementation.
7. Resource Allocation: In real-world applications, resources like processing
power and memory are finite. Analyzing complexity helps allocate these
resources optimally, ensuring that an algorithm can run efficiently on the
available hardware.
8. Troubleshooting: When an algorithm exhibits unexpected behavior or
performance issues, analyzing its time and space complexity can pinpoint the
source of the problem. This aids in debugging and fine-tuning the algorithm.
Programming Constructs: are used to describe the control flow of the algorithm.
SEQUENCE represents linear tasks sequentially performed one after the other.
WHILE a loop with a condition at its beginning.
DO-WHILE a loop with a condition at the bottom.
FOR another way of looping.
IF-THEN-ELSE a conditional statement changing the flow of the algorithm.
CASE the generalization form of IF-THEN-ELSE.
Reasons for Algorithm
A programmer writes a program to instruct the computer to do certain tasks as desired.
The computer then follows the steps written in the program code. Therefore, the
programmer first prepares a roadmap of the program to be written, before writing the
code. Without a roadmap, the programmer may not be able to clearly visualise the
instructions to be written and may end up developing a program which may not work
as expected. Such a roadmap is nothing but the algorithm which is the building block
of a computer program.
Steps Involved in Algorithm Development
An algorithm can be defined as “a complete, unambiguous, finite number of logical
steps for solving a specific problem “
Step 1. Identification of input: For an algorithm, there are quantities to be supplied
called input and these are fed externally. The input is to be identified first for any
specified problem.
Step 2: Identification of output: From an algorithm, at least one quantity is
produced, called for any specified problem.
Step 3: Identify the processing operations: All the calculations to be performed to
lead to output from the input are to be identified in an orderly manner.
Step 4: Processing Definiteness: The instructions composing the algorithm must be
clear and there should not be any ambiguity in them.
Step 5: Processing Finiteness: If we go through the algorithm, then for all cases, the
algorithm should terminate after a finite number of steps.
Step 6: Possessing Effectiveness: The instructions in the algorithm must be
sufficiently basic and in practice they can be carries out easily.
Characteristics of Algorithm
An algorithm must possess following characteristics:
1. Precision: the steps are precisely stated or defined.
2. Uniqueness: results of each step are uniquely defined and only depend on the input
and the result of the preceding steps.
3. Finiteness: the algorithm always stops after a finite number of steps.
4. Input: the algorithm receives some input.
5. Output — the algorithm produces some output
Exercise
Area of a Rectangle Calculator Solution A
Solution A: Good:
1.Ask the user to enter Width
2.Ask the user to enter Height
3.Set Areato (Width×Height)
4.Display Area for the user
As you can see in this solution, we have described the steps that are going to solve
the problem. You can describe the steps in your own way, but your description of the
steps should be obvious, logical, and sequential.
Area of a Rectangle Calculator Solution B
Solution B: Bad:
1.Ask the user to enter Width
2.Ask the user to enter Height
3.Calculate Area
4.Display Areafor the user
The reason for considering Solution B as a bad solution:
• Step 3 is not clear because it does not explain how we can calculate Area.
• So, this algorithm is bad because its steps are not obvious.
Area of a Rectangle Calculator Solution C
Solution C -Bad:
1.Set Areato (Width×Height)
2.Ask the user to enter Width
3.Ask the user to enter Height
4.Display Areafor the user
The reasons for considering Solution C as a bad solution:
• We don't know what Width and Height at the Step1 are. In other words, Width
and Height have not been defined before Step1, so we cannot use them
because they do not exist yet.
• What about Step2 and Step3? Width and Height are defined there! After
Step2, Width does exist, but Height does not. After Step3, Height does exist.
Both Width and Height are available to be used at or after step4.
• So, this algorithm is bad because its steps are not correctly sequential.
Algorithms calculate Simple Inter set
Step 1: Read the three input quantities’ P, N and R.
Step 2: Calculate simple interest as Simple interest = P* N* R/100
Step 3: Print simple interest.
Step 4: Stop.
Algorithm find Area of Triangle
Step 1: Input the given elements of the triangle namely sides 𝑏, 𝑐 and angle between
the sides 𝐴
Step 2: Area = 12∗𝑏∗𝑐∗𝑠𝑖𝑛(𝐴)
Step 3: Output the Area
Step 4: Stop.
3. Write an algorithm to find the largest of three numbers 𝑋,𝑌,𝑍.
Algorithm find Largest of Three Numbers
Step 1 Read the numbers 𝑋,𝑌,𝑍.
Step 2 If (X > Y)
big = X
Else big = Y
Step 3 If (big < Z)
big = Z
Step 4 Print big
Step 5 Stop.
Write an algorithm to add two numbers entered by user.
Step 1: Start
Step 2: Declare variables num1, num2 and sum.
Step 3: Read values num1 and num2.
Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2
Step 5: Display sum
Step 6: Stop
Flowcharts
Flowcharting is a tool developed in the computer industry, for showing the steps
involved in a process. A flowchart is a diagram made up of boxes, diamonds, and
other shapes, connected by arrows - each shape represents a step in the process, and
the arrows show the order in which they occur. Flowcharting combines symbols and
flowlines, to show figuratively the operation of an algorithm.
A flowchart is a graphical representation of an algorithm or of a portion of an
algorithm. Flowcharts are drawn using symbols. The main purpose of a flowchart is
to analyze different processes. The main symbols used to draw a flowchart are shown
in following figures.
Example 1: Flowchart that sum two input numbers
Example 2: Flowchart that Print numbers from 1 to 20
Pseudocode
Pseudocode (pronounced SOO-doh-kohd) is a detailed yet readable description of
what a computer program or algorithm must do, expressed in a formally styled natural
language rather than in a programming language. Pseudocode is sometimes used as a
detailed step in the process of developing a program. It allows designers or lead
programmers to express the design in detail and provides programmers a detailed
template for the next step of writing code in a specific programming language.
Pseudo code is a term which is often used in programming and algorithm-based
fields. It is a methodology that allows the programmer to represent the
implementation of an algorithm. Simply, we can say that it’s the cooked up
representation of an algorithm. Often at times, algorithms are represented with the
help of pseudo codes as they can be interpreted by programmers no matter what their
programming background or knowledge is.
Reasons for using Pseudocode
1. Better readability. Often, programmers work alongside people from other
domains, such as mathematicians, business partners, managers, and so on. Using
pseudocode to explain the mechanics of the code will make the communication
between the different backgrounds easier and more efficient.
2. Ease up code construction. When the programmer goes through the process of
developing and generating pseudocode, the process of converting that into real code
written in any programming language will become much easier and faster as well.
3. A good middle point between flowchart and code. Moving directly from the idea
to the flowchart to the code is not always a smooth ride. That’s where pseudocode
presents a way to make the transition between the different stages somewhat
smoother.
4. Act as a start point for documentation. Documentation is an essential aspect of
building a good project. Often, starting documentation is the most difficult part.
However, pseudocode can represent a good starting point for what the documentation
should include. Sometimes, programmers include the pseudocode as a docstring at
the beginning of the code file.
5. Easier bug detection and fixing. Since pseudocode is written in a human-readable
format, it is easier to edit and discover bugs before writing a single line of code.
Editing pseudocode can be done more efficiently than testing, debugging, and fixing
actual code.
The main constructs of pseudocode
The core of pseudocode is the ability to represent 6 programming constructs (always
written in uppercase): SEQUENCE, CASE, WHILE, REPEAT-UNTIL, FOR, and IF-
THEN-ELSE. These constructs — also called keywords —are used to describe the
control flow of the algorithm.
1. SEQUENCE represents linear tasks sequentially performed one after the other.
2. WHILE a loop with a condition at its beginning.
3. DO-WHILE a loop with a condition at the bottom.
4. FOR another way of looping.
5. IF-THEN-ELSE a conditional statement changing the flow of the algorithm.
6. CASE the generalization form of IF-THEN-ELSE.
Exercises
1. Write pseudocode that reads two numbers and multiplies them together and print
out their product.
READ 𝑛𝑢𝑚1, 𝑛𝑢𝑚2
SET product to 𝑛𝑢𝑚1* 𝑛𝑢𝑚2
Write product
2. Write pseudocode that tells a user that the number they entered is not a 5 or a 6.
READ isfive
IF (isfive = 5)
WRITE "your number is 5"
ELSE IF (isfive = 6)
WRITE "your number is 6"
ELSE
WRITE "your number is not 5 or 6"
END IF
3. Write pseudocode to print all multiples of 5 between 1 and 100 (including both 1
and 100).
SET x to 1
WHILE (x < 20)
WRITE x
WRITE x = x*5
ADD 1 to x
END WHILE
Algorithm (Pseudocode and Flowchart)
Algorithm: Print numbers from 1 to 20:
Step 1: Start
Step 2: Initialize X as 0
Step 3: Increment X by 1
Step 4: Print X
Step 5: If X is less than 20 then go back to step 3
Step 6: Stop
Convert Temperature from Fahrenheit (℉) to Celsius (℃)
Step 1: Start
Step 2: Read temperature in Fahrenheit
Step 2: Calculate temperature with formula C=5/9*(F-32)
Step 3: Print C
Step 4: Stop
Simple Calculator
The Pseudocode and Flowchart
Suppose that you are asked to write a calculator program that can sum and subtract
two integer numbers. Write the program requirements, specifications, and algorithm.
The algorithm (pseudocode and flowchart):
1.print “Welcome to our Calculator”
2.X= input “Enter the first number:“
3.Y= input“Enter the second number:”
4.Sign= input "Select –or +"
5.if Signis equal to "+" then:
6.Sum= X+ Y
7.else:
8.Sum= X–Y
9.End if
10.print Sum
Verifying The Algorithm
1.Display a welcome message that says, “Welcome to our Calculator".
2.Ask the user to enter the first number and save it to X.
3.Ask the user to enter the second number and save it to Y.
4.Ask the user to select the sign (-,+) and save it in Sign.
5.if Signis equal to “+”, make Sum= X+ Y
6.Otherwise, make Sum= X-Y
7.Display Sum
Determining a Student’s Final Grade Algorithm
Write an algorithm and pseudocode to determine a student’s final grade and indicate
whether it is passing or failing. The final grade is calculated as the average off our
marks.
Algorithm:
1.Ask the user to enter 4 marks (Mark1, Mark2, Mark3, Mark4)
2.Calculate the marks average (Avg) by summing marks and it dividing by 4
3.If average (Avg) is greater than or equal 60
4.Print “Pass”
5.Else
6.Print “Fail”
7.End if
s
Determining The Largest Value Example
Write a Pseudocode that reads two values, determines the largest value and prints the
largest value with an identifying message.
Pseudocode:
1.Input VALUE1, VALUE2
2.if (VALUE1> VALUE2) then
3.MAX=VALUE1
4.else
5.MAX=VALUE2
6.endif
7.print “The largest value is”, MAX
End
Play & Learn
•Be familiar with basic logic and problem-solving techniques through practicing at
Code.org.
•Visit https://studio.code.org/hoc/1and play.
How Do We Write a Program?
• A Computer is not intelligent.
• It cannot analyze a problem and come up with a solution.
A human (the programmer) must analyze the problem, develop the instructions for
solving the problem, and then have the computer carry out the instructions.
To write a program for a computer to follow, we must go through a two-phase
process: problem solving and implementation.
Problem-Solving Phase
1. Analysis and Specification-Understand (define) the problem and what the solution
must do.
2. General Solution (Algorithm)-Specify the required datatypes and the logical
sequences of steps that solve the problem.
3. Verify-Follow the steps exactly to see if the solution really does solve the problem.
Implementation Phase
• Concrete Solution (Program) -Translate the algorithm (the general solution)
into a programming language.
• Test-Have the computer followed the instructions.
• Then manually check the results.
• If you find errors, analyze the program and the algorithm to determine the
source of the errors, and then make corrections.
• Once a program is tested, it enters into next phase (Maintenance).
• Maintenance requires modification of the program to meet changing
requirements or to correct any errors that show up while using it.
C Programming Language
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.
Why Use C?
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 might be:
• Operating Systems
• Language Compilers
• Assemblers
• Text Editors
• Print Spoolers
• Network Drivers
• Modern Programs
• Databases
• Language Interpreters
• Utilities
Local Environment Setup
If you want to set up your environment for C programming language, you need the
following two software tools available on your computer, (a) Text Editor and (b) The
C Compiler.
Text Editor
This will be used to type your program. Examples of a few editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
The C Compiler
The source code written in source file is the human readable source for your program.
It needs to be "compiled" into machine language so that your CPU can execute the
program as per the instructions given. The compiler compiles the source codes into
final executable programs. The most frequently used and free available compiler is
the GNU C/C++ compiler, otherwise, you can have compilers either from HP or
Solaris if you have the respective operating systems.
Installation on Windows
To install GCC on Windows, you need to install MinGW. To install MinGW, go to
the MinGW homepage, www.mingw.org, and follow the link to the MinGW
download page. Download the latest version of the MinGW installation program,
which should be named MinGW-<version>.exe. While installing MinGW, at a
minimum, you must install gcc-core, gcc-g++, binutils, and the MinGW runtime, but
you may wish to install more.
Add the bin subdirectory of your MinGW installation to your PATH environment
variable, so that you can specify these tools on the command line by their simple
names.
After the installation is complete, you will be able to run gcc, g++, ar, ranlib, dlltool,
and several other GNU tools from the Windows command line.
Let us look at a simple code that would print the words "Hello World":
#include <stdio.h>
int main()
{
/* my first program in C */
printf("Hello, World! \n");
return 0;
}
1. The first line of the program #include <stdio.h> is a preprocessor command,
which tells a C compiler to include stdio.h file before going to actual
compilation.
2. The next line int main() is the main function where the program execution
begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add
additional comments in the program. So such lines are called comments in the
program.
4. The next line printf(...) is another function available in C which causes the
message "Hello, World!" to be displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value
0.
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, everyone 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 */
Identifiers
• A C identifier is a name used to identify a variable, function, or any other user
defined item. An identifier starts with a letter A to Z, a to z, or an underscore
‘_’ followed by zero or more letters, underscores, and digits (0 to 9).
• C does not allow punctuation characters such as @, $, and % within
identifiers.
• C is a case-sensitive programming language. Thus, Manpower and manpower
are two different identifiers in C. Here are some examples of acceptable
identifiers:
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.
Whitespace in C
A line containing only whitespace, possibly with a comment, is known as a blank
line, and a C compiler totally ignores it. Whitespace is the term used in C to describe
blanks, tabs, newline characters and comments. Whitespace separates one part of a
statement from another and enables the compiler to identify where one element in a
statement, such as int, ends and the next element begins. Therefore, in the following
statement:
int age;
Data Types
Data types in C refer to an extensive system used for declaring variables or functions
of different types. The type of a variable determines how much space it occupies in
storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows:
int: Integer type. Used to store integers (whole numbers).
• int x = 5;
float: Floating-point type. Used to store single-precision floating-point numbers.
• float x = 3.14;
double: Double-precision floating-point type. Used to store double-precision
floating-point numbers.
• double x = 3.14159265;
char: Character type. Used to store single characters.
• char c = 'A';
Variables
variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C has a specific type, which determines the size and
layout of the variable's memory; the range of values that can be stored within that
memory; and the set of operations that can be applied to the 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. 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:
Int variable_list;
#include <stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of c : 30
value of f : 23.333334
Operator
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
Arithmetic Operators
#include <stdio.h>
int main() {
int a = 10, b = 5, result;
// Addition
result = a + b;
printf("a + b = %d\n", result);
// Subtraction
result = a - b;
printf("a - b = %d\n", result);
// Multiplication
result = a * b;
printf("a * b = %d\n", result);
// Division
result = a / b;
printf("a / b = %d\n", result);
// Modulus
result = a % b;
printf("a %% b = %d\n", result);
return 0;
}
Relational Operators
#include <stdio.h>
int main() {
int a = 10, b = 5;
// Equal to
printf("a == b: %d\n", a == b);
// Not equal to
printf("a != b: %d\n", a != b);
// Greater than
printf("a > b: %d\n", a > b);
// Less than
printf("a < b: %d\n", a < b);
// Greater than or equal to
printf("a >= b: %d\n", a >= b);
// Less than or equal to
printf("a <= b: %d\n", a <= b);
return 0;
}
Logical Operators
#include <stdio.h>
int main() {
int a = 10, b = 5;
// Logical AND
printf("(a > b) && (b > 0): %d\n", (a > b) && (b > 0));
// Logical OR
printf("(a > b) || (b < 0): %d\n", (a > b) || (b < 0));
// Logical NOT
printf("!(a == b): %d\n", !(a == b));
return 0;
}
Bitwise Operators
#include <stdio.h>
int main() {
int a = 10, b = 5;
// Bitwise AND
printf("a & b: %d\n", a & b);
// Bitwise OR
printf("a | b: %d\n", a | b);
// Bitwise XOR
printf("a ^ b: %d\n", a ^ b);
// Bitwise NOT
printf("~a: %d\n", ~a);
// Left shift
printf("a << 1: %d\n", a << 1);
// Right shift
printf("a >> 1: %d\n", a >> 1);
return 0;
}
Assignment Operators
#include <stdio.h>
int main() {
int a = 10, b = 5, result;
// Simple assignment
result = a;
printf("result = a: %d\n", result);
// Add and assign
result += b;
printf("result += b: %d\n", result);
// Subtract and assign
result -= b;
printf("result -= b: %d\n", result);
// Multiply and assign
result *= b;
printf("result *= b: %d\n", result);
// Divide and assign
result /= b;
printf("result /= b: %d\n", result);
// Modulus and assign
result %= b;
printf("result %%= b: %d\n", result);
return 0;
}
Miscellaneous Operators
#include <stdio.h>
int main() {
int a = 10, b = 5;
// sizeof operator
printf("Size of a: %lu bytes\n", sizeof(a));
// Ternary operator
printf("Ternary Operator (a > b ? a : b): %d\n", (a > b) ? a : b);
// Address-of operator
printf("Address of a: %p\n", (void*)&a);
return 0;
}
Decision-making structures require that the programmer specifies one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most
of the programming languages:
if Statement
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
The syntax of an ‘if’ statement in C programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result:
a is less than 20;
if…else Statement
An if statement can be followed by an optional else statement, which executes when
the Boolean expression is false.
Syntax
The syntax of an if...else statement in C programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
Flow Diagram
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the
following result:
a is not less than 20;
value of a is : 100
if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very
useful to test various conditions using single if...else if statement.
When using if…else if…else statements, there are few points to keep in mind:
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be
• tested.
Syntax
The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a == 10 )
{
/* if condition is true then print the following */
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
/* if else if condition is true */
printf("Value of a is 20\n" );
}
else if( a == 30 )
{
/* if else if condition is true */
printf("Value of a is 30\n" );
}
else
{
/* if none of the conditions is true */
printf("None of the values is matching\n" );
}
printf("Exact value of a is: %d\n", a );
return 0;
}
When the above code is compiled and executed, it produces the following result:
None of the values is matching
Exact value of a is: 100
Nested if Statements
It is always legal in C programming to nest if-else statements, which means you can
use one if or else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
switch Statement
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
switch case.
Syntax
The syntax for a switch statement in C programming language is as follows:
switch(expression){
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
Well done
Your grade is B
Loop
You may encounter situations when a block of code needs to be executed several
number of times. In general, statements are executed sequentially: The first statement
in a function is executed first, followed by the second, and so on. Programming
languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. Given below is the general form of a loop statement in most of the
programming languages:
while Loop
A while loop in C programming repeatedly executes a target statement as long as a
given condition is true.
Syntax
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
Syntax
The syntax of a for loop in C programming language is:
for ( init; condition; increment )
{
statement(s);
}
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do…while Loop
Unlike for and while loops, which test the loop condition at the top of the loop, the
do...while loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to
execute at least one time.
Syntax
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}while( condition );
Flow Diagram
Example
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19