Simple Sequential Algorithm
1 Example Real-Life Algorithms
An algorithm is a sequence of well-defined steps used to solve a problem. Here are some real-world examples:
-
Preparing a cup of tea:
-
Boil water.
-
Add tea leaves or a tea bag to the cup.
-
Pour the boiling water into the cup.
-
Add sugar or milk as desired.
-
Stir and serve.
-
-
Turning on a computer:
-
Press the power button.
-
Wait for the operating system to load.
-
Enter your password if required.
-
Open the desired program.
-
2 Algorithm Definition
An algorithm1 is a finite set of precise and logical instructions that describe a step-by-step process to solve a specific problem. It must satisfy the following properties:
-
Input: The algorithm takes input values (if needed).
-
Output: The algorithm produces at least one result.
-
Definiteness/Clarity: Each step must be clear and unambiguous.
-
Finiteness: The algorithm must terminate after a finite number of steps.
-
Effectiveness: All steps must be feasible to perform.
-
Efficiency: The algorithm should produce the result in manageable time.
Algorithms are fundamental in computer science and are used in various applications, from simple calculations to complex data processing and problem-solving tasks.
Let’s see some algorithms and whether or not they satisfy the properties of finiteness, definiteness, and effectiveness.
Making a Cake
-
Make a cake (input = recipe, output = cake).
-
Prepare a tray.
-
Put a number of eggs.
-
Put a cup of sugar.
-
Add some butter.
-
Mix.
-
Cook for 40-60 minutes.
-
-
Criteria Satisfaction.
-
Definiteness: No. The algorithm is ambiguous: “a number of” eggs, “some” butter, etc.
-
Finiteness, effectiveness, efficiency: Cannot argue since description is not accurate.
-
Shop in a Mall
-
Shop from mall (input = shopping list + money, etc., output = you have bought some stuff).
-
Enter mall.
-
Go to the clothes section, buy a green shirt.
-
Go to the jewellery section, buy a watch.
-
Go to the clothes section, buy a red shirt.
-
Go to the home appliances section and buy a vacuum cleaner.
-
Go to the clothes section, buy a blue shirt.
-
Go to the jewellery section, buy a ring.
-
Go to the home appliances section and buy a sandwich maker.
-
Pay at the till and exit the mall.
-
-
Criteria Satisfaction.
-
Definiteness: Yes (if we agree so).
-
Finiteness: Yes, the number os steps is finite.
-
Effectiveness: Yes, each step is feasible i.e. it can be performed.
-
Efficiency: No. Could have finished buying at one section before moving to the next.
-
Crack a Password
-
Crack a password of 10-character length (input = password-protected entity, output = the password). You know the password contains characters a-z, A-Z, 0-9.
-
Try all combinations in ascending lexicographical order.
-
0000000000
-
0000000001
-
...
-
ZZZZZZZZZZ
-
-
Terminate when the password is found.
-
-
Criteria Satisfaction.
-
Definiteness: Yes.
-
Finiteness: Yes, the number of runtime steps is bounded.
-
Effectiveness: Yes, each step is doable.
-
Efficiency: No. The number of combinations is (26 + 26 + 10)10. If 109 generated passwords are checked per second, the total number of years could grow up – in the worst case – to more than 26 years to find the password (less if you are lucky).
-
Find the Max
-
Find the maximum of 3 integers (input = three integers r1, r2, r3, output = the largest of them).
-
Define a variable max.
-
Compare r1 and r2, store largest in variable max.
-
Compare max and r3, store largest in variable max.
-
The variable max holds the max value.
-
-
Criteria Satisfaction.
-
Definiteness: Yes.
-
Finiteness: Yes, the number of runtime steps is bounded.
-
Effectiveness: Yes, each step is doable.
-
Efficiency: Yes.
-
3 Structuring an Algorithm
To make an algorithm easy to understand, it should be properly structured:
-
Title: A meaningful name for the algorithm.
-
Declarations: Variables and constants used in the algorithm.
-
Instructions: The steps to execute.
-
Indentation: Proper indentation to improve readability.
Example: Algorithm for Adding Two Numbers
Vars a, b, sum: integer; Start sum ← a + b write (sum) End
The algorithm "Add Two Numbers" can be evaluated according to the criteria for structuring an algorithm as follows:
Title:
The title of the algorithm is "Add Two Numbers", which is clear and meaningful. It precisely describes the task the algorithm performs, i.e., adding two numbers. This satisfies the criterion for a meaningful name.
Declarations:
The algorithm includes a declaration of variables: a, b, and sum, all of which are integers. This is done in the first step:
Vars a, b, sum: integer;
This step is important because it explicitly declares the variables that will be used in the algorithm, making it clear which data the algorithm will work with. The declaration is correct but could also mention initialization values for completeness (e.g., a = 0, b = 0 if needed). However, it satisfies the declaration criterion by listing the variables.
Instructions:
The algorithm’s instructions (or steps) are clearly outlined:
-
Step 1: Sum the values of a and b, and assign it to sum:
sum ← a + b
-
Step 2: Output the result stored in sum:
write (sum)
These steps are simple, direct, and easy to follow, addressing the task of adding two numbers and displaying the result. The steps are logically ordered and correspond to the process of performing an addition and displaying the result. This meets the instructions criterion.
Indentation:
Indentation is used to improve readability: The instructions within the algorithm are indented, making it easier to distinguish the body of the algorithms.
4 Variables and Constants in Algorithms
When designing an algorithm, it is essential to understand the roles of variables and constants. These elements help manage and process data effectively throughout the algorithm’s execution.
-
Variable: A variable is a symbol or name used to store data that can change during the execution of the algorithm. Variables are fundamental for performing operations, storing intermediate results, or managing dynamic input.
-
Constant: A constant is a fixed value that does not change during the execution of the algorithm. Constants are often used to define values that remain the same throughout, such as mathematical constants or fixed thresholds.
Using variables and constants allows algorithms to be flexible, reusable, and easy to understand. Variables can represent data inputs or results that change with different runs of the algorithm, while constants provide a stable reference for values that must not vary, ensuring the correctness of computations.
In the previous algorithm “Add Two Numbers" to calculate the sum of two numbers, a, b, and sum are variables. Their values can change based on the user’s input or the specific instance of execution.
The following algorithm calculates the area of a circle. The mathematical value of π is treated as a constant. It does not change during the execution of the algorithm. Using a constant ensures consistency and accuracy in computations involving fixed values.
Vars radius, area: real Const pi ← 3.14159 Start area ← pi × radius × radius write (area) End
In the following algorithm, we calculate the total price of items after applying a tax rate. The algorithm uses both variables and constants. Here, the tax rate is a constant, while the item price and total price are variables.
Vars item_price, total_price: real Const tax_rate ← 0.07 Start total_price ← item_price × (1 + tax_rate) write (total_price) End
5 Basic Data Types
In algorithm design, it is essential to understand the types of data that algorithms can process. Different data types determine the kind of operations that can be performed on the data and how it is stored.
A data type in programming and algorithms defines the type of data that a variable can store and how it will be used during computation. It sets the rules for operations that can be performed on the data, how the data is stored in memory, and how much memory it consumes.
The basic data types commonly used in algorithms are:
-
Integer: Represents whole numbers, both positive and negative, such as 1, -42, or 100. Integers are often used for counting, indexing, or any operation where fractional values are not required.
-
Real: Represents numbers with decimal points, such as 3.14, -7.89, or 0.001. Real numbers are essential in scenarios involving measurements, calculations with precision, or any computation requiring fractions.
-
Character: Represents single symbols, such as ’A’, ’z’, or ’1’. Characters are often used in text processing, comparisons, or as part of string data.
Additional Considerations:
-
Limits of Data Types: Each type has its own range. For example, integers may be limited by the system’s architecture, such as 32-bit or 64-bit integers.
-
Type Conversion: Algorithms may require converting between data types (e.g., from integer to real) to handle mixed-type operations effectively.
6 Simple Steps: Input, Output, and Assignment
Every algorithm, regardless of its complexity, relies on three fundamental operations: Input, Output, and Assignment. These steps form the building blocks of any computational process.
-
Input (Reading): The process of gathering data from an external source (e.g., user input, sensor data, file reading). This step allows the algorithm to adapt to varying data instead of working with fixed values.
-
Output (Displaying/Writing): The act of presenting results to the user or another system. Output ensures that the information generated by the algorithm can be observed or utilized effectively.
-
Assignment: The action of storing a value in a variable. Assignment enables algorithms to keep track of data and perform calculations. It is expressed as
variable \leftarrow value, signifying that the variable now holds the given value.
6.1 Examples
6.1.1 Example 1: Add Two Numbers
This example demonstrates input, assignment, and output steps in a basic addition operation. This algorithm is a modification of the previous algorithm by adding input/output.
Vars a, b, sum: integer Start read (a) read (b) sum ← a + b write (sum) End
6.1.2 Example 2: Convert Celsius to Fahrenheit
This example demonstrates how input is processed and output is displayed based on an assignment.
Vars celsius, fahrenheit: real Start read (celsius) fahrenheit ← (celsius × 9/5) + 32 write (fahrenheit) End
6.1.3 Example 3: Display Initials
This example focuses on character input and output while showcasing assignment to store the initials.
Vars firstInitial, lastInitial: character; Start read (firstInitial) read (lastInitial) write ("Your initials are: ") write (firstInitial, lastInitial) End
7 Solving Simple Problems with Algorithms
Here are several examples of simple problems that can be solved with basic algorithms, demonstrating input, processing, and output.
Example 1: Find the Area of a Rectangle
This algorithm calculates the area of a rectangle given its length and width.
Vars length, width, area: real Start read (length) read (width) area ← length × width write (area) End
Example 2: Convert Hours to Minutes
This algorithm converts a given number of hours into minutes.
Vars hours, minutes: integer Start read (hours) minutes ← hours × 60 write (minutes) End
Example 3: Calculate the Perimeter of a Triangle
This algorithm calculates the perimeter of a triangle given its three sides.
Vars side1, side2, side3, perimeter: real Start read (side1) read (side2) read (side3) perimeter ← side1 + side2 + side3 write (perimeter) End
Example 4: Display Full Name
This algorithm concatenates first and last names to display the full name.
Vars firstName, lastName, fullName: character Start read (firstName) read (lastName) fullName ← firstName + " " + lastName write (fullName) End
Example 5: Calculate Average of Three Numbers
This algorithm calculates the average of three numbers.
Vars num1, num2, num3, average: real Start read (num1) read (num2) read (num3) average ← (num1 + num2 + num3) / 3 write (average) End
8 Graphical Representation of an Algorithm: Flowchart
Flowcharts are diagrams that represent the steps of an algorithm graphically.
9 Algorithmic and Programming Syntax (C)
When writing algorithms or programs, we must follow some strict notation and syntax (grammar). Algorithmic languages are pen-and-paper languages; which means that we do not feed them to computers, and they obviously have no compilers. There is no universal way of choosing an algorithmic language. For example, in order to store some value val into some variable var, we can do any the of the following:
-
var = val -
var \leftarrow val -
var receives val -
...
We are free to choose any notation and syntax, however, once we choose one, we must use it consistently.
Programming languages on the other hand have their own fixed syntax. Although, the word "fixed" here should account for the evolution of a language by adding more constructs, etc.
9.1 Reserved Words
Reserved words are predefined terms in a programming language that have specific meanings and cannot be used by the programmer to define new elements. Each language has its own set of reserved words. For example, “if" and “while" are reserved in C.
9.2 Identifiers
Identifiers are names created by the programmer to represent elements within an algorithm, such as variables, types, constants, or functions. In C, as well as in algorithmic language, there are specific rules for naming identifiers:
-
It cannot be a reserved word.
-
An identifier can contain letters (A-Z, a-z), digits (0-9), and the underscore symbol ("_").
-
It must start with a letter or an underscore ("_") but cannot start with a digit.
-
It must be a single word, meaning it cannot contain spaces.
-
Each identifier must be unique; no two elements can have the same name.
-
It is recommended to use descriptive names, such as “length" instead of “l".
9.3 Values
Values represent data and can take different forms, such as numbers, characters, strings, boolean values, etc.
-
In programming, we differentiate between numbers that are integer, and those that are decimal.
-
Characters are single entities such as the letter
‘c’, the number ‘1’, the symbol ‘@’, etc. Notice that for a computer the number5and the character‘5’are not the same. A character is enclosed in single-quotation marks. -
Strings are chains of characters such as
"melon". Notice that100and"100"are different. A string is enclosed in double-quotation marks.
9.4 Variables and Constants
9.4.1 Constant
A constant refers to a value (either numeric or symbolic) that is assigned a name and remains unchanged throughout the execution of the program. The main advantages of using constants are the following.
-
They condense the code by allowing long expressions to be replaced with shorter names, such as using
PIinstead of3.14. -
They help minimize errors by providing descriptive names.
-
They simplify maintenance since the value only needs to be updated in one location.
9.4.2 Variable
A variable is a memory location designated for storing data. It has an associated name, type, and value.
-
Name: The identifier utilized by the programmer to reference and manipulate the variable, such as
velocity. -
Type: In computing, all data is represented in binary (0s and 1s). The type dictates how data is interpreted and determines the memory size to allocate, e.g.,
int(32 bits). -
Value: The actual data represented by the bits constituting the variable, typically the part that changes during program execution. For example,
1001signifies the number9, or-1if the leftmost bit indicates a negative sign.
For example, in C, we would write int num = 1; to declare a variable called num whose type is integer (int), with an initial value of 1. We would write float weight = 88.2; to declare a variable called weight whose type is float (float), with an initial value of 88.2.
A comma , can be used to declare multiple variables of the same type. For example, we can say int x,y = 10; declare two variables called x and y whose type is integer (int), with an initial value of 10 for both of them.
9.5 Types
9.5.1 Predefined Types
The following tables summarize the fundamental types used in algorithms and their C equivalents.
Integers in algorithms range from − ∞ to + ∞:
| Types | Size (bytes) | Size (bits) | Range |
|---|---|---|---|
| char | 1 | 8 | [ − 27, 27 − 1] |
| short | 2 | 16 | [ − 215, 215 − 1] |
| long | 4 | 32 | [ − 231, 231 − 1] |
| long (64-bit systems) | 8 | 64 | [ − 263, 263 − 1] |
| int | 4 | 32 | [ − 231, 231 − 1] |
Natural numbers in algorithms range from 0 to + ∞: Since integers encompass natural numbers, they are typically used for representation. To represent only natural numbers in C, the unsigned keyword can be added before a type.
| Types | Size (bytes) | Size (bits) | Range |
|---|---|---|---|
| unsigned char | 1 | 8 | [0, 28 − 1] |
| unsigned short | 2 | 16 | [0, 216 − 1] |
| unsigned long | 4 | 32 | [0, 232 − 1] |
| unsigned long (64-bit systems) | 8 | 64 | [0, 264 − 1] |
| unsigned int | 4 | 32 | [0, 232 − 1] |
Real numbers:
| Types | Size (bytes) | Precision |
|---|---|---|
| float | 4 | 6 |
| double | 8 | 8 |
| long double | 10 | 8 |
Boolean type: C does not have a distinct boolean type; instead, int is utilized, with true represented by 1 and false by 0. Any non-zero value is interpreted as true.
Character type: The character type is char.
String type: In C, strings are expressed using arrays of characters or pointers.
9.5.2 Notes
-
The
inttype serves as the generic type for integers. -
The
chartype is applicable for both integers and characters, with each character linked to a numerical value.
9.5.3 Type Conversion
-
Implicit: This conversion is automatically handled by the compiler, progressing from a smaller type to a larger type without data loss (e.g.,
chartoint,inttofloat, orfloattodouble). Converting 5 tofloatyields 5.0. -
Explicit (casting): When there’s a risk of data loss, the programmer must specify the operation. This is done by indicating the destination type in parentheses before the expression to be converted, for instance,
(int) 3.14results in 3.
If included in another instruction, 1 is added or subtracted according to the operation before the expression is evaluated, using the new variable value.
Example:
x = 2;
x *= 3 + 4; // x = x * (3 + 4);
x = 2;
y = 3 + x++; // y = 3 + x; x = x + 1;
x = 2;
y = 3 + ++x; // x = x + 1; y = 3 + x;
9.6 Basic Statements
9.6.1 Assignment
Assignment is the process through which we store a value in a variable. In algorithmic notation we use variable \leftarrow exp, in C and many other languages we use variable = exp;, and in some programming languages we use variable := exp;.
-
variable: This denotes the name of the variable.
-
exp: This is an expression (comprising identifiers, values, and operations), evaluated to yield a unique value assigned to the variable.
When an assignment occurs, only the variable on the left changes, discarding its previous value and adopting the new one. For the assignment to work correctly, the types of the expression on the right and the variable on the left must either match or be compatible. The following are example assignments involving different variable types.
x \leftarrow 5 // x gets 5
y \leftarrow x * 2 // y gets 10
x \leftarrow 0 // x gets 0
y \leftarrow y - 1 // y gets 9
z \leftarrow 'y' // z gets the character 'y'
w \leftarrow y > x // w gets the boolean value true
s \leftarrow "name" // s gets the word/string "name"
Before utilizing a variable, it must be declared and assigned an initial value. If a variable is not initialised when declared, its initial value is declared by the language specification. In C, a non-initialised variable has undefined value. When the program is compiled, some compilers might decide to give it the 0 value, or an undefined value which is usually the value already stored in the variable’s memory location.
9.6.2 Input/Output Functions
Programs without interaction with the user are no fun. Therefore, programming languages come with functions to allow the program to receive input from the user, and give output to the user.
In algorithmic language, the functions Read() and Write() are used to perform input and output respectively. The Read() function captures a value from the user via the keyboard and assigns it to the variable specified within parentheses. For example Read(num) will assign the value entered in the keyboard to the variable num. The Write() function displays on the screen whatever is placed inside its parentheses. For example Write(exp) writes the value of the expression exp on the screen, and Write("text") writes some text text.
When the program is executed and encounters an input operation, it pauses until the user inputs data, concluding the input by pressing the Enter key. The program then resumes execution.
9.7 Input/Output in C
In C programming, handling input and output is fundamental for interacting with users and managing data. The two primary functions used for I/O operations are printf and scanf. These functions are part of the C standard I/O library stdio, which provides a range of functionalities to work with console input and output.
9.7.1 Output with printf()
The printf() function is used to display output to the standard output, typically the console. It allows developers to print formatted text, variables, and other data types.
In most languages, one print function can print all sorts of data types. However, in C, printf() requires that we tell it the format of the variable we want to print.
-
%d: Integer -
%f: Floating-point number -
%c: Character -
%s: String
For example:
int age = 25;
float height = 5.9;
char initial = 'A';
char name[] = "Alice";
printf("Name: %s\n", name);
printf("Initial: %c\n", initial);
printf("Age: %d years\n", age);
printf("Height: %.1f feet\n", height);
9.7.2 Input with scanf()
The scanf() function is used to read input from the standard input, typically the keyboard. It allows the program to take user input and store it in variables. Just like printf(), the function scanf() also requires a format specifying the type of the value to read from the user.
For example:
int age;
float height;
char name[50];
printf("Enter your name: ");
scanf("%s", name); // Reading a string
printf("Enter your age: ");
scanf("%d", &age); // Reading an integer
printf("Enter your height (in feet): ");
scanf("%f", &height); // Reading a float
printf("Name: %s, Age: %d, Height: %.1f\n", name, age, height);
9.8 Operations
9.8.1 Arithmetic Operations
-
Sign: The
+and-signs can be applied to numbers. -
Addition and Subtraction (
+,-): When both operands are integers, the result is an integer. If one operand is real, the result is a real number. -
Multiplication (
*): Works similarly to addition and subtraction. -
Division (
/): For real division, the result is always a real number. -
Modulo (
%): Calculates the remainder of the division. Both operands must be integers; the result is always an integer. -
Integer Division (
~/): Calculates the quotient in integer division. -
Exponentiation: Calculates the power of a number. In C, the function
pow()is used, and the result is a real number. -
Square Root: In C, the function
sqrt()is used to calculate the square root of a number.
9.8.2 Relational Operators
-
>, >=, <, <=: These operators work the same in C. -
Equality: Represented as
==in C to denote equality (while=is used for assignment). -
≠: Not equal is represented as
!=in C. -
The result of a comparison is always a Boolean value, i.e., true or false.
9.8.3 Logical Operators
-
Not (
!): Returns true if the operand is false, and false if the operand is true. -
And (
&&): Returns true only if both operands are true; otherwise, it returns false. -
Or (
||): Returns true if at least one operand is true; otherwise, it returns false.
9.8.4 Operator Precedence
When evaluating an expression, the operations follow the priority summarized in Table 1.1. If two operations have the same priority, evaluation proceeds from left to right.
| Priority | Operation |
|---|---|
| 0 | Parentheses () |
| 1 | Sign + and -, Not |
| 2 | Multiplication *, Division /, Mod %, Integer Division div |
| 3 | Addition + and Subtraction - |
| 4 | Relational Operators >, >=, <, <= |
| 5 | Equality Operators !=, == |
| 6 | Logical and |
| 7 | Logical or |
Parentheses can be used to override priority and improve readability.
9.8.5 Expressions
An expression is a structure that combines values and identifiers with operations. When evaluated, it produces a single result. Expressions can include values, variables, parentheses, and operations.
For example, if a = 1, b = 2, and flag=true, we get:
| Expression | Result |
|---|---|
| 5 | 5 |
| a + 3 | 4 |
| flag | true |
| a | 1 |
| a >b && flag | false |
9.8.6 Statements
A statement is a step in the algorithm/program, representing an action that will be executed.
9.8.7 Block of Statements
A block of statements consists of a sequence of commands, starting with Begin and ending with End. In C, blocks are enclosed in braces {}.
9.8.8 Comments
Comments are ignored by the compiler and serve to explain code. In C, comments are written with // for single-line comments or /* */ for multi-line comments. Example:
// Single-line comment
/* Multi-line
comment */
9.9 Example 1: Summing Two Numbers
In order to sum two numbers, we follow the steps in the following flowchart.
We can express the steps in human format as the following.
Start Declare two variables: num1, num2 Declare a variable sum to store the result Set num1 to 5 Set num2 to 10 Set sum to num1 + num2 End
We can use a more mathematical description (pseudo code).
Start var num1 var num2 var sum num1 ← 5 num2 ← 10 sum ← num1 + num2 End
Equivalent C Program
// The word "void" means the function returns nothing
// The meaning of "return" will become clear later on
// "main()" is the name of the "function" which means
// a modular block of the program
// In this example, "main()" is the entire program
// The opening bracket "{" of is "Start"
// The closing bracket "}" is "End"
void main()
{
// Declare variable num1
int num1;
// Declare variable num2
int num2;
// Declare variable sum
int sum;
// Assign 5 to num1
num1 = 5;
// Assign 10 to num2
num2 = 10;
// Arithmetic operation: addition of num1 and num2
// and then assignment of result to sum
sum = num1 + num2;
}
Explanation of Concepts
-
Variable Declaration: In the C program,
int num1,int num2, andint sumare variable declarations. Theintkeyword specifies that these variables will store integer values. There are other types in C, for examplecharto store characters andfloatto store decimal points. Everything we use in a programming language must be declared. A variable acts as a container to store values and it must have atypee.g.intto store integers such as1and15,charto store characters such as’b’,’1’, and’@’, floating-point (decimal) numbers such as3.14and0.1. -
Assignment: The variables
num1andnum2are assigned values 5 and 10 respectively, using the assignment operator (=). This meansnum1 = 5stores the value 5 in the variablenum1. The assignmentx = y;means the value ofyis stored inx, not the other way around. -
Operators: The
+symbol is the addition operator, which adds the values ofnum1andnum2. The result is assigned to the variablesumwithsum = num1 + num2. There are many other operators in C, for example*for multiplication and/for division. -
Comments: The lines starting with
//are comments. They explain what each part of the code does and are not executed by the program (the compiler ignores comments).
In this example, the algorithm computes the sum of two numbers but we do not see the result, so we add some output by using the C printf() function to produce output at the end. The printf() function is available from a library or package called stdio which must be imported to the file using #include.
#include <stdio.h>
void main()
{
int num1;
int num2;
int sum;
num1 = 5;
num2 = 10;
sum = num1 + num2;
// Output the result to terminal
// this will print show: The sum is: X
// where X is the value of the variable sum
// %d indicates that the value we want to print is integer
printf("The sum is: %d\n", sum);
}
Next, instead of forcing the input to have specific values in the program, we want to obtain it from the user. We achieve this using the C function scanf() which also comes from the library stdio.
#include <stdio.h>
void main()
{
int num1;
int num2;
int sum;
// This will prompt the user to enter a value
// in the terminal.
// The value is automatically assigned to the
// variable num1.
scanf("%d", &num1);
// This will prompt the user to enter another value
// in the terminal.
// The value is automatically assigned to the
// variable num2.
scanf("%d", &num2);
sum = num1 + num2;
printf("The sum is: %d\n", sum);
}
The problem with the latter code is that the user only sees a prompt, and is not guided to what to do. So it is better to print a message asking the user to perform the input.
#include <stdio.h>
void main()
{
int num1;
int num2;
int sum;
printf("Enter the first value: ");
scanf("%d", &num1);
printf("Enter the second value: ");
scanf("%d", &num2);
sum = num1 + num2;
printf("The sum is: %d\n", sum);
}
We can change int to float in the program, to obtain decimal values, apply arithmetic operations to them, and print them out. Notice that we change %d to %f in printf() and scanf().
#include <stdio.h>
void main()
{
float num1;
float num2;
float sum;
printf("Enter the first value: ");
scanf("%f", &num1);
printf("Enter the second value: ");
scanf("%f", &num2);
sum = num1 + num2;
printf("The sum is: %f\n", sum);
}
We can also ask the user for non-numerical input e.g. characters. We use %c to capture a character from the input. In order to take into account the new-line character n created when the user hits enter after input, we precede %c by a space in scanf(),
#include <stdio.h>
void main()
{
char letter;
char symbol;
char number;
printf("Enter a letter: ");
scanf(" %c", &letter);
printf("Enter a symbol: ");
scanf(" %c", &symbol);
printf("Enter a digit: ");
scanf(" %c", &number);
printf("You have entered the following characters: %c, %c, and %c.\n", letter, symbol, number);
}
-
Algorithms are named after the famous Muslim scientist Muhammad Ibn Musa Al-Khwarizmi.↩︎