Computer Programming and Fundamentals MIDTERM
Computer Programming and Fundamentals MIDTERM
Jenneth R. Mondez
Kurt Robin A. San Jose
Marlon L. Atanacio
i
Table of Contents
Module 5: Variables and Data Types
Introduction 64
Learning Outcomes 64
Content and Discussion
Lesson 1: Data Type 65
Integer Type 65
Floating Point Type 66
Boolean Data Type 66
Lesson 2: Variables 67
Rules for naming a variable 67
Variable Declaration in C 67
Lesson 3: Constants and Literals 69
Integer Literal 69
Floating Point Literal 69
Logical Operators 69
Character Constants 70
String Literals 70
Defining Constants 70
Lesson 4: Input and Output Statements 72
Scanf and Printf Functions 72
Assessment Task 80
Summary 81
References 82
ii
Module 7: The Conditional Statements
Introduction 100
Learning Outcomes 100
Content and Discussion
Lesson 1: Decision Making 101
Statement and Description 102
Lesson 2: If Statement 102
If Statement Syntax 103
Lesson 3: If – Else Statement 104
If-Else Statement Syntax 104
Program Sample 1 105
Program Sample 2 107
Program Sample 3 109
Assessment Task 111
Summary 112
References 112
iii
List of Figures
Figures Description
6.1 Operator of Precedence 89
iv
List of Tables
Table Description
v
MODULE 5
VARIABLES AND DATA TYPES
Introductio
n
In real life, if you asked for something like water, there should be a container to
hold the water such as glass or a bottle. The same analogy is applicable in the world of
computer. If you need to store data in the system, there should be a variable which will
hold the data. In this case, the data is like the water while the glass or bottle is the variable.
Technically, a variable must have a data type for the compiler to check whether the data
can be properly stored in the variable. Thus, the developer must know the appropriate
data type to be assigned to the variables in the program. Having a good understanding on
this matter will contribute to the effectiveness and efficiency of the program.
In this module, you will be able to learn various data types, its description and
range of values. Furthermore, the concepts of variable is discussed in detailed such as its
importance, rules in naming variables as well as the syntax in variable declaration. The
standard input/output statement on how to store and access values from the variable is
also discussed.
Learning
Outcomes
At the end of the lesson, the student is expected to:
1. Identify the data types in C;
2. Differentiate variables and constants;
3. Recognize the literals in a program;
4. Apply the use of variables in programming; and
5. Create programs using input and output statements in C.
64
As cited in the book entitled “Learn C Programming: C Programming Language”,
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. Table 1 below shows the classifications of
C data types.
The array types and structure types are referred collectively as the aggregate
types. The type of a function specifies the type of the function's return value. This module
focuses on the basic arithmetic types and as well as boolean data type.
Integer Types
Integer data types store whole numbers. The following table provides the details
of standard integer types with their storage sizes and value ranges:
65
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned 2 bytes 0 to 65,535
short
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
Floating-Point Types
Floating-Point types store numbers with fractional parts. The following table
provides the details of standard floating-point types with storage sizes and value ranges
and their precision (tutorialspoint, Learn C Programming: C Programming Language,
2016):
Based on the basic types explained above, the table below shows the primitive
data types (tutorialspoint, Learn C Programming: C Programming Language, 2016).
66
void Represents the absence of type
Lesson 2: Variables
A variable is a name given to a storage area that 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 (tutorialspoint, Learn C Programming: C
Programming Language, 2016).
Always try to give meaningful names to variables. For example: firstName is a better
variable name than fn. Always remember that C is a strongly typed language. This means
that the variable type cannot be changed once it is declared (C Variables, Constants and
Literals, n.d.).
Variable Declaration in C
A variable declaration provides assurance to the compiler that there exists a
variable with the given type and name so that the compiler can proceed for further
compilation without requiring the complete detail about the variable. A variable
declaration has its meaning at the time of compilation only, the compiler needs actual
variable declaration at the time of linking the program (tutorialspoint, Learn C
Programming: C Programming Language, 2016). The general syntax for declaring a
variable is,
data_type var_name;
67
Here, data_type refers to the type of data that the variable may hold while var_name
refers to a valid variable name.
Examples: 1. int num1;
int num2,
2. float grade;
The first example declares two variables namely num1 and num2 having an integer data
type while the second example declares grade having a float data type. The first
example can be simplified using the syntax below:
where var1, var2, .. , varn pertains to a series of variables all having the indicated data
type. Hence, example 1 above can be simplified as,
In the example above, the first line declares num1 as a variable with an integer data type
while the second line assigns 0 to be the initial value of num1. However, these statements
can be simplified as,
int num1= 0;
Similarly,
int num1, num2;
num1 = 0;
num2 = 0;
68
Lesson 3: Constants and Literals ( (tutorialspoint, Learn C Programming:
C Programming Language, 2016)
Constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals. Constants can be of any of the basic data types
like an integer constant, a floating constant, a character constant, or a string literal.
Constants are treated just like regular variables except that their values cannot be
modified after their definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal.
An integer literal can also have a suffix that is a combination of U and L, for unsigned and
long, respectively. The suffix can be uppercase or lowercase and can be in any order. Here
are some examples of integer literals:
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and
an exponent part. You can represent floating point literals either in decimal form or
exponential form. While representing decimal form, you must include the decimal point,
the exponent, or both; and while representing exponential form, you must include the
69
integer part, the fractional part, or both. The signed exponent is introduced by e or E. Here
are some examples of floating-point literals:
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Character Constants
Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type. A character literal can be a plain character (e.g., 'x'), an escape
sequence (e.g., '\t'), or a universal character (e.g., '\u02C0'). There are certain characters
in C that represent special meaning when preceded by a backslash, for example, newline
(\n) or tab (\t). Some of these escape sequence codes were discussed in the previous
module.
String Literals
String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape sequences, and
universal characters. You can break a long line into multiple lines using string literals and
separating them using whitespaces. Here are some examples of string literals.
“hello”
“dear"
“hello dear”
Defining Constants
There are two simple ways in C to define constants:
1. Using #define preprocessor
2. Using const keyword
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant:
70
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{
int area;
area = LENGTH * WIDTH;
printf("Value of Area : %d", area);
printf("%c", NEWLINE);
return 0;
}
Output:
Value of Area : 50
#include <stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("Value of Area : %d", area);
printf("%c", NEWLINE);
return 0;
}
Output:
Value of Area : 50
71
Lesson 4: Input and Output Statements
According to Ahlawat (2020) input means to provide the program with some data
to be used in the program and output means to display data on screen or write the data
to a printer or a file. C programming language provides many built-in functions to read any
given input and to display data on screen when there is a need to output the result.
Example:
#include<stdio.h>
int main()
{
int i;
printf("Please enter a value...");
scanf("%d", &i);
printf( "\nYou entered: %d", i);
return 0;
}
In the sample code above, printf() is an output statement while scanf() is an input
statement. If you will compile the above code, the statement “Print enter a value” will be
displayed on the screen, then the integer will be accepted by the program using the
scanf() function. Finally, the inputted integer will be displayed on the screen using the
printf() function.
You must be wondering what is the purpose of %d inside the scanf() or printf()
functions. It is known as format string and this informs the scanf() function, what type of
input to expect and in printf(), it is used to give a heads up to the compiler, what type of
output to expect. Below are some of the most useful format specifiers:
72
Format String Meaning
%d Scan or print an integer as signed decimal number
%f Scan or print a floating number
%lf Scan or print a number with double data type
%c Scan or print a character
%s To scan or print a character string. The scanning ends at
whitespace.
We can also limit the number of digits or characters that can be inputted or
outputted, by adding a number with the format string specifier, like "%1d" or "%3s", the
first one means a single numeric digit and the second one means 3 characters, hence if
you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the case
for output. In C Language, computer monitor, printer etc output devices are treated as
files and the same process is followed to write output to these devices as would have
been followed to write the output to a file (Ahlawat, 2020).
Example:
#include <stdio.h>
int main()
{
char let = 'L';
char str[20] = "Laguna University";
int num = 123;
float num1 = 123.45;
double num2 = 12.345678;
printf("Character is %c \n",let);
printf("String is %s \n" , str);
printf("Integer value is %d\n" , num);
printf("Octal value is %o \n", num);
printf("Hexadecimal value is %x \n", num);
printf("Float value is %f \n", num1);
printf("Double value is %lf \n", num2);
return 0;
}
Output:
73
Character is L
String is Laguna University
Integer value is 123
Octal value is 173
Hexadecimal value is 7B
Float value is 123.45
Double value is 12.345678
Example:
#include <stdio.h>
int main()
{
char let;
int num;
float num1;
double num2;
printf("Enter a character.\n”);
scanf(“%c”, &let);
printf("Enter an integer.\n”);
scanf(“%d”, &num);
printf("Enter a number with floating point.\n");
scanf(“%f”, &num1);
printf("Enter a number with more floating points.\n");
scanf(“%lf”, &num2);
74
Always remember that in using format specifiers, an ampersand (&) symbol must
be appended before the variable if you will use it in the scanf() function. The said symbol
is no longer needed in the variable if you will use it in the printf() function.
To illustrate the use of the standard input and output statements in C, try to
encode the program below.
#include <stdio.h>
int main()
{
int NUM1; /* variable declaration */
int NUM2; /* variable declaration */
int SUM; /* variable declaration */
printf("Enter the first integer:"); /* output statement */
scanf("%d", &NUM1); /* input statement */
printf("Enter the second integer:"); /* output statement */
scanf("%d", &NUM2); /* input statement */
SUM=NUM1+NUM2; /* process */
printf("The sum is %d.", SUM); /* output statement */
return 0;
}
The source code illustrates how to add two integers. If you will run the program,
the output would look like this:
Alternatively, your code may look like the one shown below.
75
#include <stdio.h>
int main()
{
int NUM1, NUM2, SUM;
printf("Enter two integers:"); /* output statement */
scanf("%d %d", &NUM1, &NUM2); /* input statement */
SUM=NUM1+NUM2; /* process */
printf("The sum is %d.", SUM); /* output statement */
return 0;
}
In the source code above, the three (3) variables are declared in one line since all
of them have integer data type. Likewise, two (2) or more variables may be included in a
single scanf() statement. However, the number of format specifiers and the number of
variables in the scanf() statement must be equal. The output will look like this:
Write a C program that will calculate the sum of two input numbers and then display the
result.
Algorithm:
76
5
5
The sum: 10
#include <stdio.h>
main()
{
int sum, n1, n2;
printf("\n Enter two Numbers:\n");
scanf("%d%d", &n1,&n2);
sum=n1+n2;
printf("\n The sum: %d",sum);
Explanation:
The first line in our program is the #include statement which means we tell the C
compiler to use the standard input/output header file <stdio.h> that contains the
standard input/output function such as printf(), scanf(), and much more (Pepito, 2003).
The second line is the main(), function statement. Every C program should have
this statement. The third line is the list of variables declared as integer data type. The
fourth line is the printf() output function that commands the computer to display the
message in the screen “Enter two Numbers:” (Pepito, 2003).
The \n (backlash n) control character is used to tell the C compiler to occupy the
whole line in the screen regardless of how long the message is to be displayed in the next
line or new line (Pepito, 2003).
The fifth line is the scanf() standard input function which tells the C compiler to
scan( read or accept) the values typed from the keyboard and store them into variables.
This is the input operation in our program (Pepito, 2003).
77
The two %d are the data type format of the n1 and n2 variables. The variables to
be scanned should be preceded with &symbol. The sixth line is the calculation of sum. We
are the one who formulate this equation based on our previous knowledge in basic
mathematics. This part is the process operation. The seventh line is our output part
where we output the value of variable sum (Pepito, 2003).
Another sample:
Write a C program that computes the average of three input quizzes then display
the result.
Algorithm:
Input: Enter three quizzes (q1,q2,q3)
Process: Compute the average (ave=q1+q2+q3/3)
Output: Display the average (ave)
Solution:
#include <stdio.h>
main()
{
int q1,q2,q3;
float ave;
printf("Enter three quizzes:");
scanf("%d%d%d",&q1,&q2,&q3);
ave=(q1+q2+q3) / 3;
printf("\n The average: %f",ave);
}
That is why we have to declare a data type float for a variable that holds the
computed value of an equation that involves a division (/) operation. Based on our
previous knowledge in mathematics, we came up with the equation: ave=(q1+q2+q3)/3.
78
This means that we need a basic background in mathematics before we can successfully
solve a given worded-problem in our computer subject (Pepito, 2003).
Assessment Tasks
_________1. ‘a’
_________2. 86
79
_________3. 2.58
_________4. ‘H’
_________5. 56.1246789
_________6. 1.56789045345345353465423
_________7. 4627
_________8. -0.465
_________9. -502
_________10. 3299784747254987379834529
Summary
80
• Constants refer to fixed values that the program may not alter during its
execution.
• Fixed values are also called literals.
• An integer literal can be a decimal, octal, or hexadecimal constant.
• A floating-point literal has an integer part, a decimal point, a fractional part, and
an exponent part.
• Character literals are enclosed in single quotes, e.g., 'x' can be stored in a simple
variable of char type.
• String literals or constants are enclosed in double quotes "".
• The two simple ways of defining constants in C are #define preprocessor and using
const keyword.
• Input means to provide the program with some data to be used in the program.
• Output means to display data on screen or write the data to a printer or a file.
• The standard input-output header file, named stdio.h contains the definition of the
functions printf() and scanf(), which are used to display output on screen and to
take input from user respectively.
References
81
What is boolean in C? (2020, August 27). Retrieved from www.educative.io:
https://www.educative.io/edpresso/what-is-boolean-in-c
MODULE 6
Operators and Expressions
Introduction
82
An operator in a programming language is a representation that tells the compiler
to perform a detailed mathematical, relational or logical operation and show the final
result. This module will discuss the concept of operators and expression and it will also
take you through the important arithmetic and relational operators available in C
programming language.
Learning Outcomes
Lesson 1: Operators in C
Operators are the foundation of any programming language. Thus, the functionality
of C language is incomplete without the use of operators. Operators allow us to perform
different kinds of operations on operands. In C, operators in Can be categorized in
following categories (sirraghavgupta & akhilsharma870, 2015):
83
• Assignment Operators (=, +=, -=, *=, etc)
Assignment Operator
Assignment operators are used to assigning value to a variable. The left side
operand of the assignment operator is a variable and right-sand operand of the
assignment operator is a value. The value on the right side must be of the same data-type
of the variable on the left side otherwise the compiler will raise an error (RishabhPrabhu,
2018).
• “= “: This is the simples assignment operator. This operator is used to assign the
value on the right to the variable on the left. the variable on the left
(RishabhPrabhu, 2018).
Example:
• a = 10;
• b = 20;
• ch = ‘y’;
• “+=”: This operator is a combination of ‘+’ and ‘=’ operators. This operator first
adds the current value of the variable on left to the value on the right and then
assigns the result to the variable on the left (RishabhPrabhu, 2018)
Example:
(a +=b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
• “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first
subtracts the current value of the variable on left from the value on the right and
then assigns
the result to the variable on the left (RishabhPrabhu, 2018).
Example:
(a -= b) can be written as (a = a – b)
84
If initially value stored in a is 8. Then (a -= 6) = 2.
• “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first
multiplies the current value of the variable left (RishabhPrabhu, 2018).
Example:
(a *= b) can be written as (a = a * b)
If initially value stored in a is 5. Then (a *= 6) = 30.
• “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first
divides the current value of the variable on left by the value on the right and then
assigns the result
to the variable on the left (RishabhPrabhu, 2018).
Example:
(a /=b) can be written as (a = a/b) a / b)
If initially value stored in a is 6. Then (a /= 2) = 3.
Arithmetic Operator
The Arithmetic operators are some of the C Programming Operator, which are used
to perform arithmetic operations includes operators like Addition, Subtraction,
Multiplication, Division and Modulus (sirraghavgupta & akhilsharma870, 2015).
There are two types of arithmetic operators (sirraghavgupta & akhilsharma870, 2015):
I. Unary Operators: Operators that operates or works with a single operand are unary
operators. For example: (++ , –)
II. Binary Operators: Operators that operates or works with two operands are binary
operators. For example: (+ , – , * , /)
Unary Operators:
85
The ones falling into the category of unary arithmetic operators are (sirraghavgupta &
akhilsharma870, 2015):
• Increment: The ‘++’ operator is used to increment the value of an integer. When
placed before the variable name (also called pre-increment operator), its value is
incremented instantly. For example, ++x (sirraghavgupta & akhilsharma870,
2015).
And when it is placed after the variable name (also called post-increment
operator), its value is preserved temporarily until the execution of this statement
and it gets updated before the execution of the next statement. For example, x++
(sirraghavgupta & akhilsharma870, 2015).
And when it is placed after the variable name (also called post-decrement
operator), its value is preserved temporarily until the execution of this statement
and it gets updated before the execution of the next statement. For example, x – –
(sirraghavgupta & akhilsharma870, 2015).
// post-decrement example:
// result is assigned 11 only, a is not updated yet
result = a--; 86
printf("a is %d and result is %d\n", a, result); // a becomes 10 now
// pre-increment example:
// result is assigned 11 now since a is updated here itself
Output:
a is 11 and result is 10
a is 10 and result is 11
a is 11 and result is 11
a is 10 and result is 10
Binary Operators
These are used to perform arithmetic/mathematical operations on operands. The binary
operators falling in this category are (sirraghavgupta & akhilsharma870, 2015):
• Addition: The ‘+’ operator adds two operands. For example, x+y.
• Subtraction: The ‘-‘ operator subtracts two operands. For example, x-y.
• Multiplication: The ‘*’ operator multiplies two operands. For example, x*y.
• Division: The ‘/’ operator divides the first operand by the second. For
example, x/y.
87
• Modulus: The ‘%’ operator returns the remainder when first operand is divided
by the second. For example, x%y.
//printing a and b
printf("a is %d and b is %d\n", a, b);
// addition
result = a + b;
printf("a+b is %d\n", result);
// subtraction
result = a - b;
printf("a-b is %d\n", result);
// multiplication
result = a * b;
printf("a*b is %d\n", result);
// division
result = a / b;
printf("a/b is %d\n", result);
// modulus
result = a % b;
printf("a%b is %d\n", result);
return 0;
}
Output:
a is 10 and b is: 4
a+b is: 14
a-b is: 6
a*b is: 40
a/b is: 2
a%b is: 2
88
Lesson 2: Operator Precedence and Associativity in C
For example: ‘*’ and ‘/’ have same precedence and their associativity is Left to Right, so
the expression “100 / 10 * 10” is treated as “(100 / 10) * 10” (Operator Precedence and
Associativity in C - GeeksforGeeks, 2014).
89
Fig. 6.2 Operator
Associativity
Operators Precedence and Associativity are two characteristics of operators that
determine the evaluation order of sub-expressions in absence of brackets (Operator
Precedence and Associativity in C - GeeksforGeeks, 2014).
100 + 200 / 10 – 3 * 10
90
Fig. 6.3 Operator Precedence and Associativity
1) Associativity is only used when there are two or more operators of same precedence.
The point to note is associativity doesn’t define the order in which operands of a single
operator are evaluated. For example, consider the following program, associativity of the
+ operator is left to right, but it doesn’t mean f1() is always called before f2(). The output
of the following program is in-fact compiler dependent (Operator Precedence and
Associativity in C - GeeksforGeeks, 2014).
#include <stdio.h>
int x = 0;
int f1()
{
x = 5;
return x;
}
int f2()
{
x = 10;
return x;
}
int main()
{
int p = f1() + f2();
2) Allprintf("%d ", x); with the same precedence have same associativity
operators
return 0;
This
} is necessary, otherwise, there won’t be any way for the compiler to decide evaluation
order of expressions which have two operators of same precedence and different
associativity. For example, + and – have the same associativity (Operator Precedence and
Associativity in C - GeeksforGeeks, 2014).
91
4) Comma has the least precedence among all operators and should be used carefully
- For example consider the following program, the output is 1. For more example visit this
link about comma operator (Operator Precedence and Associativity in C - GeeksforGeeks,
2014).
https://www.geeksforgeeks.org/a-comma-operator-question/
#include <stdio.h>
int main()
{
int a;
a = 1, 2, 3; // Evaluated as (a = 1), 2, 3
printf("%d", a);
return 0;
}
Relational Operators
Relational operators are used to compare values of two expressions. Relational
operators are binary operators because they require two operands to operate. An
expression which contains the relational operators is called relational expression. If the
relation is true then the result of the relational expression is 1, if the relation is false then
the result of the relational expression is 0 (Relational Operators in C - Tutorialspoint,
2012).
The following table lists relational operators along with some examples (Relational Operators in
C - Tutorialspoint, 2012):
Table 6.1 Relational operators’ example.
Operator Description Example Result
> Greater than 1>2 0
>= Greater than or equal to 3>=2 1
< Smaller than 10 < 5 0
<= Smaller than or equal to 6 <= 7 1
== equal to 98==98 1
!= not equal to 10 != 9 1
92
In C, all non-zero values are considered as true while 0 is considered as false. The
following program demonstrates relational operators in action (Relational Operators in C
- OverIQ.Com, 2020), take some time to try this program:
#include<stdio.h>
int main()
{
int x = 12, y = 13;
// Is x is greater than y?
printf("x > y : %d\n", x > y);
// Is x is smaller than y?
printf("x < y : %d\n", x < y);
// Is x is equal to y?
printf("x == y : %d\n", x == y);
// Is x is not equal to y?
printf("x != y : %d\n", x != y);
x > y : 0
x >= y : 0
x < y : 1
x <= y : 1
x == y : 0
x != y : 1
The following table shows all the relational operators supported by C language. Assume
variable A holds 10 and variable B holds 20 then – (Relational Operators in C -
Tutorialspoint, 2012)
93
Table 6.2 Relational Operators Supported by C
Language
Operator Description Example
> Checks if the value of left operand is greater than the (A > B) is
value of right operand. If yes, then the condition not true.
becomes true.
< Checks if the value of left operand is less than the value (A < B) is
of right operand. If yes, then the condition becomes true. true.
<= Checks if the value of left operand is less than or equal (A <= B) is
to the value of right operand. If yes, then the condition true.
becomes true.
94
The compound assignment operators consist of a binary operator and the simple
assignment operator. They perform the operation of the binary operator on both operands
and store the result of that operation into the left operand, which must be a modifiable
value (Relational Operators in C - Tutorialspoint, 2012).
The following table shows the operand types of compound assignment expressions
(Relational Operators in C - Tutorialspoint, 2012):
+= or -= Arithmetic Arithmetic
a *= b + c
is equivalent to
a = a * (b + c)
and not
a=a*b+c
The following table lists the compound assignment operators and shows an expression
using each operator(Relational Operators in C - Tutorialspoint, 2012):
95
Operator Example Equivalent expression
Although the equivalent expression column shows the left operands (from the example
column) twice, it is in effect evaluated only once(Relational Operators in C -
Tutorialspoint, 2012).
Assessment Task
Figure out the output of the program given about the Assignment and
Arithmetic
Operation on these C program codes.
1)
96
2)
3)
4)
97
5)
Summary
98
References
MODULE 7
Introduction to Conditional Control Structures
Introduction
99
than one statements. If the given condition is true then the set of statements are
executed otherwise the next one is skipped.
Learning Outcomes
100
Fig. 7.1 Typical decision-making structure found in
most of the programming languages
and if it is either zero or null, then it is assumed as FALSE value (Kwinn et al.,
2010).
• If...Else statement
An if statement (TRUE) can be followed by an optional else statement
(FALSE), which executes when the Boolean expression is false.
101
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.
• Nested if statements
You can use one if or else if statement inside another if or else if
statement(s).
• Switch statement
A switch statement allows a variable to be tested for equality against a list of
values. For example: Options (Option1, 2 and so on..)
Lesson 2: If Statement
If Statement Syntax
If(condition) {
102
The condition inside the parentheses of the IF statement is evaluated. If the result
of the test condition is true, then the instructions inside the IF body are executed. If the
result of the condition is false, then the statements are skipped (Pepito, 2003).
How it works?
Take a few times to write the program sample of If statement that will display the variable
x is less than y.
#include <stdio.h>
int main()
{
int x = 20;
int y = 22;
if (x<y)
{
printf("Variable x is less than y");
}
return 0;
}
Output:
Variable x is less than y
Explanation: The condition (x<y) specified in the “if” returns true for the value of x and
y, so the statement inside the body is executed (Pepito, 2003).
Notice that the difference between IF statement and IF-ELSE statement is that
there's an additional ELSE attached to it. The IF statement is executed if the statement
inside the test condition evaluates to true; otherwise the statements inside the ELSE block
is executed (Pepito, 2003).
If – else statement syntax
103
if(condition) {
/* statement(s) will execute if the condition is TRUE */
}
else {
/* statement(s) will execute if the condition is FALSE */
}
The IF-ELSE statement is used to follow a certain set of instructions based on the
result of a decision. Consider a situation in real life when you would want to make a
decision based on a condition (Krishna, n.d.).
Let's take a very basic example that we face in everyday life. Consider a rainy weather
outside.
• If it rains, you will use or bring an umbrella; otherwise you will not.
104
Actually, the else part is optional which means that it can be included or not in our
program; (our program will still even run without it). When the condition of if statement is
proven true, statement 1 is executed, otherwise statement 2 is executed. In the absence
of else statement, there is nothing to be executed if the if conditional statement is
evaluated false (Krishna, n.d.).
Algorithm:
Enter age
If (age>18)
printf (“\n Qualified to vote”);
else
printf(“\n Too young!”)
#include <stdio.h>
main()
{
int age;
printf ("\n Enter Age:");
scanf ("%d", &age);
if (age >= 18)
printf("\n Qualified to Vote");
else
printf("\n Too Young!");
}
Output:
105
Enter Age: 20
Qualified to Vote
Our program works fine when we enter a reasonable age such as 15, 30, 13, 50,
45, 62 and 20. However, when we enter an impossible age like 501, this value (age) will
still be accepted by our program and would display an output (which is supposed not to):
“Qualified to vote”. Our output message doesn’t fit to the given input value. The message
should be: “You are already dead, Magellan?” (and you’ll probably add: “Now go back to
your grave”) (Pepito, 2003).
Not only this, our program will accept negative values (age) too, such as -1, -9, and
even 0. Imagine, we input an age -1, our program will display a message: “Too Young!”;
when in fact, the right message is: “You are still a fetus, baby?”. We know that there is no
such age as -1 or 0. The probable logic that we can construct to solve this dilemma could
be: (Pepito, 2003)
However, this correct solution is hard to understand since it applies the nested if
or ladderized-if (an if statement within an if statement) Most especially if all the
statements are not properly indented (written in the same column; the common style of
those lazy humans, no not you man, not you, really, I mean it). As we move further in our
modules, we will encounter the nested if in a different lesson (Pepito, 2003).
106
Write a program that determines if the input number is POSITIVE or NEGATIVE.
Consider 0 as positive (considering that It contains no negative sign) (Pepito, 2003).
Algorithm:
Solution:
#include <stdio.h>
main()
{
int n;
printf ("\n Enter a Number:");
scanf ("%d", &n);
if (n>=0)
printf("\n Positive No.");
else
printf("\n Negative No.");
}
Output:
107
Enter a Number: 5
Positive No.
Explanation:
To come up with a correct algorithm, we have to think how and when the number
becomes negative. Eventually, we could think that the number becomes negative if it is
less than 0. From this idea in logic, we can construct the correct solution. So, we can also
have this second solution and algorithm (Pepito, 2003).
if (n<0)
printf(“\n Negative Number”);
else
printf(“\n Positive Number”);
In the same manner, a number that is greater than or equal to zero s a positive
number, otherwise that number is negative. Some programmers used the solution below
as their answer which is equally correct (Pepito, 2003).
if (n<=-1)
printf (“\n Negative Number”);
else
printf (“\n Positive Number”);
As you might notice, we can take many resolutions in a given specific problem. It
depends on how we think and evaluate. Our logic can be different, but we may come to
same correct solution.
Write a program that determines if the input number is ODD or EVEN number.
Algorithm:
108
r=n%2
if (r= =0)
printf(“\n Even Number”);
else
printf(“\n Odd Number”)
Solution:
#include <stdio.h>
main()
{
int r, n;
Output:
Enter a Number: 5
109
Odd Number
How would we know that a number is EVEN number? We would know that it is an EVEN
number if it is divisible by 2. It further means that if a number is divided by 2 and it yields
a remainder of 0 then that number is divisible by 2: Even number. Even if we are given a
very large number such as 129788, we can still determine if it is an even number by
considering the last digit of a given large number. In this case it is 8. The number 8 is
divisible by 2, therefore it is an even number. On the contrary, Odd
numbers are numbers that cannot be divided by 2. To identify a number a number as odd
or even easily, we will look at their end number. If the number ends in a 0, 2, 4, 6, or 8,
then it is even. If the numbers end in a 1, 3, 5, 7 or 9 then it is ODD (Pepito, 2003).
Assessment Task
Write a C program that accepts the input magic number. If the input is right, the
magic word will be displayed. The magic number is 143 and its corresponding magic words
are “I love you”. If the input number is wrong display “Sorry better luck next time”. Write
first the algorithm then the solution on the space provided.
110
Summary
References
Books:
Online References:
111
IF, ELSE, & IF-ELSE Statements in C Programming. (2018, August 24). Retrieved from
https://study.com/academy/lesson/if-else-if-else-statements-in-c-programming.html.
Kwinn, M. J., Parnell, G. S., & Dees, R. A. (2010). Decision Making. Decision Making in
Systems Engineering and Management: Second Edition.
https://doi.org/10.1002/9780470926963.ch12
112
- END OF MODULE FOR MIDTERM PERIOD –
Midterm Examination will be given on November 19 to November 21, 2020.
Kindly check your class schedule for this course.
113