0% found this document useful (0 votes)
24 views93 pages

It 122 1

This document outlines the course code, title, target population, instructor, overview, content, objectives, and instructions for the Introduction to C Programming 1 course. The content includes the history of C, flowcharts, variables, and identifiers. The objectives are to describe and explain flowcharts and their uses and to construct a program using a flowchart process. Learners are advised to read the module and complete exercises each week.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views93 pages

It 122 1

This document outlines the course code, title, target population, instructor, overview, content, objectives, and instructions for the Introduction to C Programming 1 course. The content includes the history of C, flowcharts, variables, and identifiers. The objectives are to describe and explain flowcharts and their uses and to construct a program using a flowchart process. Learners are advised to read the module and complete exercises each week.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 93

WEEK 2

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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:

 Describe the meaning of flowchart and its uses.


 Explain the types of flowchart and its uses.
 Construct a program with flowchart process.

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

 Operating Systems  Network Drivers


 Language Compilers  Modern Programs
 Assemblers  Databases
 Text Editors  Language Interpreters
 Print Spoolers  Utilities

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.

Guidelines for Developing Flowcharts


These are some points to keep in mind while developing a flowchart −
 Flowchart can have only one start and one stop symbol
 On-page connectors are referenced using numbers
 Off-page connectors are referenced using alphabets
 General flow of processes is top to bottom or left to right
 Arrows should not cross each other

Flowchart Symbols
Here is a chart for some of the common symbols used in drawing flowcharts.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

Used for denoting program inputs


Input/ Output and outputs.

Stands for decision statements in a


program, where answer is usually
Yes or No.
Decision

Shows relationships between


different shapes.
Arrow

Connects two or more parts of a


flowchart, which are on the same
page.
On-page Connector

Connects two parts of a flowchart


which are spread over different
Off-page Connector pages.

Differentiates between steps that


prepare for work and steps that
Preparation/Initialization actually do work. It helps introduce
the setup to another step within
the same 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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 3 of 93
Thus, Manpower and manpower are two different identifiers in C. Here are some examples of acceptable identifiers:

Mohd zara abc move_name a23b9

retVal a_123 myname50 _temp j

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 4 of 93
Example of Flow Chart

- Start of the process

- Initializing/Declaring variable

- Storing data to the variable

- Printing the data from the variable

- End of Process
END

Example:

Here is a flowchart how to login on Facebook:

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 5 of 93
Sum of Two Numbers

- Start of the program

- Initialize a, b, and sum as int

- Input data value for the variables a and b

- Add a and b. The answer


will be stored in variable sum.

- Display the value of the variable sum

- End of the program

Draw a flowchart that will find the sum of two numbers.

- Start

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 6 of 93
- Initialize two numbers ( a and b ), and sum

- Input a = 5 and b = 6

- sum = 5 + 6

- sum = 11

- End

Flowchart to Input and Output a name

- Start of the Program

- Initialize name as char

- Input data value for the variable name

- Display output

- End of the Program

Draw a flowchart that will solve for the average of two numbers.

- Start of the Program

- Initialize the two numbers ( a and b) and the average

- Input data value of the two numbers ( a and b)

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 7 of 93
- Solve for the average of the two numbers. The answer will be stored in
the average.

- Display the average.

- End of the Program

NOTE: Follow PEMDAS (Parenthesis, Exponents, Multiplication, Division, Addition, Subtraction) rule.

Example:

Draw a flowchart that will find the average of two numbers

- Start

- Initialize the two numbers ( a


and b), and average.

- Input a = 20 and b = 10

- Average = (20 + 10 ) / 2

Print - Average = 15
average

- End

Draw a flowchart that will swap the data of two numbers.

- Start of the Program

- Initialize the two numbers ( a, b) and c


IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

- End of the Program

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 10 of 93
WEEK 3

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

OPERATOR DESCRIPTION EXAMPLE


+ Adds two operands. A + B = 30
- Subtracts second operand from A - B = -10
the first.
* Multiplies both operands. A * B = 200
/ Divides numerator by de- B/A=2
numerator.
% Modulus Operator and remainder B%A=0
of after an integer division.
++ Increment operator increases the A++ = 11
integer value by one.
-- Decrement operator decreases the A-- = 9
integer value by one.

Relational Operators

The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20, then:

OPERATOR DESCRIPTION EXAMPLE


== Checks if the values of two (A == B) is not true.
operands are equal or not. If yes,
then the condition becomes true.
!= Checks if the values of two (A != B) is true.
operands are equal or not. If the
values are not equal, then the
condition becomes true.
> Checks if the value of left operand (A > B) is not true.
is greater than the value of right
operand. If yes, then the condition
becomes true.
< Checks if the value of left operand (A < B) is true.
is less than the value of right
operand. If yes, then the condition
becomes true.
>= Checks if the value of left operand (A >= B) is not true.
is greater than or equal to the
value of right operand. If yes, then
the condition becomes true.
<= Checks if the value of left operand (A <= B) is true.
is less than or equal to the value of
IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

OPERATOR DESCRIPTION EXAMPLE


&& Called Logical AND operator. If (A && B) is false.
both the operands are non-zero,
then the condition becomes true.
|| Called Logical OR Operator. If any (A || B) is true.
of the two operands is non-zero,
then the condition becomes true
! Called Logical NOT Operator. It is !(A && B) is true.
used to reverse the logical state of
its operand. If a condition is true,
then Logical NOT operator will
make it false.

Assignment Operators

The following tables lists the assignment operators supported by the C language:

OPERATOR DESCRIPTION EXAMPLE


= Simple assignment operator. C = A + B will assign the value of A
Assigns values from right side + B to C
operands to left side operand.
+= Add AND assignment operator. It C += A is equivalent to C = C + A
adds the right operand to the left
operand and assigns the result to
the left operand.
-= Subtract AND assignment C -= A is equivalent to C = C - A
operator. It subtracts the right
operand from the left operand and
assigns the result to the left
operand.
*= Multiply AND assignment operator. C *= A is equivalent to C = C * A
It multiplies the right operand with
the left operand and assigns the
result to the left operand.
/= Divide AND assignment operator. It C /= A is equivalent to C = C / A
divides the left operand with the
right operand and assigns the
result to the left operand.
%= Modulus AND assignment C %= A is equivalent to C = C % A
operator. It takes modulus using
two operands and assigns the
result to the left operand.
<<= Left shift AND assignment C <<= 2 is same as C = C << 2
operator.
>>= Right shift AND assignment C >>= 2 is same as C = C >> 2
operator.
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and C ^= 2 is same as C = C ^ 2
assignment operator.
|= Bitwise inclusive OR and C |= 2 is same as C = C | 2
IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 13 of 93
assignment operator.

Misc Operators ↦sizeof & ternary

Besides the operators discussed above, there are a few other important operators including sizeof and ? :
supported by the C Language.

OPERATOR DESCRIPTION EXAMPLE


Sizeof() Returns the size of a variable. sizeof(a), where a is integer, will
return 4.
& Returns the address of a variable &a; returns the actual address of
the variable.
* Pointer to a variable. *a;
?: Conditional Expression. If Condition is true ? then value X :
otherwise value Y

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.

CATEGORY OPERATOR ASSOCIATIVITY


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Left to right
Assignment = += -= *= /= %=>>= <<= &= ^= |= Left to right
Comma , Left to right

Flowchart with 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:

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

An if statement consists of a Boolean expression followed by one or more statements.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

If else statement Flowchart

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

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

6 == 6 true Print Share

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

5 >= 10 && 5 >= 2

False

10 >= 5 && 10 >= 2 True Print “b is


a the largest
c number”

IT 122: Introduction to C Programming 1


End
SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

2. Draw a flowchart that will check if a Leap Year.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 19 of 93
WEEK 4

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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.

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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 following rules apply to a switch statement:

 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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

case ‘M’ True

Print male

End

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

case 0 True The


number
is even

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:

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a ? expression is determined like this:

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:

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 24 of 93
C programming language provides the following types of loops to handle looping requirements.

LOOP TYPE DESCRIPTION


While Loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
For Loop Executes a sequence of statements multiple times
and abbreviates the code that manages the loop
variable.
Do While Loop It is more like a while statement, except that it tests
the condition at the end of the loop body.
Nested Loop You can use one or more loops inside any other
while, for, or do..while loop.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 25 of 93
Example:

1. Flowchart that will print numbers from 1 to 10 using while loop.

2. Flowchart that will print numbers from 1 to 10 using while loop in reverse.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 27 of 93
WEEK 5

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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 in flowchart


 do while loop in flowchart
 nested loop in flowchart
 Loop Control Statement
 The infinite loop

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

Here is the flow of control in a ‘for’ loop:


1. The initialization step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a semicolon
appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body
of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’
loop.
3. After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment
statement. This statement allows you to update any loop control variables. This statement can be left
blank, as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process repeats itself
(body of loop, then increment step, and then again condition). After the condition becomes false, the
‘for’ loop terminates.
Example:

1. Flowchart that will print natural numbers from 1 to 10 using for loop.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 30 of 93
Example:

1. Flowchart that will count total digits in a given integer using do while loop.

2. Flowchart that will print the alphabets from a – z;

Nested Loop
C programming allows to use one loop inside another loop. The following section shows a few
examples to illustrate the concept.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 31 of 93
Example:

1. Flowchart that will print even numbers using nested loop.

2. Flowchart that will print right triangle star pattern using nested loop.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

2. Draw a flowchart that will find the first digit of a number.

Example:

Input: 46765

Output: 4

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 34 of 93
WEEK 6

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

Hello World Example


A C program basically consists of the following parts:
 Preprocessor Commands
 Functions
 Variables
 Statements & Expressions
 Comments
Let us look at a simple code that would print the words "Hello World":

#include <stdio.h>

int main()

/* my first program in C */

printf("Hello, World! \n");

return 0;

Let us take a look at the various parts of the above program:


1. The first line of the program #include is a preprocessor command, which tells a C compiler to include stdio.h
file before going to actual compilation.
2. The next line int main() is the main function where the program execution begins.
3. The next line /*...*/ will be ignored by the compiler and it has been put to add additional comments in the
program. So such lines are called comments in the program.
4. The next line printf(...) is another function available in C which causes the message "Hello, World!" to be
displayed on the screen.
5. The next line return 0; terminates the main() function and returns the value 0.

Compile and Execute C Program

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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("Hello, World! \n");

The individual tokens are:

printf

"Hello, World! \n"

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:

printf("Hello, World! \n");

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

fruit = apples + oranges; // get the total fruit

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 getchar() and putchar() Functions

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;

printf( "Enter a value :");


c = getchar( );

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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 –

Enter a value : this is test


You entered: t

The gets() and puts() Functions


The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s until either a
terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to stdout.

#include <stdio.h>
int main( ) {

char str[100];

printf( "Enter a value :");


gets( str );

printf( "\nYou entered: ");


puts( str );

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 –

Enter a value : this is test


You entered: this is test

The scanf() and printf() Function


The int scanf(const char *format, ...) function reads the input from the standard input
stream stdin and scans that input according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard output
stream stdout and produces the output according to the format provided.
The format can be a simple constant string:

FORMAT STRING MEANING

%d Scan or print an integer as signed decimal number

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 39 of 93
%f Scan or print a floating point number

%c To scan or print a character

%s To scan or print a character string. The scanning ends at whitespace.

Example:

#include <stdio.h>
int main( ) {

char str[100];
int i;

printf( "Enter a value :");


scanf("%s %d", str, &i);

printf( "\nYou entered: %s %d ", str, 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 −

Enter a value : seven 7


You entered: seven 7

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:

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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()

printf("Storage size for int : %d \n", sizeof(int));

return 0; }

When you compile and execute the above program, it produces the following result:

Storage size for int : 4

Floating-Point Types
The following table provides the details of standard floating-point types with storage sizes and value
and their precision:

TYPES STORAGE SIZE VALUE RANGE PRECISION


float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

The void Type


The void type specifies that no value is available. It is used in three kinds of situations:

S.N. TYPES AND DESCRIPTION


Function returns as void
1 There are various functions in C which do not return any value or you can say they return void. A
function with no return value has the return type as void. For example, void exit (int status);
Function arguments as void
2 There are various functions in C which do not accept any parameter. A function with no
parameter can accept a void. For example, int rand(void);
3 Pointers to void
A pointer of type void * represents the address of an object, but not its type. For example, a
memory allocation function void *malloc(size_t size); returns a pointer to void which can be
IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 42 of 93
WEEK 7

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

type variable_name = value;

Some examples are:

extern int d = 3, f = 5; // declaration of d and f.

int d = 3, f = 5; // definition and initializing d and f.

byte z = 22; // definition and initializes z.

char x = 'x'; // the variable x has the value 'x'.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

value of c : 30 value of f : 23.333334

Lvalues and Rvalues in C


There are two kinds of expressions in C:
 lvalue : Expressions that refer to a memory location are called "lvalue" expressions. An lvalue may
appear as either the left-hand or right-hand side of an assignment.
 rvalue : The term rvalue refers to a data value that is stored at some address in. An rvalue is an
expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not
on the left-hand side of an assignment.
Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are
rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid
and invalid statements:

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 45 of 93
int g = 20; // valid statement

10 = 20; // invalid statement; would generate compile-time error

Constant and Literals


Constants refer to fixed values that the program may not alter during its execution. These fixed values are
also called literals.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character
constant, or a string literal. There are enumeration constants as well.
Constants are treated just like regular variables except that their values cannot be modified after their
definition.

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:

ESCAPE SEQUENCE MEANING


\\ \ character
\’ ‘ character
\” “ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\ooo Octal number of one to three digits
\xhh… Hexadecimal number of one or more digits

Following is the example to show a few escape sequence characters:

#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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

There are two simple ways in C to define constants:


 Using #define preprocessor
 Using const keyword

The #define Preprocessor


Given below is the form to use #define preprocessor to define a constant:

#define identifier value

The following example explains it in detail:

#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

The const Keyword

You can use const prefix to declare constants with a specific type as follows:

const type variable = value;

The following example explains it in detail:

#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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

Note that it is a good programming practice to define constants in CAPITALS.

Laboratory Exercises :
1. Create a program that will print.

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 48 of 93
WEEK 8

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

The auto Storage Class


The auto storage class is the default storage class for all local variables.

{
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

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

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 50 of 93
#include<stdio.h>

/* function declaration */
void func(void);

static int count = 5; /* global variable */

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

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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; }

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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;
}

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Line 1 - a is not equal to b


Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Line 1 - Condition is true


Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Line 1 - = Operator Example, Value of c = 21


Line 2 - += Operator Example, Value of c = 42
Line 3 - -= Operator Example, Value of c = 21
Line 4 - *= Operator Example, Value of c = 441
Line 5 - /= Operator Example, Value of c = 21
Line 6 - %= Operator Example, Value of c = 11
Line 7 - <<= Operator Example, Value of c = 44
Line 8 - >>= Operator Example, Value of c = 11
Line 9 - &= Operator Example, Value of c = 2
Line 10 - ^= Operator Example, Value of c = 0
Line 11 - |= Operator Example, Value of c = 2

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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;
}

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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;
}

3. Create a program that will find the sum of two numbers.


4. Create a program that will find the average of 3 numbers.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 58 of 93
WEEK 9

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

 Decision making program

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

An if statement consists of a Boolean expression followed by one or more statements.

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:

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

The syntax of an if...else statement in C programming language is:

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:

a is not less than 20;


value of a is : 100

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Enter two numbers: 10 12


12 is maximum

2. Create a program check whether a number is divisible by 5 and 11 or not.

#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

Enter any number: 55


Number is divisible by 5 and 11

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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;

/* check the boolean condition */


if( a == 10 )
{
/* if condition is true then print the following */
printf("Value of a is 10\n" );
}
else if( a == 20 )
{
/* if else if condition is true */
printf("Value of a is 20\n" );
}
else if( a == 30 )
{
/* if else if condition is true */
printf("Value of a is 30\n" );
}
else
{
/* if none of the conditions is true */
printf("None of the values is matching\n" );

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

None of the values is matching


Exact value of a is: 100

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:

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Enter three numbers:


10
20
30
Num3 is max.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 66 of 93
WEEK 10

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

The syntax for a switch statement in C programming language is as follows:

switch(expression)
{
case constant-expression :
statement(s);
break; /* optional */
case constant-expression :
statement(s);
break; /* optional */

/* you can have any number of case statements */


default : /* Optional */
statement(s);
}

The following rules apply to a switch statement:


 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.
 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.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true. No break is needed
in the default case.

Example:

#include<stdio.h>
int main ()
{
/* local variable definition */
char grade = 'B';
switch(grade)
{
case 'A' :
IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Well done Your grade is B

Example:

1. Create a program to print day of week name using switch case

#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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 69 of 93
case 7:
printf("Sunday");
break;
default:
printf("Invalid input! Please enter week number between 1-7.");
}
return 0;
}

Output:

Enter week number (1-7): 3


Wednesday

2. Create a program to check vowel or consonant using switch case

#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:

Enter any alphabet: P


Consonant

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

2. Create a program to create Simple Calculator.

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

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 71 of 93
WEEK 11

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

LOOP TYPE DESCRIPTION


While Loop Repeats a statement or group of statements while a
given condition is true. It tests the condition before
executing the loop body.
For Loop Executes a sequence of statements multiple times
and abbreviates the code that manages the loop
variable.
Do While Loop It is more like a while statement, except that it tests
the condition at the end of the loop body.
Nested Loop You can use one or more loops inside any other
while, for, or do..while loop.

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;

/* while loop execution */


while( a < 20 )
{
printf("value of a: %d\n", a);
IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

1. Create a program to print natural numbers from 1 to n.

#include <stdio.h>
int main()
{
int i, n;

printf("Enter any number: ");


scanf("%d", &n);

printf("Natural numbers from 1 to %d : \n", n);


i = 1;
while( i<=n)
{
printf("%d\n", i);
i++;
}

return 0;
}

Output:

Enter any number: 5


Natural numbers from 1 to 10:
1
2
3
4
5

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Enter starting value: 9


Enter end value: 3
9
8
7
6
5
4
3

Laboratory Exercises :

1. Create a program that will print “Good” 10 times.


2. Create a program that will find the sum of numbers between 30 to 40. Use while loop statement.

Personal Activity:
1. Create a program that will check whether a number is a palindrome or not. Use While Loop Condition

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 75 of 93
WEEK 12

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

for ( init; condition; increment )


{
statement(s);
}

Here is the flow of control in a ‘for’ loop:


1. The init step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and the flow of control jumps to the next statement just after the ‘for’
loop.
3. After the body of the ‘for’ loop executes, the flow of control jumps back up to the
increment statement. This statement allows you to update any loop control variables. This statement can be left
blank, as long as a semicolon appears after the condition.
4. The condition is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false,
the ‘for’ loop terminates.

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;
}

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

1. Create a program to display n terms of natural number and their sum.

#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

The first 7 natural number is :


1234567
The Sum of Natural Number up to 7 terms : 28

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Input the 10 numbers :


Number-1 :2
...
Number-10 :2
Expected Output :
The sum of 10 no is : 55
The Average is : 5.500000

Laboratory Exercises :

1. Create a program that will print multiplication table of a given number.

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 79 of 93
WEEK 13

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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;
}

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

Enter any number to find sum of its digit: 1234


Sum of digits = 10

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 83 of 93
WEEK 14

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

for ( init; condition; increment )


{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}

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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 86 of 93
Example:

1. Create a program to find any factors of any number

#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:

Enter any number to find its factor: 100

All factors of 100 are:


1, 2, 4, 5, 10, 20, 25, 50, 100

2. Create a program that will print half pyramid of *

#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;
}

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 87 of 93
Output

*
**
***
****
*****

Laboratory Exercises :

1. Create a program that will print half pyramid of * in reverse.

Expected Output:

*****
****
***
**
*

2. Create a program that will print:

*****
*****
*****
*****
*****

Personal Activity:

1. Create a program that will find the GCF of two numbers. Use nested loop.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 88 of 93
WEEK 15

COURSE OUTLINE

COURSE CODE : IT 122


TITLE : Introduction to C Programming 1
TARGET POPULATION : All BS Information Technology Students
INSTRUCTOR : MR. PINK FLOYD B. JANEO

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

 Loop control statement


 Break Statement
 Continue Statement
 Infinite Loop

Objectives:
 Explain the loop constructs in C
 Create a program with loops
 Use break and continue statement in loops

Instruction to the Learner

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

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 89 of 93
task given will be every Monday during your scheduled class hour.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

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.

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.

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;
}

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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:

The syntax for a continue statement in C is as follows:

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

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

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.

NOTE: You can terminate an infinite loop by pressing Ctrl + C keys.

Laboratory Exercises :
1. Create a program that will result in an Infinite Loop. Use do while loop.

2. What is the output of this program:

#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.

IT 122: Introduction to C Programming 1

SOUTH EAST ASIAN INSTITUTE OF TECHNOLOGY, INC.

Page 93 of 93

You might also like