It 122 1
It 122 1
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
History of C
Flowchart
Variable
Identifier
Objectives:
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 1 of 93
History of C
C was developed by Dennis M. Ritchie
C was invented to write an operating system called UNIX.
C is a successor of B language which was introduced around the early 1970s.
The language was formalized in 1988 by the American National Standard Institute (ANSI).
The UNIX OS was totally written in C.
Today C is the most widely used and popular System Programming Language.
Most of the state-of-the-art software have been implemented using C.
Today's most popular Linux OS and RDBMS MySQL have been written in C.
Why Use C?
C was initially used for system development work, particularly the programs that make-up the operating
system. C was adopted as a system development language because it produces code that runs nearly as fast as the
code written in assembly language. Some examples of the use of C might be:
C Programs
A C program can vary from 3 lines to millions of lines and it should be written into one or more text files with
extension ".c"; for example, hello.c. You can use "vi", "vim" or any other text editor to write your C program into a
file. This tutorial assumes that you know how to edit a text file and how to write source code inside a program file.
Flowchart
is a diagrammatic representation of sequence of logical steps of a program. Flowcharts use simple geometric
shapes to depict processes and arrows to show relationships and process/data flow.
Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.
Page 2 of 93
SYMBOL SYMBOL NAME PURPOSE
Used at the beginning and end of
Start/Stop the algorithm to show start and
end of the program.
Indicates processes like
mathematical operations.
Process
Variable a name given to a storage area that our programs can manipulate.
Variable Data Types
TYPE DESCRIPTION
char Character data
int Signed whole numbers
float Floating point numbers
double Double precision floating point numbers
void Represents the absence of type
Identifiers is a name used to identify a variable, function, or any other user-defined item. An identifier starts with a
letter A to Z, a to z, or an underscore ‘_’ followed by zero or more letters, underscores, and digits (0 to 9). C does not
allow punctuation characters such as @, $, and % within identifiers. C is a case-sensitive programming language.
Page 3 of 93
Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers:
Page 4 of 93
Example of Flow Chart
- Initializing/Declaring variable
- End of Process
END
Example:
Page 5 of 93
Sum of Two Numbers
- Start
Page 6 of 93
- Initialize two numbers ( a and b ), and sum
- Input a = 5 and b = 6
- sum = 5 + 6
- sum = 11
- End
- Display output
Draw a flowchart that will solve for the average of two numbers.
Page 7 of 93
- Solve for the average of the two numbers. The answer will be stored in
the average.
NOTE: Follow PEMDAS (Parenthesis, Exponents, Multiplication, Division, Addition, Subtraction) rule.
Example:
- Start
- Input a = 20 and b = 10
- Average = (20 + 10 ) / 2
Print - Average = 15
average
- End
Page 8 of 93
- Input data value of the two numbers ( a and b )
- The value of the variable “a” is copied temporary to the variable “c”.
Then the value of the variable “b” is copied to the variable “a”. Finally,
the value of the variable “c” is copied back to the variable “b”.
- Print a and b
Page 9 of 93
Laboratory Exercises :
1. Draw a flowchart that will find the difference of two numbers. Use either Windows Word,
Excel, or PowerPoint to draw the flowchart.
2. Draw a flowchart that will sum 5 numbers. Use either Windows Word, Excel, or PowerPoint to
draw the flowchart.
Review Questions:
1. Draw a flowchart that will find the perimeter of a triangle.
2. Draw a flowchart that will convert temperature from degree Celsius to Fahrenheit.
Page 10 of 93
WEEK 3
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Operators
Flowchart with decision making
If statement in flowchart
If else statement in flowchart
Objectives:
Learn the different types of operators used in C Programming.
Be able to make use of logical operators with if statement
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 11 of 93
OPERATORS
An operator is a symbol that tells the compiler to perform specific mathematical or logical functions. C
language is rich in built-in operators and provides the following types of operators:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Misc. Operators
Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume variable A holds
10 and variable B holds 20, then:
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20, then:
Page 12 of 93
right operand. If yes, then the
condition becomes true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then:
Assignment Operators
The following tables lists the assignment operators supported by the C language:
Page 13 of 93
assignment operator.
Besides the operators discussed above, there are a few other important operators including sizeof and ? :
supported by the C Language.
Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a
higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so
it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.
Decision-making structures require that the programmer specifies one or more conditions to be evaluated or
tested by the program, along with a statement or statements to be executed if the condition is determined to be
true, and optionally, other statements to be executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most of the programming
languages:
Page 14 of 93
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it
is assumed as false value.
STATEMENT DESCRIPTION
if statement An if statement consists of a Boolean expression
followed by one or more statements.
if...else statement An if statement can be followed by an optional else
statement, which executes when the Boolean
expression is false.
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.
nested switch statements You can use one switch statement inside another
switch statement(s).
If statement flowchart
Page 15 of 93
Example:
1. Draw a flowchart that will check if variable a is less than 20.
Start
Initialize a
Input a = 11
True 11 < 20
a is less
than 20
End
An if statement can be followed by an optional else statement, which executes when the Boolean expression
is false.
Example:
1. Draw a flowchart that will print “Young” if the age is less than or equal to 19, else print “Old”.
Start
Initialize age
Input age = 15
True 15 <= 19
IT 122: Introduction to C Programming 1
True
SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.
Page 16 of 93
End
2. Draw a flowchart that will input a number print “I love Philippines” if the number if below 30, else print “I
am hungry”.
Young
Start
Initialize number
Input number = 20
True 20 < 30
I Love
Philippines
End
An if statement can be followed by an optional else if...else statement, which is very useful
to test various conditions using single if...else if statement.
When using if…else if…else statements, there are few points to keep in mind:
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Page 17 of 93
Example
1. Draw a flowchart that will print “Like” if the number is equal to 5, Print “Share” if the number is equal to 6,
else print Subscribe.
Start
Initialize x
x=6
6 == 5
false
End
2. Draw a flowchart that will find the largest among three numbers.
Start
Initializa a, b and c
a = 5, b= 10, c= 2
False
Page 18 of 93
Laboratory Exercises :
1. Draw a flowchart that will check if the number is above 100. Print “Strong” if true, print “Weak”
if false. Use the if else statement. Use either Windows Word, Excel, or PowerPoint to draw the
flowchart.
2. Draw a flowchart that will check if a person is a teen (13-19). Print “Teen” if true, “Not Teen” if
false. Use the if else statement. Use either Windows Word, Excel, or PowerPoint to draw the
flowchart.
Personal Activity:
1. Draw a flowchart that will check whether a number is odd or even.
Page 19 of 93
WEEK 4
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Nested if statement in flowchart
Nested switch statement in flowchart
The ?: Operator
Loops in flowchart
while loop in flowchart
Objectives:
State additional feature like nested ifs
Be able to make use of logical operators with if
Develop a number of programs using these various statements.
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 20 of 93
Nested if Statements
It is always legal in C programming to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).
You can nest else if...else in the similar way as you have nested if statements.
Example:
1. Draw a flowchart that will find the largest among three numbers (using nested if else).
Start
Initialize a, b, c
a = 2, b=34, c=60
2 >= 34 False
60
34 >= 60
False
C is the
largest
number
End
Page 21 of 93
2. Draw a flowchart that will check if the number input is “neutral”, “positive” or negative.
Start
Initialize number
number = 5
5 == 0 False
True 5>0
Print positive
End
Switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
The expression used in a switch statement must have an integral or enumerated type, or be of a
class type in which the class has a single conversion function to an integral or enumerated type.
You can have any number of case statements within a switch. Each case is followed by the value
to be compared to and a colon.
The constant-expression for a case must be the same data type as the variable in the switch, and
it must be a constant or a literal.
IT 122: Introduction to C Programming 1
Page 22 of 93
When the variable being switched on is equal to a case, the statements following that case will
execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the
next line following the switch statement.
Example:
1. Draw a flowchart that will print gender (Male/Female) program according to given M/F using
switch.
Start
initialize gender
gender = “M”
switch(gender)
case ‘m’
False
Print male
End
Page 23 of 93
2. Draw a flowchart that will check if a number is odd or even using switch.
Start
Initialize number
number = 4
2%4
End
The ? : Operator:
We have covered conditional operator ? : in the previous chapter which can be used to replace
if...else statements. It has the following general form:
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
1. Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.
2. If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.
Loops
You may encounter situations when a block of code needs to be executed several number of times.
In general, statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on.
Programming languages provide various control structures that allow for more complicated execution
paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given below is
the general form of a loop statement in most of the programming languages:
Page 24 of 93
C programming language provides the following types of loops to handle looping requirements.
While Loop
A while loop in C programming repeatedly executes a target statement as long as a given condition is true.
Here, code block may be a single statement or a block of statements. The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the
program control passes to the line immediately following the loop.
Page 25 of 93
Example:
2. Flowchart that will print numbers from 1 to 10 using while loop in reverse.
Page 26 of 93
3. Flowchart that will find the sum of numbers from 1 to 10 using while loop.
Laboratory Exercises :
1. Draw a flowchart that will input a value for temperature. If the temperature is between 1 and 100
print "hot", if the temperature is above 101 print "very hot", print "cold". Use Nested if else. Use
Windows Word, Excel or PowerPoint to draw the flowchart.
2. Draw a flowchart that will input a letter. If the letter is equal to 'S' then print "Snapdragon", if the
letter is equal to 'J' then print "Java", if the letter is equal to 'R' then print "Ruby", Print "try again"
for default. Use the switch statement. Use Windows Word, Excel or PowerPoint to draw the
flowchart.
Personal Activity:
1. Draw a flowchart that will find the maximum between two numbers using switch case.
Page 27 of 93
WEEK 5
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Objectives:
Explain the meaning of loops
Explain the loop constructs in C
Use loop nesting
Create a program with while loops, do while loops and nested loops
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 28 of 93
For Loop
A while loop in C programming repeatedly executes a target statement as long as a given condition is
true.
1. Flowchart that will print natural numbers from 1 to 10 using for loop.
Page 29 of 93
2. Flowchart that will find the power of a number using for loop.
Do While Loop
Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in
C programming checks its condition at the bottom of the loop. A do...while loop is similar to a while loop, except the
fact that it is guaranteed to execute at least one time
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop
executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes
again. This process repeats until the given condition becomes false.
Page 30 of 93
Example:
1. Flowchart that will count total digits in a given integer using do while loop.
Nested Loop
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
Page 31 of 93
Example:
2. Flowchart that will print right triangle star pattern using nested loop.
Page 32 of 93
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
CONTROL STATEMENTS DESCRIPTION
break Statements Terminates the loop or switch statement and
transfers execution to the statement immediately
following the loop or switch.
continue Statements Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
goto Statements Transfers control to the labeled statement.
break Statement
The break statement in C programming has the following two usages:
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter). If you are
using nested loops, the break statement will stop the execution of the innermost loop and start executing
the next line of code after the block.
continue Statement
The continue statement in C programming works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control to pass to the
conditional tests.
Page 33 of 93
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used
for this purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless
loop by leaving the conditional expression empty.
Laboratory Exercises
1. Draw a flowchart that will print numbers 15 to 17. use For Loop. Use Windows Word, Excel or
PowerPoint to draw the flowchart.
2. Draw a flowchart that will print numbers 5 to 9 in reverse. Use do while Loop. Use Windows Word,
Excel or PowerPoint to draw the flowchart.
3. Draw a flowchart that will result in an infinite loop. Use Windows Word, Excel or PowerPoint to draw
the flowchart.
Personal Activity
1. Draw a flowchart that will count the number of digits in an integer.
Example:
Input: 1234567890
Output: 10
Example:
Input: 46765
Output: 4
Page 34 of 93
WEEK 6
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Program Structure
C Input and Output
Format Strings
Data Types
Objectives:
Present a C program structure
Discuss input/output functions in C
Explain what are C tokens and types of C tokens
Explain the various data types in C
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
IT 122: Introduction to C Programming 1
Page 35 of 93
Program Structure
Before we study the basic building blocks of the C programming language, let us look at a
bare minimum C program structure so that we can take it as a reference in the upcoming chapters.
#include <stdio.h>
int main()
/* my first program in C */
return 0;
1. Start Dev-C++
Double Click the shortcut on the desktop or from the Start button
2. Open a new source file.
From the menu bar:
o File > New > Source File (Ctrl + N)
Or From the Special Toolbar, Click the New button:
3. Type in your source code.
4. Save the file.
From the menu bar:
o File > Save
Or From the Main Toolbar:
o Click the Save (Ctrl + S) button
o Type a name for the file, such as prog1.c
o Click the Save Button.
5. Compiling the program.
From the menu bar:
IT 122: Introduction to C Programming 1
Page 36 of 93
o Execute > Compile (Ctrl + F9)
o Or click the compile button on the Compile and Run Toolbar.
6. A window will open displaying any syntax errors found.
Correct any compilation errors.
Save the changes.
Compile again.
Repeat the procedure until the program is compilation error and warning free.
7. Click the Close Button
8. Now that your program is error and warning free, run the program. (You could use the Compile command
followed by the Run command or you can use the Compile and Run command if you are confident your code
is compilation error free.)
Basic Syntax
You have seen the basic structure of a C program, so it will be easy to understand other basic building
blocks of the C programming language.
Tokens in C
A C program consists of various tokens and a token is either a keyword, an identifier, a constant, a string
literal, or a symbol. For example, the following C statement consists of five tokens:
printf
Semicolons
In a C program, the semicolon is a statement terminator. That is, each individual statement must be ended
with a semicolon. It indicates the end of one logical entity. Given below are two different statements:
return 0;
Comments
Comments are like helping text in your C program and they are ignored by the compiler. They start with /*
and terminate with the characters */ as shown below:
/* my first program in C */
You cannot have comments within comments and they do not occur within a string or character literals.
Keywords
The following list shows the reserved words in C. These reserved words may not be used as constants or
variables or any other identifier names.
IT 122: Introduction to C Programming 1
Page 37 of 93
auto else long switch
break enum register typedef
case extern return union
char float short unsigned
const for signed void
continue goto sizeof volatile
default if static while
do int struct _Packed
double
Whitespace
A line containing only whitespace, possibly with a comment, is known as a blank line, and a C compiler
totally ignores it. Whitespace is the term used in C to describe blanks, tabs, newline characters and comments.
Whitespace separates one part of a statement from another and enables the compiler to identify where
one element in a statement, such as int, ends and the next element begins. Therefore, in the following
statement:
int age;
there must be at least one whitespace character (usually a space) between int and age for the compiler to
be able to distinguish them. On the other hand, in the following statement:
no whitespace characters are necessary between fruit and =, or between = and apples, although you are
free to include some if you wish to increase readability.
C Input and Output
When we say Input, it means to feed some data into a program. An input can be given in the form of
a file or from the command line. C programming provides a set of built-in functions to read the given input and feed
it to the program as per requirement.
When we say Output, it means to display some data on screen, printer, or in any file. C
programming provides a set of built-in functions to output the data on the computer screen as well as to save it in
text or binary files.
The int getchar(void) function reads the next available character from the screen and returns it as an
integer. This function reads only single character at a time. You can use this method in the loop in case you want to
read more than one character from the screen.
The int putchar(int c) function puts the passed character on the screen and returns the same character.
This function puts only single character at a time. You can use this method in the loop in case you want to display
more than one character on the screen. Check the following example –
#include <stdio.h>
int main( ) {
int c;
Page 38 of 93
printf( "\nYou entered: ");
putchar( c );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a
text and press enter, then the program proceeds and reads only a single character and displays it as follows –
#include <stdio.h>
int main( ) {
char str[100];
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then the program proceeds and reads the complete line till end, and displays it as follows –
Page 39 of 93
%f Scan or print a floating point number
Example:
#include <stdio.h>
int main( ) {
char str[100];
int i;
return 0;
}
When the above code is compiled and executed, it waits for you to input some text. When you enter a text
and press enter, then program proceeds and reads the input and displays it as follows −
Data Types
Data types in C refer to an extensive system used for declaring variables or functions of different types. The
type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.
The types in C can be classified as follows:
S.N. DESCRIPTION
Basic Types:
1 They are arithmetic types and are further classified into: (a) integer types and (b) floating-point
types.
Enumerated types:
2 They are again arithmetic types and they are used to define variables that can only assign certain
discrete integer values throughout the program.
The type void:
3
The type specifier void indicates that no value is available.
Derived types:
4 They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types, and (e)
Function 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. We will see the basic types in the following section, whereas other
types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and value
ranges:
Page 40 of 93
TYPE STORAGE SIZE VALUE RANGE
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -
2,147,483,648 to 2,147,483,647
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 short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The
expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get the
size of int type on any machine:
#include<stdio.h>
#include<limits.h>
int main()
return 0; }
When you compile and execute the above program, it produces the following result:
Floating-Point Types
The following table provides the details of standard floating-point types with storage sizes and value
and their precision:
Page 41 of 93
casted to any data type.
Example:
1. Create a program that will print the word “I am a Filipino”.
#include<stdio.h>
int main()
{
printf(“I am a Filipino”);
return 0;
}
2. Create a program that will ask a user to input a name and print it.
#include<stdio.h>
int main()
{
char name[100];
printf(“Enter a name: ”);
gets(name);
printf(“Hello: ”);
puts(name);
return 0;
}
Laboratory Exercises :
1. Create a program that will ask a user to input a number.
2. Create a program that will ask a user to input their name, age and address.
Personal Activity:
1. Create a program that will find the area of a triangle.
Page 42 of 93
WEEK 7
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Variables
Constant and Literals
Character Literals
String Literals
Defining constant
The const keyword
Objectives:
Explain what is a variable.
Differentiate the difference between variable definition and variable declaration.
Discuss the character literals and string literals
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 43 of 93
Variables
A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable
in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can
be stored within that memory; and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must begin
with either a letter or an underscore. Upper and lowercase letters are distinct because C is case-sensitive.
C programming language also allows to define various other types of variables, which we will cover in
subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic
variable types.
Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the variable. A variable
definition specifies a data type and contains a list of one or more variables of that type as follows:
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined
object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations
are shown here:
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j and k; which instruct the compiler to create
variables named i, j, and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an
equal sign followed by a constant expression as follows:
For definition without an initializer: variables with static storage duration are implicitly initialized with
NULL (all bytes have the value 0); the initial value of all other variables are undefined.
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.
Page 44 of 93
A variable declaration is useful when you are using multiple files and you define your variable in one of
the files which will be available at the time of linking the program. You will use the keyword extern to declare a
variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only
once in a file, a function, or a block of code.
Example:
Try the following example, where variables have been declared at the top, but they have been defined
and initialized inside the main function:
#include<stdio.h>
// Variable declaration:
extern int a, b;
extern int c;
extern float f;
int main ()
{
/* variable definition: */
int a, b;
int c;
float f;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
printf("value of c : %d \n", c);
f = 70.0/3.0;
printf("value of f : %f \n", f);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Page 45 of 93
int g = 20; // valid statement
Character Literals
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). Here, you have a list of such escape sequence codes:
#include<stdio.h>
int main()
{
printf("Hello\tWorld\n\n");
return 0;
}
When the above code is compiled and executed, it produces the following result:
Hello World
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.
IT 122: Introduction to C Programming 1
Page 46 of 93
You can break a long line into multiple lines using string literals and separating them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
Defining Constant
#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;
}
When the above code is compiled and executed, it produces the following result:
value of area : 50
You can use const prefix to declare constants with a specific type as follows:
#include<stdio.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area; area = LENGTH * WIDTH;
IT 122: Introduction to C Programming 1
Page 47 of 93
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of area : 50
Laboratory Exercises :
1. Create a program that will print.
SO UTH EAS T
H’ ELL\ O ? “
2. Create a program that will print “SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.” use at least 3
character literals.
Personal Activity:
1. Create a program that will print:
He\ll'o\' Wor l
Page 48 of 93
WEEK 8
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Storage Class
Operators Program
Relational Operators program
Logical Operators program
Assignment Operators program
Misc. Operator program
Objectives:
Explain the storage class and its four different types.
Explain what are operators.
Explain what are Logical, Relational and Operational Operators
Create different programs with logical, relational and operational operators
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 49 of 93
Storage Class
A storage class defines the scope (visibility) and life-time of variables and/or functions within a C Program.
They precede the type that they modify. We have four different storage classes in a C program:
auto
register
static
extern
{
int mount;
auto int month;
}
The example above defines two variables within the same storage class. ‘auto’ can only be used within
functions, i.e., local variables.
The register storage class is used to define local variables that should be stored in a register instead of
RAM. This means that the variable has a maximum size equal to the register size (usually one word) and can't have
the unary '&' operator applied to it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as counters. It should also be
noted that defining 'register' does not mean that the variable will be stored in a register. It means that it MIGHT be
stored in a register depending on hardware and implementation restrictions.
The static storage class instructs the compiler to keep a local variable in existence during the life-time of the
program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local
variables static allows them to maintain their values between function calls. The static modifier may also be applied
to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is
declared. In C programming, when static is used on a class data member, it causes only one copy of that member to
be shared by all the objects of its class.
Page 50 of 93
#include<stdio.h>
/* function declaration */
void func(void);
main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result:
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern storage class is used to give a reference of a global variable that is visible to ALL the
program files. When you use 'extern', the variable cannot be initialized, however, it points the variable name at a
storage location that has been previously defined.
When you have multiple files and you define a global variable or function, which will also be used in other
files, then extern will be used in another file to provide the reference of defined variable or function. Just for
understanding, extern is used to declare a global variable or function in another file.
Operators
We discussed the meaning and types of operators (Week 2) now try the following example to
understand all the arithmetic operators available in C.
Page 51 of 93
Arithmetic Operator
#include<stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 - Value of c is %d\n", c );
c = a - b;
printf("Line 2 - Value of c is %d\n", c );
c = a * b;
printf("Line 3 - Value of c is %d\n", c );
c = a / b;
printf("Line 4 - Value of c is %d\n", c );
c = a % b;
printf("Line 5 - Value of c is %d\n", c );
c = a++;
printf("Line 6 - Value of c is %d\n", c );
c = a--;
printf("Line 7 - Value of c is %d\n", c );
return 0;
}
When you compile and execute the above program, it produces the following result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Example:
1. Create a program that will sum two numbers 5 and 6.
#include<stdio.h>
int main()
{
int a, b, sum;
a = 5;
b = 6;
sum = a + b;
printf(“%d”,sum);
return 0; }
Page 52 of 93
2. Create a program that will sum two numbers entered by the user.
#include<stdio.h>
int main()
{
int a, b, sum;
printf(“Enter the data for the first number: “);
scanf(“%d”,&a);
printf(“Enter the data for the second number: “);
scanf(“%d”,&b);
sum = a + b;
printf(“%d”,sum);
return 0;
}
Page 53 of 93
Relational Operators
#include<stdio.h>
main()
{
int a = 21;
int b = 10;
int c ;
if( a == b )
{
printf("Line 1 - a is equal to b\n" );
}
else
{
printf("Line 1 - a is not equal to b\n" );
}
if ( a < b )
{
printf("Line 2 - a is less than b\n" );
}
else
{
printf("Line 2 - a is not less than b\n" );
}
if ( a > b )
{
printf("Line 3 - a is greater than b\n" );
}
else
{
printf("Line 3 - a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b )
{
printf("Line 4 - a is either less than or equal to b\n" );
}
if ( b >= a )
{
printf("Line 5 - b is either greater than or equal to b\n" );
}
}
When you compile and execute the above program, it produces the following result:
Page 54 of 93
Logical Operators
#include<stdio.h>
main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
printf("Line 1 - Condition is true\n" );
}
if ( a || b )
{
printf("Line 2 - Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true\n" );
}
else
{
printf("Line 3 - Condition is not true\n" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true\n" );
}
}
When you compile and execute the above program, it produces the following result:
Page 55 of 93
Assignment Operator
#include<stdio.h>
main()
{
int a = 21;
int c ;
c = a;
printf("Line 1 - = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 - += Operator Example, Value of c = %d\n", c );
c -= a;
printf("Line 3 - -= Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 - *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 - /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 - %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 - <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 - >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 - &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 - ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 - |= Operator Example, Value of c = %d\n", c );
}
When you compile and execute the above program, it produces the following result:
Page 56 of 93
Misc Operator ↦ sizeof & ternary
#include<stdio.h>
main()
{
int a = 4;
short b;
double c;
int* ptr;
/* example of sizeof operator */
printf("Line 1 - Size of variable a = %d\n", sizeof(a) );
printf("Line 2 - Size of variable b = %d\n", sizeof(b) );
printf("Line 3 - Size of variable c= %d\n", sizeof(c) );
/* example of & and * operators */
ptr = &a;
/* 'ptr' now contains the address of 'a'*/
printf("value of a is %d\n", a);
printf("*ptr is %d.\n", *ptr);
/* example of ternary operator *
/ a = 10;
b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );
b = (a == 10) ? 20: 30;
printf( "Value of b is %d\n", b );
}
When you compile and execute the above program, it produces the following result:
value of a is 4 *ptr is 4.
Value of b is 30
Value of b is 20
Laboratory Exercises :
1. Write the output of the program:
#include<stdio.h>
int main()
{
int a, b, c;
a=5;
b=a;
c=b+2;
printf("%d",c);
return 0;
}
Page 57 of 93
2. Write is the output is the program:
#include<stdio.h>
int main(){
int a, b, c;
a=4, b=3;
c= a + b;
c++;
printf("%d",c);
return 0;
}
Personal Activity
1. Create a program that will check if a person can vote or not. Use logical operators.
2. Create a program that will convert centimeter to kilometers.
3. Create a program that will find the area of a triangle.
Page 58 of 93
WEEK 9
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Objectives:
State additional feature like nested ifs.
Be able to make use of logical operators with if statement.
Develop a number of programs using these various control statements
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 59 of 93
Decision Making
Decision-making structures require that the programmer specifies one or more conditions to be evaluated or
tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and
optionally, other statements to be executed if the condition is determined to be false.
Shown below is the general form of a typical decision-making structure found in most of the programming
languages:
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then
it is assumed as false value.
C programming language provides the following types of decision-making statements.
STATEMENT DESCRIPTION
if statement An if statement consists of a Boolean expression
followed by one or more statements.
if...else statement An if statement can be followed by an optional else
statement, which executes when the Boolean
expression is false.
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.
nested switch statements You can use one switch statement inside another
switch statement(s).
if Statement
Syntax:
The syntax of an ‘if’ statement in C programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the Boolean expression evaluates to true, then the block of code inside the ‘if’ statement will be executed. If
the Boolean expression evaluates to false, then the first set of code after the end of the ‘if’ statement (after the closing curly
brace) will be executed.
C programming language assumes any non-zero and non-null values as true and if it is either zero or null, then
it is assumed as false value.
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* check the boolean condition using if statement */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Page 60 of 93
a is less than 20;
value of a is : 10
if…else Statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
Syntax
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the Boolean expression evaluates to true, then the if block will be executed, otherwise, the else block will be
executed.
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is
assumed as false value.
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
/* check the boolean condition */
if( a < 20 )
{
/* if condition is true then print the following */
printf("a is less than 20\n" );
}
else
{
/* if condition is false then print the following */
printf("a is not less than 20\n" );
}
printf("value of a is : %d\n", a);
return 0;
}
When the above code is compiled and executed, it produces the following result:
Page 61 of 93
1. Create a program to find the maximum between two numbers using if…else
#include <stdio.h>
int main()
{
int num1, num2, max;
/* Input two numbers from user */
printf("Enter two numbers: ");
scanf("%d%d", &num1, &num2);
/* Compare num1 with num2 */
if(num1 > num2)
max = num1;
else
max = num2;
printf("%d is maximum.", max);
return 0;
}
Output:
#include <stdio.h>
int main()
{
int num;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
/*
* If num modulo division 5 is 0
* and num modulo division 11 is 0 then
* the number is divisible by 5 and 11 both
*/
if((num % 5 == 0) && (num % 11 == 0))
{
printf("Number is divisible by 5 and 11");
}
else
{
printf("Number is not divisible by 5 and 11");
}
return 0;
}
Output
Page 62 of 93
if...else if...else Statement
An if statement can be followed by an optional else if...else statement, which is very useful to test various
conditions using single if...else if statement.
When using if…else if…else statements, there are few points to keep in mind:
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be tested.
Syntax:
The syntax of an if...else if...else statement in C programming language is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
Page 63 of 93
}
printf("Exact value of a is: %d\n", a );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Nested if Statements
It is always legal in C programming to xnest if-else statements, which means you can use one if or else if
statement inside another if or else if statement(s).
Syntax:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if statements.
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
/* check the boolean condition */
if( a == 100 )
{
/* if condition is true then check the following */
if( b == 200 )
{
/* if condition is true then print the following */
printf("Value of a is 100 and b is 200\n" );
}
}
printf("Exact value of a is : %d\n", a );
printf("Exact value of b is : %d\n", b );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Page 64 of 93
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
1. Create a program to find maximum between given three numbers (using nested if else).
#include <stdio.h>
int main()
{
/* Declare three integer variables */
int num1, num2, num3;
/* Input three numbers from user */
printf("Enter three numbers: ");
scanf("%d%d%d", &num1, &num2, &num3);
if(num1 > num2)
{
if(num1 > num3)
{
/* If num1>num2 and num1>num3 */
printf("Num1 is max.");
}
else
{
/* If num1>num2 but num1<num3 */
printf("Num3 is max.");
}
}
else
{
if(num2 > num3)
{
/* If num1<num2 and num2>num3 */
printf("Num2 is max.");
}
else
{
/* If num1<num2 and num2<num3 */
printf("Num3 is max.");
}
}
return 0;
}
Output:
Page 65 of 93
Laboratory Exercises :
1. Create a program that will check if the number input is equal to 20. Print “True” if true, else print
“False”.
2. Create a program that will check if a number is divisible by 3 and 5. Print “Good’ if true, else print
“Try Again”.
Personal Activity:
1. Create a program that will calculate for the loss and profit.
Page 66 of 93
WEEK 10
COURSE OUTLINE
Content
Switch Statement
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Objectives:
Explain the switch statements
Develop a number of programs using various switch statements
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 67 of 93
switch Statement
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each switch case.
Syntax
switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
IT 122: Introduction to C Programming 1
Page 68 of 93
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break; case 'F' :
printf("Better try again\n" );
break;
default :
printf("Invalid grade\n" );
}
printf("Your grade is %c\n", grade );
return 0;
}
When the above code is compiled and executed, it produces the following result:
Example:
#include <stdio.h>
int main()
{
int week;
/* Input week number from user */
printf("Enter week number(1-7): ");
scanf("%d", &week);
switch(week)
{
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
IT 122: Introduction to C Programming 1
Page 69 of 93
case 7:
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
return 0;
}
Output:
#include <stdio.h>
int main()
{
char ch;
/* Input an alphabet from user */
printf("Enter any alphabet: ");
scanf("%c", &ch);
/* Switch value of ch */
switch(ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
printf("Vowel");
break;
default:
printf("Consonant");
}
return 0;
}
Output:
Page 70 of 93
Laboratory Exercises :
1. Create a program that will find the average of two numbers. Print the output base on the following
conditions:
If the average is equal to 5 print “Sad”.
If the average is equal to 10 print “Meh”.
If the average is equal to 15 print “Happy”.
Print Try again for default.
Expected Output:
First Number: 6
Second Number: 4
Arithmetic Operator: +
Output: 10
Personal Activity:
1. Create a program that will find the maximum between two numbers using switch case.
2. Create a program that will input a letter (A,B,C,D,F). Print the output base on the following
conditions:
If the letter is equal to A print “Excellent”
If the letter is equal to B print “Keep it Up”
If the letter is equal to C print “Well done”
If the letter is equal to D print “You passed!”
If the letter is equal to F print “Better luck next time”
Print “Invalid Case” for default
Page 71 of 93
WEEK 11
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Loops
While Loop
Objectives:
Explain the meaning of loops
Explain the loop constructs in C
Create a program with while loops
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 72 of 93
Loops
You may encounter situations when a block of code needs to be executed several number of times.
In general, statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times
C programming language provides the following types of loops to handle looping requirements.
while Loop
A while loop in C programming repeatedly executes a target statement as long as a given condition is
true.
Syntax:
The syntax of a while loop in C programming language is:
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression,
and true is any nonzero value. The loop iterates while the condition is true. When the condition becomes false, the
program control passes to the line immediately following the loop.
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
Page 73 of 93
a++;
}
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
#include <stdio.h>
int main()
{
int i, n;
return 0;
}
Output:
Page 74 of 93
2. Create a program to print natural numbers in reverse from n to 1.
#include <stdio.h>
int main()
{
int i, start;
printf("Enter starting value: ");
scanf("%d", &start);
i = start;
while(i>=1)
{
printf("%d\n", i);
i--;
}
return 0;
}
Output:
Laboratory Exercises :
Personal Activity:
1. Create a program that will check whether a number is a palindrome or not. Use While Loop Condition
Page 75 of 93
WEEK 12
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
For Loop
Objectives:
Explain the loop constructs in C
Create a program with for loops
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 76 of 93
for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax:
The syntax of a for loop in C programming language is:
Example:
#include<stdio.h>
int main ()
{
/* for loop execution */
for( int a = 10; a < 20; a = a + 1 )
{
printf("value of a: %d\n", a);
}
return 0;
}
Page 77 of 93
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
#include <stdio.h>
void main()
{
int i,n,sum=0;
printf("Input Value of terms : ");
scanf("%d",&n);
printf("\nThe first %d natural numbers are:\n",n);
for(i=1;i<=n;i++)
{
printf("%d ",i);
sum+=i;
}
printf("\nThe Sum of natural numbers upto %d terms : %d \n",n,sum);
return 0;
}
Output
Page 78 of 93
2. Create a program in C to read 10 numbers from keyboard and find their sum and average.
#include <stdio.h>
void main()
{
int i,n,sum=0;
float avg;
printf("Input the 10 numbers : \n");
for (i=1;i<=10;i++)
{
printf("Number-%d :",i);
scanf("%d",&n);
sum +=n;
}
avg=sum/10.0;
printf("The sum of 10 no is : %d\nThe Average is : %f\n",sum,avg);
return 0;
}
Output:
Laboratory Exercises :
Expected Output:
Input
Input number: 5
Output
5*1=5
5*2=10
5*10 = 50
2. Create a program that will find the sum of odd numbers from 1 to 10. Use (for loop)
Personal Activity:
1. Create a program that will find the LCM of two numbers.
2. Create a program that prompts the user to input an integer and then outputs the number with the digits
reversed. For example, if the input is 12345, the output should be 54321.
Page 79 of 93
WEEK 13
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Do While loop
Objectives:
Explain the loop constructs in C
Create a program with do-while loops
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 80 of 93
do…while
Loop Unlike for and while loops, which test the loop condition at the top of the loop, the do...while
loop in C programming checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least
one time.
Syntax :
The syntax of a do...while loop in C programming language is:
do
{
statement(s);
}
while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
executes again. This process repeats until the given condition becomes false.
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
printf("value of a: %d\n", a);
a = a + 1;
}
while( a < 20 );
return 0;
}
Page 81 of 93
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Example:
1. Create a program to find the sum of first and last digit using loop.
#include <stdio.h>
int main()
{
int num, sum=0, firstDigit, lastDigit;
/* Input a number from user */
printf("Enter any number to find sum of first and last digit: ");
scanf("%d", &num);
/* Find last digit to sum */
lastDigit = num % 10;
/* Copy num to first digit */
firstDigit = num;
/* Find the first digit by dividing num by 10 until first digit is left */
do{
num = num / 10;
}while(num >= 10);
firstDigit = num;
/* Find sum of first and last digit*/
sum = firstDigit + lastDigit;
printf("Sum of first and last digit = %d", sum);
return 0;
}
Output:
Enter any number to find sum of first and last digit: 12345
Sum of first and last digit = 6
Page 82 of 93
2. Create a program to find sum of digits of a number.
#include <stdio.h>
int main()
{
int num, sum=0;
/* Input a number from user */
printf("Enter any number to find sum of its digit: ");
scanf("%d", &num);
/* Repeat till num becomes 0 */
do{
/* Find last digit of num and add to sum */
sum += num % 10;
/* Remove last digit from num */
num = num / 10;
}while(num!=0);
printf("Sum of digits = %d", sum);
return 0;
}
Output:
Laboratory Exercises :
1. Create a program that will find the sum of even numbers from 300 to 450. Use do while loop.
2. Create a program that will loop if the number is equal to 1.
Personal Activity:
1. Create a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum
displayed. The loop should ask the user whether he or she wishes to perform the operation again. If so, the
loop should repeat; otherwise it should terminate.
Page 83 of 93
WEEK 14
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Nested loop
Objectives:
Explain the loop constructs in C
Create a program with nested loops
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
task given will be every Monday during your scheduled class hour.
Page 84 of 93
Nested Loops
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.
Syntax :
The syntax for a nested for loop statement in C is as follows:
The syntax for a nested while loop statement in C programming language is as follows:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows:
do {
statement(s);
do
{
statement(s);
}while( condition );
}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a
‘for’ loop can be inside a ‘while’ loop or vice versa.
Page 85 of 93
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#include<stdio.h>
int main ()
{
/* local variable definition */
int i, j;
for(i=2; i<100; i++){
for(i=2; i<= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j)) printf("%d is prime\n", i);
}
return 0;
When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Page 86 of 93
Example:
#include <stdio.h>
int main()
{
int i, num;
/* Input number from user */
printf("Enter any number to find its factor: ");
scanf("%d", &num);
printf("All factors of %d are: \n", num);
/* Iterate from 1 to num */
for(i=1; i<=num; i++)
{
/*
* If num is exactly divisible by i
* Then i is a factor of num
*/
if(num % i == 0)
{
printf("%d, ",i);
}
}
return 0;
}
Output:
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
Page 87 of 93
Output
*
**
***
****
*****
Laboratory Exercises :
Expected Output:
*****
****
***
**
*
*****
*****
*****
*****
*****
Personal Activity:
1. Create a program that will find the GCF of two numbers. Use nested loop.
Page 88 of 93
WEEK 15
COURSE OUTLINE
Overview:
C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the
UNIX operating system at Bell Labs. C was originally first implemented on the DEC PDP-11 computer in 1972. In 1978,
Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R
standard. The UNIX operating system, the C compiler, and essentially all UNIX application programs have been
written in C.
Content
Objectives:
Explain the loop constructs in C
Create a program with loops
Use break and continue statement in loops
Each chapter in this module contains a major lesson involving the use of Flowchart and its purpose. The units
are characterized by continuity, and are arranged in such a manner that the present unit is related to the next unit.
For this reason, you are advised to read this module. After each unit, there are exercises to be given. Submission of
IT 122: Introduction to C Programming 1
Page 89 of 93
task given will be every Monday during your scheduled class hour.
Page 90 of 93
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope,
all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
break Statement
Syntax
The syntax for a break statement in C is as follows:
break;
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* while loop execution */
while( a < 20 )
{
printf("value of a: %d\n", a);
a++;
if( a > 15)
{
/* terminate the loop using break statement */
break;
}
}
return 0;
}
Page 91 of 93
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
continue Statement
The continue statement in C programming works somewhat like the break statement. Instead of forcing
termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the for loop, continue statement causes the conditional test and increment portions of the loop to
execute. For the while and do...while loops, continue statement causes the program control to pass to the
conditional tests.
Syntax:
continue;
Example:
#include<stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Page 92 of 93
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this
purpose. Since none of the three expressions that form the ‘for’ loop are required, you can make an endless
loop by leaving the conditional expression empty.
Example:
#include<stdio.h>
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}
When the conditional expression is absent, it is assumed to be true. You may have an initialization and
increment expression, but C programmers more commonly use the for(;;) construct to signify an infinite loop.
Laboratory Exercises :
1. Create a program that will result in an Infinite Loop. Use do while loop.
#include<stdio.h>
int main(){
int i=1;
while(1)
{
if(i > 10)
break;
printf("%d",i);
i++;
}
return 0;
}
Personal Activity:
1. Create a program that contains one break and one continue. Use any looping statements.
Page 93 of 93