Fundamentals of Programming
Fundamentals of Programming
Fundamentals of Programming
of PROGRAMMING:
C / C++ LANGUAGE
Chapter 1
PROGRAMMING CONCEPTS
Program Planning and Development
Each program has to be well thought of. Instructions must be ordered in a logical
sequence that can easily be understood by the computer. The problem must be analyzed to
such a level of detail that all logical conditions that may be encountered during the process are
taken into consideration. Otherwise, wrong results will be obtained.
There are 5 stages in developing a program: (1) defining the problem; (2) designing a
solution; (3) writing the program; (4) compiling, debugging and testing the program; (5)
documenting the program.
The first step in defining a problem begins with recognizing the need for information.
This information may be a request for a solution to a particular problem. The problem is then
thoroughly analyzed in order to determine what is required of its solution.
To fully analyze the problem, there is a need to define what outputs are required of the
program. The programmer must determine what data are needed, what form they are to be in,
what information is to be outputted, and how the data are to be manipulated to produce this
output.
Defining a Solution
When the definition of the problem is finished, the design of the solution begins.
Designing the solution requires breaking the problem into discrete steps. This sequence of
steps, a strategy for solving the problem is called an algorithm.
Flowcharting
Pseudocode
A pseudocode is a version of the instructions describing each step the computer must
follow. It is written in an abbreviated form of spoken language and there lies somewhere
commands written in ordinary English and those in a computer language.
Despite the fact that programming languages differ in the commands they use, most
high-level programming languages have certain types of programming statements in common.
These are comments, declarations, input/output statements, computations, transfer of control,
and comparison.
Comments are statements that have no effect on the program. They are simply used to
make the program easier to understand. They are inserted at key points in the program and
serve as an internal documentation of the program.
The programmer uses declarations to define items used in the program. Examples
include definitions of files, records, initial values, reusable functions and the like.
Input/output statement transfer data to and from the primary storage for use by the
program, as well as to and from other I/O devices like the monitor and the keyboard.
Commands such as READ and PRINT are examples of these types of statements.
Comparisons allow two items to be compared. Based on the result of the comparison,
input/output, computation, or transfer of control could occur.
As the program is being coded, the programmer should be aware that although
generating the correct output is the primary goal of the program, it is not the only requirement of
a good program. The programmer should try to incorporate the following qualities into any
program:
Programs should be easy to read and understandable. Data names should be
descriptive. Statements should be placed in a format that is easy to read and follow.
Placing enough comments can help in making the program easier to understand.
Programs should be efficient. Programs should execute as little time as possible.
Programs should be reliable. Programs should consistently produce the correct
output. All formulas and computations, as well as all logic test and transfer control, must
be accurate.
Programs must be robust. Programs should work under all conditions. Reliability alone
is no guarantee for a successful program. Internal logic maybe correct but an incorrect
data item could produce an incorrect output. For example, how a program would react if
a person’s age were 2, 45 or -54?
Programs should be maintainable. They should be easy to update and modify.
Programs should be written in independent modules so that a change in one module
does not necessitate a change in others.
Compiling, Debugging and Testing the Program
Instructions must be translated into machine language before they can be executed. A
compiler is a special program for each programming language that is located into the computer
when that language is used. It translates each line of code into the machine instruction that can
be understood by the computer.
The process of documentation is an ongoing one. It begins with the initial request for
information. The individual making the request should be identified. So should those responsible
for designing the system and required programs.
During the problem definition stage, the problem should be described clearly in a short
narrative statement. The objectives of the program should be included with the problem
statement. Several other descriptions are needed.
A complete description of the contents and formats of all data inputs, outputs and files to
be used.
A statement of the hardware requirements for running the program, as well as estimated
processing time and storage requirements.
A statement of software requirements, such as utility programs and library programs.
In the planning phase, the most important documentation produced is the flowchart. Descriptive
comments may be included for each processing step. The test data used to test the program
should also be included.
Programming Language
Machine Language
It is the only language that the computer understands. It consists only of numbers. Each
different type of CPU has its own unique machine language. A programming language, on the
other hand defines a vocabulary and a set of grammatical rules for instructing a computer to
perform specific tasks. Each language has a unique set of keywords and a special syntax for
organizing program instructions.
Machine Language is the lowest level programming language. It is the only language
understood by computers and consists of pure numbers. Machine language functions as the
target language of other language programs. The other language programs must be translated
into machine language before the computer can execute the instructions. Because the data in
digital computers is stored as either on or off electrical states, machine language takes the form
of either 1 or 0.
Low-Level Language
Low level languages are also called Assembly language and are similar to machine
language. But in contrast, assembly language is much easier to understand than a machine
language. Assembly languages were developed to overcome the disadvantage of machine
language. Instead of using 1’s and 0’s, to specify machine instructions, programmers use
mnemonics or machine op codes. The mnemonics are English-like abbreviations for the
machine language instructions.
Programmers who write low-level language programs must be highly skilled in two
areas. First, they must know a great deal about the internal workings of the microprocessor, and
a broad technical knowledge of the computer is needed. Secondly, the programmer must be
detailed oriented, every step of the computer must be coded and the actual numerical address
of the instructions and data must be specified.
High-level programming languages enable the programmer to write programs that are
more or less independent of a particular type of computer. Such languages are considered high-
level because they are closer to human language than the machine language the computer truly
understands. The main advantage of a high level language over low level language is that they
are easier to understand. They allow the programmers to focus on solving the problem rather
than knowing how to program the computer.
Ultimately, programs written in a high level language must be translated into machine
language. Examples of High Level Languages are C, FORTRAN and Pascal. Since their
development in the 1950’s, many other languages have been developed today. These include
Ada, Algol, BASIC, COBOL, C++, LISP and Prolog. Most programming languages were created
to serve specific purposes, such as teaching programming concepts, aiding in scientific
research, creating graphics or controlling input and output devices. However, programmers
found that languages could develop for one purpose, with few modifications serve equally well
in writing other programs.
The question of what programming language to use depends on the type of problem you
want to solve. Every language has its advantage and disadvantage. For example FORTRAN is
a good language for processing numerical data, but it is not good in organizing very large
programs. C language is a very good language for writing well-structured and readable
programs. C++ has a powerful object oriented capability but it is complex to learn.
1. BASIC
BASIC is an acronym for Beginner’s All-Purpose Symbolic Instruction Code.
It was developed by John Kemeny and Thomase Kurtz in the early 1960’s. Their goal
was to create a language that could be easily learned and that would help students to
understand programming. BASIC is a simplified version of the first high-level language
that was FORTRAN.
An example of a BASIC program that will multiply two numbers, 243 and 87 and
printing the results is shown.
10 LET A = 87
20 LET B = 243
30 LET C = A * B
40 PRINT A; “ TIMES ” ;
50 PRINT B; “ = “; C
60 END
2. FORTRAN
An example of a FORTRAN program that will multiply two numbers, 243 and 87
and printing the result is shown.
INTEGER A, B, C
A = 87
B = 243
C = A * B
WRITE (6,50) A, B, C
FORMAT (1X, I3M ‘ TIMES ‘, * I3, ‘=’ , I6)
STOP
3. COBOL
COBOL is short for Common Business-Oriented Language and it is the most
frequently used business programming language. It is used extensively in business,
education and government. COBOL was stated in the early 1960’s when a committee
led by the U.S. Department of Defense and other computer users and manufacturers,
known as CODASYL ( Conference of Data Systems Language ) wanted to develop a
common business programming language. They were the ones who established the
specifications for the COBOL language. Dr. Grace Murray Hopper was a major
contributor to the structure and development of the COBOL language. By mid 1960’s the
first commercial version of the COBOL language was offered. In 1968 ANSI published
guidelines for standardized COBOL that became known as ANSI COBOL.
An example of a COBOL program that will multiply two numbers 243 and 87
and printing the result is shown.
IDENTIFICATION DIVISION
PROGRAM-ID. SAMPLE.
ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SOURCE COMPUTER. IDIAC-747.
OBJECT COMPUTER. IDIAC-747.
DATA DIVISION.
WORKING–STORAGE SECTION .
01 A; PICTURE IS S9 (3) .
01 B; PICTURE IS S9 (3) .
01 C; PICTURE IS S9 (3) .
PROCEDURE DIVISION.
000–MAIN–LINE.
MOVE 87 TO A.
MULTIPLY B GIVING C.
4. PASCAL
PASCAL was the language named after the seventeenth century French
mathematician Blaise Pascal who constructed one of the first adding machines. It is a
high-level language developed by Nicklaus Wirth of Zurich Switzerland in the late
1960’s. Pascal is one of the first languages developed using a structured programming
approach. Pascal reflects a top-down modular programming design. It forces the
programmers to design programs methodically and carefully. It is for this reason that
Pascal became a popular teaching language. Pascal language is a balance between a
wordy language like COBOL and terse language like FORTRAN. Originally intended for
teaching purposes, Pascal rapidly expanded and was used in business and scientific
applications.
An example of a PASCAL program that will multiply two numbers, 243 and 87
and printing the result is shown.
PROGRAM SAMPLE;
VAR
A, B, C : INTEGER;
BEGIN
A := 87;
B := 243;
C := A * B;
WRITELN(OUTPUT, ‘ ‘, A, ‘TIMES’ , B, ‘ = ‘, C) ;
END.
5. C LANGUAGE
C is a high-level programming language developed by Dennies Ritchie at the
Bell Laboratories in 1972. The language was named C, because it was influenced by
another language called B developed by Ken Thompson. It was originally designed as a
systems programming language, which means that it was used to write operating system
programs. The UNIX operating system and its utilities were written in over 300,000 lines
of C code.
An example of a C program that will multiply two numbers, 243 and 87 and
printing the results is shown.
#include <stdio.h>
void main()
{
int a, b, c;
a = 87;
b = 243;
c = a * b;
printf(“\n%d times %d equals %d\n”, a,b,c);
}
6. C++ LANGUAGE
During the late 1980’s until the early 1990’s object-oriented programming
started to become popular. This led to the development of object-oriented languages:
Object-Pascal, Modula-2, Mesa, Cedar, Neon, Objective-C, LISP and C++. C++ was
developed by Bjarned Stroustrup while working at the Bell Laboratories. C++ is actually
an extension of C, and while it is not entirely a new language, significant extensions to
the C language have been adopted. C++ is considered a superset of C, and it has the
same capabilities as C with added object-oriented features. C++ is a powerful language,
but the languages still has the flexibility and efficiency of C with added support for
creating object classes. Although C++, was originally designed to aid in the management
of very large programs, its applications are not limited to this. The object-oriented
capabilities of C++ can be applied to virtually any programming task. C++ is one of the
most powerful and efficient programming languages today.
An example of C++ program that will multiply two numbers, 243 and 87 and
printing the result is shown.
#include <iostream.h>
void main()
{
int a = 243, b = 87, c;
c = a * b;
cout<< a<<” times “<<b <<” equals “ << c;
}
7. JAVA
The JAVA programming language is the popular programming for creating
applications on the Web. These applications are called “applets” because they are small
application program. Before the development of Java web pages were viewed as static
documents on the Web browser. These “static” web pages were creating using HTML
(Hypertext Markup Language) and most companies organize web pages using CGI
(Common Gateway Interface).
Java, whose original name was Oak, was developed in December 1990 by Un
Microsystems. Java was created as a programming tool, part of the Green project of Sun
whose task was to create something new and exciting. The original team members of
the Green project (also known as the secret “Green Team”) were Patrick Naughton, Bill
Joyo and James Gosling and were later joined by Chris Warth, Ed Frank and Craig
Forrest.
Regardless of what type of language you use, eventually you will convert your programs
into a machine language so that the computer can understand it. When we write our programs
in a high-level language the computer cannot understand the language because it only operates
in bit. There is a need for translation process that will convert the programs written in high-level
language into machine language. There are two ways of doing this either compile the program
or interpret the program. Compiling and interpreting a program can be accomplished by using
other programs called compilers and interpreters, these programs translate the program written
into a machine language.
Compiler
Interpreter
The advantage of an interpreter, however, is that it does not need to go through the
compilation stage during which machine instructions are generated. This compilation process
can be time-consuming if the program is long. The interpreter, on the other hand, can
immediately execute high-level programs.
____Chapter 1_____
EXERCISE 1
1. Enumerate the 5 stages in developing a program and briefly explain what is done in
each stage.
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________________
2. Define Algorithm.
____________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_____
4. Differentiate the different types of programming language. What are the advantages of
high-level compare with low level languages.
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________
Student’s Name: Year/Section:
Instructor’s Name: Date:
____Chapter 1____
EXERCISE 2
1. What are the things that a programmer must know in order to solve a problem?
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________
2. What is a programming language?
_________________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________________
_________________________________________________________________________________________
_________________________________________________________________________________________________
3. What is the lower level of language that the computer can understand?
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________
6. Give the two methods of program translation from high-level language to machine
language.
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________
Chapter 2
FLOWCHARTING
or
e. Only one flow line should enter a decision symbol, but two or three flow lines, one for
each possible answer, should leave the decision symbol.
<0 >0
=0
h. If the flowchart becomes complex, it is better to use connector symbols to reduce the
number of flow lines. Avoid the intersection of flow lines if you want to make it more
effective and better way of communication.
i. Ensure that the flowchart has a logical start and finish.
j. It is useful to test the validity of the flowchart by passing through it with a simple test
data.
FLOWCHARTING EXAMPLES
start
input num1
print sum
end
start
Area = side2
input side Perimeter = 4 * side
print area
end
T
age >= 18 print “can vote”
end
start
Create a flowchart that will
input two integer values and will
num1 = 0
print the higher number/value.
num2 = 0
input num1
T
num1 > num2 print num1
start
Create a flowchart that will
print the numbers from 1 to
10.
ctr = 1
F
ctr < = 10 end
T T
print ctr
ctr = ctr + 1
start
Create a flowchart that will
print even numbers from 1 to
x=2 10.
x < = 10 end
T
print x
x=x+2
____Chapter 2____
EXERCISE 1
1. Create a flowchart that will input two (2) numbers and display the sum, product,
difference and quotient.
2. Create a flowchart that will compute and display the area and circumference of a circle.
Note:
Area = pi * r * r
Circumference = 2 * pi * r
3. Create a flowchart that will compute and display the area and perimeter of a rectangle.
Note:
Area = length * width
Perimeter = 2 (length + width)
4. Create a flowchart that will input a number in feet, convert and display the number in
inches.
5. Create a flowchart that will ask the user to input a number in feet and display the number
in yards.
____Chapter 2____
EXERCISE 2
1. Create a flowchart that will input three (3) numbers and display the highest number.
(assume no equal values.)
2. Create a flowchart that will input a number and display “even” if the number is an even
number and “odd” if the number is an odd number.
3. Create a flowchart that will input a number and will print “Divisible” if the number is
divisible by 5, otherwise print “Not Divisible”.
4. Create a flowchart that will ask the user to input a character “m” or “f” and will display
“Hello Sir” if the input is “m” otherwise “Hello Madam”.
5. Create a flowchart that will input grade and will display “Passed” if the grade is 75 or
higher, otherwise it will display “Failed”.
____Chapter 2____
EXERCISE 3
1. Create a flowchart that will print all odd numbers from 15 to 48.
2. Create a flowchart that will input a starting number and an ending number and will print
all even numbers within the two numbers.
3. Create a flowchart that will print all numbers divisible by five (5) starting from 257 down
to 189.
4. Create a flowchart that will print the following numbers: 120, 100, 80, 60, 40, 20.
5. Create a flowchart that will print all even numbers from 10 to 26 and display how many
numbers were generated.
6. Create a flowchart that will display the sum of all numbers from 1 to 15.
Chapter 3
INTRODUCTION TO
C LANGUAGE
It is a general purpose and structured programming language that includes certain low level
features that are normally available only in assembly or machine language.
Historical Background of C
C was developed in the 1970’s to be originally used with the UNIX operating system by
Brian W. Kernighan and Dennis M. Ritchie. Kernighan and Ritchie gave the classic definition of
C in their book “THE C PROGRAMMING LANGUAGE”. Five years later ANSI (American
National Standards Institute) defined and developed a new standard for the C programming
language. Several Compilers were developed to implement the ANSI standard, among them
were:
Microsoft C Borland C
Turbo C AT & T C
The birth of a new paradigm in programming, Object Oriented Programs (OOP), paved
the way to new versions of the language with object oriented capabilities like:
Borland C++
Turbo C++
Microsoft Visual C++
The milestones in C’s development as a language are listed below:
Characteristics of C
Small in size
Structured language
Low level (BitWise) programming readily available
Pointer implementation – extensive use of pointers for memory, array,
Structures and Functions
C has now become a widely used professional language for various reasons.
C Program Structure
1. Headers
The segment of a C program where libraries are included in the compilation
process and where macros to be defined are written and stated. It may contain the
following:
a. Preprocessor. A system program that modifies a C program prior to its
compilation.
b. Preprocessor directive. A C program line beginning with # that provides an
instruction to the preprocessor.
A constant macro is a name that is replaced by a particular constant value before the
program is sent to the compiler.
Example
#define pi_value 3.14159
#define k 2
Note: The contents of a named constant memory location cannot change during program execution.
2. Declaration
All functions, variables, units or objects that contain values or group of values
must be made known to the computers so that memory spaces will be allocated for each
of them.
3. Functions
These are parts of a C program that performs a specific task. The task assigned
to a function is performed whenever C encounters the function name. In C, there should
be at least one function and it is the function main.
The function main() in C language declares the main program and call other functions.
4. Comments
These are remarks and non executable phrases or sentences.
Types of Comments:
Identifiers
Identifiers are names given to various program elements, such as variables, functions
and arrays. The following are the guidelines in creating identifiers:
It consists of letters and digits without space, in any order, except that the first character
must be a letter.
Uppercase and lowercase are permitted but they are not interchangeable. As an
exception, an underscore may be used as the first character of the identifier.
Reserved words and standard functions must not be redefined.
Reserved Words
Reserved words are keywords that have standard predefined meaning in C. These
reserved words can be used only for intended purpose and they cannot be used as programmer
defined identifiers.
There are four basic data types in C as shown in the table below:
Typical Memory
Data Type Description
Requirements
int positive and negative numbers without decimal 2 bytes or 1 word (varies from
point one computer to another)
char single character 1 byte
float number containing decimal point and or
4 bytes
exponent
double double precision floating point number (higher
8 bytes
precision)
In order to give more flexibility and extend the range of the various data types there are
four type qualifiers:
signed
unsigned
long
short
The modifiers long and short have been covered for integers. Prior to the ANSI standard
there were similar modifiers for floats. However, the introduction of double removed the
requirement for a long float. This is why a double has the format command % If in the printf()
and scanf() functions.
It is, however, now possible to declare a long double which uses 16 bytes of storage and
has approximately 24 digits of precision.
The signed and unsigned qualifiers are used to remove the special meaning assigned to
the first bit of storage for char and int. By default these are signed. If the first (signed) bit is zero
the number is positive, if it is one the number is negative. The effect of making a variable
unsigned is that the first bit becomes part of the positive number, thus extending the possible
range above zero. The full list of ranges can be seen in the table given.
sizeof Function
There is a C function called sizeof which returns the number of bytes allocated to the
variable or data type given in the operand. For example,
Variable
Variable Declaration
Every variable must be individually declared (or defined) before it can appear in a
program.
Variable Initialization
A variable can be given a value at the time of declaration. This is known as initialization.
Example:
The statement labeled line 1 initializes an integer variable sum with the value zero.
The statement labeled line 2 initializes a char variable mi with the value ‘S’.
The standard C library contains two functions that perform formatted input and output.
These are:
printf () which writes to the screen
scanf () which reads data from the keyboard
The term formatted means that these functions can read and write data in various
formats that the programmer decides.
The header file associated with the standard input and output is stdio.h. Any program
using these functions must incorporate this header file in the preprocessor directives.
printf () function
The sample code below shows how to use the gotoxy function in C to move the text
cursor to a different location on the screen Code.
#include<stdio.h>
#include<conio.h>
int main (void)
{
int i;
printf (“This is the first line. \n”);
gotoxy (10, 4);
printf(“This is the second line. \n”);
gotoxy (20, 8);
printf(“And this is line 3. \n”);
return 0;
}
The control string in the printf() function can contain three types of characters:
Format Commands
The format commands can be used in any combination as long as the number of
arguments exactly matches the number of format commands. Commas separate successive
arguments from each other. For example:
Scientific Notation
Floating point values may be displayed in scientific notation. In this case, %e or %E will
be used as the control string.
Example
float a = 0.000435;
printf(“0.000435 in scientific notation form is %e or %E”,a,a);
Output
0.000435 in scientific notation form is 4.350000e-4 or 4.350000E-4
Note: Single characters need to be marked with single quotes and strings in doubles.
%c Single Character
%s String of Characters
%d Decimal
%i Integer (same as %d)
%f Decimal Floating Point Number
%e Scientific Notation
%g Uses %e or %f, whichever is shorter
%o Octal
%u Unsigned Decimal
%x Hexadecimal
%% Percent Sign
%p Pointer
#include<stdio.h>
void main ()
{
printf(“This is a single character : %c \n”, ‘A’);
printf(“This is a string : %s \n”, “Hello World”);
printf(“This is a decimal number : %d \n”, 24);
printf(“This is a floating point number : %f \n”, 37.51);
}
Output:
This is a single character : A
This is a string : Hello World
This is a decimal number : 24
This is a floating point number : 37.510000
There are two format command modifiers to printf() which allow it to display either short
or long integers.
A short integer has the format command %d and a long integer has the format command
%ld.
It is possible to specify a minimum field width for a particular type of field. Placing a
number between the % sign and the format character (d, c, s, or f) does this. If the value of the
argument takes fewer characters than the width then the field will be right justified and padded
with spaces.
It is possible to pad the field with zeros by placing a decimal point and a number after
the number specifying the field width. Various examples can be seen in the program field.c in
the next page.
It is possible to combine minimum field widths. This has the effect of truncating field
values to the correct length while padding the field with requisite number of leading spaces.
These can also be seen in the program field.c.
Add a number between the % and the d of the %d placeholder for the integer in the printf
format string. This number specifies how many columns are to be used for the display of the
digits, the field width. Values are right justified.
Formatting Values of type double (n,mf) n = total field width, m = desired number of decimal
places
Value Placeholder Printed Output
3.14159 %5.2f #3.14
3.14159 %4.2f 3.14
3.14159 %5.1f ##3.1
3.14159 %5.3f 3.142
3.14159 %.4f 3.1416
0.1234 %4.2f 0.12
-0.006 %4.2f -0.01
-99.42 %6.2f -99.42
0.123 %6.2f ##0.12
-9.536 %6.2f #-9.54
-25.554 %6.2f -25.55
99.999 %6.2f 100.00
999.4 %6.2f 999.40
The program field.c demonstrates the use of field width specifiers and justification.
void main ()
}
Output:
This is a string in a 10 character space: Hello
This is a short integer in a 5 character space: 21
This is short integer padded with zeros: 00024
This is a left justified string: Hello
This is a string with a truncated field: Hello Wo
This shows a truncated field with padding: Hello Wo
This shows a floating point number to 2 places: 37.17
In floating point numbers the use of a decimal point before the field width specifier is
different from its use in strings and integers. It means that the field should be printed only to that
number of decimal places (the default is 6).
Escape Sequences
To provide even more formatting in printing, there are various escape sequences. The
most common is \n which is the escape sequence to print a newline character. This is taken
from UNIX. The full list of escape sequences can be seen in the table below.
\a Alert (bell)
\b Backspace
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
\’ Single quote
\” Double quote
\\ Left switch
\0 Null
As printf() writes to the screen (or stdout) scanf() reads input from the keyboard (or
stdin). It has the same general form and uses the same format commands. However, where
printf() writes the value directly to the screen, the scanf() function needs to know where to write
the input value from stdin to their memory address. This is achieved by using the operator &
meaning address of. For example, to read a value from stdin into a short integer called hicount
the scanf() function call would be:
scanf(“%d”, &hicount);
Another important part of the scanf() function is the use of white spaces.
Any number of spaces, tabs, or newline characters is white spaces. This includes
combinations of the three. Therefore, if 3 integers are to be received, then scanf() will continue
to wait until a non-white space character is typed. For example,
, will wait until all three values have been entered separate by white space. The three
distinct values will be assigned to variables hinum1, hinum2, hinum3, respectively.
A non-white space character in the control string will be read and ignored if it is matched
exactly in the input string. If not, the function will be terminated. For example,
,will require the two input numbers to be separated by a comma. The comma must be
typed during the input string. It is possible to say that there will be a character that separates the
two variables, but the exact character is unknown. This is usually done for dates which is
achieved by using the * to suppress the assignment of the value. For example,
,would allow input of 10:20, 10/20 or 10,20. The middle character must be present, but is
effectively ignored. This also applies if a white space character is entered, hence 10 20 would
also match this statement.
String Addresses
A string is, in fact, only an array of characters. The base name of an array is its address.
Therefore, when allocating values to string using scanf() there is no requirement to use the
address-of (&) operator. This is shown in the following example:
scanf(“%s”, cname);
It is important to note that the string is read only to the first white space character. Any
spaces would mean that a second part to the name would be ignored. It is possible to limit the
maximum number of characters read into a string by placing a specifier before the format
command for the string:
scanf(“%15s”, cname);
getch()function
gets a character from console but does not echo to the screen
Example
ch = getch(); a character input is assigned to ch even without entering a white
space
getche()function
Example
ch = getche(); a character input is assigned to ch even without entering a white
space and displays the character to the screen
Assignment Operator
This operator is denoted by a single equals sign ( = ) and is used in assigning values to
variables.
Assignment Statement
variable_name = value;
This statement assigns the value on the right to the variable named on the left. Consider
the given example.
int x, y, z;
z = 5; x = 6; y = 4; // line 1
x = x + y; // line 2 x gets the value of 10
y = y + 5; // line 3 y gets the value of 9
The statement labeled line 1 assigns he values 5, 6 and 4 to the variables z, x and y
respectively
The statement labeled line 2 increments the value of the variable x by 4
The statement labeled line 3 increments the value of the variable y by 5.
Operators
Operators are symbols that tells the compiler to perform specific mathematical or logic
manipulations
1. Arithmetic
2. Relational
3. Logical
4. Bitwise
Arithmetic Operators
Precedence of Operators
() Parenthesis highest
*, /, % Multiplication, Division, Modulus whichever comes first
from left to right if any to
+, - Addition, Subtraction whichever comes first from left
to right if any. lowest
Refer to the following example
9 * 3=27
5 + 12 = 17
Modulus Operator
The modulus operator is denoted by a percent sign (%). It returns the integer remainder
of two integer operands. Refer to the given example
int a, b, c;
a = 8;
b = 3;
c = a % b; //line1 c = 2
c = b % a; //line2 c = 3
The statement labeled line1 assigns the integer value 2 to the variable c since the
remainder is 2 when 8 is divided by 3.
The statement labeled line2 assigns the integer value 3 to the variable c since the
remainder is 3 when 3 is divided by 8.
abc a*b*c
a + bc a+b*c
y3 y*y*y
a a / (b+c)
(b+c)
a (a+b) a * (a+b)
C provides special assignment operators that make possible a more concise notation of
statements. Statement of the form variable op = expression is an alternate way of writing the
statement variable = variable op (expression ; Refer to the example below:
Example
Statements Explanation
a = 5; c = 0; c = 6 and a = 6
c = ++a;
a = 5; c = 0; c = 5 and a =6
c = a++;
b = 3; c = 0; c = 2 and b = 2
c = --b;
b = 3; c = 0; c = 3 and b = 2
c = b--;
Relational Operators
Logical Operators
&& AND
|| OR
! NOT
Note:
The logical operators AND and OR take precedence to the relational operators. The logical
NOT, however, takes a higher precedence than anything.
As with relational operators, any expression involving a logical test will return either true
(1) or false (0) value.
Logical OR ( || )
Logical Logical Logical Expression1 OR Logical Result
Expression1 Expression2 Expression2
False(0) False(0) False || False 0 || 0 False (0)
False(0) True(1) False || True 0 || 1 True(1)
True(1) False(0) True || False 1 || 0 True(1)
True(1) True(1) True || True 1 || 1 True(1)
Logical OR is denoted by || (double pipe sign). Notice that based on the table, if one
logical expression is true the result is also true.
Example:
Logical AND is denoted by && (double ampersand sign). Notice that based on the table,
if one logical expression is false the result is also false.
Example:
Logical NOT negates the logical expression. Negating a true expression gives a false
value and negating a false expression gives a true value. Consider the example shown below.
Bitwise Operators
& Binary operator AND
Example:
int a = 3, b = 5, c;
c = a & b; // c = 1 0011 & 0101 = 0001
| Binary operator OR
int a = 3, b = 5, c;
c = a|& b; // c =7 0011 & 0101 = 0111
^ Exclusive OR
int a = 3, b =5, c;
c = a & b; // c = 7 0011 & 0101 = 0110
Shift Operators
<<Shift Left
int a = 4,b;
b = a<<1; // a is 0100 b is 1000
>>Shift Right
int a = 4,b;
b = a>>2; // a is 0100 b is 0001
Order of Precedence
From high priority to low priority the order for some C operators is:
() &&
!, ,-,*,&,++,- ||
*,/,% ?:
+,- =, + =, - =
<, <=,>=,>
==,!=
&
,|
Student’s Name: Year/Section:
Instructor’s Name: Date:
____Chapter 3____
EXERCISE 1
a. 5.78 = _____________________________
b. -9 = _____________________________
c. 8.904 = _____________________________
d. ‘u’ = _____________________________
e. 898 = _____________________________
Output:
____________________________________________________________________________
______________________________________________________________________
__________
Output:
____________________________________________________________________________
______________________________________________________________________
__________
c. a = 5 ; b = 4 ; c = 8;
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________
Output:
____________________________________________________________________________
______________________________________________________________________
__________
e. a = 5 ; b = 4 ; c = 8;
Output:
____________________________________________________________________________
______________________________________________________________________
__________
a = 6;
b = 7;
c = a++ + b --;
printf(“ the value is %d”, c);
printf(“ the value is %d”, a);
printf(“ the value is %d”, b);
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______
____Chapter 3____
LABORATORY EXERCISE 1
c. printf(“Hello World”);
d. scanf(“%d”, &value);
e. \\\Hello!, How are you?? “I’m fine!”//
2. Create a program that will input two (2) numbers and display the sum, product,
difference and quotient.
3. Create a program that will compute and display the area and circumference of a circle.
Note:
area = pi * r * r
circumference = 2 * pi * r
4. Create a program that will compute and display the area and perimeter of a rectangle.
Note:
area = length * width
perimeter = 2 (length + width)
5. Create a program that will input a number in feet, convert and display the number in
inches.
6. Create a program that will ask the user to input a number in feet and display the number
in yards.
7. Create a program that will ask the user to enter student’s prelim, midterm and finals
grade and will automatically display the average grade of the student.
Chapter 4
SELECTION STATEMENTS
a. if statement
b. switch statement
The if statement
The flowchart below illustrates how the if statement works. It performs an action if the
conditional expression is true or skips the action if the conditional expression is false. The if
statement requires the use of parenthesis around the conditional expression. There is no
semicolon after the parenthesis and after the end of the curly brace. This limits the range of
actions subject to the conditional expression. The else part is optional. It may or may not be
included in an if statement. An example is given by the program if_c.c Notice that there is no
else part in the if statement.
Exit
The else keyword is optional and is used when there are two possible courses of action
after an if statement. The first course of action is taken if the test is found to be true, else the
second of action is taken if the test is found to be false. An example is given by the program
if_else.c.
#include<stdio.h>
void main()
{
int num;
Note:
The body of the selection statements are contained in curly braces. If there is only one
statement associated with the conditional expression then there is no requirement for the
curly braces, but it is not a good programming practice.
if (conditional expression1)
{
statement1;
statementn;
}
else if (conditional expression2)
{
statement1;
statementn;
}
.
.
else
{
statement1;
statementn;
}
The conditional expressions are evaluated from top to bottom. Once a true condition is
found, the statement associated with it is executed and the rest of the statements are bypassed.
If none of the conditions are true then the final else is executed. Let us all recall that the else
part is optional. Thus, if the else part is not present then, no action takes place if all other
conditions are false. The program if else.c evaluates the integer grade using the if..else if
construct.
#include<stdio.h>
void main ()
{
int grade;
float numgrade;
scanf(“%d”, &grade);
if (grade >= 100)
{
printf(“Excellent”);
numgrade = 4.0;
}
else if (grade >= 95)
{
printf(“Superior”);
numgrade = 3.5;
}
else if (grade >= 90)
{
printf(“Very Good”);
numgrade = 3.0;
}
else if (grade >= 85)
{
printf(“Good”);
numgrade = 2.5;
}
else if (grade >= 80)
{
printf(“Satisfactory”);
numgrade = 2.0;
}
else if (grade >= 75)
{
printf(“Passed”);
numgrade = 1.5;
}
else
{
printf(“Failed”);
numgrade = 0.0;
}
}
Another variant of the program ifelse.c is the program ifand.c. The Logical operator
AND tests the range of values for grade.
#include<stdio.h>
void main ()
{
int grade;
float numgrade;
scanf(“%d”, &grade);
if (grade >= 75 && grade <=79)
{
printf(“Passed”);
numgrade = 1.5;
}
else if (grade >= 90 && grade <= 94)
{
printf(“Very Good”);
numgrade = 3.0;
}
else if (grade >= 95 && grade <= 99)
{
printf(“Superior”);
numgrade = 3.5;
}
else if (grade >= 85 && grade <= 89)
{
printf(“Good”);
numgrade = 2.5;
}
else if (grade >= 80 && grade <=84)
{
printf(“Satisfactory”);
numgrade = 2.0;
}
else if (grade > 100)
{
printf(“Excellent”);
numgrade = 4.0;
}
else
{
printf(“Failed”);
numgrade = 0.0;
}
The program ifor.c uses the logical operator || to determine if the input marital code is an
uppercase or a lowercase.
#include<stdio.h>
void main ()
{
char marital_code;
scanf(“%c”, &marital_code);
if(marital_code == ‘M’ || marital_code == ‘m’)
printf(“Married”);
else if(marital_code == ‘S’ || marital_code == ‘s’)
printf(“Single”);
else if(marital_code == ‘D’ || marital_code == ‘d’)
printf(“Divorced”);
else if(marital_code == ‘W’ || marital_code == ‘w’)
printf(“Widowed”);
else
printf(“invalid code”);
}
The string functions toupper or tolower can be used instead of the logical operator OR.
String functions are discussed in Chapter 6.
One of the problems with multiple if-else-if constructs is that they become unwieldy to
use and difficult to read. To avoid this problem the switch statement exists. It is, in effect, a
series of if statements nested into one construct. The flowchart below illustrates how the switch
statement works.
true
Variable = constant1 First case body
false
true
Variable = constant2 Second case body
false
Where the if statement can test for relational or logical expressions, the switch statement
can only test for equality. The constant1, constant2, etc must be exact matches to the
expression in parenthesis (usually a variable).
The inside of the curly braces will consist of blocks of code that specify actions if the
constant is matched. These blocks of code are given a label which consists of:
The default keyword specifies what action is taken if no match is found. The label is
optional; no action will be taken at all if no match is found and the default is missing.
The switch statement will progress through all available actions once the constant has
been matched. for this reason the break keyword prevents the switch statement from
performing actions unrelated to that particular constant.
Where the actions to be processed are applicable to more than one constant, then it is
possible to have more than one label above these actions. However, each label must
follow the format specified above.
The program switcha.c uses the switch construct to determine the value of the
marital_code found in the program ifor.c.
#include<stdio.h>
void main ()
{
char marital_code;
scanf(“%c”, &marital_code);
switch(marital_code)
{
case ‘M’:
case ‘m’: printf(“Married”);
break;
case ‘S’:
case ‘s’: printf(“Single”);
break;
case ‘D’:
case ‘d’: printf(“Divorced”);
break;
case ‘W’:
case ‘w’: printf(“Widowed”);
default : printf(“invalid code”);
break;
}
}
/* switch.c */
#include<stdio.h>
void main ()
{
int num;
case 3:
case 4:
printf(“Three or Four \n”);
break;
case 5:
case 6:
printf(“Five or Six \n”);
case 7:
case 8:
printf(“Bigger than Four \n”);
break;
default:
printf(“Invalid Number \n”);
break;
}
}
In the example, the user is asked to input a number. If the number is 1, 2, 3, or 4 then
the program will say either “One or Two” or “Three or Four”. The break statements will then
make the program jump to the end of the switch statement and move on with the processing.
If the user types a 5 or 6, the first constant to match is case 5 or case 6. This will cause
the program to print out “Five or Six”. However, as there are no break statement, the program
will continue through the next actions and print “Bigger than Four.
If a 7 or 8 typed then the program will simply state “Bigger than Four”.
If any other number is typed then the default option is chosen which prints “Invalid
Number”.
The ? (ternary condition) operator is a more efficient form for expressing simple if
statements. It has the following form:
z=(a<b) ? a : b;
if(a<b)
z = a;
else
z = b;
Suppose you want to print the string Even if the number is divisible by 2 otherwise print
Odd. Using the ternary condition operator the statement is
if(num % 2 = = 0)
printf(“Even”);
else
printf(“Odd”);
Student’s Name: Year/Section:
Instructor’s Name: Date:
____Chapter 4____
EXERCISE 1
Determine the output of the following program fragments
1. x = 3;
y = 5;
if ( x < 2 )
printf(“%d”,x);
else
printf(“%d”,y);
Output:
____________________________________________________________________________
______________________________________________________________________
__________
2. x = 4;
y = 5;
if ( x==4 )
printf(“%d”,x);
else
printf(“%d”,y);
Output:
____________________________________________________________________________
______________________________________________________________________
__________
3. status = 4;
if(status == 3)
{
printf(“Chemist\n”);
if(status == 4)
printf(“Physicist\n”);
else
printf(“Botanist\n”);
}
else
printf(“Biologist\n”);
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________
4. x = 5;
if ( x < 6)
printf(“%d”, x);
else if ( x < 7 )
printf(“%d”, 2 * x);
else if ( x < 8 )
printf(“%d”, 3 * x);
else
printf(“%d”, 4 * x);
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________
5. value = 1;
switch (value)
{
case 0: printf(“Red\n”);
break;
case 1:printf(“Yellow\n”);
break;
case 2:printf(“Pink\n”);
break;
}
printf(“End of switch”);
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________
6. value = 1;
switch(value)
{
case 0: printf(“Red\n”);
case 1:printf(“Yellow\n”);
case 2:printf(“Pink\n”);
}
printf(“End of switch”);
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________
____Chapter 4____
EXERCISE 2
___________ 1. Which condition determines whether the value of the score variable is between
90 and 100 inclusive?
___________ 2. For the compound condition to be true when the Or operator is being used,
the______.
a. False
b. True
c. No value
d. 0 or false value
___________ 4. For the compound condition to be true when the And operator is being used,
the______.
a. 50
b. True
c. Yes
d. t
____Chapter 4____
LABORATORY EXERCISE
1. Create a program that will input three (3) numbers and display the highest number.
(Assume no equal values).
2. Create a program that will input a number and display “even” if the number is an even
number and “odd” if the number is an odd number.
3. Create a program that will input a number and will print “Divisible” if the number is
divisible by 5, otherwise print “Not Divisible”.
4. Create a program that will ask the user to input a character “m” or “f” and will display
“Hello Sir” if the input is “m” otherwise “Hello Madam”.
5. Create a program that will input grade and will display “Passed” if the grade is 75 or
higher, otherwise it will display “Failed”.
6. Create a program that will ask the user to input student’s Prelim, Midterm and Final
grade. After accepting the input, the program should automatically compute for its Final
Subject Grade and display the grade and its equivalent.
Formula:
Grade Equivalence:
96-100 = 1.00
94-95 = 1.25
92-93 = 1.50
89-91 = 1.75
87-88 = 2.00
84-86 = 2.25
80-83 = 2.50
78-79 = 2.75
75-77 = 3.00
Below 75 = 5.00
Chapter 5
REPETITIVE STATEMENTS
The for loop is the most powerful and flexible of all of the loops used in C. The flowchart
below illustrates how the for statement works.
initialization expression
false
Conditional exit
true
Body of loop
increment/decrement expression
.
.
statement n;
}
Note:
The body of loop or all iterative/repetitive statements are contained in curly braces. If there is only
one statement then of
An example there
theisuse
no of
requirement
for loop isforshown
the curly braces,
in the but it for1.c
program is not ausing
good an
programming
increment
practice.
expression.
void main()
{
int num;
initialization Conditional expression Increment expression
Output:
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Another example of a for loop is shown in the program for2.c using a decrement
expression.
void main()
{
int num;
initialization Conditional expression Increment expression
Infinite Loop
It is possible to omit any element within the parenthesis provided the semicolon is
retained. For example,
for( ; ; )
{
printf(“This loop runs forever\n”);
}
The for loop shown above causes an infinite loop. That is, a loop that runs forever.
Note that there is still only one conditional test. Although it may be a compound test of
more than one piece of logic, it will always equate to true (1) or false (0).
false
Conditional expression exit
true
Body of loop
In order that the loop body is executed the conditional expression should equate to true
(i.e.: 1).
Note that there is no semicolon after the conditional expression, but each independent
action within the body does.
Note that the variable num is initialized to zero when it is declared. The conditional
expression is that num is less or equal to five. It is also important that the body of the loop
contains an increment/decrement expression. In this case, the increment is the special
assignment operator +=.
Without the increment, the conditional expression would never be false and the loop
would continue forever.
#include<stdio.h>
void main()
{
int num = 0; initialization
Output
Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Output
Count is 0
Count is 1
Count is 2
initialization;
while (conditional expression)
{
statement1;
statement2;
increment/decrement expression;
}
The program while2.c demonstrates an equivalent while statement of the for statement
shown in the program for2.c
#include<stdio.h>
void main()
{
int num = 5; initialization
The do Statement
The do statement is different from the while statement. The body of the loop is
performed once before the conditional expression is tested. Thus, it executes the body of the
loop at least once. The flowchart below illustrates how the do statement works.
Body of loop
false
conditional exit
true
do
{
statement1;
statement2; /* Body of loop */
…
…
statementn;
}while(conditional expression);
For this particular loop the semicolon is required after the conditional expression. An
example of the use of the loop is shown in the program do.c. The loop, in this case, has exactly
the same effects as the while loop given by the program while.c.
Nested Loop
The body of loop may include another loop. In this case, the loops are said to be nested.
The program nested.c contains a nested loop. The outer loop counts from 1 to 5 and the inner
loop counts from 1 to 4.
#include<stdio.h>
int ctr1, ctr2;
main()
{
Outer loop for (ctr1 = 1; ctr1 <= 5; ctr1++)
{
Inner loop for (ctr2 = 1; ctr2 <= 4; ctr2++)
{
printf(“outer loop count -> %d”, ctr1);
printf(“inner loop count -> %d\n”, ctr2);
}
}
}
The break keyword can also be used as a means of control within a loop. It is often used
as
the loop control mechanism in a forever loop. The important thing to note is that it will only
break out of the current loop, so any nested loops will break to only one level higher. An
example is shown in the program break.c.
#include<stdio.h>
void main()
{
int num;
for( ; ; )
{
printf(“Please type in a number”);
scanf(“%d”, &num);
if(num = = 521)
{
break;
}
}
printf(“Finished Looping”);
}
Once the break statement is reached, the loop is exited and the processing continues
with
the “Finished Looping” statement.
This key word is used to exit the current iteration of the loop, but continue with the next
loop control statement (i.e.: increment). An example of this is seen in the program continue.c,
where any user who is under eighteen will not be asked the subsequent questions. However,
the program will still run through ten iterations.
#include<stdio.h>
void main()
{
int num = 0, age;
char answer[15];
for(num = 0 ; num <= 10 ; num++)
{
printf(“Next person: please type in your age”);
scanf(“%d”, &age);
if(age < 18)
{
continue;
}
printf(“Do you drink coffee? \n”);
scanf(“%s”, answer);
}
printf(“Finished Looping”);
}
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________
3. x = 8;
while(x >= 0)
{
printf(“%d\n”, x);
x = x-2;
}
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________
4. x = 8;
while ( x >= 0 )
{
x = x-2;
}
printf(“%d\n”, x);
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________
5. x = 2;
while ( x == 2 )
{
x = x – 1;
printf(“%d\n”, x);
}
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________
6. x = 2;
while ( x == 2 )
{
x = x – 1;
}
printf(“%d\n”, x);
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________
Student’s Name: Year/Section:
Instructor’s Name: Date:
____Chapter 5____
LABORATORY EXERCISE
1. Create a program that will print all odd numbers from 15 to 48.
2. Create a program that will input a starting number and an ending number and will print
all even numbers within the two numbers.
3. Create a program that will print all numbers divisible by five (5) starting from 257 down to
189.
4. Create a program that will print the following numbers: 120, 100, 80, 60, 40, 20.
5. Create a program that will print all prime numbers from 1 to 100.
6. Create a program that will display the sum of all numbers from 1 to 15.
7. Create a program that will display the following:
a. **********
**********
**********
**********
**********
b. *
**
***
****
*****
c. *
***
*****
*******
*********
d. 1
121
12321
1234321
123454321
8. Create a program that will display a Fibonacci series of numbers. The program should
ask the user to enter the size of the series and will automatically show the Fibonacci
series from 0 to the given size.
9. Create a program that will display a multiplication table of numbers. Starting from 1 to
10.
10. Create a program that will ask the user to input a starting number and ending number.
Based from the given range, display all odds, even and prime numbers.
Chapter 6
FUNCTIONS
Functions are used in modular programming. Functions are called in the void main
program and perform a specific task.
Advantages
Characteristics
A section of a program that performs a specific task. The task assigned to a function is
performed whenever C encounters the function name.
Functions are the building blocks in a C program. Every C program has at least one
function and every executable C statement appears inside some function or another.
As its simplest level a function performs a single task or operation. A computer program
generally consists of a series of tasks, each of which can be coded as a function and
called from the body of the program. In this way repetitive code is avoided.
Function Prototypes
C functions should be both declared and defined. A function declaration states the
return type, the function name, the parameter list it may take. This is known as function
prototype.
A function definition actually creates the function and allocates the memory required.
Parts of a Function
1. Function header
a. Return Type
Specifies the type of value that the function returns using the return
statement.
If no type is specified, the function is assumed to return an integer result
b. Function name
Identifier name for the function
c. Parameter list
A comma-separated list of variables that receive the values of the arguments
when the function is called
Also known as value parameters
A function may or may not have parameters
2. Declaration section
Local variable declaration
3. Function statements.
Note: The declarations for the standard C functions are contained in header files, while
the definitions are in the standard C library. Functions written by the programmer
should be declared at the beginning of the program and may be coded before or after
the void main() function.
Return Statement
Void Functions
Functions with no return values are called void functions. The program Func_a.c
contains the void function display that displays five asterisk.
/* Func_a.c demonstrates the function display that displays five
asterisks */
#include<stdio.h>
void display ( ); // function prototype
void main ( )
{
display ( ); //function call, execute function display
}
void display ( ) //function definition
{
int ctr; //local variable
for (ctr=1; ctr<=5; ctr++)
printf(“*”);
}
Output:
*****
Functions can be called more than once in a program. The program Func_b.c contains
the function display_asterisk. Notice that the function display_asterisk is inside the for loop.
This causes the function display_asterisk to execute five times.
}
void display_asterisk ( ) //function definition
{
printf(“*”);
}
The program fntn1.c contains the function compute_sum that accepts two integer
parameters a and b and returns the integer sum. It also contains the function
compute_product that accepts two float parameters c and d and then returns the product that
is of type float.
/* fntn1.c: A program that demonstrates the function compute_sum that
returns an integer value and compute_product that returns a float
value */
#include<stdio.h>
void main()
{
printf(“the sum is %d”, compute_sum(8,9)); /*function call,
execute function */
The program fntc2.c contains the function display_letter_grade that accepts an integer
parameter grade and returns the equivalent character grade.
#include<stdio.h>
char display_letter_grade(int grade);
void main()
{
int grade;
scanf(“%d”, &grade);
printf(“%c”, display_letter_grade(grade));
}
Pass by Value
A copy of the arguments value is made and passed to the called function. Changes to
the copy do not affect the original variable’s value in the caller. It should be used whenever the
function does not need to modify the value of the original variable. The program swap_a.c
contains the function swap with two parameters a and b that are passed by value.
#include<stdio.h>
void swap(int a, int b);
void main()
{
int a = 5, b = 10;
swap(a,b); //function call
printf(“In function void main\n”);
printf(“a = %d\n b = %d”, a,b);
}
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
printf(“In function swap\n”);
printf(“a = %d b = %d \n”, a,b);
}
Output:
In function swap
a = 10 b = 5
In function void main
a = 5 b = 10
Notice that the values of a and b in function void main did not change after the execution
of the function swap.
Passed by Reference
It allows the function to modify the original variable’s value. The program swap_b.c
contains the function swap and passed the parameters by reference. In passing by reference.
The address to the argument is copied to the parameter.
/* swap_b.c */
#include<stdio.h>
void swap (int *a, int *b);
void main()
{
int a = 5, int b = 10;
swap(&a, &b); /* pass the address of the parameters */
printf(“In function void main \n”);
printf(“a = %d \n b = %d”, a,b);
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
printf(“In function swap \n”);
printf(“a = %d b = %d \n”, a,b);
}
Output:
In function swap
a = 10 b = 5
In function void main
a = 10 b = 5
1. Global variables are known throughout the entire program and may be used by any
piece of code.
2. Local variables are variables that are declared inside a function and may only be used
inside the function where it is declared.
#include<stdio.h>
int x = 20; Global Variable
void local_function();
void main()
{
printf(“the value of x in function void main is %d”, x);
local_function();
printf(“the value of x after the execution of local_function is
%d”, x);
}
void local_function()
{
int x = 5; Local Variable
____Chapter 6____
EXERCISE 1
1. What is printed?
int f( );
int g( );
void main()
{
int x,y,s;
s = 2;
y = f(s);
g = f(s);
z = f(s);
printf(“%d %d %d”, s,y,z);
}
int f (int a)
{
int t = 8;
a += 5;
t -= 4;
return (a + t);
}
int g (int a)
{
int t = 1;
a += 5;
t += a;
return (a + t);
}
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________
2. What is printed?
float x = 4.5;
float f (int a);
void main()
{
float y;
x *= 2.0;
y = f(x);
printf(“%f %f \n”, x,y);
}
float f(float a)
{
a += 1.3;
x -= 4.8;
return (a + x);
}
Output:
____________________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
__________________________________________________________
3. Which of the following statements can be used to call a void function named printHead,
that accepts two integer parameters named title and grade?
4. Which of the following function prototypes can be used for a void function named
dispHead that will be passed the address of two integer variables name num1 and
num2.
____Chapter 6____
LABORATORY EXERCISES
1. Write a function Oriented Program that converts the input inches into its equivalent
centimeters. One inch is equal to 2.4 cms. Display the converted centimeters value.
2. Write a function Oriented Program that calculates the area of a Circle. Use the formula: )
is equal to 3.1416 (approximately).
3. Write a function-oriented program that generates the Fibonacci series numbers of n (as
input) and display them. In Fibonacci, the current third number is the sum of two
previous numbers.
4. Write a function-oriented program that calculates the power value of the input base
number and exponent number. Then display the power value.
Sample Input/Output:
Chapter 7
ARRAY
A fixed number of data items which are stored contiguously and the elements can be
accessed by an index/subscript. It is also a finite ordered collection of homogenous elements.
Thus, the following are the characteristics of an array:
Finite. There is a specific number of elements in the array.
Ordered. All the elements of the array are arranged so that there is first, second, third
and so on.
Homogeneous. All the elements in the array must be of the same type (e.g. all integers,
all characters, all floating point).
Extraction is an operation that accepts an array variable, indicated by its array name
and element of its index type and returns the array’s content
Example: X = b[3];
H = x[ctr1][ctr2];
Example: A[4] = 4;
F[ctr] = ctr + 1;
Sample Declaration:
The program Array1.c contains three (one dimensional) arrays namely: array_int,
array_char and array_float. array_int has five elements which are integers, array_char has five
elements which are characters and array_float has five elements which are floats. The first for
loop stores integers, characters and float values to all the elements of the three arrays. The
second for loop displays the contents of all the elements of the three arrays. The first element of
an array has a subscript of 0, the second element has a subscript of 1, the third element has a
subscript of 2 and so on. Refer to the figure below.
#include<stdio.h> array_int[0] 2
void main() array_int[1] 3
array_int[2] 4
array_int[3] 5
array_int[4] 6
array_char[0]
‘a’
array_char[1]
array_char[2] ‘a’
array_char[3] ‘a’
‘a’
{
int array_int [5];
int array_char [5];
int array_float [5];
int ctr;
The program Array2.c allows the user to store 10 integers, accumulate their sum and
extract (print) the integers in reverse order.
#include<stdio.h>
void main()
{
int array_int [10];
int ctr, sum;
sum = 0;
A two dimensional array has two pairs of square brackets. The statement int array_2d[2][3];
defines a two dimensional array of integers with 6 elements. To compute for the number of elements,
simply multiply the first dimension with the second dimension. In the declaration, simply multiply 2 by 3.
Two subscripts are needed to access each element. Refer to the figure below.
#include<stdio.h> 3 3 3
void main() 3 3 3
{
int array_2d [2][3]; array_2d
____Chapter 7____
EXERCISE 1
x = 2; y = 3;
array_1dim[0] = 4;
array_1dim[1] = 3;
array_1dim[2] = 5;
array_1dim[3] = 7;
array_1dim[4] = 8;
Output:
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
____________________________________________________________________________
___________________________________________________________
____Chapter 7____
LABORATORY EXERCISES
1. Create a program that stores integer values to an array whose size is 15. Futhermore,
increment by five the integers that are divisible by 3.
2. Create a program that stores 10 integers. Print the maximum and the minimum integer
found in the array.
3. Create a program that will ask the user to input 9 integer numbers and display its vertical
and horizontal sum. The numbers should be encoded in a 3 rows and 3 columns
manner. After the user entered each set of numbers in a row, the horizontal sum of the
set of numbers should automatically be shown.
Example:
5 10 15 = 30
Once all 3 set of numbers have been entered, the vertical sum should automatically be
displayed.
Example:
5 10 15 = 30
3 6 9 = 18
1 2 3 = 6
_____________________________
9 18 27 = 55
4. Create a program that will display magic square of numbers based on a given odd magic
square size. A magic square is a square array of numbers consisting of the distinct
positive integers 1,2, …, arranged such that the sum of the numbers in any horizontal,
vertical, or main diagonal line is always the same number, known as the magic constant.
The program should ask the user to enter an odd integer that will serve as the size of the
square. The program should validate if the entered number is an odd or even number. If
the number is even, the program should display an error message and ask the user to
enter a number again. Once a valid size is entered, the program should automatically
display the magic square.
Example:
Enter the size of the square: 3
The magic square of size 3 is:
6 1 8
7 5 3
2 9 4