Programming - Final Arc
Programming - Final Arc
LESSON 1
Introduction
Welcome to the world of programming! In this course, you will learn how to write a program using Turbo
C.
A programming language is an artificial language that can be used to control the behavior of a machine,
particularly a computer.
1. Problem statement. The programming process begins with a clear, written statement of the
problem to be solved by the computer.
2. Algorithm development: Once the problem has been clearly stated and all the requirements have
been understood, the next step is to develop the program logic necessary for accomplishing the
task.
An algorithm is defined as a logical sequence of steps that must be performed in order to
accomplish a given task.
Sample Tool: Flowchart
3. Program coding: When the programmer is satisfied with the efficacy of the logic developed in the
preceding step, it is time to convert that logic (in either flowchart or pseudocode form) to the
specific syntax of the programming language that will be used.
4. Program testing: The coded program is next checked for errors.
5. Program documentation: The programming process is complete when the program has been fully
documented.
Before we start with learning how to write C codes, let’s have first the three common programming errors.
1. Syntax error occurs when your code violates one or more grammar rules of C and is detected by
the compiler as it attempts to translate your program. Note that if a statement has a syntax error,
it cannot be translated and your program will not be executed.
2. Run-time error is a detected error and displayed by the compiler during the execution of the
program. It occurs when the program directs the computer to perform illegal operation, such as
dividing a number by zero or an attempt to perform an invalid operation, and detected during
program execution. When a run-time error occurs, the computer will stop executing your program
and will display a diagnostic message that indicates the line where the error was detected.
3. Logic Errors occur when a program follows a faulty algorithm. It does not cause a run-time error
and does not display error messages, so is very difficult to detect. The only sign of a logic error
may be incorrect program output.
What is Turbo C?
C Programming Basics
Turbo C is an Integrated Development Environment and compiler for the C programming language from
Borland. First introduced in 1987, it was noted for its integrated development environment, small size,
extremely fast compile speed, comprehensive manuals and low price.
LESSON 2
Turbo C General Structure
Let’s start!
#include <stdio.h>
int main(void) {
printf("Hello World!\n");
return 0;
}
Now, let’s understand the structure.
The C Preprocessor is a program that is executed before the source code is compiled.
Directives are how C preprocessor commands are called, and begin with a pound / hash symbol (#). No
white space should appear before the #, and a semi colon is NOT required at the end.
There are two directives in C, namely, include and define. For this section, we will first get to know and
use include.
#include gives program access to a library. It tells the preprocessor that some names used in the program
are found in the standard header file. It causes the preprocessor to insert definitions from a standard
header file into the program before compilation.
For example:
#include<stdio.h> tells the preprocessor to open the library “stdio.h” that contains built-in
functions like scanf and printf.
Every C program has a main function. This is where program execution begins. Note that you cannot
change the name of main.
C Programming Basics
Braces {} enclose the body of the function and indicate the beginning and end of the function main.
1. Declaration is the part of the program that tells the compiler the names of memory cells in a
program needed in the function, commonly data requirements identified during problem analysis
C Programming Basics
Example:
int num1, num2, sum;
2. Executable statements are derived statements from the algorithm into machine language and
later executed.
Example:
printf(“Enter 2 numbers: ”);
scanf(“%d%d”,&num1,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
return 0;
Try this!
#include<stdio.h>
int main(void) {
int num1, num2, sum;
printf(“Enter 2 numbers: ”);
scanf(“%d%d”,&num1,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
return 0;
}
LESSON 3
Variable Declaration
As a programmer, one of the most important things to consider is how to allocate memory that would
handle the data.
Variable declaration is a statement that communicates to the C compiler the names of all variables used
in the program and the kind of information stored in each variable. It also tells how that information will
be represented in memory.
Examples:
int x,age; float
sum,a,b;
char middle_intial;
Data Type is a set of values and a set of operations that can be performed on those values.
1. char
2. double
3. int
short
long
signed
unsigned
The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is
not cast in stone. ANSI has the following rules:
1. Text (data type char) – made up of single characters (example x,#,9,E) and strings (“Hello”), usually
C Programming Basics
3. Floating-point values – numbers that have fractional portions such as 12.345, and exponents
1.2e+22.
6. void – signifies values that occupy 0 bit and have no value. You can also use this type to create
generic pointers.
7. Pointer – does not hold information as do the other data types. Instead, each pointer contains the
address of the memory location.
Example:
5;
Example:
float Miles;
Miles = 5.6;
double is used to define BIG floating point numbers. It reserves twice the storage for the number.
Example:
double Atoms;
Atoms = 2500000;
Example:
char Letter;
Letter = 'x';
What is a variable?
Variable is like a container in your computer's memory - you can store a value in it and retrieve or modify
it when necessary. It is associated with a memory cell whose value can change as the program executes.
Sequential Control Structure
A variable is an identifier. An identifier is name that identifies or labels the identity of an object. In C, the
following are the naming conventions for an identifier.
Examples:
Names... Example
CANNOT start with a number 2i
The previous example has a variable sum that is initialized during declaration.
Sequential Control Structure
LESSON 4
The following are the basic operators fundamental in the development of a program.
1. Equal sign (=) is called an assignment operator in C. It is the most basic operator where the value
on the right of the equal sign is assigned to the variable on the left.
The left value or lvalue is the destination variable, while the right value or rvalue can be a value, a
process or arithmetic expression, or a command that receives a value.
The following are some examples on how to use the assignment operator.
c = c + 1;
radius = 2 * diameter;
stat = getch();
2. The binary operators are arithmetic operators that take two operands and return a result.
3. Address operator (&) returns the address of a variable. This operator is significant in the input
process when the command needs to get the address of a variable to know where to put the data
and when using a reference variable to indirectly access a value. The first use will be explained
briefly in the next lesson. The second use will not be discussed in this course.
Try this!
#include<stdio.h>
int main(void){
int c;
Output: 6
// Assign 5 to variable c.
c = 5;
The following are the basic commands fundamental in the development of a program.
scanf() is one of the Turbo C object streams that is used to accept data from the standard input,
usually the keyboard. Though it can accept any type of data, it has limits when used to input a
value other than numeric.
The data received from the standard input is assigned to the variable. The address operator returns
the address of the variable where to assign the data.
Format specifier defines the type of data to be accepted from the standard input. The list of format
specifiers for scanf is shown in the table below.
The first example assigns an integer value to num1 since %d is a format specifier for int and num1
should be of type int. The second example accepts two inputs, thus needs to have two formats.
The assignment of value is done by position. Whitespace input separates the values.
The following table summarizes the scanf format specifiers for each of the data types.
Sequential Control Structure
Double %lf
Float %f
unsigned int %u
Int %d
Short %hd
Char %c
Try this!
#include<stdio.h> Input: 10
int main(void){ Output: 10
int num1;
//Input a value and assign it to variable
num1.
scanf("%d", &num1);
printf("%d", num1);
}
Sequential Control Structure
#include<stdio.h> Input: 5
int main(void){ 10
int num1, num2; Output: 5 10
//Input two integer values and assign them
to variables num1 and num2.
scanf("%d%d", &num1, &num2);
printf("%d %d", num1, num2);
}
printf() writes formatted output to the standard output device such as the monitor. It can be a
statement with either pure string expression, a formatted value or a mixed expression. A
formatted value is a value from a variable.
The first example displays “Hello world”. The second statement displays the value of num1. The format is
%d if num1 is of type int. The third statement should display “Value: 10” if the value of num1 is 10.
Format specifier defines the type of data to be printed in the standard output. The list of format specifiers
for printf is shown in the table below.
The following table summarizes the printf format specifiers for each of the data types.
Double %f
Float %f
unsigned int %u
Int %d
Short %hd
Char %c
Try this!
printf("Hello world");
}
#include<stdio.h>
int main(void){ 5
int num1;
num1 = 5;
printf("%d",num1);
}
Sequential Control Structure
3. Displays the value of num1 with the message “The value of num1: ”.
#include<stdio.h>
int main(void){ The value of num1: 5
int num1;
num1 = 5;
printf("The value of num1: %d",num1);
}
Sequential Control Structure
Control structure specifies the sequence of execution of a group of statements. There are three types of
control structure, namely: sequential, conditional and iterative.
Each of the three control structures will be discussed on the succeeding lessons.
In general, the following is the block diagram of the programming life cycle.
A sequential control structure is organized such that statements are executed in sequence, i.e., one after
the other in the order of their appearance in the source code.
Write a program that accepts two integers and computes and displays their sum.
First, we define the programming problem. After restating and analyzing the problem, we do the last three
steps:
Always remember that you can use any variable name that best describes its meaning as long as it is not
a reserved word.
Finally, we write the code. We follow the correct structure of the C program as shown below.
Preprocessor Directives
int main(void){
local declarations
statements
}
Here is the algorithm. We skip directly to the content of the program. The directive and the main header
are pre-defined.
Variables should be declared using their appropriate data types, thus, we use int for all the
variables.
}
Sequential Control Structure
Try it!
#include<stdio.h>
int main(void){
int num1, num2,sum;
printf(“Enter two numbers: ”);
scanf(“%d”,&num1);
scanf(“%d”,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
}
Sequential Control Structure
LESSON 6
C Language Elements
#define
As mentioned in the earlier lesson, C has only two directives, include and define. Now, we will tackle the
second directive define.
The directive define allows you to make text substitutions before compiling the program. By convention,
all identifiers that are to be changed by the preprocessor are written in capital letters.
For example,
#define MAX 10
if(a>MAX) {
printf("\nToo large.\n"); }
else if(a<MIN) {
printf("\nToo small.\n"); }
else { printf("\nThanks.\n");
okay = TRUE; }
}
return 0;
}
Library
Libraries are C implementations that contain collections of useful functions and symbols that may be
accessed by a program. Each library has a standard header file whose name ends with .h. A C system may
expand the number of operations available by supplying additional libraries that are called user-defined.
As mentioned in the earlier lesson, #include is used to open a library. To open a predefined library, a pair
Sequential Control Structure
of angle brackets (<>) is used to enclose the header file. To open a user-defined library, a pair of double
quotes (“”) is used.
Comments
You can add comments to your code by enclosing your multi-line remarks with /* and */ while a pair of
slashes precedes a single-line. However, nested comments aren't allowed.
They can be used to inform the person viewing the code what the code does. This is helpful when
you revisit the code at a later date.
The compiler ignores all the comments. Hence, commenting does not affect the efficiency of the
program.
You can use /* and */ to comment out sections of code when it comes to finding errors, instead
of deletion.
In C, a reserved word is defined as the word that has a special meaning and cannot be used for other
purposes. It cannot be used as an identifier.
The following is a table that shows the complete list of 32 C reserved words.
Sequential Control Structure
Punctuation Marks
The following table shows the punctuations marks used in C, with their names and meanings.
LESSON 7
C Constants
Constants are identifiers that are having a constant value all throughout the program execution. By
convention, constants are written in uppercase letters.
To create a constant or a read-only variable, the const keyword is used. Once initialized, the value of the
variable cannot be changed but can be used just like any other variable. Thus, constants should be
initialized during declaration.
Fixed values that may not be altered by the program are also called constants.
The following table shows the list of backslash character constants or escape sequence
characters.
LESSON 8
More Operators
Unary Operators
Unary minus (-) or unary plus (+) changes the sign of a value or variable.
Examples:
2 + -3 ≈ 2 - 3
((-x) + (+y)) ≈ -x + y
The ++ or increment operator adds one to the value of a variable. The -- or decrement operator subtracts
one from the value of a variable.
The value of the expression in which ++ or -- operator is used depends on the position of the operator.
Prefix increment is when the ++ is placed in front of its operand. For this, the value of the expression is
the variable’s value after the increment.
Prefix decrement is when the -- is placed in front of its operand. For this, the value of the expression is the
variable’s value after the decrement.
Postfix increment is when the ++ is placed immediately after the operand. Postfix increment is when the
expression’s value is the value of the variable before it is incremented.
Postfix decrement is when the -- is placed immediately after the operand. Postfix decrement is when the
expression’s value is the value of the variable before it is decremented.
To summarize, prefix increments or decrements a variable value and then uses it, while postfix uses the
variable and then increments or decrements its value.
Here are demonstrations on the use of the increment and decrement operators.
5 6 5 5
Decrements: y = --x y = x--
After: x y x y
Sequential Control Structure
5 4 5 5
LESSON 9
The math handling library is math.h. All the functions available in this library take double as an argument
and return double as the result.
The following table contains the list of commonly used mathematical functions.
The math functions were constructed to translate arithmetic expressions to C codes. For example, the
equivalent C code for the arithmetic expression
x = √𝑎2 + 𝑏2
is
x = sqrt(pow(a,2) + pow(b,2));
Sequential Control Structure
LESSON 10
In the earlier lesson, the two input/output functions, scanf and printf, were discussed as fundamentals in
writing a program using the C Language. For this lesson, we will learn the rest of the basic input and output
functions used in C.
getchar()
getch()
getche()
gets()
puts()
putchar()
getchar()
var_name = getchar();
where var_name is of type char that receives the inputted character value.
Try this!
Sequential Control Structure
#include<stdio.h>
int main(void){
char letter;
letter = getchar();
printf(“Value of letter: %c”,letter);
}
getch()
The getch function allows the user to input a character and wait for the enter key. Inputted character will
not be echoed but could be stored if location is specified. It is a nonstandard function and is present in
conio.h header file.
var_name = getch();
where var_name is of type char that receives the inputted character value.
Sequential Control Structure
Try this!
#include<stdio.h>
int main(void){
char letter;
letter = getch();
printf(“\nValue of letter: %c”,letter);
}
getche()
The getche function allows the user to input a character and there is no need for the enter key. Inputted
character will be echoed but could be stored if location is specified.
var_name = getche();
where var_name is of type char that receives the inputted character value.
Try this!
#include<stdio.h>
int main(void){
char letter;
letter = getche();
printf(“\nValue of letter:%c”,letter);
}
gets()
The gets function allows the user to input a sequence of characters or string.
gets(var_name);
Try this!
Sequential Control Structure
#include<stdio.h>
int main(void){
char word[30];
gets(word);
printf(“The word is:%s”,word);
}
puts()
The puts function writes the string to the standard output device such as the monitor and positions the
cursor to the next line.
puts(“string expression”);
Try this!
#include<stdio.h>
int main(void){
puts(“Hello Philippines!”);
}
putchar()
putchar(var_name); and
putchar(int);
where the parameter may be a char variable with a value, or an integer value for a character.
Sequential Control Structure
Try this!
#include<stdio.h>
int main(void){
char letter=’a’;
putchar(letter);
putchar(65);
}
Sequential Control Structure
Conditional control structure is organized in such a way that there is always a condition that has to be
evaluated first. The condition evaluates to either a true or a false.
In C, false is zero (0) and true is non-zero (i.e. positive or negative value).
The conditional control structure has two types, namely the if statement (including if-else and nested-if)
and the switch-case statement.
Conditional expressions or statements use two types of operators, namely relational and logical.
The relational or conditional operators evaluate to true or false. The following table shows the list of
operators with their use and meaning.
The logical operators consist of the logical “and”, “or” and “not”. The following table shows the list of
operators with their use and meaning.
When the expression is a combination or arithmetic, relational and logical operations, it is evaluated
following the order of precedence as detailed below where the topmost has the higher precedence down
to the lowest.
Arithmetic Operators *, /, %
+, -
Logical Operators !
&&
||
Let’s evaluate some expressions, assuming that result is either 1 for true and 0 for false.
Sequential Control Structure
1. x = 3 * 2 > 10 % 2;
The result for x is 1 since (3 * 2) which is 6 is greater than (10 % 2) that is 0.
2. x = 6 – 3 < 10 / 3 || 7 * 2 == 28 / 4;
The result for x is 0 since both the left and right expressions of the logical OR result to false or 0.
if Statement
The if statement performs a task or a group of tasks when the condition is true or when it is false, if there
is an alternative for false. For multiple statements inside an alternative, they should be enclosed with a
pair of braces.
1. if (single alternative)
4. Nested-if
The if (single alternative) performs an indicated action only when the condition is true, otherwise the
action is skipped.
if (<conditional expression>)
<statement>
For example:
Another example:
For the first example, if the condition evaluates to true then the message “You are an adult!” displays. If
the condition evaluates to false, then nothing happens.
The second example uses a pair of braces to enclose the multiple statements that will be performed when
the condition evaluates to true.
Sequential Control Structure
Write a program that accepts a number and determines whether the number is positive. If it is positive,
display the message “Positive!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
}
The if-else (double alternatives) allows the programmer to specify that different actions are to be
performed when the condition is true and when the condition is false. If the condition evaluates to true,
then statementTrue is executed and statementFalse is skipped; otherwise, statementTrue is skipped and
statementFalse is executed.
if (<conditional expression>)
<statementTrue>
else
<statementFalse>
For example:
else
If the condition results to true then the message “You are an adult!” is displayed. If otherwise, the message
“You are a minor!” is displayed.
The following states the good programming practices to be observed when using the if-else statement.
Write a program that accepts a number and determines whether the number is positive or negative. If it
is positive, display the message “Positive!”. Otherwise, display “Negative!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
else
printf(“Negative!”);
}
The conditions in a multiple-alternative decision are evaluated in sequence until a true condition is
reached. If a condition is true, the statement following it is executed, and the rest of the multiple-
alternative decision is skipped. If a condition is false, the statement following it is skipped, and the
condition next is tested. If all conditions are false, then the statement following the final else is executed.
if (<conditional expression>)
<statement>
<statement>
<statement>
else
<statement>
Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0)
printf("Positive!");
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}
Nested-if
A nested if statement can perform much faster than a series of single-selection if statements because of
the possibility of early exit after one of the conditions is satisfied.
In a nested if statement, you test the conditions that are more likely to be true at the beginning of the
nested if statement. This will enable the nested if statement to run faster and exit earlier than testing
infrequently occurring cases first.
Sequential Control Structure
if (<conditional expression>){
if (<conditional expression>)
<statement>
else
<statement>
Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”. Furthermore, if the number is positive, it
determines whether it is even or odd and displays either “Even!” or “Odd!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0){
printf("Positive!");
if(num%2==0)
printf(“Even!”);
else
printf(“Odd!”);
}
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}
Here are the sample outputs:
Sequential Control Structure
In general, the following are the good programming practices to be observed in using the if statement.
• Always putting the braces in an if...else statement (or any control statement) helps prevent their
accidental omission, especially when adding statements to an if or else clause at a later time. To
avoid omitting one or both of the braces, some programmers prefer to type the beginning and
ending braces of blocks even before typing the individual statements within the braces.
• Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors
in a program.
• Placing a semicolon after the condition in an if statement leads to a logic error in single-selection
if statements and a syntax error in double-selection if...else statements (when the if part contains
an actual body statement).
The switch statement uses a variable to be compared to a set of values. Each value is called a case which
should only be an int or a char, that should also be the data type for the variable.
In the switch statement, the variable or also called the controlling expression, is evaluated and compared
to each of the case labels in the case constant until a match is found. A case constant is made of one or
more labels of the form case followed by a constant value and a colon. When a match between the value
of the controlling expression and a case label value is found, the statement following the case label are
executed until a break statement is encountered. Then the rest of the switch statement is skipped.
break;
break;
. . .
default: <statement>
The break at the end is necessary since it allows the rest of the matching and statements to be skipped.
Because of break, if there are multiple statements in a case, the pair of braces that are usually used to
group the statements are not needed.
Make a program that would input the year code (between 1 and 4) and output “Freshman”, “Sophomore”,
“Junior”, or “Senior”. Furthermore, if year is not between 1 and 4, output “Error”.
#include<stdio.h>
int main(void){
int yearcode;
scanf("%d", &yearcode);
switch(yearcode){
default: printf("Error");
}
Here are the sample outputs:
Conditional Control Structure
Conditional control structure is organized in such a way that there is always a condition that has to be
evaluated first. The condition evaluates to either a true or a false.
In C, false is zero (0) and true is non-zero (i.e. positive or negative value).
The conditional control structure has two types, namely the if statement (including if-else and nested-if)
and the switch-case statement.
Conditional expressions or statements use two types of operators, namely relational and logical.
The relational or conditional operators evaluate to true or false. The following table shows the list of
operators with their use and meaning.
The logical operators consist of the logical “and”, “or” and “not”. The following table shows the list of
operators with their use and meaning.
When the expression is a combination or arithmetic, relational and logical operations, it is evaluated
following the order of precedence as detailed below where the topmost has the higher precedence down
to the lowest.
Arithmetic Operators *, /, %
+, -
Logical Operators !
&&
||
Let’s evaluate some expressions, assuming that result is either 1 for true and 0 for false.
1. x = 3 * 2 > 10 % 2;
The result for x is 1 since (3 * 2) which is 6 is greater than (10 % 2) that is 0.
2. x = 6 – 3 < 10 / 3 || 7 * 2 == 28 / 4;
The result for x is 0 since both the left and right expressions of the logical OR result to false or 0.
if Statement
The if statement performs a task or a group of tasks when the condition is true or when it is false, if there
is an alternative for false. For multiple statements inside an alternative, they should be enclosed with a
pair of braces.
1. if (single alternative)
4. Nested-if
if (Single Alternative)
The if (single alternative) performs an indicated action only when the condition is true, otherwise the
action is skipped.
if (<conditional expression>)
<statement>
For example:
Another example:
For the first example, if the condition evaluates to true then the message “You are an adult!” displays. If
the condition evaluates to false, then nothing happens.
The second example uses a pair of braces to enclose the multiple statements that will be performed when
the condition evaluates to true.
Here is a sample problem for the single-if:
Write a program that accepts a number and determines whether the number is positive. If it is positive,
display the message “Positive!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
}
The if-else (double alternatives) allows the programmer to specify that different actions are to be
performed when the condition is true and when the condition is false. If the condition evaluates to true,
then statementTrue is executed and statementFalse is skipped; otherwise, statementTrue is skipped and
statementFalse is executed.
if (<conditional expression>)
<statementTrue>
else
<statementFalse>
For example:
else
The following states the good programming practices to be observed when using the if-else statement.
Write a program that accepts a number and determines whether the number is positive or negative. If it
is positive, display the message “Positive!”. Otherwise, display “Negative!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
else
printf(“Negative!”);
}
The conditions in a multiple-alternative decision are evaluated in sequence until a true condition is
reached. If a condition is true, the statement following it is executed, and the rest of the multiple-
alternative decision is skipped. If a condition is false, the statement following it is skipped, and the
condition next is tested. If all conditions are false, then the statement following the final else is executed.
if (<conditional expression>)
<statement>
<statement>
else
<statement>
Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0)
printf("Positive!");
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}
Nested-if
A nested if statement can perform much faster than a series of single-selection if statements because of
the possibility of early exit after one of the conditions is satisfied.
In a nested if statement, you test the conditions that are more likely to be true at the beginning of the
nested if statement. This will enable the nested if statement to run faster and exit earlier than testing
infrequently occurring cases first.
Here is the syntax of a nested-if:
if (<conditional expression>){
if (<conditional expression>)
<statement>
else
<statement>
Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”. Furthermore, if the number is positive, it
determines whether it is even or odd and displays either “Even!” or “Odd!”.
#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0){
printf("Positive!");
if(num%2==0)
printf(“Even!”);
else
printf(“Odd!”);
}
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}
Here are the sample outputs:
In general, the following are the good programming practices to be observed in using the if statement.
• Always putting the braces in an if...else statement (or any control statement) helps prevent their
accidental omission, especially when adding statements to an if or else clause at a later time. To
avoid omitting one or both of the braces, some programmers prefer to type the beginning and
ending braces of blocks even before typing the individual statements within the braces.
• Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors
in a program.
• Placing a semicolon after the condition in an if statement leads to a logic error in single-selection
if statements and a syntax error in double-selection if...else statements (when the if part contains
an actual body statement).
The switch statement uses a variable to be compared to a set of values. Each value is called a case which
should only be an int or a char, that should also be the data type for the variable.
In the switch statement, the variable or also called the controlling expression, is evaluated and compared
to each of the case labels in the case constant until a match is found. A case constant is made of one or
more labels of the form case followed by a constant value and a colon. When a match between the value
of the controlling expression and a case label value is found, the statement following the case label are
executed until a break statement is encountered. Then the rest of the switch statement is skipped.
break;
break;
. . .
default: <statement>
The break at the end is necessary since it allows the rest of the matching and statements to be skipped.
Because of break, if there are multiple statements in a case, the pair of braces that are usually used to
group the statements are not needed.
#include<stdio.h>
int main(void){
int yearcode;
scanf("%d", &yearcode);
switch(yearcode){
default: printf("Error");
}
Here are the sample outputs:
Loop/Iteration/Repetition
Loop is a control structure that repeats a group of steps in a program. It defines a block of code that is
repeatedly executed. Depending on the kind of loop that you are using, the block of code could be
executed a set number of times or until a certain condition is met.
1. Initialization of variables is setting an initial value before the loop statement is reached.
The condition to check is usually made on the current value of the variable initialized in (1) for it
controls the loop repetition.
4. Update is a statement inside the body of the loop that updates the value of the variable that is
initialized during each repetition.
Since the problem is to repeat the phrase 10 times, then we count from 1 to 10. However, we can also
start from 10 to 1. For problems with a specified number of times to repeat, a counter is used.
A counter is set up in a program to keep track the number of times the program segment is repeated. The
program can then be terminated after the completion of a predetermined number of passes.
For the above problem, we will use a counter. Now, we derive the four components.
Body: Display of the message “Hello world!”. Using C, we use that statement
printf(“Hello world!”);
Assuming we use variable ctr to count, this is how the use of a counter is done.
To write the complete program that would answer the problem, let us learn the use of the different loop
structures.
1. for statement
2. do-while statement
3. while statement
The for Loop
The for loop is used to execute code block for a specified number of times.
Statement/s
printf(“Hello world!”);
Try this!
#include<stdio.h>
int main(void){
int ctr;
printf(“Hello world!”);
Note that all expressions of the for loop are optional. It means that you can omit any expression or all of
them. When you omit all expressions, the C for loop behaves slightly similar to the while loop and do while
loop with break statement.
For example:
ctr=1;
for (; ctr<=5;){
printf(“Hello world!”);
ctr++;
}
Try this!
#include<stdio.h>
int main(void){
int ctr=1;
for (;ctr<=10;){
printf(“Hello world!”);
ctr++;
Input N integers and count how many negative, positive and zeroes were entered. At the end, print the
counted values.
#include<stdio.h>
int main(void){
scanf("%d",&N);
for (ctr=1;ctr<=N;ctr++){
scanf(“%d”,&num);
if(num<0)
neg++;
else if(num>0)
pos++;
else
zero++;
printf(“Negatives: %d\n”,neg);
printf(“Positives: %d\n”,pos);
printf(“Zeroes: %d\n”,zero);
Try this!
#include<stdio.h>
int main(void){
scanf("%d",&N);
for (ctr=1;ctr<=N;ctr++){
scanf(“%d”,&num);
if(num<0)
neg++;
else if(num>0)
pos++;
else
zero++;
printf(“Negatives: %d\n”,neg);
printf(“Positives: %d\n”,pos);
printf(“Zeroes: %d\n”,zero);
The do-while loop executes a block of codes as long as the specified condition is true.
It is a post checked loop because it checks the controlling condition after the code is executed.
initialization
do{
Statement/s
update
}while(condition);
ctr=1;
do{
printf(“Hello world!”);
ctr++;
}while(ctr<=10);
Try this!
#include<stdio.h>
int main(void){
int ctr=1;
do{
printf(“Hello world!”);
ctr++;
}while(ctr<=10);
}
For problems where there is no specified number of times to repeat a task, the best loop structure to use
is either do-while or while. For example,
Write a program that continuously accepts a number until a 0. The 0 terminates the loop.
The 0 is called a trailer record. A trailer record is a special value used to terminate a loop instead of a
counting process. The value is chosen to be a data value which is outside the range of the data values to
be processed.
Here is the code segment that would answer the above problem using do-while and would demonstrate
the use of the trailer record.
do{
scanf(“%d”,&num);
}while(num!=0);
Try this!
#include<stdio.h>
int main(void){
int num;
do{
scanf(“%d”,&num);
}while(num!=0);
Like do-while, the while loop will execute a block of codes while the given condition is true.
It is a pre-checked loop because it checks the controlling condition first before the code is executed.
initialization
while(condition){
Statement/s
update
ctr=1;
while(ctr<=10){
printf(“Hello world!”);
ctr++;
}
Try this!
#include<stdio.h>
int main(void){
int ctr=1;
while(ctr<=10){
printf(“Hello world!”);
ctr++;
Break exits from the lowest-level loop in which it occurs. It used for early exit from the loop, or for exiting
a forever loop.
An integer is said to be prime if it is divisible only by 1 and itself. For example, 2, 3, 5 and 7 are
prime, but 4, 6 and 9 are not. Write a program that determines whether an integer is prime or not.
Try this!
#include<stdio.h>
int main(void){
int num,ctr,prime=1;
scanf("%d",&num);
for(ctr=2;ctr<=num/2;ctr++){
if(num%ctr==0){
prime=0;
break;
if(prime==1)
printf("Prime!");
else
printf("Not Prime!");
Continue causes immediate loop iteration, skipping the rest of the loop statements. It jumps to the loop
test when used with while or do. It jumps to loop increment, then test when used with for. It does not exit
the loop (unless next loop is false).
Write a program that prints numbers 1 to 20, excepts those that are divisible by 3.
To try and run the complete program that answers the problem above, click the link below:
#include<stdio.h>
int main(void){
int ctr;
for(ctr=1;ctr<=20;ctr++){
if(ctr%3==0)
continue;
printf("%d ",ctr);
Nested Loop
Like the conditional control structure, a loop within a loop or a nested loop is allowed in C.
For example:
011111
101111
110111
111011
111101
111110
Try this!
#include<stdio.h>
int main(void){
int i, j;
for(i=1;i<=6;i++){
for(j=1;j<=6;j++){
if(i==j)
printf("0 ");
else
printf("1 ");
printf("\n");
}
FUNCTION
A function is a subroutine that contains one or more statements and performs a single well-defined task.
Before we start writing user-defined functions, let’s have the difference first between the main program
and the function. Note that the main program is actually the main function. The main function is where
program execution begins, that’s why we call it the main program.
A function is a subprogram therefore the structure of a function is similar to the main program.
A program has the life cycle input->process->output. Since a function is a subprogram, it has the same life
cycle with a program. Both have the same process. The main program uses pre-defined input and output
functions, while the function has parameter as input and a return statement for output.
Write a program that accepts two numbers and computes and prints their sum.
int main(void){
//input
scanf("%d%d",&num1,&num2);
//process
//output
printf("%d",sum);
Elements of a Function
Write a function that accepts two numbers and computes and returns their sum.
Before we write the function, here are the three elements we need to define:
1. Function declaration/prototype
2. Function definition/implementation
3. Function call
The following are the syntaxes of the elements with the code segments to answer the revised problem.
Function Declaration/Prototype
Function declaration is first read by the compiler. When a function is called, it is checked whether the
name exists and whether the number of parameters and data types are correct based on how it is
declared.
Syntax:
Example:
Note:
ReturnType – is any standard data type in C of the value to be returned by the function.
parameter list – consists of variables that receive the value of the arguments used in the function
call. The variable name is optional.
Function Definition/Implementation
Function definition is composed of statements that perform the task asked for the function. The
parameter serves as input to the function. It means that when a function is called, the value of the
parameter passed becomes the value of the parameter of the called function. Parameter passing is done
by position. If there is a return type, the function is expected to return a value.
Syntax:
Example:
int sum;
return sum;
2. It can be used to cause an immediate exit from the function it is in. That is, the return will cause
program execution to return to the calling as soon as it is encountered.
Note: The return statement can also be used without any value associated with it.
Function Call
Function call invokes a function. A function only exists when it is called. As mentioned above, parameters
are passed by position. When a function returns a value, the calling function either receives the value by
assigning it to a variable or passes it to another function.
int main(void){
printf("%d",sum);
Note:
Argument – is the value that is passed to the function at the time that it is called.
1. If there are parameters, there should be no pre-defined input functions inside the function.
2. If there is a return type, the computed value is expected to be returned, not to be displayed. It
could destroy the format defined in main.
3. If the function does not need an input, use void or just leave the parameter empty. This can only
be the time to have a pre-defined input function, and only when it is an input function.
4. If the function does not return a value, use void. This can only be the time to have a pre-defined
output function, and only when it is an output function.
#include<stdio.h>
int sum;
return sum;
int main(void){
sum = computeSum(num1,num2);
printf("%d",sum);
Problem: Write a program that performs the four mathematical operations, addition, subtraction,
multiplication, division (one function each operation). The main program lets you choose what operation
to perform using the switch statement. The following are the case labels (+,-,*,/). If the operation chosen
is subtraction, the minuend should always be greater than the subtrahend to avoid a negative answer. If
the operation chosen is division, the dividend should be greater than the divisor.
#include<stdio.h>
int main(void){
int num1,num2,ans=0;
char op;
op=getchar();
scanf("%d%d",&num1,&num2);
switch(op){
printf("%d",ans);
}
Write a function accepts a distance expressed in kilometers and returns the distance expressed in miles,
where 1 kilometer equals 0.62137 miles. Test the function inside main().
#include<stdio.h>
return km * 0.62137;
int main(){
printf("%.2f",toMiles(2));
There are 12 inches in a foot and an inch is 2.54 centimeters long. Write a function that accepts distance
expressed in feet and inches and output the equivalent distance in centimeters. Test the function inside
main().
#include<stdio.h>
int main(){
scanf("%d",&ft);
scanf("%d",&inch);
printf("%.2f",toCm(ft,inch));