Algorithm, Iteration, and Program Control

Share this post:

What is an Algorithm?

  • The sequential set of actions that need to be executed in order to solve a problem using software is collectively designated as the algorithm.
  • This means that the algorithm has 2 properties:
    • Actions – This is the set of executable statements and functions that complete a task or series of tasks.
    • Order – The algorithm is an ordered procedure whose actions are executed in a sequential manner as determined by the programmer. Specifying this order is called program control because it determines whether the program will complete the tasks correctly or not.
  • The actions to be performed and how they will be performed can be written down as statements in plain English. This is called the pseudocode because it allows the programmer to think out the actions that the program is to perform, as well as the decisions that it should take during operation.
  • The algorithm can be ordered in two ways:
    • Sequential Execution: The executable statements are executed one by one according to the way they have been written in the program. This means that the first statement in the code is executed, and then the second statement is executed, and thereafter the third statement is executed and so on.
    • Selection Execution: The algorithm is set so that an executable statement specifies the next statement to be executed. This allows for non-sequential execution of statements.
  • The capability of one statement to decide which statement is to be executed next is called transfer of control, and is the basis of selection execution.
  • In the 1960s, the goto statement was used to manage transfer of control, but its indiscriminate use led to difficult-to-trace bugs in software as well as repeated program crashes. This led to a quest to eliminate goto statements, and this formed the basis of structured programming.
  • In May 1966, a paper titled Flow Diagrams, Turing Machines, and Languages with Only Two Formation Rules which was authored by Böhm and Jacopini was published. It explained how goto elimination can be achieved in programming. This paper laid the foundation of goto-less programming of the 1970s. This form of programming allows for bug-free software to be developed using three control structures:
    • Sequence Structure: This applies sequential execution in the algorithm.
    • Selection Structure: It uses one or more of the selection statements.
    • Iteration Structure: It uses one or more of the 3 iterations statements. Iteration means repeat an action in a loop format i.e keep repeating the action until instructed to stop.
  • There are only 7 control structures in the C programming language: the sequence structure, 3 selection structures, and 3 iteration structures. With these 7 control structures, complex programs such as operating systems and accounting software can be developed.

Flowchart

  • The algorithm can be represented graphically using a flowchart that is made up of special-purpose symbols that are connected together by flowlines.
  • The flowchart can be used alongside pseudocode to show how control structures are expected to operate in the algorithm.

Special Purpose Symbols

The main special purpose symbols used in the flowchart are:

  • Rounded Rectangle: It is used to indicate the begin or end of an algorithm. It is represented as:
  • Straight Rectangle: It is used to indicate that an action is to be performed by an executable statement or function. For this reason, it is called the action rectangle. It is represented as:
  • Connector Symbol: When the flowchart does not represent the entire algorithm, the rounded rectangles are omitted and are instead substituted with connector symbols which are small circles:
  • Decision Symbol: This is the most important symbol in a flowchart as it shows that a decision is to be made by a statement concerning the next statement that will be executed. It is represented by a diagonal symbol as thus:
  • Flowline: It is used to connect the abovementioned special symbols together in the flowchart, as well as show the direction of execution of the program. It is represented by an arrow line:
  • The set that is made up of an action rectangle, an entry connector symbol, and an exit connector symbol is called a single-entry/single-exit control statement. It is represented as:
  • The exit connector symbol of the above control statement can serve as the entry connector symbol of the next control statement, and this is called control statement stacking. This forms the basis of the stacking rule which stipulates that a single action rectangle can be replaced by multiple action rectangles connected together by sequential flowlines. This is represented as follows:
  • There are only two ways to connect 2 control statements together:
  1. Control Statement Stacking.
  2. Nesting.

Selection Statements

  • There are 3 types of selection statements:
    • Single selection statement: It performs an action only if its condition is fulfilled (or true). It is called the if statement.
    • Double selection statement: It can perform either one of two conditional actions. The first action is performed when the condition is true, and this is described as the execution of the if statement. The second action is performed when the condition is false, and this is described as the execution of the else statement. As expected, this is called the if…else statement.
    • Multiple selection statement: It has a set of actions that can be performed, and the actions that are chosen to be performed are determined by the values in the expressions. It is called the switch statement.
  • The if statement is a single-entry/single-exit control statement that can be represented in the flowchart format as follows:
  • The above is the graphical representation of the action-decision model of program development.
  • The if …else statement can be represented in the flowchart format as follows:
  • The double selection if…else statement is associated with the only ternary operator in C language. This operator which is symbolized as ?: is the conditional operator.
  • A ternary operator has three(3) operands.
  • A conditional expression is formed by the 3 operands and the conditional operator. It is syntactically written as follows:
condition ? if_true : else_false
  • This reveals that the first operand is the condition, the second operand is the action to perform if the condition is true, and the third operand is the action to perform if the condition is false.
  • The use of curly braces when writing conditional statements is mandatory when connecting control statements through nesting as shown below:
if (condition1)
   {function/statement}
   else
   {
      if (condition2)
      {statement}
      else
      {
         if (condition3)
         {statement}
         else
         {statement}
      }
   }
  • If a number of control statements are to be executed if a condition is true or false, then the use of curly braces is mandatory (as shown above). These statements form a set of statements associated with a condition, and they are thus designated as a compound statement. This compound statement is also called a block. This block is enclosed inside a single pair of curly braces.
  • The block is the body of the selection statement.
  • Exclusion of the curly braces creates the dangling-else problem where the second and any subsequent statement executes whether the condition has been fulfilled or not.
  • Nesting of control statements forms the basis of the nesting rule, which stipulates that the action rectangle in any flowchart can be replaced by nested control statements.
  • The application of the stacking rule and the nesting rule defines C programming language as a structured programming language. A structured programming language is also called a procedural language.

While Loop

  • The iteration statement is used to create a loop in an algorithm. This statement is also called the repetition statement because it causes the program to repeat an action(s) if a condition is fulfilled. The repeating of this action is called the loop. Equally, because this statement is initialized by the while keyword, it is called the while statement.
  • The iteration statement is executed until the condition is no longer true i.e its termination occurs when the state of fulfillment of the condition shifts from true to false. For example, consider a geometric sequence with a scale factor of 2 that starts at 2 and whose value does not exceed 320 i.e 2, 4, 8, 16, 32… This is coded as follows:
int value = 2;
while (value <= 320)
{
 value = 2 * value
}
// The value provided are 4,8,16,32,64,128,256,512. 
// Because 512 is greater than 320, it is not multiplied by 2 and the while loop terminates at this point.
  • Termination of the iteration statement allows the subsequent statement to be executed.
  • The condition in the loop must be fulfilled initially, and then become false so that the loop is terminated. This condition is designated as the loop-continuation condition because the loop terminates when it is falsified. Otherwise, if the condition does not become falsified, the loop will continue in perpetuity, and this is a logic error known as an infinite loop.
  • The loop can be defined as a set of instructions that must be executed repeatedly as long as the loop-continuation condition remains true.
  • The flowchart of the while statement is shown below:

Counter-Controlled Iteration

  • If the number of repeats is known before the loop starts to execute, then the iteration is known as a definite iteration.
  • If the number of repeats (i.e count of repeats) is used as the condition to initialize and terminate the loop, then this loop is called a counter-controlled iteration. The loop-continuation condition in this counter-controlled iteration is the control variable which counts the number of iterations that need to be executed before the loop is terminated. The value assigned to this control variable is the number of iterations that must be executed till loop termination.
  • The control variable is also called the loop counter, and it must have the following 4 properties or attributes:
    • Definition: This is the name of the variable as well as the data type that the variable will hold in memory.
    • Initialization: An initial value must be assigned to the variable.
    • Increment or Decrement Value: This is the value that is added or subtracted from the initial value once the loop completes a single repeat.
    • Final Value: This is the value that sets the number of iterations that must be executed till loop termination. This value is what differentiates the definite iteration from the indefinite iteration (that is explained in the next subsection).
  • The final value must always be an integer value. For this reason, the control variable is defined as an int type.
  • The definite iteration can be executed using the for statement. The statement is called such because it uses the for keyword.
  • The for statement encapsulates the following 4 attributes of the control variable in its header parenthesis:
    • Definition and Initialization.
    • Loop continuation condition.
    • Increment/Decrement.
  • The for header excludes the block of the statement. In other words, the for statement is made up of the for header and its compound statement.

Pseudocode: for (definition and initialization; loop continuation condition; increment/decrement) {compound statement}

for (definition = initialization; final value; increment/decrement) //This is the for header. Each attribute in the header can be described as a parameter. The parameter is the equivalent of an argument in an executable statement.

/* For Statement */
for (definition = initialization; final value; increment/decrement) {definite loop} // The header together with the loop body form a  complete statement.
for (int variable_name = initialization_value; variable_name <||>= final_value; ++/--variable_name)
    {definite loop}
  • In the for header, each property is separated from the next by a semicolon (;) but the entire for statement does not end in a semicolon, but instead has curly braces that contain the body i.e block of the statement.
  • The semicolon serves as a separator between two adjacent properties.
  • The property variable_name equality_operator final_value is the loop continuation condition.
  • The control variable can only be accessed inside the body of the for statement, and any attempt to access it outside this statement results in a compilation error.
  • If the control variable was defined outside the for statement, then it can be omitted in the statement but its semicolon remains i.e for (; variable_name <= final_value; ++/–variable_name).
  • If a semicolon is placed before the curly braces of the statement’s block, then the for statement becomes an empty statement. The reason for this is that it becomes a header that is terminated without performing any action (the block contains the actions that need to be performed according to the instructions in the header).
  • If the non-strict inequality operator is replaced with a strict inequality operator in the loop continuation condition e.g <= is replaced with <, then this results in the loop terminating at one value less than (or greater than) the final value. This is a logic error that is described as an off-by-one error.
  • C language suffers from representational error when it comes to floating-point values e.g 3.14. The decimal point is the floating point, and the floating point value is an approximation of the real value which can have an infinite number of decimal places. This approximation to a specified number of decimal digits is called representational error and it is why the numerical equality operator cannot be used to equate the floating-point value to its real value e.g 4 = 3.9999999 is wrong because 4 ≠ 3.9999.
  • Using incorrect syntax in the block or header of a function (or statement) results in a syntax error, which is usually detected by the compiler and prevents an executable file from being built from the source code. This is different from the logic error which allows the program to compile and be executed when this error results in an execution time error which at times could be a fatal runtime error.

Indefinite Definition and Sentinel-Controlled Iteration

  • If the number of repeats is not known before the loop starts to execute, then the iteration is known as an indefinite iteration.
  • The indefinite iteration needs to have an end to data entry so that the loop can be terminated. This means that its condition must have a way to be falsified so as to achieve loop termination. One of the best ways to achieve this is to use a sentinel value.
  • The sentinel value is used to mark the end of user data input. This value is not an acceptable user input and is therefore ignored by the control statements and functions, but it marks the end of data input. It is for this reason that it is called the dummy value. This dummy value is also described as the flag value or signal value because it flags or signals the end/termination of data entry.
  • Unlike the counter final value of the definite iteration, the sentinel value of the indefinite iteration must be entered by the user i.e the sentinel value is a user-input value.
  • An indefinite iteration that uses a sentinel value is called a sentinel-controlled iteration. When writing this iteration in pseudocode, the top-down stepwise refinement approach should be used.
  • The top-down stepwise refinement approach starts by stating the function of the program, and then listing the main processes that will achieve this function. As expected, the top of this approach is stating the function of the program, and the first refinement is noting the main processes of the program. The main process can have subprocesses which can be noted as the second refinement (which is the second level of refinement). This approach allows for use of indentation for the first refinement, and further indentation for the second refinement. Likewise, it allows for the rough documentation of the program in pseudocode.
  • As a rule of thumb, the higher the levels of refinement, the more complex and bug-free the program can become. This makes the pseudocode a vital yet informal software development aid/tool.
//Kagirison Mean Calculator
//Program for calculating mean and exiting of no value is provided

/*Preprocessor Directive*/
#include <stdio.h>

/*Main Function of the Program*/
int main(void)
{
    int total = 0; //Definition of the total sum of the values entered by the user
    int count = 0; //Definition of the number of values that the user inputs

    printf("Enter the value (Type -1 to mark end of entry): ");
    int value = 0; //Definition of the value that the user inputs to the program
    scanf ("%d", &value);

    while (value != -1) //Loop continuation condition is that the value entered should NOT be -1
    {
        total = total + value;
        count = count + 1;
        printf("Enter the value (Type -1 to mark end of entry): ");
        scanf ("%d", &value);
    }

    if (count != 0)
    {
        printf("The Total Value is %d \n", total);
        printf("The Total Count is %d \n", count);
        
        double mean = (double) total / (count);
        printf("The Mean Value is %.2f \n", mean);
        
    }
    else
    {
        puts("No Values were provided\n"); // This is the statement that the program prints on the screen if the user does not input any value
    }
}
/*End of Function*/
/*End of Program*/

do/while Iteration Statement

  • The while statement always tests the loop continuation condition before executing the body of the statement i.e the loop body.
  • The loop continuation condition can also be tested after the loop body has been executed, and this is achieved using the do…while statement.
  • The do…while statement allows the loop to execute once before the loop continuation condition is tested. This contrasts with the while statement which first tests the loop continuation condition before executing the loop body. This means that if the loop body does not satisfy the loop continuation condition, it will execute once in the do…while statement but it will not execute at all in the while statement.
  • The flowchart of the do…while statement is shown below:

Phases of a Program

  • The basic program has 3 phases of execution. These are the logical phases of the program, and they are:
    • Initialization: This is the first phase where the variables are initialized in readiness for execution in a function.
    • Processing: This is the second phase where the user inputs and returns values to the function. These values are then handled by the statements in the function to produce an output.
    • Termination: The program delivers the output to the user.
  • A good pseudocode outlines the algorithm well enough to allow for easy writing of the program code. This means that the algorithm is first created as a pseudocode before it can be turned into a program code.
  • In calculation, floating-point numbers are decimal fraction numbers e.g 10.50 that have been written in a straight-line form with a decimal point differentiating the whole number (located to its left) from the fraction value (located to its right). The data type int only handles whole numbers, not floating-point numbers. The data type for handling floating-point numbers is double.
  • When dividing two whole numbers of int data type, the result that is provided by the function is a whole integer even if the real result is a floating point. For example, 5 ÷ 2 = 2.5 but if the variable was defined as an int, then the result provided will be 2. This is because integer division yields an integer quotient, with the fractional values ignored. This ignoring of all fractional values in integer division is called truncation.
  • To get the floating point result during division, the data type of the variable needs to be converted. This conversion can be done using the unary operator called double.
  • This operator converts a decimal value into its equivalent floating-point value by adding a decimal point and two zeros after it e.g 5 becomes 5.00. This conversion only happens to the operand of this operator, not all values in the statement. For this reason, this operator is invoked to the value that needs to be converted e.g (double) quotient = (double) dividend / divisor means that quotient and dividend are floating values while divisor is still an integer value.
  • The unary operator that converts an operand from one type to a different type is called a cast.
  • A cast operator is formed by placing the unary operator in parenthesis () as follows:
(operator)
  • Unary operators have higher precedence than binary operators, and are grouped right-to-left.
  • The conversion specification of the floating-point number is symbolized by %f. This evaluates to this format control string: “%f”. By default, the %f conversion specification outputs values to 6 decimal digits (i.e 6 numerals after the decimal point). To reduce the number of decimal digits, the precision is added as follows %.2f. The .2 inserted in the conversion specification is the precision that ensures that only 2 digits will appear after the decimal point i.e the decimal number is rounded to the nearest 2 decimal digits.
  • The assignment operator is used to assign a value to a variable. The simplest assignment operator is the = operator that assigns the value to its right to the variable positioned to its left e.g variable = 10;. This operator can be concatenated with a binary operator in order to abbreviate assignment expressions as follows:
    • Addition Assignment Operator which is symbolized as += performs a special assignment operation. It first adds the value to its right to the initial variable, and then stores this new value in the variable to its left. Thus, it can be represented as follows: variable = (initial) variable + value which is shortened to variable += value.
    • Subtraction Assignment Operator is symbolized as -= and it subtracts the value on its right from the initial variable value, and then assigns the difference to the variable on its left.
    • Multiplication Assignment Operator is symbolized as *= and it multiplies the value on its right with the initial variable value, and then assigns the product to the variable on its left.
    • Division Assignment Operator is symbolized as /= and it divides the initial variable value with the divisor value on its right, and then assigns the quotient to the variable on its left.
    • Modulus Assignment Operator is symbolized as %= and it divides the initial variable value with the divisor value on its right, and then assigns the remainder to the variable on its left.
  • C language features the unary increment and decrement operators, and this is how they function:
    • Unary Increment Operator is symbolized as ++ (double plus), and it adds 1 to the integer variable. The way it is used in an expression matters because variable++ is not the same as ++variable.
      • ++Variable means that 1 is added to the integer variable to yield a new variable value which serves as the new variable e.g ++3 = 4. Because the operator is prefixed to the variable, it is called a preincrement operator. This operator is the substitute for variable += 1.
      • Variable++ means that 1 is added to the integer variable but the sum does not become the new variable e.g 3++ leaves the variable as 3. Because the operator is post-fixed (or suffixed) to the variable, it is called a postincrement operator. It shows that a value is added to a non-changing variable.
    • Unary Decrement Operator is symbolized as – – (double minus), and it subtracts 1 from the integer variable.
      • – – Variable means that 1 is subtracted from the integer variable to yield a new variable value which serves as the new variable e.g –3 = 2. This operator is called the predecrement operator and it serves as the substitute for variable -= 1.
      • Variable – – means that 1 is subtracted from the integer variable but the difference does not become the new variable e.g 3– leave the variable as 3. This is called the postdecrement operator.
  • Conventionally, the unary operator is directly concatenated with its operand i.e there is no space between the two.

Switch Statement

  • In multiple selection, there are different decisions that the program can choose from depending on the control variable or expression. Each decision executes a different action, and the program can choose to execute one or more of the selected decisions.
  • The multiple selection statement in C language is also called the switch statement because it uses the switch keyword.
  • Each of the selection statement is called a case, and there can be a default case that will execute if the program fails to make a decision on which case to select.
  • Each case is labeled/identified by a case label. This means that each case label is associated with one (or more) executable statement(s.)
  • The getchar function is used to read a character from the keyboard and then store it as either a char or integer type. The most accurate data type for a character is the char type, and in fact getchar is the truncation for get character. Nonetheless, the character can also be stored as an integer type because all characters are converted to their corresponding one-byte integers by the Unicode Standard. The conversion specification for the character is %c and as expected, its format control string is “%c”.
  • To assign getchar to a variable, it needs to be concatenated with parenthesis as such getchar() e.g variable = getchar().
  • The switch statement must have two items before it can execute any of its cases. These two items are the:
    • Controlling Expression – This is the equivalent to the loop continuation condition in the if statement and the for statement. Each case label is compared to the value of this controlling expression. The syntax for this expression is: (variable = value_assignment())
    • Final Value to terminate the iteration. Its syntax is: relational_operator label_value e.g != EOF // EOF means End Of File
  • The above syntax of the items of the switch statement give it the following syntax:
switch ((variable = value_assignment()) relational_operator label_value)
  • The default syntax of the case is:
case label :
case statement(s);
  • To ensure that not all the cases in the body of the switch statement are executed; a break statement is added at the end of each case. This statement is so called because it is a one-word statement and that word is the keyword break. Expectedly, it is written simply as break;.
  • If the break statement is excluded, then all the cases succeeding the selected case are executed and this is called fallthrough. This fallthrough can create a logic error if it was not needed in the program.
  • The switch statement needs a default case which will execute when none of the case labels has been selected. Usually, this default case is placed as the last case in the body of the statement.
  • Combining the above syntax together evaluates the complete syntax of the switch statement and its body as:
switch ((variable = value_assignment()) relational_operator label_value)
{
case label :
case statement(s);
break;
case label :
case statement(s);
break;
default case:
case statement(s);
}
  • The switch statement that uses the getchar function needs to ignore the tab space, character space, and new line in user input; and this is done by creating case labels ‘\t’, ‘ ’, and ‘\n‘ respectively and then leaving them empty (i.e without case statements) as follows:
case ‘\t’: // Ignore tab space
case ‘ ’: // Ignore character space
case ‘\n’: // Ignore new line
break;
  • Adjacent case labels without any intervening statement do execute the same action. In the above case, they ignore the following user inputs: tab space, character space, and new line.
  • The label of each case is a constant integral expression. The constant can be a character or an integer, and it should evaluate to a single (constant) integer value. Therefore, F and f are two different constants as they evaluate to the integer values 70 and 102 respectively. Likewise, there is need to differentiate between F as a character and F as a string. For this reason, single quotes ‘(character)’ are used in the label to show that it encloses a character, while double quotes “(string)” enclose a string.
  • The flowchart of the switch statement that has 2 cases and the default case is shown below:
  • At times, the programmer may want the loop to skip specific cases if the preceding case has been evaluated as true e.g if case A is true, then case B, case C, and case D need to be skipped so that the loop can be iterated again. To achieve this, the continue statement is used.

Logical Operators

  • The relational operator is used to test the validity of only a single condition in a conditional statement.
  • To test multiple conditions, C provides the logical operator.
  • The logical operator allows for concatenation of simple conditions to form complex conditions that can be executed in a function.
  • The logical operator groups or associates from left to right.
  • The 3 main logical operators are explained below.
  • Logical AND is symbolized as &&. It combines two simple conditions that need to be fulfilled together.
    • It uses both logical and relational operators, with the logical operators having the lower level of precedence.
    • Its syntax is:
conditional statement (conditional expression && conditional expression)
{statement body}

  • The following table shows whether the statement body will execute or not if the conditional expressions are true or false:
First Conditional ExpressionSecond Conditional ExpressionStatement Body
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
  • The above table can be converted into a Truth Table by assigning the value 0 to False and the value 1 to True as follows:
First Conditional ExpressionSecond Conditional ExpressionStatement Body
111
100
010
000
  • The true value can be set to any non-zero value apart from 1 but C by default sets it to 1. Setting the default value of true to 1 is due to the assignment of integer values to the Boolean type. The Boolean type can only hold one of two values: 1 or 0, and its keyword is _Bool. This type uses true and false as named representations of the integer values 1 and 0 respectively.
  • The setting of the true value to any non-zero value creates an error if the assignment operator is used instead of the equality operator e.g if (control_variable = 3) is used instead of (control_variable == 3), then condition does not evaluate if the value is 3 but instead checks if the value is true (because 3 is a non-zero value). This logic error cannot be caught by the compiler, and the program will produce unintended results. To mitigate against this, the programmer can use lvalues.
  • When assigning a value to a variable, the syntax is variable = value; which shows that the value is to the right side of the assignment operator. This value is thus called the rvalue which is truncation for right value. The equality operator allows the value to be placed to the left of the operator i.e value == variable; and this value is called the lvalue (short for left value). The assignment operator does not support an lvalue and will return a syntax error if it is used. Therefore, using lvalues for equality expressions and rvalues for assignment operations can help avoid errors of confusing the == operator with the = operator. Simply put, the fixed lvalue can be used as an rvalue, but the (changing) rvalue cannot be used as the lvalue i.e the variable cannot be equated to a changing value (but it is the (changing) value that can be assigned to a variable).
  • The identifier of a variable cannot be placed to the right of the assignment operator. On the other hand, the identifier of a variable can be placed on the right side of a strict (numerical) equality operator if a constant is placed to the left of this operator.
  • This logical operator evaluates from left to right, so if the first condition is not true, then the statement body cannot be executed, and the evaluation stops without considering the second condition. This is called short-circuit evaluation and it improves the performance of a program. For this reason, the condition that is most likely to be false should be placed to the left of this operator.
  • Logical OR is symbolized as ||. It combines two simple conditions together, but only one of the conditions needs to be fulfilled. If both conditions are fulfilled, then the statement body is executed. The truth table for this logical operator is shown below:
First Conditional ExpressionSecond Conditional ExpressionStatement Body
111
101
011
000
  • Logical Negation is symbolized as ! and is called the Logical NOT. It uses the unary operator ! to reverse the meaning of the condition. Unlike the above-explained 2 logical operators, this unary operator uses only 1 condition.
  • Instead of using the logical negation operator, it is advised that the unary operator is concatenated with the assignment = operator to create the NOT EQUAL TO != relational operator.
  • The Logical AND operator has a higher level of precedence than the Logical OR operator.
  • The beauty of structured programming is its simplicity because it can be reduced to only 3 forms of program control:
  1. Sequence.
  2. Selection: The if statement is its building block, and in fact, all if…else statements and switch statements can be reduced to multiple if statements. For this reason, the if/else and switch statements are regarded as compound if statements.
  3. Iteration: Its building block is the while loop. This means that all do…while statements and the for statements can be reduced to multiple while statements.
  • The logical operators allow for multiple selection statements or iteration statements to be combined in a single statement, thus minimizing the LoC of a program which translates to minimal code size.
  • The selection and iteration forms of control allow for the creation of 2 different types of control statements: the selection statement and the iteration statement. By default, C language uses the sequential process flow. There are only 2 ways to combine the different types of control statements: stacking and nesting.

How to Create a Mean Calculator and Compound Interest Calculator

Mean Calculator

//Kagirison Mean Calculator
//Program for calculating mean and exiting of no value is provided

/*Preprocessor Directive*/
#include <stdio.h>

/*Main Function of the Program*/
int main(void)
{
    int total = 0; //Definition of the total sum of the values entered by the user
    int count = 0; //Definition of the number of values that the user inputs

    printf("Enter the value (Type -1 to mark end of entry): ");
    int value = 0; //Definition of the value that the user inputs to the program
    scanf ("%d", &value);

    while (value != -1) //Loop continuation condition is that the value entered should NOT be -1
    {
        total = total + value;
        count = count + 1;
        printf("Enter the value (Type -1 to mark end of entry): ");
        scanf ("%d", &value);
    }

    if (count != 0)
    {
        printf("The Total Value is %d \n", total);
        printf("The Total Count is %d \n", count);
        
        double mean = (double) total / (count);
        printf("The Mean Value is %.2f \n", mean);
        
    }
    else
    {
        puts("No Values were provided\n"); // This is the statement that the program prints on the screen if the user does not input any value
    }
}
/*End of Function*/
/*End of Program*/

Interest Calculator

//Compound Interest Calculator
//Calculate Interest based on provided rate and principal.

#include <stdio.h>

int main(void) 
{
        
    printf("Enter the amount of loan taken: ");
    int principal = 0;
    scanf ("%d", &principal);
    printf("Enter the interest rate of the loan: ");
    int rate = 0;
    scanf("%d", &rate);
    printf("Enter the number of years given to repay the loan: ");
    int period = 0;
    scanf("%d", &period);

    int interest = 0;
        interest = (principal * rate / 100);

    int amount = principal + interest;

    int year = 1;
    int loan = 0;

    printf("The loan to be repaid after the first year is %d. \n", amount);


    while (year <= period)
    {

        year = year + 1;
        //Amount for next year
        interest = amount * rate / 100;
        amount = amount + interest;

        if (year != period + 1)
        printf("The loan to be repaid after %d years is %d. \n", year, amount);

    }
   
}

Leave a Reply

Discover more from Kagirison

Subscribe now to keep reading and get access to the full archive.

Continue reading