0% found this document useful (0 votes)
41 views64 pages

Programming - Final Arc

This document provides an introduction to C programming basics. It discusses what computer programming and programming languages are. It then outlines the five stages of the computer programming process: problem statement, algorithm development, program coding, program testing, and program documentation. It also discusses common programming errors like syntax errors, runtime errors, and logic errors. Finally, it introduces the C programming language and environment Turbo C, describing its history, components, and general program structure.

Uploaded by

skew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views64 pages

Programming - Final Arc

This document provides an introduction to C programming basics. It discusses what computer programming and programming languages are. It then outlines the five stages of the computer programming process: problem statement, algorithm development, program coding, program testing, and program documentation. It also discusses common programming errors like syntax errors, runtime errors, and logic errors. Finally, it introduces the C programming language and environment Turbo C, describing its history, components, and general program structure.

Uploaded by

skew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

C Programming Basics

LESSON 1
Introduction

Welcome to the world of programming! In this course, you will learn how to write a program using Turbo
C.

What is computer programming?

Computer programming is creating a sequence of instructions to enable the computer to do something.

What is programming language?

A programming language is an artificial language that can be used to control the behavior of a machine,
particularly a computer.

Computer programming has five stages.

1. Problem statement. The programming process begins with a clear, written statement of the
problem to be solved by the computer.
2. Algorithm development: Once the problem has been clearly stated and all the requirements have
been understood, the next step is to develop the program logic necessary for accomplishing the
task.
An algorithm is defined as a logical sequence of steps that must be performed in order to
accomplish a given task.
Sample Tool: Flowchart
3. Program coding: When the programmer is satisfied with the efficacy of the logic developed in the
preceding step, it is time to convert that logic (in either flowchart or pseudocode form) to the
specific syntax of the programming language that will be used.
4. Program testing: The coded program is next checked for errors.
5. Program documentation: The programming process is complete when the program has been fully
documented.

Before we start with learning how to write C codes, let’s have first the three common programming errors.

1. Syntax error occurs when your code violates one or more grammar rules of C and is detected by
the compiler as it attempts to translate your program. Note that if a statement has a syntax error,
it cannot be translated and your program will not be executed.
2. Run-time error is a detected error and displayed by the compiler during the execution of the
program. It occurs when the program directs the computer to perform illegal operation, such as
dividing a number by zero or an attempt to perform an invalid operation, and detected during
program execution. When a run-time error occurs, the computer will stop executing your program
and will display a diagnostic message that indicates the line where the error was detected.
3. Logic Errors occur when a program follows a faulty algorithm. It does not cause a run-time error
and does not display error messages, so is very difficult to detect. The only sign of a logic error
may be incorrect program output.

Brief Turbo C History

Turbo C was developed by Dennis MacAlistair Ritchie at AT&T Bell Laboratories.

What is Turbo C?
C Programming Basics

Turbo C is an Integrated Development Environment and compiler for the C programming language from
Borland. First introduced in 1987, it was noted for its integrated development environment, small size,
extremely fast compile speed, comprehensive manuals and low price.

LESSON 2
Turbo C General Structure

Let’s start!

The following is the Turbo C general structure.


Preprocessor Directives
int main(void){
local declarations
statements
}

The following is your first sample program.

#include <stdio.h>
int main(void) {
printf("Hello World!\n");
return 0;
}
Now, let’s understand the structure.

The C Preprocessor is a program that is executed before the source code is compiled.

Directives are how C preprocessor commands are called, and begin with a pound / hash symbol (#). No
white space should appear before the #, and a semi colon is NOT required at the end.

There are two directives in C, namely, include and define. For this section, we will first get to know and
use include.

#include gives program access to a library. It tells the preprocessor that some names used in the program
are found in the standard header file. It causes the preprocessor to insert definitions from a standard
header file into the program before compilation.

For example:

#include<stdio.h> tells the preprocessor to open the library “stdio.h” that contains built-in
functions like scanf and printf.

Every C program has a main function. This is where program execution begins. Note that you cannot
change the name of main.
C Programming Basics

Braces {} enclose the body of the function and indicate the beginning and end of the function main.

Main has two parts.

1. Declaration is the part of the program that tells the compiler the names of memory cells in a
program needed in the function, commonly data requirements identified during problem analysis
C Programming Basics

Example:
int num1, num2, sum;

2. Executable statements are derived statements from the algorithm into machine language and
later executed.

Example:
printf(“Enter 2 numbers: ”);
scanf(“%d%d”,&num1,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
return 0;

The complete program is shown below.

Try this!
#include<stdio.h>
int main(void) {
int num1, num2, sum;
printf(“Enter 2 numbers: ”);
scanf(“%d%d”,&num1,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
return 0;
}

Note: The programs inside the textboxes are executable.


C Programming Basics

LESSON 3

Variable Declaration

As a programmer, one of the most important things to consider is how to allocate memory that would
handle the data.

Variable declaration is a statement that communicates to the C compiler the names of all variables used
in the program and the kind of information stored in each variable. It also tells how that information will
be represented in memory.

In C, a variable is declared before a pre-defined function.

Here is the syntax for declaration:


Data type variable list;

Examples:
int x,age; float
sum,a,b;
char middle_intial;

What is a data type?

Data Type is a set of values and a set of operations that can be performed on those values.

The following are the standard pre-defined data types in C:

1. char

2. double

3. int

The three data types above have the following modifiers.

 short

 long

 signed

 unsigned

The modifiers define the amount of storage allocated to the variable. The amount of storage allocated is
not cast in stone. ANSI has the following rules:

short int <= int <= long int

float <= double <= long double

Seven Basic C Data Types:

1. Text (data type char) – made up of single characters (example x,#,9,E) and strings (“Hello”), usually
C Programming Basics

8 bits, or 1 byte with the range of 0 to 255.


C Programming Basics

2. Integer values – those numbers you learned to count with.

3. Floating-point values – numbers that have fractional portions such as 12.345, and exponents
1.2e+22.

4. Double-floating point values – have extended range of 1.7e-308 to 1.7e+308.

5. Enumerated data types – allow for user-defined data types.

6. void – signifies values that occupy 0 bit and have no value. You can also use this type to create
generic pointers.

7. Pointer – does not hold information as do the other data types. Instead, each pointer contains the
address of the memory location.

Explaining each of the data types:

int is used to define integer numbers.

Example:

int Count; Count =

5;

float is used to define floating point numbers.

Example:

float Miles;

Miles = 5.6;

double is used to define BIG floating point numbers. It reserves twice the storage for the number.

Example:

double Atoms;

Atoms = 2500000;

char defines characters.

Example:

char Letter;

Letter = 'x';

What is a variable?

Variable is like a container in your computer's memory - you can store a value in it and retrieve or modify
it when necessary. It is associated with a memory cell whose value can change as the program executes.
Sequential Control Structure

A variable is an identifier. An identifier is name that identifies or labels the identity of an object. In C, the
following are the naming conventions for an identifier.

1. Names are made up of letters and digits.

2. The first character must be a letter.

3. C is case-sensitive, example ‘s’ is not the same with ‘S’.

4. The underscore symbol (_) is considered as a letter in C. It is not recommended to be used,


however, as the first character in a name.

5. At least the first 3 characters of a name are significant.

6. It should not be a reserved word/keyword in C.

Examples:

Names... Example
CANNOT start with a number 2i

CAN contain a number elsewhere h2o

CANNOT contain any arithmetic operators... r*s+t

CANNOT contain any other punctuation marks... #@x%£!!a

CAN contain or begin with an underscore _height_

CANNOT be a C keyword struct

CANNOT contain a space im stupid

CAN be of mixed cases XSquared

The following is an example of a variable declaration.


int num;

Here is another one.

int num, num2;

Here is another one.


int num, num2, sum=0;

The previous example has a variable sum that is initialized during declaration.
Sequential Control Structure

LESSON 4

Fundamental Commands and Operators

The following are the basic operators fundamental in the development of a program.

1. Equal sign (=) is called an assignment operator in C. It is the most basic operator where the value
on the right of the equal sign is assigned to the variable on the left.

The syntax of the use of the assignment operator is,


lvalue = rvalue;

The left value or lvalue is the destination variable, while the right value or rvalue can be a value, a
process or arithmetic expression, or a command that receives a value.

The following are some examples on how to use the assignment operator.

c = c + 1;

radius = 2 * diameter;

stat = getch();

2. The binary operators are arithmetic operators that take two operands and return a result.

Operator Use Result


+ op1 + op2 adds op1 to op2

- op1 - op2 subtracts op2 from op1

* op1 * op2 multiplies op1 by op2


/ op1 / op2 divides op1 by op2

% op1 % op2 computes the remainder from dividing op1 by op2

3. Address operator (&) returns the address of a variable. This operator is significant in the input
process when the command needs to get the address of a variable to know where to put the data
and when using a reference variable to indirectly access a value. The first use will be explained
briefly in the next lesson. The second use will not be discussed in this course.

Sample Program for the Fundamental Operators


Sequential Control Structure

Try this!

#include<stdio.h>
int main(void){
int c;
Output: 6
// Assign 5 to variable c.
c = 5;

// Add 1 to c and assign the result back to c.


c = c + 1;
printf(“%d”,c);
}

Fundamental Input Command - scanf

The following are the basic commands fundamental in the development of a program.

scanf() is one of the Turbo C object streams that is used to accept data from the standard input,
usually the keyboard. Though it can accept any type of data, it has limits when used to input a
value other than numeric.

The following is the syntax of scanf.


scanf(“format specifier”, &var_name);

The data received from the standard input is assigned to the variable. The address operator returns
the address of the variable where to assign the data.

Format specifier defines the type of data to be accepted from the standard input. The list of format
specifiers for scanf is shown in the table below.

The following are examples on the use of scanf.


scanf(“%d”, &num1);
scanf(“%d%d”, &num1, &num2);

The first example assigns an integer value to num1 since %d is a format specifier for int and num1
should be of type int. The second example accepts two inputs, thus needs to have two formats.
The assignment of value is done by position. Whitespace input separates the values.

The following table summarizes the scanf format specifiers for each of the data types.
Sequential Control Structure

Date Types Format

long double %Lf

Double %lf

Float %f

unsigned long int %lu

long int %ld

unsigned int %u

Int %d

Short %hd

Char %c

Try this!

#include<stdio.h> Input: 10
int main(void){ Output: 10
int num1;
//Input a value and assign it to variable
num1.
scanf("%d", &num1);
printf("%d", num1);
}
Sequential Control Structure

#include<stdio.h> Input: 5
int main(void){ 10
int num1, num2; Output: 5 10
//Input two integer values and assign them
to variables num1 and num2.
scanf("%d%d", &num1, &num2);
printf("%d %d", num1, num2);
}

Fundamental Output Command - printf

printf() writes formatted output to the standard output device such as the monitor. It can be a
statement with either pure string expression, a formatted value or a mixed expression. A
formatted value is a value from a variable.

The following are syntaxes of printf.


printf(“string expression”);
printf(“format specifier”,var_name);
printf(“format specifier with string expression ”,var_name);

The following are examples of the use of printf.


printf(“Hello world”);
printf(“%d”,num1);
printf(“Value: %d”,num1);

The first example displays “Hello world”. The second statement displays the value of num1. The format is
%d if num1 is of type int. The third statement should display “Value: 10” if the value of num1 is 10.

Format specifier defines the type of data to be printed in the standard output. The list of format specifiers
for printf is shown in the table below.

The following table summarizes the printf format specifiers for each of the data types.

Date Types Format

long double %Lf


Sequential Control Structure

Double %f

Float %f

unsigned long int %lu

long int %ld

unsigned int %u

Int %d

Short %hd

Char %c

Try this!

1. Displays the message “Hello world”.

#include<stdio.h> Hello world


int main(void){

printf("Hello world");
}

2. Displays the value of num1.

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

int num1;
num1 = 5;

printf("%d",num1);
}
Sequential Control Structure

3. Displays the value of num1 with the message “The value of num1: ”.
#include<stdio.h>
int main(void){ The value of num1: 5
int num1;
num1 = 5;
printf("The value of num1: %d",num1);
}
Sequential Control Structure

LESSON 5 Control Structure

Control structure specifies the sequence of execution of a group of statements. There are three types of
control structure, namely: sequential, conditional and iterative.

Each of the three control structures will be discussed on the succeeding lessons.

Defining a Programming Problem

The following are the five steps in defining a programming problem:

1. Restate the problem.

2. Analyze the problem.

3. Identify the output.

4. Identify the input.

5. Identify the process.

In general, the following is the block diagram of the programming life cycle.

Input Process Output

That is the sequential control structure.

Sequential Control Structure

A sequential control structure is organized such that statements are executed in sequence, i.e., one after
the other in the order of their appearance in the source code.

Let us try solving a problem.

Write a program that accepts two integers and computes and displays their sum.

First, we define the programming problem. After restating and analyzing the problem, we do the last three
steps:

Identifying the output: sum

Identifying the inputs: two integers

Identifying the process: add / addition

Next, we identify the variables to use. Let us use

sum for sum,


Sequential Control Structure

num1 for the first integer, and

num2 for the second integer.


Sequential Control Structure

Always remember that you can use any variable name that best describes its meaning as long as it is not
a reserved word.

Finally, we write the code. We follow the correct structure of the C program as shown below.

Preprocessor Directives
int main(void){
local declarations
statements
}

Here is the algorithm. We skip directly to the content of the program. The directive and the main header
are pre-defined.

1. Declare the variables.

Variables should be declared using their appropriate data types, thus, we use int for all the
variables.

2. Then we follow the programming life cycle.


a. Read two integer values.
b. Add the two numbers.
c. Display the sum.

Here is the final program.


#include<stdio.h> //preprocessor directive
int main(void){ //function main header
int num1, num2,sum; //variable declarations
printf(“Enter two numbers: ”);
scanf(“%d”,&num1); //input
scanf(“%d”,&num2); //input
sum = num1 + num2; //process
printf(“Sum = %d”,sum); //output

}
Sequential Control Structure

Try it!

#include<stdio.h>
int main(void){
int num1, num2,sum;
printf(“Enter two numbers: ”);
scanf(“%d”,&num1);

scanf(“%d”,&num2);
sum = num1 + num2;
printf(“Sum = %d”,sum);
}
Sequential Control Structure

LESSON 6

C Language Elements

#define

As mentioned in the earlier lesson, C has only two directives, include and define. Now, we will tackle the
second directive define.

The directive define allows you to make text substitutions before compiling the program. By convention,
all identifiers that are to be changed by the preprocessor are written in capital letters.

For example,

#define MAX 10

MAX is a substitute of 10. Every time MAX is stated, it means 10.

Here is sample program using #define.


#include <stdio.h>
#define MIN 0 /*defines*/
#define MAX 10
#define TRUE 1
#define FALSE 0
int main() { /*beginning of program */
int a;
int okay=FALSE; /*the compiler sees this as int okay=0;*/
while(!okay) {
printf("Input an integer between %d and %d: ", MIN, MAX);
scanf("%d", &a);

if(a>MAX) {
printf("\nToo large.\n"); }
else if(a<MIN) {

printf("\nToo small.\n"); }
else { printf("\nThanks.\n");

okay = TRUE; }
}
return 0;
}

Library

Libraries are C implementations that contain collections of useful functions and symbols that may be
accessed by a program. Each library has a standard header file whose name ends with .h. A C system may
expand the number of operations available by supplying additional libraries that are called user-defined.

As mentioned in the earlier lesson, #include is used to open a library. To open a predefined library, a pair
Sequential Control Structure

of angle brackets (<>) is used to enclose the header file. To open a user-defined library, a pair of double
quotes (“”) is used.

The following are examples on how to open a library.


Sequential Control Structure

#include <stdio.h> //If stdio.h is predefined.

#include “sample.h” //If sample.h is user-defined.

Comments
You can add comments to your code by enclosing your multi-line remarks with /* and */ while a pair of
slashes precedes a single-line. However, nested comments aren't allowed.

Here are few properties of comments.

 They can be used to inform the person viewing the code what the code does. This is helpful when
you revisit the code at a later date.
 The compiler ignores all the comments. Hence, commenting does not affect the efficiency of the
program.
 You can use /* and */ to comment out sections of code when it comes to finding errors, instead
of deletion.

Here are examples of commented code.


/* Comments spanning several
lines can be commented
out like this!*/
/* But this is a simpler way of doing it! */
//These are C++ style comments and should NOT be used with C
//but allowed when working on a C++ editor
/* /* NESTED COMMENTS ARE ILLEGAL!! */ */
Reserved Words

In C, a reserved word is defined as the word that has a special meaning and cannot be used for other
purposes. It cannot be used as an identifier.

The following is a table that shows the complete list of 32 C reserved words.
Sequential Control Structure

Punctuation Marks

The following table shows the punctuations marks used in C, with their names and meanings.

Punctuation Name Use


/* */ slash asterisk enclose a single line remarks
“ double quotation display series of characters, and initializing string constant
; Semicolon statement separator
, Comma separate one variable to another
= equal sign assignment operator
‘ single quotation for initializing character expression
& Ampersand address operator
{} open/close braces denotes the beginning and end of the program
Sequential Control Structure

LESSON 7

C Constants

Constants are identifiers that are having a constant value all throughout the program execution. By
convention, constants are written in uppercase letters.

To create a constant or a read-only variable, the const keyword is used. Once initialized, the value of the
variable cannot be changed but can be used just like any other variable. Thus, constants should be
initialized during declaration.

Here are examples on the use of the const keyword.

const float PI = 3.14;

const int DEGREE = 360;

const char QUIT = 'q';

Fixed values that may not be altered by the program are also called constants.

Here are examples of constant values.

1. Character constants are enclosed between single quotes.


Examples: ‘A’, ‘+’
2. Integer constants are specified as numbers without fractional components.
Examples: 5, -160
3. Floating constants require the use of decimal point followed by the number’s fractional
components.
Examples: 16.234, 4.23
4. String constants are sets of characters enclosed by double quotes.
Examples: “bag”, “this is good”
5. Backslash character constants are values including all character constants in single quotes
that works for most printing characters.

The following table shows the list of backslash character constants or escape sequence
characters.

SEQUENCE NAME MEANING


\a Alert Sound a beep
\b Backspace Backs up one character
\f Form feed Starts a new screen of page
\n New line Moves to the beginning of the next line
\r Carriage Return Moves to the beginning of the current line
\t Horizontal tab Moves to the next Tab position
\v Vertical tab Moves down a fixed amount
\\ Backslash Displays an actual backslash
\’ Single quote Displays an actual single quote
\? Question mark Displays an actual question mark
Sequential Control Structure

\”” Double quote Displays an actual double quote

LESSON 8

More Operators

Unary Operators

Unary minus (-) or unary plus (+) changes the sign of a value or variable.

Examples:

2 + -3 ≈ 2 - 3

((-x) + (+y)) ≈ -x + y

Increment (++) and Decrement (--) Operators

The ++ or increment operator adds one to the value of a variable. The -- or decrement operator subtracts
one from the value of a variable.

The value of the expression in which ++ or -- operator is used depends on the position of the operator.

Prefix increment is when the ++ is placed in front of its operand. For this, the value of the expression is
the variable’s value after the increment.

Prefix decrement is when the -- is placed in front of its operand. For this, the value of the expression is the
variable’s value after the decrement.

Postfix increment is when the ++ is placed immediately after the operand. Postfix increment is when the
expression’s value is the value of the variable before it is incremented.

Postfix decrement is when the -- is placed immediately after the operand. Postfix decrement is when the
expression’s value is the value of the variable before it is decremented.

To summarize, prefix increments or decrements a variable value and then uses it, while postfix uses the
variable and then increments or decrements its value.

Here are demonstrations on the use of the increment and decrement operators.

Increments: y = ++x y = x++


After: x y x y

5 6 5 5
Decrements: y = --x y = x--

After: x y x y
Sequential Control Structure

5 4 5 5

LESSON 9

Predefined Mathematical Functions

The math handling library is math.h. All the functions available in this library take double as an argument
and return double as the result.

The following table contains the list of commonly used mathematical functions.

Function Purpose Example


double fabs(double x) Returns the absolute value of x. x=fabs(-5.2); x=5.2
double ceil(double x) Rounds up or returns the x=ceil(5.2); x=6
smallest whole number that is
not less than x.
double floor(double x) Rounds down or returns the x=floor(5.2); x=5
largest whole number that is not
greater than x.
double sqrt(double x) Returns the non-negative square x=sqrt(25); x=5
of x.
double pow(double x, double y) Returns x raise to the power of y. x=pow(4,2); x=16
double fmod(double x, double y) Returns the remainder of x x=fmod(10.0,3.0) x=1
divided by y.

The math functions were constructed to translate arithmetic expressions to C codes. For example, the
equivalent C code for the arithmetic expression

x = √𝑎2 + 𝑏2
is
x = sqrt(pow(a,2) + pow(b,2));
Sequential Control Structure

LESSON 10

More I/O Functions

In the earlier lesson, the two input/output functions, scanf and printf, were discussed as fundamentals in
writing a program using the C Language. For this lesson, we will learn the rest of the basic input and output
functions used in C.

The I/O functions that will be covered in this lesson are:

 getchar()
 getch()
 getche()
 gets()
 puts()
 putchar()

getchar()

The getchar function reads a single character from a standard input.

The syntax of the use of getchar is

var_name = getchar();

where var_name is of type char that receives the inputted character value.

Try this!
Sequential Control Structure

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

char letter;
letter = getchar();
printf(“Value of letter: %c”,letter);
}

getch()

The getch function allows the user to input a character and wait for the enter key. Inputted character will
not be echoed but could be stored if location is specified. It is a nonstandard function and is present in
conio.h header file.

The syntax of the use of getch is

var_name = getch();

where var_name is of type char that receives the inputted character value.
Sequential Control Structure

Try this!

#include<stdio.h>
int main(void){
char letter;
letter = getch();
printf(“\nValue of letter: %c”,letter);
}

getche()

The getche function allows the user to input a character and there is no need for the enter key. Inputted
character will be echoed but could be stored if location is specified.

The syntax of the use of getche is

var_name = getche();

where var_name is of type char that receives the inputted character value.

Try this!

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

char letter;
letter = getche();

printf(“\nValue of letter:%c”,letter);
}

gets()

The gets function allows the user to input a sequence of characters or string.

The syntax for the use of gets is

gets(var_name);

where var_name is an array of characters.

Try this!
Sequential Control Structure

#include<stdio.h>
int main(void){
char word[30];
gets(word);
printf(“The word is:%s”,word);
}

puts()

The puts function writes the string to the standard output device such as the monitor and positions the
cursor to the next line.

The syntax for the use of puts is

puts(“string expression”);

Try this!

#include<stdio.h>
int main(void){
puts(“Hello Philippines!”);
}

putchar()

The putchar function writes a single character to the screen.

The syntaxes for the use of putchar are

putchar(var_name); and

putchar(int);

where the parameter may be a char variable with a value, or an integer value for a character.
Sequential Control Structure

Try this!

#include<stdio.h>
int main(void){
char letter=’a’;
putchar(letter);
putchar(65);
}
Sequential Control Structure

Conditional Control Structure

Conditional control structure is organized in such a way that there is always a condition that has to be
evaluated first. The condition evaluates to either a true or a false.

In C, false is zero (0) and true is non-zero (i.e. positive or negative value).

The conditional control structure has two types, namely the if statement (including if-else and nested-if)
and the switch-case statement.

Conditional expressions or statements use two types of operators, namely relational and logical.

The relational or conditional operators evaluate to true or false. The following table shows the list of
operators with their use and meaning.

Operator Use Result


> op1 > op2 true if op1 is greater than op2
>= op1 >= op2 true if op1 is greater or equal to op2
< op1 < op2 true if op1 is less than op2
<= op1 <= op2 true if op1 is less or equal to than op2
== op1 == op2 true if op1 is equal to op2
!= op1 != op2 true if op1 is not equal to op2

The logical operators consist of the logical “and”, “or” and “not”. The following table shows the list of
operators with their use and meaning.

Operator Use Result


&& op1 && op2 true if op1 and op2 are both true
|| op1 || op2 true if either op1 or op2 is true
! !op1 op1 is false if its original value is true and vice versa

When the expression is a combination or arithmetic, relational and logical operations, it is evaluated
following the order of precedence as detailed below where the topmost has the higher precedence down
to the lowest.

Arithmetic Operators *, /, %

+, -

Relational Operators <, <=, >, >=, ==, !=

Logical Operators !

&&

||

Let’s evaluate some expressions, assuming that result is either 1 for true and 0 for false.
Sequential Control Structure

1. x = 3 * 2 > 10 % 2;
The result for x is 1 since (3 * 2) which is 6 is greater than (10 % 2) that is 0.
2. x = 6 – 3 < 10 / 3 || 7 * 2 == 28 / 4;
The result for x is 0 since both the left and right expressions of the logical OR result to false or 0.
if Statement

The if statement performs a task or a group of tasks when the condition is true or when it is false, if there
is an alternative for false. For multiple statements inside an alternative, they should be enclosed with a
pair of braces.

The four types of the if structure are:

1. if (single alternative)

2. if-else (double alternatives)

3. If-else if-else (multiple alternatives)

4. Nested-if

The subsequent lessons will fully discuss the individual if structures.


if (Single Alternative)

The if (single alternative) performs an indicated action only when the condition is true, otherwise the
action is skipped.

Here is the syntax for single-if:

if (<conditional expression>)

<statement>

For example:

if(age > 18)

printf(“You are an adult!”);

Another example:

if(age > 18){

printf(“You are an adult!”);

printf(“Welcome to the club!”);

For the first example, if the condition evaluates to true then the message “You are an adult!” displays. If
the condition evaluates to false, then nothing happens.

The second example uses a pair of braces to enclose the multiple statements that will be performed when
the condition evaluates to true.
Sequential Control Structure

Here is a sample problem for the single-if:

Write a program that accepts a number and determines whether the number is positive. If it is positive,
display the message “Positive!”.

Here is the answer. Try this!

#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
}

Here are the sample outputs:

if-else (Double Alternatives)

The if-else (double alternatives) allows the programmer to specify that different actions are to be
performed when the condition is true and when the condition is false. If the condition evaluates to true,
then statementTrue is executed and statementFalse is skipped; otherwise, statementTrue is skipped and
statementFalse is executed.

Here is the syntax for if-else:

if (<conditional expression>)

<statementTrue>

else

<statementFalse>

For example:

if(age > 18)

printf(“You are an adult!”);

else

printf(“You are a minor!”);


Sequential Control Structure

If the condition results to true then the message “You are an adult!” is displayed. If otherwise, the message
“You are a minor!” is displayed.

The following states the good programming practices to be observed when using the if-else statement.

1. Indent both body statements of an if...else statement.


2. If there are several levels of indentation, each level should be indented the same additional amount
of space.

Here is a sample problem for the double-if:

Write a program that accepts a number and determines whether the number is positive or negative. If it
is positive, display the message “Positive!”. Otherwise, display “Negative!”.

Here is the answer. Try this!

#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
else
printf(“Negative!”);
}

Here are the sample outputs:

if - else if - else (Multiple Alternatives)

The conditions in a multiple-alternative decision are evaluated in sequence until a true condition is
reached. If a condition is true, the statement following it is executed, and the rest of the multiple-
alternative decision is skipped. If a condition is false, the statement following it is skipped, and the
condition next is tested. If all conditions are false, then the statement following the final else is executed.

Here is the syntax:

if (<conditional expression>)

<statement>

else if (<conditional expression>)


Sequential Control Structure

<statement>

else if (<conditional expression>)

<statement>

else

<statement>

Here is a sample problem for multiple-if:

Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”.

Here is the answer. Try this!

#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0)
printf("Positive!");
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}

Here are the sample outputs:


Sequential Control Structure

Nested-if

Placing another if statement inside an if statement is called a nested if.

A nested if statement can perform much faster than a series of single-selection if statements because of
the possibility of early exit after one of the conditions is satisfied.

In a nested if statement, you test the conditions that are more likely to be true at the beginning of the
nested if statement. This will enable the nested if statement to run faster and exit earlier than testing
infrequently occurring cases first.
Sequential Control Structure

Here is the syntax of a nested-if:

if (<conditional expression>){

if (<conditional expression>)

<statement>

else

<statement>

Here is a sample problem for the nested-if:

Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”. Furthermore, if the number is positive, it
determines whether it is even or odd and displays either “Even!” or “Odd!”.

Here is the answer. Try this!

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

int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0){
printf("Positive!");
if(num%2==0)
printf(“Even!”);
else
printf(“Odd!”);
}
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}
Here are the sample outputs:
Sequential Control Structure

In general, the following are the good programming practices to be observed in using the if statement.

• Always putting the braces in an if...else statement (or any control statement) helps prevent their
accidental omission, especially when adding statements to an if or else clause at a later time. To
avoid omitting one or both of the braces, some programmers prefer to type the beginning and
ending braces of blocks even before typing the individual statements within the braces.

• Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors
in a program.

• Placing a semicolon after the condition in an if statement leads to a logic error in single-selection
if statements and a syntax error in double-selection if...else statements (when the if part contains
an actual body statement).

The switch Statement

The switch statement uses a variable to be compared to a set of values. Each value is called a case which
should only be an int or a char, that should also be the data type for the variable.

In the switch statement, the variable or also called the controlling expression, is evaluated and compared
to each of the case labels in the case constant until a match is found. A case constant is made of one or
more labels of the form case followed by a constant value and a colon. When a match between the value
of the controlling expression and a case label value is found, the statement following the case label are
executed until a break statement is encountered. Then the rest of the switch statement is skipped.

Here is the syntax of the switch statement:

switch (<controlling expression>){

case constant: <statement>

break;

case constant: <statement>

break;

. . .

default: <statement>

The break at the end is necessary since it allows the rest of the matching and statements to be skipped.
Because of break, if there are multiple statements in a case, the pair of braces that are usually used to
group the statements are not needed.

Here is a sample problem for the switch statement:


Sequential Control Structure

Make a program that would input the year code (between 1 and 4) and output “Freshman”, “Sophomore”,
“Junior”, or “Senior”. Furthermore, if year is not between 1 and 4, output “Error”.

Here is the answer. Try this!

#include<stdio.h>

int main(void){

int yearcode;

printf("Enter the year code: ");

scanf("%d", &yearcode);

switch(yearcode){

case 1: printf("Freshman"); break;

case 2: printf("Sophomore"); break;

case 3: printf("Junior"); break;

case 4: printf("Senior"); break;

default: printf("Error");

}
Here are the sample outputs:
Conditional Control Structure

Conditional control structure is organized in such a way that there is always a condition that has to be
evaluated first. The condition evaluates to either a true or a false.

In C, false is zero (0) and true is non-zero (i.e. positive or negative value).

The conditional control structure has two types, namely the if statement (including if-else and nested-if)
and the switch-case statement.

Conditional expressions or statements use two types of operators, namely relational and logical.

The relational or conditional operators evaluate to true or false. The following table shows the list of
operators with their use and meaning.

Operator Use Result


> op1 > op2 true if op1 is greater than op2
>= op1 >= op2 true if op1 is greater or equal to op2
< op1 < op2 true if op1 is less than op2
<= op1 <= op2 true if op1 is less or equal to than op2
== op1 == op2 true if op1 is equal to op2
!= op1 != op2 true if op1 is not equal to op2

The logical operators consist of the logical “and”, “or” and “not”. The following table shows the list of
operators with their use and meaning.

Operator Use Result


&& op1 && op2 true if op1 and op2 are both true
|| op1 || op2 true if either op1 or op2 is true
! !op1 op1 is false if its original value is true and vice versa

When the expression is a combination or arithmetic, relational and logical operations, it is evaluated
following the order of precedence as detailed below where the topmost has the higher precedence down
to the lowest.

Arithmetic Operators *, /, %

+, -

Relational Operators <, <=, >, >=, ==, !=

Logical Operators !

&&

||

Let’s evaluate some expressions, assuming that result is either 1 for true and 0 for false.
1. x = 3 * 2 > 10 % 2;
The result for x is 1 since (3 * 2) which is 6 is greater than (10 % 2) that is 0.
2. x = 6 – 3 < 10 / 3 || 7 * 2 == 28 / 4;
The result for x is 0 since both the left and right expressions of the logical OR result to false or 0.

if Statement

The if statement performs a task or a group of tasks when the condition is true or when it is false, if there
is an alternative for false. For multiple statements inside an alternative, they should be enclosed with a
pair of braces.

The four types of the if structure are:

1. if (single alternative)

2. if-else (double alternatives)

3. If-else if-else (multiple alternatives)

4. Nested-if

The subsequent lessons will fully discuss the individual if structures.

if (Single Alternative)

The if (single alternative) performs an indicated action only when the condition is true, otherwise the
action is skipped.

Here is the syntax for single-if:

if (<conditional expression>)

<statement>

For example:

if(age > 18)

printf(“You are an adult!”);

Another example:

if(age > 18){

printf(“You are an adult!”);

printf(“Welcome to the club!”);

For the first example, if the condition evaluates to true then the message “You are an adult!” displays. If
the condition evaluates to false, then nothing happens.

The second example uses a pair of braces to enclose the multiple statements that will be performed when
the condition evaluates to true.
Here is a sample problem for the single-if:

Write a program that accepts a number and determines whether the number is positive. If it is positive,
display the message “Positive!”.

Here is the answer. Try this!

#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
}

Here are the sample outputs:

if-else (Double Alternatives)

The if-else (double alternatives) allows the programmer to specify that different actions are to be
performed when the condition is true and when the condition is false. If the condition evaluates to true,
then statementTrue is executed and statementFalse is skipped; otherwise, statementTrue is skipped and
statementFalse is executed.

Here is the syntax for if-else:

if (<conditional expression>)

<statementTrue>

else

<statementFalse>

For example:

if(age > 18)

printf(“You are an adult!”);

else

printf(“You are a minor!”);


If the condition results to true then the message “You are an adult!” is displayed. If otherwise, the message
“You are a minor!” is displayed.

The following states the good programming practices to be observed when using the if-else statement.

1. Indent both body statements of an if...else statement.


2. If there are several levels of indentation, each level should be indented the same additional amount
of space.

Here is a sample problem for the double-if:

Write a program that accepts a number and determines whether the number is positive or negative. If it
is positive, display the message “Positive!”. Otherwise, display “Negative!”.

Here is the answer. Try this!

#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>=0)
printf("Positive!");
else
printf(“Negative!”);
}

Here are the sample outputs:

if - else if - else (Multiple Alternatives)

The conditions in a multiple-alternative decision are evaluated in sequence until a true condition is
reached. If a condition is true, the statement following it is executed, and the rest of the multiple-
alternative decision is skipped. If a condition is false, the statement following it is skipped, and the
condition next is tested. If all conditions are false, then the statement following the final else is executed.

Here is the syntax:

if (<conditional expression>)

<statement>

else if (<conditional expression>)


<statement>

else if (<conditional expression>)

<statement>

else

<statement>

Here is a sample problem for multiple-if:

Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”.

Here is the answer. Try this!

#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0)
printf("Positive!");
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}

Here are the sample outputs:

Nested-if

Placing another if statement inside an if statement is called a nested if.

A nested if statement can perform much faster than a series of single-selection if statements because of
the possibility of early exit after one of the conditions is satisfied.

In a nested if statement, you test the conditions that are more likely to be true at the beginning of the
nested if statement. This will enable the nested if statement to run faster and exit earlier than testing
infrequently occurring cases first.
Here is the syntax of a nested-if:

if (<conditional expression>){

if (<conditional expression>)

<statement>

else

<statement>

Here is a sample problem for the nested-if:

Write a program that accepts a number and determines whether the number is positive, negative or a
zero. It displays the message “Positive!”, “Negative!” or “Zero!”. Furthermore, if the number is positive, it
determines whether it is even or odd and displays either “Even!” or “Odd!”.

Here is the answer. Try this!

#include<stdio.h>
int main(void){
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num>0){
printf("Positive!");
if(num%2==0)
printf(“Even!”);
else
printf(“Odd!”);
}
else if(num<0)
printf(“Negative!”);
else
printf(“Zero!”);
}
Here are the sample outputs:
In general, the following are the good programming practices to be observed in using the if statement.

• Always putting the braces in an if...else statement (or any control statement) helps prevent their
accidental omission, especially when adding statements to an if or else clause at a later time. To
avoid omitting one or both of the braces, some programmers prefer to type the beginning and
ending braces of blocks even before typing the individual statements within the braces.

• Forgetting one or both of the braces that delimit a block can lead to syntax errors or logic errors
in a program.

• Placing a semicolon after the condition in an if statement leads to a logic error in single-selection
if statements and a syntax error in double-selection if...else statements (when the if part contains
an actual body statement).

The switch Statement

The switch statement uses a variable to be compared to a set of values. Each value is called a case which
should only be an int or a char, that should also be the data type for the variable.

In the switch statement, the variable or also called the controlling expression, is evaluated and compared
to each of the case labels in the case constant until a match is found. A case constant is made of one or
more labels of the form case followed by a constant value and a colon. When a match between the value
of the controlling expression and a case label value is found, the statement following the case label are
executed until a break statement is encountered. Then the rest of the switch statement is skipped.

Here is the syntax of the switch statement:

switch (<controlling expression>){

case constant: <statement>

break;

case constant: <statement>

break;

. . .

default: <statement>

The break at the end is necessary since it allows the rest of the matching and statements to be skipped.
Because of break, if there are multiple statements in a case, the pair of braces that are usually used to
group the statements are not needed.

Here is a sample problem for the switch statement:


Make a program that would input the year code (between 1 and 4) and output “Freshman”, “Sophomore”,
“Junior”, or “Senior”. Furthermore, if year is not between 1 and 4, output “Error”.

Here is the answer. Try this!

#include<stdio.h>

int main(void){

int yearcode;

printf("Enter the year code: ");

scanf("%d", &yearcode);

switch(yearcode){

case 1: printf("Freshman"); break;

case 2: printf("Sophomore"); break;

case 3: printf("Junior"); break;

case 4: printf("Senior"); break;

default: printf("Error");

}
Here are the sample outputs:
Loop/Iteration/Repetition

Loop is a control structure that repeats a group of steps in a program. It defines a block of code that is
repeatedly executed. Depending on the kind of loop that you are using, the block of code could be
executed a set number of times or until a certain condition is met.

Loop has the following four components:

1. Initialization of variables is setting an initial value before the loop statement is reached.

2. Condition/testing would evaluate to either true or false.

The condition to check is usually made on the current value of the variable initialized in (1) for it
controls the loop repetition.

3. Body consists of statements that are repeated in the loop.

4. Update is a statement inside the body of the loop that updates the value of the variable that is
initialized during each repetition.

Here is a sample problem for loops:

Write a program that prints “Hello world!” ten times.

Since the problem is to repeat the phrase 10 times, then we count from 1 to 10. However, we can also
start from 10 to 1. For problems with a specified number of times to repeat, a counter is used.

A counter is set up in a program to keep track the number of times the program segment is repeated. The
program can then be terminated after the completion of a predetermined number of passes.

For the above problem, we will use a counter. Now, we derive the four components.

Body: Display of the message “Hello world!”. Using C, we use that statement

printf(“Hello world!”);

Assuming we use variable ctr to count, this is how the use of a counter is done.

Initialization Condition Update

If the counting is from 1 to 10: ctr=1; ctr<=10; ctr++;

If the counting is from 10 to 1: ctr=10; ctr>=1; ctr--;

To write the complete program that would answer the problem, let us learn the use of the different loop
structures.

The following are the three types of loop:

1. for statement

2. do-while statement

3. while statement
The for Loop

The for loop is used to execute code block for a specified number of times.

Here is the syntax of the for loop:

for (initialization; condition; update)

Statement/s

For example: To answer the problem,

Write a program that prints “Hello world!” ten times.

for (ctr=1; ctr<=10; ctr++)

printf(“Hello world!”);

Try this!

#include<stdio.h>

int main(void){

int ctr;

for (ctr=1; ctr<=10; ctr++)

printf(“Hello world!”);

Note that all expressions of the for loop are optional. It means that you can omit any expression or all of
them. When you omit all expressions, the C for loop behaves slightly similar to the while loop and do while
loop with break statement.

For example:

ctr=1;

for (; ctr<=5;){

printf(“Hello world!”);

ctr++;

}
Try this!

#include<stdio.h>

int main(void){

int ctr=1;

for (;ctr<=10;){

printf(“Hello world!”);

ctr++;

Here is another sample problem:

Input N integers and count how many negative, positive and zeroes were entered. At the end, print the
counted values.

Here is the program:

#include<stdio.h>

int main(void){

int N, ctr, neg=0, pos=0, zero=0, num;

scanf("%d",&N);

for (ctr=1;ctr<=N;ctr++){

scanf(“%d”,&num);

if(num<0)

neg++;

else if(num>0)

pos++;

else

zero++;

printf(“Negatives: %d\n”,neg);

printf(“Positives: %d\n”,pos);
printf(“Zeroes: %d\n”,zero);

Try this!

#include<stdio.h>

int main(void){

int N, ctr, neg=0, pos=0, zero=0, num;

scanf("%d",&N);

for (ctr=1;ctr<=N;ctr++){

scanf(“%d”,&num);

if(num<0)

neg++;

else if(num>0)

pos++;

else

zero++;

printf(“Negatives: %d\n”,neg);

printf(“Positives: %d\n”,pos);

printf(“Zeroes: %d\n”,zero);

The do-while Loop

The do-while loop executes a block of codes as long as the specified condition is true.

It is a post checked loop because it checks the controlling condition after the code is executed.

Here is the syntax of the do-while loop:

initialization

do{

Statement/s

update
}while(condition);

For example: To answer the problem,

Write a program that prints “Hello world!” ten times.

ctr=1;

do{

printf(“Hello world!”);

ctr++;

}while(ctr<=10);

Try this!

#include<stdio.h>

int main(void){

int ctr=1;

do{

printf(“Hello world!”);

ctr++;

}while(ctr<=10);

}
For problems where there is no specified number of times to repeat a task, the best loop structure to use
is either do-while or while. For example,

Write a program that continuously accepts a number until a 0. The 0 terminates the loop.

The 0 is called a trailer record. A trailer record is a special value used to terminate a loop instead of a
counting process. The value is chosen to be a data value which is outside the range of the data values to
be processed.

Here is the code segment that would answer the above problem using do-while and would demonstrate
the use of the trailer record.

do{

scanf(“%d”,&num);

}while(num!=0);
Try this!

#include<stdio.h>

int main(void){

int num;

do{

scanf(“%d”,&num);

}while(num!=0);

The while Loop

Like do-while, the while loop will execute a block of codes while the given condition is true.

It is a pre-checked loop because it checks the controlling condition first before the code is executed.

Here is the syntax of the while loop:

initialization

while(condition){

Statement/s

update

For example: To answer the problem,

Write a program that prints “Hello world!” ten times.

ctr=1;

while(ctr<=10){

printf(“Hello world!”);

ctr++;

}
Try this!

#include<stdio.h>

int main(void){

int ctr=1;

while(ctr<=10){

printf(“Hello world!”);

ctr++;

Break and Continue

Repetition loops can also be altered by break or continue statements.

Break exits from the lowest-level loop in which it occurs. It used for early exit from the loop, or for exiting
a forever loop.

Here is a sample problem that uses break to terminate the loop.

An integer is said to be prime if it is divisible only by 1 and itself. For example, 2, 3, 5 and 7 are
prime, but 4, 6 and 9 are not. Write a program that determines whether an integer is prime or not.
Try this!

#include<stdio.h>

int main(void){

int num,ctr,prime=1;

scanf("%d",&num);

for(ctr=2;ctr<=num/2;ctr++){

if(num%ctr==0){

prime=0;

break;

if(prime==1)

printf("Prime!");

else

printf("Not Prime!");

Continue causes immediate loop iteration, skipping the rest of the loop statements. It jumps to the loop
test when used with while or do. It jumps to loop increment, then test when used with for. It does not exit
the loop (unless next loop is false).

Here is a sample problem that uses continue.

Write a program that prints numbers 1 to 20, excepts those that are divisible by 3.

To try and run the complete program that answers the problem above, click the link below:
#include<stdio.h>

int main(void){

int ctr;

for(ctr=1;ctr<=20;ctr++){

if(ctr%3==0)

continue;

printf("%d ",ctr);

Nested Loop

Like the conditional control structure, a loop within a loop or a nested loop is allowed in C.

For example:

Write a program that would generate the following pattern.

011111

101111

110111

111011

111101

111110

Try this!
#include<stdio.h>

int main(void){

int i, j;

for(i=1;i<=6;i++){

for(j=1;j<=6;j++){

if(i==j)

printf("0 ");

else

printf("1 ");

printf("\n");

}
FUNCTION

A function is a subroutine that contains one or more statements and performs a single well-defined task.

Two Types of Function:

1. Pre-defined – a function written by for us (by some other programmers).

Examples: printf(), pow(), sqrt()

2. User-defined – the function that we are going to write/implement by ourselves.

Before we start writing user-defined functions, let’s have the difference first between the main program
and the function. Note that the main program is actually the main function. The main function is where
program execution begins, that’s why we call it the main program.

A function is a subprogram therefore the structure of a function is similar to the main program.

Main Program Function

Input Output Input Output

scanf printf parameter return

A program has the life cycle input->process->output. Since a function is a subprogram, it has the same life
cycle with a program. Both have the same process. The main program uses pre-defined input and output
functions, while the function has parameter as input and a return statement for output.

Here is a sample problem for a program:

Write a program that accepts two numbers and computes and prints their sum.

Here is the implementation:

int main(void){

int num1, num2, sum;

//input

scanf("%d%d",&num1,&num2);

//process

sum = num1 + num2;

//output
printf("%d",sum);

Elements of a Function

Here is the problem for a function:

Write a function that accepts two numbers and computes and returns their sum.

Before we write the function, here are the three elements we need to define:

1. Function declaration/prototype
2. Function definition/implementation
3. Function call

The following are the syntaxes of the elements with the code segments to answer the revised problem.

Function Declaration/Prototype

Function declaration is first read by the compiler. When a function is called, it is checked whether the
name exists and whether the number of parameters and data types are correct based on how it is
declared.

Syntax:

ReturnType FunctionName(parameter list);

Example:

int computeSum(int num1, int num2);

Note:

FunctionName – is an identifier. It names the function.

ReturnType – is any standard data type in C of the value to be returned by the function.

parameter list – consists of variables that receive the value of the arguments used in the function
call. The variable name is optional.

Function Definition/Implementation

Function definition is composed of statements that perform the task asked for the function. The
parameter serves as input to the function. It means that when a function is called, the value of the
parameter passed becomes the value of the parameter of the called function. Parameter passing is done
by position. If there is a return type, the function is expected to return a value.

Syntax:

ReturnType FunctionName(parameter list){


Statement/s

Example:

int computeSum(int num1, int num2){

int sum;

sum = num1 + num2;

return sum;

The return keyword has two important uses:

1. It can be used to return a value.

2. It can be used to cause an immediate exit from the function it is in. That is, the return will cause
program execution to return to the calling as soon as it is encountered.

Note: The return statement can also be used without any value associated with it.

Function Call

Function call invokes a function. A function only exists when it is called. As mentioned above, parameters
are passed by position. When a function returns a value, the calling function either receives the value by
assigning it to a variable or passes it to another function.

int main(void){

int num1=5, num2=10, sum;

sum = computeSum(num1,num2); //received by a variable

printf("%d",sum);

printf(“%d”, computeSum(num1,num2)); //passed to another function

Note:

Argument – is the value that is passed to the function at the time that it is called.

Additional Things to Remember in Using Functions

Here are additional things to remember in using functions:

1. If there are parameters, there should be no pre-defined input functions inside the function.
2. If there is a return type, the computed value is expected to be returned, not to be displayed. It
could destroy the format defined in main.
3. If the function does not need an input, use void or just leave the parameter empty. This can only
be the time to have a pre-defined input function, and only when it is an input function.
4. If the function does not return a value, use void. This can only be the time to have a pre-defined
output function, and only when it is an output function.

Sample Program Using a Function

#include<stdio.h>

int computeSum(int num1, int num2);

int computeSum(int num1, int num2){

int sum;

sum = num1 + num2;

return sum;

int main(void){

int num1=5, num2=10, sum;

sum = computeSum(num1,num2);

printf("%d",sum);

Sample Program with Multiple Functions

Problem: Write a program that performs the four mathematical operations, addition, subtraction,
multiplication, division (one function each operation). The main program lets you choose what operation
to perform using the switch statement. The following are the case labels (+,-,*,/). If the operation chosen
is subtraction, the minuend should always be greater than the subtrahend to avoid a negative answer. If
the operation chosen is division, the dividend should be greater than the divisor.

#include<stdio.h>

int computeSum(int num1, int num2);

int computeDifference(int num1, int num2);

int computeProduct(int num1, int num2);

int computeQuotient(int num1, int num2);


int computeSum(int num1, int num2){

return num1 + num2;

int computeDifference(int num1, int num2){

return num1 - num2;

int computeProduct(int num1, int num2){

return num1 * num2;

int computeQuotient(int num1, int num2){

return num1 / num2;

int main(void){

int num1,num2,ans=0;

char op;

op=getchar();

scanf("%d%d",&num1,&num2);

switch(op){

case '+': ans=computeSum(num1,num2); break;

case '-': ans=computeDifference(num1,num2); break;

case '*': ans=computeProduct(num1,num2); break;

case '/': ans=computeQuotient(num1,num2); break;

default: printf("Invalid operator!");

printf("%d",ans);
}

Sample 1 for Function:

Write a function accepts a distance expressed in kilometers and returns the distance expressed in miles,
where 1 kilometer equals 0.62137 miles. Test the function inside main().

#include<stdio.h>

float toMiles(float km);

float toMiles(float km){

return km * 0.62137;

int main(){

printf("%.2f",toMiles(2));

Sample 2 for Function:

There are 12 inches in a foot and an inch is 2.54 centimeters long. Write a function that accepts distance
expressed in feet and inches and output the equivalent distance in centimeters. Test the function inside
main().

#include<stdio.h>

float toCm(int ft, int inch);

float toCm(int ft, int inch){

return ((ft*12) + inch) * 2.54;

int main(){

int ft, inch;

scanf("%d",&ft);

scanf("%d",&inch);

printf("%.2f",toCm(ft,inch));

You might also like