EC201 - FUNDAMENTAL PROGRAMMING.pdf
Transcript of EC201 - FUNDAMENTAL PROGRAMMING.pdf
1
COURSE : EC201 FUNDAMENTAL PROGRAMMING INSTRUCTIONAL DURATION : 15 WEEKS
CREDIT(S) : 2
SYNOPSIS:
FUNDAMENTAL PROGRAMMING provides an introduction to programme design and development. A structured, multiphase programme development process featuring a series of steps involving understanding of a problem, formal programme definition, and programme specification through graphic design methodologies and pseudo coding is stressed. A selected high-level programming language, C, is used to illustrate the implementation phase of programme development.
LEARNING OUTCOMES:
Upon completion of this course, students should be able to:-
1. solve various problem systematically using the 6 step procedure and specified design tools.
2. select the appropriate data types for a particular solution. 3. perform data handling in solving a given problem correctly. 4. execute the whole process of programming, using a high level programming language,
in solving a variety of engineering and scientific problems. 5. deliver a presentation and answer questions with confidence on a well-organized
assigned group project inclusive of a report within a stipulated time frame.
MAIN OBJECTIVES:
At the end of this course, students should be able to:
1.0 INTRODUCTORY CONCEPTS
1.1 Introduction To Programming
1.1.1 Define the following terms: a. programme b. programmer c. programming language
1.1.2 List the various types of programming languages 1.1.3 Explain the various types of programming languages 1.1.4 Explain the following types of programming:
a. Structured programming b. Modular programming c. Object-Oriented programming
1.1.5 Compare between the following types of programming: a. Structured programming b. Modular programming c. Object-Oriented programming
http://modul2poli.blogspot.com/
2
1.2 Understand Problem Solving 1.2.1 List the stages involved in problem solving. 1.2.2 List the elements of problem analysis:
a. Input b. Process c. Output
1.2.3 Explain the elements of problem analysis. 1.2.4 Determine input, process and output for a given problem. 1.2.5 List the design tools for problem solving:
a. Flowchart b. Pseudocode c. IPO chart (Input-Process-Output chart) d. Structured chart
1.2.6 Explain the flowchart, pseudocode, IPO chart and structured chart. 1.2.7 Illustrate the various design tools. 1.2.8 Use the design tools to solve a given problem. 1.2.9 Identify the various types of error in programming:
a. Syntax Error b. Run-Time Error c. Logical Error
1.2.10 Explain the various types of error in programming. 1.2.11 Write programme source code. 1.2.12 Execute the debugged programme source code.
2.0 PROGRAMME DESIGN
2.1 Know Operators And Expressions 2.1.1 Explain the operand and operator. 2.1.2 Describe the different types of operator: arithmetic, relational, logical, and
Boolean operator 2.1.3 Explain expressions in application
2.2 Understand Programme Flow Control Structures 2.2.1 Identify Programme Flow Control Structures. 2.2.2 List the various types of logical structures. 2.2.3 Explain the various types of logical structures.
a. Sequence b. Selection c. Looping
2.2.4 Describe the different types of selection structure. a. if, if..else, switch..case b. Nested selection c. Decision table
2.2.5 Describe the different types of looping structures. a. For b. while, do.. while c. Nested looping
2.2.6 Solve sequence, selection and looping structure problems using programme design tools.
a. Flowchart b. IPO chart
http://modul2poli.blogspot.com/
3
c. Structured chart d. Pseudocode
2.3 Know Storing Information 2.3.1 Define a variable and a constant. 2.3.2 Describe the following basic data types: numeric, character, string,
logical. 2.3.3 Identify the operators used in programming. 2.3.4 Explain the operators used in programming.
a. Mathematical operators b. Relational operators c. Logical operators
2.3.5 Use operators in expression statements. 2.3.6 Explain the differences between a formula and an expression. 2.3.7 Convert formula into expression and vice versa.
2.4 Understand Array And Programme Design
2.4.1 Define what an array is. 2.4.2 Describe array structure. 2.4.3 Identify single-dimensional array and multi-dimensional array. 2.4.4 Compare single-dimensional array and multi-dimensional array. 2.4.5 Solve single and multi dimensional array problems using programme
design tools. a. Flowchart b. IPO chart c. Structured chart d. Pseudocode 3.0 C FUNDAMENTALS
3.1 Understand Structure Of C Programme
3.1.1 Describe the general form of C programmes. 3.1.2 Write the general form of C programmes. 3.1.3 Compile C programmes. 3.1.4 Execute the debugged C programmes. 3.1.5 Define the pre-processing directives and header files
a. #include b. #define
3.1.6 Create header file in C programmes. a. stdio.h b. ctype.h c. math.h d. conio.h e. string.h
3.1.7 Create block { .. } in Main function. 3.1.8 Create return statement in programmes. 3.1.9 Explain the usage of comments. 3.1.10 Create comments in programmes.
http://modul2poli.blogspot.com/
4
3.2 Know Constants And Variables (Identifiers) 3.2.1 Identify the rules for naming constants and variables. 3.2.2 Declare constants and variables. 3.2.3 Identify the scope of constants and variables. 3.2.4 Build constants and variables in programmes. 3.2.5 Identify and explain keywords in C programmes. 3.2.6 Use keywords in programmes
3.3 Understand Data Types
3.3.1 List the basic data types in C. 3.3.2 Explain the basic data types in C.
a. int b. char c. float d. double
3.3.3 Use data types in C programmes.
3.4 Understand Operators and expressions. 3.4.1 List the basic Operators and expressions in C programmes. 3.4.2 Explain the Operators and expressions in C programmes. 3.4.3 Use the Operators and expressions in C programmes.
4.0 DATA INPUT AND OUTPUT
4.1 Understand Input Output Statements
4.1.1 Define of input output statements. 4.1.2 Explain the function of input output statements.
a. printf() and puts() b. scanf() and gets()
4.1.3 Use format specified in programmes 4.1.4 Modify input output file in programmes. 4.1.5 Create input output operations.
5.0 CONTROL STATEMENT
5.1 Understand Programme Controls 5.1.1 Write C programme using selection statements.
a. if b. if..else c. nested if d. switch..case
5.1.2 Compare the differences between the various selection structures. 5.1.3 Write C programme using looping statements.
a. do..while b. while c. for d. nested loop
5.1.4 Compare the differences between the various loop structures.
http://modul2poli.blogspot.com/
5
5.2 Understand Arrays 5.2.1 Describe the steps to define an array.
a. Declaring array b. Initializing array c. Accessing array d. Manipulating array e. Passing array to function as a parameter
5.2.2 Modify a 1-dimension array in C programme. 5.2.3 Write C programme using array.
6.0 FUNCTIONS
6.1 Understand Functions 6.1.1 Define what Function is? 6.1.2 Explain the use of Functions in C programme. 6.1.3 Identify the following types of function:
a. Predefined function b. User-defined function
6.1.4 Compare the differences between the types of function. 6.1.5 Describe the following components in the user-defined function:
a. Function prototypes b. Function definition c. Return statement d. Call function
6.1.6 Compare the differences between function call by value and call by reference.
6.1.7 Write C programme using user-defined function.
ASSESSMENT
TYPES OF ASSESSMENT The course is assessed through 100% Continuous Assessment
________________________________________________________________________ [ Assessment Task above (a–e (i)) to be executed during Lecture/Practical/ Tutorial hour ]
a. Quiz (minimum 4) 10% b. Theory Test (minimum 1) 20% c. Practical Test (minimum 1) 10% d. Lab Work (minimum 6) 50% e. Other Assessment Task 10% i. Presentation (minimum 1) ii. Project (minimum 1) iii. End of chapter problem (minimum 2)
http://modul2poli.blogspot.com/
2/17/2011
1
1.1 Introduction concepts
1.0 Introduction To Programming
1.1.1 Term
programme
programmerProgramming
language
Program: A set of step-by-step instructions that directs a computer to
perform a specific task and to produce the required results.
Programming:
Programming is a process of designing/ creating a program.
Programmer:
Programmer is a person who writes the program.
c) A programming language
is set of instructions that can be used to
construct a program. A notation for
writing programs, which are specifications
of a computation or algorithm.
is a language designed to describe a set of
consecutive actions to be executed by a
computer. A programming language is
therefore a practical way for us (humans)
to give instructions to a computer.
http://modul2poli.blogspot.com/
2/17/2011
2
1.1.2 Various types of Programming
Languages There are three basic types of
programming languages.
1.1.3 (i) Machine language
The lowest-level programming language
Machine languages are the only languages understood by computers.
While easily understood by computers, machine languages are almost impossible for humans to use because they consist entirely of numbers.
Expressed in binary form, an instruction might be 0111010110110011. Very difficult to use. Lowest level of computer languages.
For example, a program written in Apple PC cannot be run in IBM PC
ii) Assembly language
Second level of language.An assembler
translates assembly language.
It was developed to replace "0" and "1" used in Machine Language.
Machine languages consist entirely of numbers and are almost impossible for humans to read and write.Takes a long time to write programs
English-like abbreviations representing
elementary computer
operations (translated via assemblers)
Example: C++, C , FORTH
http://modul2poli.blogspot.com/
2/17/2011
3
iii) High-level language
Instruction is written as a series of English-like words.
Translator (Compiler/Interpreter) is needed to translate high level language to machine language.
It is Machine-Independent. The program can be written and executed on any computer.
E.g. Fortran, COBOL, SQL, PROLOG, C
1.1.4 Structured Programming
Languages
Definition of Structured Programming
Structured programming can be defined as a Software application programming technique that follows a top down design approach with block oriented structures.
It support loop such as while, do-while and for.
Structured programming
The most popular structured programming languages include C,C++, Ada, and Pascal.
Codes similar to everyday English
Use mathematical notations
Example: if (x < 10) {
printf(“too low, ry again\n”);
Scanf(“%d”,&x);
}
http://modul2poli.blogspot.com/
2/17/2011
4
b) Modular programming
Programming paradigm based on data types.
An object stores a data type value; variable name refers to object.
A programming style that brakes down program functions into modules, each of which accomplishes one function and contains all the source code and variables needed to accomplish that function.
Modular programming is a solution to the problem of very large programs that are difficult to debug and maintain. By segmenting the program into modules that perform clearly defined functions, you can determine the source of program erros more easly.
c. Object-Oriented Programming
Languages
is about relation between the data and the code operating on the data (or data operating on the code).
is a programming paradigm that uses "objects" –data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation, modularity, polymorphism, and inheritance. Many modern programming languages now support OOP
is one the newest and most powerful paradigms. In object- oriented programs, the designer specifies both the data structures and the types of operations that can be applied to those data structures.
This pairing of a piece of data with the operations that can be performed on it is known as an object. A program thus becomes a collection of cooperating objects, rather than a list of instructions.
Objects can store state information and interact with other objects, but generally each object has a distinct, limited role.
http://modul2poli.blogspot.com/
2/17/2011
5
An object stores a data type value;
variable name refers to object.
Object-oriented programming (OOP) is a
programming paradigm based on data
types.
The most popular object-oriented
programming languages include Java, Visual
Basic, C#, C++, and Python.
Object-orientated programming
languages, such as SmallTalk and
HyperTalk, incorporate modular
programming principles
1.1.5 Comparison between the
following types of programming:
a) Structured programing
The main advantage for structured
programing is that it make input easy, and
also it is better to use because it does not
merges the data we stored in strings and
variables, sometime it happens that we get
merged data if we don't use structured data.
And it also make easy to manage variables.
Structured programming is as
follows:
--Program startvarvarvar
function { ... }function { ... }function { ... }
main { ... }--- Program End
You have units of code, which operate on variables, and are called in reference to those variables, to follow a structure acting on those variables.
http://modul2poli.blogspot.com/
2/17/2011
6
b) Modular programming
-A detailed process of problem solving
-Break a large problem into several
smaller
Sub-sections are solved separately by
observing that all these small modules to
solve the whole problem of the origin
Modular Programming - Need
and Approach
Typical industry programming projects
consist of thousands of lines of code or
more
Analogous approaches: manufacturing a
spacecraft, or a car Manufacture individual
components, test separately
Assemble into larger components,
integrate and test
Modular Programming -
Process
Advantages of Modular
Programming
Manageable: Reduce problem to smaller, simpler, humanly comprehensible problems
Divisible: Modules can be assigned to different teams/programmers
Enables parallel work, reducing program development time
Facilitates programming, debugging, testing, maintenance
Portable: Individual modules can be modified to run on other platforms
• Re-usable: Modules can be re-used within a program and acrossprograms
http://modul2poli.blogspot.com/
2/17/2011
7
An Example of Code that Doesn't Use
Modular Programming
A simple example of repeated code can be seen in:
PI = 3.14159265358979
R = 1
C = 2 * PI * R
A = PI * R * R
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
R = 2
C = 2 * PI * R
A = PI * R * R
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
R = 3
C = 2 * PI * R
A = PI * R * R
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
R = 4
C = 2 * PI * R
A = PI * R * R
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
Here the same functionality is repeated but does works (as can be seen in f igure 1). However, the programmer can work more ef f iciently by using modular programming.
A Simple Example of Modular
ProgrammingThe aim of the programmer is now to ensure that code is reused as much as possible. They do this by identifying the code that can be place
separate functions and subroutines:
PI = 3.14159265358979
function circumference (R)
circumference = 2 * PI * R
end Function
function area (R)
area = PI * R * R
end function
sub print_details (R)
C = circumference (R)
A = area (R)
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
end sub
print_details 1
print_details 2
print_details 3
print_details 4
The output is the same as before (as can be seen in figure 2), but this time the chance of the operation of the script being altered due to a typing error is greatly reduced, and if there is an error then the task of correcting it is made much simpler. The programmer can also use the functionality throughout their application without worrying about having to rewrite the code, thereby improving the e ff iciency of both the code and their time.
c)Object oriented
- fourth-generation language is object
oriented.
- Programmers will more tend to think of
the objects involved
the problem and the relationships
between objects.
-Examples of programming languages are
C + + Java
Why Object Oriented Language?
Reusability-Cepatkan project
- Improve the quality of
- Easily adjusted
- Flexible
- Easy maintenance
- Reduce the risk for complex projects
http://modul2poli.blogspot.com/
2/17/2011
8
c) Object oriented
is as follows:
--- Program Startobject {varvarfunction { ... }function { ... }function { ... }}
varvar
function { ... }main { ... }--- Program end
Variables can be objects, which have their
own data and functions. Think like C and
structures, except structures can have
functions "in them" which operate
specificly on their own data.
Example 1: Object-oriented
Problem Solving Approach
Step 1: Problem Identification - Compute
the sum of two numbers and print out
the result.
Step 2: Object Identification
- Identify objects needed to solve the
problem.
Num1 - first number (object).
Num2 - second number (object).
Sum - result of the addition of the two
numbers (object).
http://modul2poli.blogspot.com/
2/17/2011
9
Step 3: Message Identification
- Messages needed to send to objects.
+ aNum - This is the message sent to the receiver object with an parameter aNum. The result of this message is the value (a numeric object) of the total sum of the receiver object and aNum. print - a message that displays the value of the receiver object.
Step 4: Object-message sequences - Following is the object-message sequence to solve the problem.
(Num1 + Num2)print The message + with a parameter Num2 (an object), is sent to the object Num1.
The result of this is an object (Num1 + Num2), which is sent the message print. The parentheses are included to avoid any ambiguity as to which message should be activated first.
Note: The sequence of Smalltalk evaluation
is from left to right unless is specified by
parentheses ( ). For example:
2 + 3 * 4 is 20
while
2 +(3 * 4) is 14
1.2.1 Stages of Problem Solving
http://modul2poli.blogspot.com/
2/17/2011
10
The steps in programming:
1-Definitions and identify problems- Identify and understand the problems to
be solvedi. Read the questions and identify and
understand the requirements of the questionii. For the analysis to determine the
problem with three main areas:* Input required* OUTPUT issued* PROCESS determine the formula
to get the output from a given input
1.2.2 Elements of problem analysis
PROCESS
2 - Planning variables
variable is a reference to a memory
location
Variables with a specific type of data to
determine the memory size provided
All variables must be used in the program
prior diishtiharkan
3. Design a flow chart (design
software) Better known as the process of
designing algorithms
algorithm - list of measures to solve
problems
Created before the actual program coding
to make sure the solution method
correct the problem that is use
http://modul2poli.blogspot.com/
2/17/2011
11
There are two ways to write the
algorithm:
i. Pseudo code
-Steps problem solving
-Written to spoken language daily
Pseudo code
Example: Changing a bulb is burned
Start
Removing the bulb is burned
Replace with new bulb
End
Is it sufficient for the
implementation of the computer?
Example: Changing a bulb is burned (details)
StartPlace the ladder in the position of the bulb burnsChoose a suitable lampTake the stairs up to the light bulb that burnsTurn the bulb counterclockwise and take out the bulbFit the new bulb in place properTurn the bulb clockwiseDown the stairsPlace the back stairsEnd
Contoh:Mengira harga
bayarbagi buku
http://modul2poli.blogspot.com/
2/17/2011
12
4-Writing program
- Represents the implementation phase in which the code was written and typed into the computer-The program should follow the syntax correctly written on the appropriate programming language- Some programming languages: BASIC, COBOL, FORTRAN, C + +, Visual BASIC and other.
Problems ---- Pseudo Code /flow chart -----program
5-Testing & debugging program
-The program that has been built to test / run (run) to ensureoutput produced is correct and meet the needs of users- Menyahsilap (debugging) --- the program is tested with real data-There is a possibility of erroneous output (error) could result from a
program written
The types of programming errors
i) Syntax Error / encoding
when programmers fail to follow the rules governing how the instruction should be written.
Example: wrong spelling of the WRITE command. The computer will print a diagnostic message.
After all syntax errors corrected or removed compiler can understand and translate the program.
ii) Logic errors
error occurred from instruction sequences that are not correct.
It might be the error in logic programming.
Instruction means may be in conflict.
Example: the programmer should write direction READ but it write WRITE
iii. Time Error
Due to data entry is not in accordance
with the instructions written in
programming
http://modul2poli.blogspot.com/
2/17/2011
13
6-Documentation Program
If the output properly certified and meet
consumer needs
- at this stage is to prepare a report for
reference and for the updates in the
future
- Facilitate the programmer to understand
the design and programmable logic
The documentation includes:
Type of problem or the specific requirements
of the appropriate
Description of inputs, outputs, constraints and
formulas for problem
A tool used logic---- flow chart or pseudo
code
Example output of the program was
implemented (executed) using the test data
The steps or guidelines for using the program
1.2.4 Determine input, process and
output for a given problem
Understand, identify and define problems.
Determine the input requirements,
process and output (IPO)
Provide IPO
Problem analysisProblem 1
Create a program that will accept three numbers as input from the user. Find the average number and the third show -the three numbers together with the average value.
Analysis of problemsInput - 3 numbersProcess - 1. Add 3 numbers
2. 3 Divide the total number to 3Output - 3 and the average number
http://modul2poli.blogspot.com/
2/17/2011
14
answers Problem 2
Given the value of x = 10 and the value of
a = 12, find the equation of state revenue
under
y = 2x + a -6
Problem analysis
1) Input:
the value of x = 10
and the value of a = 12
2) the formula / process:
y = 2x + a - 6
3) output:
the value of y
1.2.5 DESIGN TOOL
It is a framework or flow that shows the
steps in problem solving.
Methods to design a program:
Flowchart
Pseudocode
IPO Chart(input-process-output
chart)
Structure Chart
http://modul2poli.blogspot.com/
2/17/2011
15
a) Flowchart
A graphical representation of data,
information and workflow using certain
symbols that are connected to flow lines
to describe the instructions done in
problem solving.
It shows the flow of the process from
the start to the end of the problem
solving
Explanation of basic
flowchart symbol:
http://modul2poli.blogspot.com/
2/17/2011
16
Cont…Explanation of basic
flowchart symbol:
There are few additional symbols of flowchart
used in a complicated program: GOSUB and
RETURN. It’s usually used in a big program.
Example Flowchart:
Flowchart to calculate the total of fine for late
returning of library books.
http://modul2poli.blogspot.com/
2/17/2011
17
b)Pseudocode
Steps in problem solving that is written half in programming code and half in human language.
For example, some part uses C language code and some part uses Malay or English language.
Advantages:i. Easily understood.
ii. Easily maintained.
iii. The codes are changeable.
Disadvantages:
Cannot be executed in the computer.
Example:
START
Total=0, Average=0
Input a, b, c
Total = a + b + c
Average = Total / 3
Output a, b, c
Output Average
END
c)IPO Chart (Input Process
Output)Chart IPO (input output processing)
Compiling information available in the Detailed get in shape with a display input,
processing and output
Problem 1
Uncle Ahmad wants to buy 5 cans of paint
to paint his house. The price for a can of
paint is RM 25.50. Calculate the price to
be paid for 5 cans of paint to buy.
http://modul2poli.blogspot.com/
2/17/2011
18
analysis of the problem:
1) input:
Number of cans of paint purchased, the
price of a can of paint
2) The formula / process:
5 cans of paint price = price x number of
cans
3) output:
prices for purchased 5 cans of paint
Problem 2
A lecturer to determine the grade a
student based on the marks obtained by
students in the special examination. If you
score between 85 and 100, grade A if the
student is not the student will receive a
grade of B. What grades will be earned by
the student if the score is 89?
1) input:
marks obtained
2) The formula / process:
If you score 85-100, is a grade A
If the contrary is a B grade
3) Output:
grade obtained
Problem:
A photostat shops charge 5 cents
for each page copied. Design
solutions to calculate the fee should
imposed if a number of pages that have
been
diphotostat.
http://modul2poli.blogspot.com/
2/17/2011
19
definition and identify problems
plan using the variable
Writing pseudo code
Design a flow chart (design software)
Example 1:
Problem: To calculate the amount of water bill
Example 2:
Problem: To calculate area of a circleExample : Calculate the Salary of
Employee
http://modul2poli.blogspot.com/
2/17/2011
20
d)Structure Charts Structure chart is an additional method in
preparing programs that has many sub modules.
It consists rectangular boxes, which represents all the sub modules in a program and is connected by arrows.
It illustrates the top-down design of a program and is also known as hierarchical chart because its components are in hierarchical form.
The advantage is that it is easy to be drawn and to be changed.
http://modul2poli.blogspot.com/
1
2.0 PROGRAMME DESIGN 2.1 Know Operators And Expressions
2.1.1 Explain the operand and operator.
As we have seen, a mathematics expression can be made up of only one element, for example, a number, as in:
3
The above expression evaluates to three. This value of three can be represented by the number 3.
Usually, though, expressions are much more involved than the simple one above. Let's consider this one:
3 + 2
The above expression evaluates to five.
The above expression has three elements in it:
The number 3 The addition operator '+' The number 2
Well, we have already dealt with the idea that 2 and 3 are numbers representing values in an expression. Here, let's talk about the '+'.
Officially, the '+' in the above expression is called an operator. It is the addition operator.
Operators do not exist alone in expressions. That is, for example, the addition operator needs some values to add. It needs some values to operate upon.
In this expression:
3 + 2
The addition operator works with, or operates upon, the values represented by the numbers 3 and 2. The numbers 3 and 2 are said to be the operands for the '+', that is, the 3 and the 2 are operands for the addition operator.
It is very handy to think of the addition operator as 'grabbing' the 3 and the 2 and, through arithmetic, producing a value of five.
http://modul2poli.blogspot.com/
2
Speaking a bit more technically, we would say that the above expression evaluates to five because the addition operator operates on the 3 and the 2, (the number 3 and the number 2 are its operands), to produce a value of five.
So, now we know:
Mathematics expressions are made up of operators and operands. When an expression is evaluated operators accept operands, (which are values),
and produce new values through arithmetic.
Specifically, regarding the addition operator we see:
The symbol for the addition operator is '+'. The addition operator needs two operands, one to its left and one to its right. The operands for the addition operator are values.
Since the addition operator requires two operands, we say that it is a binary operator. Binary means 'consisting of two parts'.
There are other binary operators present in expressions. There is also the subtraction operator, as in:
7 - 4
Here, the subtraction operator, '-', accepts the 7 and the 4, and using arithmetic it produces a value of three.
So, we now have two examples of binary operators in mathematics expressions:
The addition operator, '+' The subtraction operator, '-'
Now, an expression can have several addition and subtraction operators in it. For example:
7 - 4 + 2
The operators are going to accept values as operands, but in this case, which operator gets the first turn at accepting these values, the '-' or the '+'?
To answer that question, it would be handy to know which operator is 'stronger'. In mathematics, when one operator is 'stronger' than another, we say that it has precedence over the other. That is, it precedes the other in the order of the steps taken necessary to evaluate the expression.
http://modul2poli.blogspot.com/
3
As it turns out the addition operator and the subtraction operator have equal precedence, one is not 'stronger' than the other. In cases like this, when two operators are of equal precedence, evaluation proceeds from left to right.
So, in this case the subtraction operator goes first since it is left most. In detail, here is how this evaluation unfolds, starting with the original expression:
7 - 4 + 2
The '-' operator goes first. It accepts the value of seven represented by the number 7 and the value of four represented by the number 4, does arithmetic called subtraction, and produces a value of three.
Since the value of three can be represented by the number 3, this work effectively changes the above expression to look like this:
3 + 2
Now, the action is handed over to the '+' operator. It accepts the value of three, (which was handed to it by the '-' operator), and the value of two represented by the number 2, does arithmetic called addition, and produces a value of five.
The value of five can be represented by the number 5, so the above expression boils down to this one:
At this point we know:
In math expressions there are operators and operands. It is the interaction among operators and operands that is called the
evaluation of the expression. The evaluation of a mathematics expression produces a final value. Binary operators require two operands. The addition operator, '+', and the subtraction operator, '-', are both binary
operators. The addition operator and the subtraction operator have equal
precedence. When two operators have equal precedence, the one to the left accepts
operands first, producing a value which is passed over to the other operator.
http://modul2poli.blogspot.com/
4
2.1.2 Describe the different types of operator: arithmetic, relational, logical, and Boolean operator
Arithmetic Operator
Operator name Syntax
Basic assignment a = b
Addition a + b
Subtraction a - b
Unary plus (integer promotion)
+a
Unary minus (additive inverse)
-a
Multiplication a * b
Division a / b
Modulo (remainder) a % b
Increment Prefix ++a
Suffix a++
Decrement Prefix --a
Suffix a--
http://modul2poli.blogspot.com/
5
Relational Operator
Operator name Syntax
Equal to a == b
Not equal to a != b
Greater than a > b
Less than a < b
Greater than or equal to a >= b
Less than or equal to a <= b
Logical Operator
Operator name Syntax
Logical negation (NOT)
!a
Logical AND a && b
Logical OR a || b
http://modul2poli.blogspot.com/
6
Boolean Operator
Operator name Syntax
Bitwise NOT ~a
Bitwise AND a & b
Bitwise OR a | b
Bitwise XOR a ^ b
Bitwise left shift[note 1] a << b
Bitwise right shift[note 1] a >> b
2.2 Understand Programme Flow Control Structures 2.2.1 Identify Programme Flow Control Structures.
Control flow is the determinant of the direction in program implementation. Beginning with the first command, control will determine the direction which will be held on until the program ends.
2.2.2 List the various types of logical structures.
There are three control structures that can be used in solving the problems there are sequence structure, selection and loop structures.
http://modul2poli.blogspot.com/
7
2.2.3 Explain the various types of logical structures. a. Sequence
Sequence structure is simple structure that directs the implementation of the program line by line in order. General form the structure of the sequence is as follows { Statement_1; …… Statement_n; }
b. Selection
The selection structure would be to use two types of statement whether the if-else or switchThere are 2 type for selection structure: 1.if. a. if b. if ..else c. if .. else if d. if / if .. else nested 2. switch and break. a. switch .. case.
c. Looping
Looping statement or repeat statement allows C is coded only once in the program but its implementation was repeated several times. The number of repetitions should be controlled so that the program can be terminated properly. There are two ways to control the replication, using counters or using sentinel data provided in the expression. Counters are used if the number of repetitions is known when the program code. Data Sentinel is used if the number of repetitions is not known when the program coded. Example fund = 2; while (fund <= 200) fund = 3 * fund
2.2.4 Describe the different types of selection structure. a. if, if..else, switch..case
if
if checks whether the value is true and if so, includes the code in “{“ until the closing “}” If not, that code is removed from the copy of the file given to the compiler prior to compilation (but it has no effect on the original source code file). There may be nested if
http://modul2poli.blogspot.com/
8
statements. It is common to comment out a block of code using the following construction because you cannot nest multi-line comments in C Example If (mark==‟A‟) printf (“pass\n”);
if ..else
If..else statement used for cases that provide a choice of two options to be implemented if the conditions are true and the other options to be implemented if the condition is false. Depending on the results of the expression conditions only one of two options wil l be executed.
The general format for these are,
if( condition 1 ) statement1; else statement2;
switch .. case. Switch case statements are a substitute for long if statements that compare a variable to several "integral" values ("integral" values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point. Example switch ( <variable> ) { case this-value: Code to execute if <variable> == this-value break; case that-value: Code to execute if <variable> == that-value break; ... default: Code to execute if <variable> does not equal the value following any of the cases break; }
http://modul2poli.blogspot.com/
9
b. Nested selection
When a selection structure‟s true path or its false path contains another selection structure, the inner selection structure is referred to as a nested selection structure Example if (early_reg)
{ if (teacher) Fee = 3000; else { If(group>=5) Fee = 2600; else Fee = 2800; } }
else { If(coporate) Fee = 3500; Else
Fee = 3100; }
2.2.5 Describe the different types of looping structures. a. For
Statement for allowing us to repeat certain parts of the program until a specified number of repetitions. This means that when we write a program, we can determine the required number of repetitions. Every time the loop, the statement for counting the number of repetitions to achieve a specified number of repetitions. After that statement after the for will be executed! General format for statement „for‟ for (prefix; test; update) statement; Prefix - an expression that assigns the initial value of loop counter.
http://modul2poli.blogspot.com/
10
Test - conditions that determine whether the end of the loop continues to loop or not. Updates - the expression to update the loop counter. Example for (bil = 1; bil <= 8; bil++) printf(“%d\t”,bil);
b. while, do.. while
while Structural repetition of the second control loop controlled conditions. This loop can be written as a while statement. While loop will loop until a certain condition is achieved. In fact while we do not need information on the number of loops, but just need to put conditions to continue to loop. When these conditions are not met, the loop will stop. General format for while statement while (expression) statement; Expression - the conditions of the loop controller that produces the value true or false. Statement - any statement that is due respect. Example total = i = 0; printf(“Enter one number bigger than 0”); scanf(“%d”, &n); while (i != n) { total += i; i ++; }
c. Nested looping
Nested looping occurs when there are two looping statements in one program. When nesting occurs, the fact that the loop will be implemented at all until the end of the loop at all times outside the loop. Example for (i = 0; i < 2; i++) {
http://modul2poli.blogspot.com/
11
for (j = 0; j < 5; j++) { printf(“%d, %d\t”, i, j); } printf(“\n”); }
2.3 Know Storing Information 2.3.1 Define a variable and a constant.
Variable
A variable is the storage location in memory that is stored by its value. A variable is identified or denoted by a variable name. The variable name is a sequence of one or more letters, digits or underscore, for example: character _
Constants
Constants have fixed value. Constants, like variables, contain data type. Integer constants are represented as decimal notation, octal notation, and hexadecimal notation. Decimal notation is represented with a number. Octal notation is represented with the number preceded by a zero character. A hexadecimal number is preceded with the characters 0x.
2.3.2 Describe the following basic data types: numeric, character, string, logical.
Numeric Integer data type used to represent negative numbers or positive integers. For example, 77, 0, 999, +999. Tues memory size of type integer is different - depending on computer system.
Integer Data Type Byte Ranges short int 2 -32767 .. 32767
unsigned short int 2 0 .. 65535 int 2 -32767 .. 32767
unsigned int 2 0 .. 65535 long int 4 -2147483647 .. 2147483647
unsigned long int 4 0 .. 4294967295
http://modul2poli.blogspot.com/
12
Character
Char type is used to represent characters such as letters, digits, or special symbols like '?'. To allot a character to a variable, we need to put these characters in single quotes ie ''. For example 'A', 'z', '@'.
Char Data Type Byte Ranges Char 1 -128 .. 127
Unsigned char 1 0 .. 255
Strings In generally string refer the character which include in the symbol “ “. For example “ “ “Hello, how are you?” If there are no character within that symbol it will known as null string. If a string is "Hello! ". Then the string will be stored in memory in the following circumstances:
H e l l o ! „\0‟
2.3.3 Identify the operators used in programming.
Refer back 2.1.2
2.3.4 Explain the operators used in programming. a. Mathematical operators
Refer back 2.1.2
b. Relational operators
Refer back 2.1.2
c. Logical operators
Refer back 2.1.2
http://modul2poli.blogspot.com/
13
2.3.6 Explain the differences between a formula (equation) and an expression.
Equation Expression
An equation is a SENTENCE.
One solves an equation. An equation HAS a relation
symbol.
Ex.
1. Ten is five less than a number. 10 = x - 5
2. A number is less than five. x < 5
An expression is a PHRASE, a sentence fragment.
One simplifies an expression.
An expression HAS NO relation symbol.
Ex.
3. a number less than five x
4. five less than a number x - 5
2.3.7 Convert formula into expression and vice versa.
Special Expression Basic Expression (Formula)
i + = j; i = i + j; i - = j; i = i – j; i * = j; i = i * j; i / = j; i = i / j;
i % = j; i = i % j;
http://modul2poli.blogspot.com/
14
2.4 Understand Array And Programme Design
2.4.1 Define what an array is.
Array The C language provides a capability that enables the user to define a set of ordered data items known as an array. Suppose we had a set of grades that we wished to read into the computer and suppose we wished to perform some operations on these grades, we will quickly realize that we cannot perform such an operation until each and every grade has been entered since it would be quite a tedious task to declare each and every student grade as a variable especially since there may be a very large number. In C we can define variable called grades, which represents not a single value of grade but a entire set of grades. Each element of the set can then be referenced by means of a number called as index number or subscript. Array by definition is a variable that hold multiple elements which has the same data type.
Declaring Arrays
We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Here is the syntax:
data_type array_name[size];
For example, to declare an integer array which contains 100 elements we can do as follows: int a[100];
There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer. We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1]. Initializing Arrays It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name. Here is an example of initializing an integer array. int list[5] = {2,1,3,7,8};
http://modul2poli.blogspot.com/
15
2.4.2 Describe array structure.
m Score [0]
m + 4 Score [2]
m + 6 Score [3]
m + 8 Score [4]
m + 10 Score [5]
m + 12 Score [6]
m + 14 Score [7]
m + 16 Score [8]
m + 18 Score [9]
Memory
Refer to the diagram above, m represents the address of the first element in the array. As the value of an integer array element, then the space used by each element is 2 bytes.
2.4.3 Identify single-dimensional array and multi-dimensional array.
Single –dimensional array Example #include <stdio.h>
void main() {
const int size = 5;
int list[size] = {2,1,3,7,8};
int* plist = list;
// print memory address of array elements
for(int i = 0; i < size;i++) {
http://modul2poli.blogspot.com/
16
printf("list[%d] is in %d\n",i,&list[i]);
}
// accessing array elements using pointer for(i = 0; i < size;i++)
{ printf("list[%d] = %d\n",i,*plist);
/* increase memory address of pointer so it go to the next element of the array */
plist++;
}
}
Here is the output list[0] is in 1310568
list[1] is in 1310572
list[2] is in 1310576
list[3] is in 1310580
list[4] is in 1310584
list[0] = 2
list[1] = 1
list[2] = 3
list[3] = 7
list[4] = 8
You can store pointers in an array and in this case we have an array of pointers. This code snippet use an array to store integer pointer. int *ap[10];
Multi – dimensional array
Often there is a need to store and manipulate two dimensional data structure such as matrices & tables. Here the array has two subscripts. One subscript denotes the row &
http://modul2poli.blogspot.com/
17
the other the column. The declaration of two dimension arrays is as follows:
data_type array_name[row_size][column_size]; int m[10][20]
Here m is declared as a matrix having 10 rows( numbered from 0 to 9) and 20 columns(numbered 0 through 19). The first element of the matrix is m[0][0] and the last row last column is m[9][19]
Elements of multi dimension arrays:
A 2 dimensional array marks [4][3] is shown below figure. The first element is given by marks [0][0] contains 35.5 & second element is marks [0][1] and contains 40.5 and so on.
marks [0][0] 35.5
Marks [0][1] 40.5
Marks [0][2] 45.5
marks [1][0] 50.5
Marks [1][1] 55.5
Marks [1][2] 60.5
marks [2][0]
Marks [2][1]
Marks [2][2]
marks [3][0]
Marks [3][1]
Marks [3][2]
Initialization of multidimensional arrays:
Like the one dimension arrays, 2 dimension arrays may be initialized by following their declaration with a list of initial values enclosed in braces
http://modul2poli.blogspot.com/
18
Example:
int table[2][3]={0,0,0,1,1,1}; Initializes the elements of first row to zero and second row to 1. The initialization is done row by row. The above statement can be equivalently written as int table[2][3]={{0,0,0},{1,1,1}}
http://modul2poli.blogspot.com/
2/17/2011
1
3.0 C FUNDAMENTALS
Structure Of C Programme
General form of c programs:
Preprocessor directives
main function heading{
executable statements;return value;
}
Structure Of C Programme
General form: Example:
#include <stdio.h>
main()
{
printf(“Hello World\n”);
return 0;
}
Preprocessor directives
main function heading
{
executable statements;
return value;
}
#include <stdio.h>
Preprocessor directive #include
<stdio.h> includes the "standard I/O
library" into your program.
The standard I/O library lets you read input from the keyboard (called "standard in"), write output to the screen (called "standard out"), process text files stored on the disk, and so on.
http://modul2poli.blogspot.com/
2/17/2011
2
main()
declares the main function.
Every C program must have a function
named main.
A function is simply a collection of
commands to perform some tasks.
curly braces { }
indicate the beginning and end of a block
of code.
Within the braces are the statements
that make up the main body of the
program.
A group of statements enclosed within
braces are called a block.
printf(“Hello World\n”);
The printf statement is the standard C
way of displaying output on the screen.
The “\n”is the escape sequence that
stands for newline, which means that
move the cursor on your screen to the
next line.
A semicolon is added onto the end of all
lines in C.
return 0;
causes the function to return an error
code of 0 (no error) to the operating
system.
This return value is important to tell the
operating system whether the program
succeeded or not.
http://modul2poli.blogspot.com/
2/17/2011
3
Output
#include <stdio.h>
main()
{
printf(“Hello World\n”);
return 0;
}
Another simple example:
Output:
Compile C programmes
Once you write
your C program ,
you must run the
c program through
a C compiler to
turn it into
machine language
Execute the debugged C
programmes
After compiled the program, you can
execute the program to see the output if
there is no error messages are displayed.
If one or more error messages are
displayed, you have to debug the program
to get rid of errors.
Debugging - Process removing errors
from a program
http://modul2poli.blogspot.com/
2/17/2011
4
Define the pre-processing
directives and header files
Preprocessor
The preprocessor is executed automatically by the compiler when we compile a C program.
It make first verification and digestions of the program code
It change the program source code base on instruction or preprocessor directives and then used for the input for next
compilation step
Preprocessing
C++ Program Executable
Program
C++
Compiler
C++
Preprocessor
Temporary file
(C++ program)
Define the pre-processing
directives and header files
Preprocessor directives are the orders that we include within our programs that are not instructions for the program itself but for the preprocessor.
A preprocessor directive always begins with a hash sign (#).
The most often-used preprocessor directives are:
a. #include
b. #define
#include
instructs the C compiler to add the
contents of an include file into your
program during compilation.
An include file (also called header file)
contains the information needed by your
program or the compiler.
http://modul2poli.blogspot.com/
2/17/2011
5
#include
There are two methods to specify a
include file as in example below:
# include “ file.h ”
# include <file.h>the preprocessor first looks for the
included files in the standard directory. If
the file isn‟t found, the preprocessor looks
for the file in the current directory
the preprocessor search included file in
current directory (directory containing
the source code being compiled) and only
in case that is not there the compiler will
searches the default directories.
#define
serves to generate what we call defined
constants or macros.
Syntax:
Its function is to define a macro called
name that whatever it is found in some
point of the code is replaced by value
#define namevalue
Example
During the preprocessing, the source code
is read as follows:
#define Max 1000
x = y* Max;
z = Max-12;
x = y* 1000;
z = 1000-12;
#define
The #define directive can also be used to create function macros.
A function macro is a type of shorthand, using something simple to
represent something more complicated.
For example, the preprocessor directive
#define HALFOF (value) (value/2)
Define a macro named HALFOF that a parameter named value.
Whenever the preprocessor encounters the text HALFOF (value)
in the source code, it replaces it with the definition text and
inserts the argument as needed. Thus, the source code line
Result= HALFOF (10);
Is replced by this line:
Result= ((10)/2);
http://modul2poli.blogspot.com/
2/17/2011
6
Create header file in C
programmes.
Header files contain numerous frequently-
used functions that programmers can use
without having to write codes for them.
stdio.h
stands for "standard input/output header".
This header file is used for declaring standard I/O streams.
Here are some functions from this header file.
Function Purpose
printf used to sends formatted output to the screen.
scanf used to reads formatted input from the keyboard
putchar used to sends a single character to the screen
getchar used to reads a single character from the keyboard
puts used to sends string s to the screen
gets used to read string s from the keyboard
fputc writes one character to a file
fgetc returns one character from a file
Example:
#include <stdio.h>
main()
{
float y;
int x;
puts(“Enter a float, then an int:”);
scanf(“%f %d”,&y,&x);
printf(“\nYou entered %f and %d”, x,
y);
printf("\n");
return 0;
}
Output:Program:
ctype.h
The header file ctype.h contains
declarations for character classification
functions, returning TRUE or FALSE
depending on whether the character
meets a certain condition.
http://modul2poli.blogspot.com/
2/17/2011
7
Function Return value
salnum (c) Non- zero if ( c ) is alphanumeric; 0 otherwise
isalpha (c) Non- zero if ( c ) is alphabetic; 0 otherwise
isascii (c) Non- zero if ( c ) is ASCII character; 0 otherwise
iscntrl (c) Non- zero if ( c ) is control character ; 0 otherwise
isdigit (c) Non- zero if ( c ) is a digit; 0 otherwise
isgraph(c) Non- zero if ( c ) is a graphic character(including space); 0
otherwise
islower (c) Non- zero if ( c ) is lowercase letter ; 0 otherwise
isprint (c) Non- zero if ( c ) is printable character ( including space ) ; 0
otherwise
ispunct(c) Non- zero if ( c ) is punctuation character ; 0 otherwise
isspace (c) Non- zero if ( c ) is a space, tab, formfeed or new line
character; 0 otherwise
isupper (c) Non- zero if ( c ) is uppercase letter; 0 otherwise
isxdigit (c) Non- zero if ( c ) is hexadecimal digit ; 0 otherwise
toascii(c) ASCII equavalent
tolower (c) Lowercase equivalent of c if it is latter; unchanged otherwise
toupper (c) Uppercase equivalent of c if it is latter; unchanged otherwise
Example:
/*read a lowercase character and display its uppercase equivalent*/#include<stdio.h>#include<ctype.h>main(){char lower, upper;printf("Enter a lowercase letter:");lower=getchar();upper=toupper(lower);printf("The Uppercase of the letter is:%c\n",upper);
return 0;}
Program: Output:
math.h Function Return value
acos(d) Arc cosine of d
asin(d) Arc sine d
atan(d) Arc sine d
atan2(d1,d2) Arc tangent of d1/d2
ceil(d) Smallest integer greater than d
cos(d) Cosine of d
exp(d) e(i.e.,2.718…) raised to the power d
fabs(d) Absolute value of d
floor(d) Largest integer smaller than d
fmod(d1,d2) Remainder of d1/d2
log(d) Natural logarithm of (d>0)
log10(d) Base logarithm of d (d>0)
pow(d1,d2) D1 raised to the power of d2
sin(d) Sine of d
sinh(d) Hyperbolic sine of d
sqrt(d) Square root of d
tan(d) Tangent of d
tanh(d) Hyperbolic tangent of d
Contain functions that perform mathematic operations.
Example:
//program that uses mathematical functions#include <math.h>#include <stdio.h>main( ){float x;printf("\nEnter a number:");scanf("%f",&x);
printf("\nSquare root:%f",sqrt(x));printf("\nCosine:%f",cos(x));printf("\nPower of two:%f",pow(x,2));
return 0;}
Program: Output:
http://modul2poli.blogspot.com/
2/17/2011
8
conio.h
Conio means “console in/out” which means ways of
getting data to and from the console device (which uses the keyboard and screen)
Some of the functions:
Function Purpose
getch Obtain the next character from the console but
does not echo to the screen
putch Output character to the text window on the
screen
gotoxy Position cursor in text window
clrscr Clear text mode window
Example:
#include < stdio.h >
#include < conio.h >
main()
{
char ch;
printf("Enter a string:");
while ((ch=getch())!='\r')
putch(ch);
printf("\nThank you\n");
return 0;
}
#include < stdio.h >
#include < conio.h >
main()
{
char ch;
printf("Enter a string:");
while ((ch=getch())!='\r')
printf("\nThank you\n");
return 0;
}
Program1: Program2:
Output: Output:
string.h defines several functions to manipulate C strings and arrays
and also various memory handling functions;
Example:
#include <stdio.h>#include <string.h>main(){char message[20];strcpy(message, "This is fun!");printf("message=%s", message);return 0;}
Program: Output:
http://modul2poli.blogspot.com/
2/17/2011
9
Create block { .. } in Main function.
A C++ program must have at least the function main( ).
The main function consists of the name main followed
by a pair of empty parentheses () and a pair of braces
{ }
Within the braces are the statements that make up the main body of the program.
main ( )
{
// statements
}
Beginblock
End block
Create return statement in
programmes.
The return statement is the command
that causes program flow to exit from the
current function and return to the calling
function.
It can also be used to return a single
value.
Syntax:
return expression;
Explain the usage of comments.
Comments are messages scattered
throughout your program that explain what‟s going on.
The compiler ignores all comments, so
they have no effect on how a program works.
Comments are important especially when your programs become larger and more complex, or when you need to modify a program you wrote six months ago.
Create comments in programmes.
C comments begin with /* and end with */. A comment can span part of a line, an
entire line, or multiple lines.
Example1:/* A single line comment */
Example2:int a; /* A partial line comment*/
Example3:/* a comment
spanningmultiple lines */
http://modul2poli.blogspot.com/
2/17/2011
10
• Many of today’s C compiler support another kind of
comment that was originally developed for C++ programs.
• The new style comment begins with two slashes (//) and ends only at the end of the line.
Create comments in programmes.
Example://Welcome program#include <stdio.h>main(){printf(“Welcome to C programming”); // welcome messagereturn 0;
}
Constants And Variables
(Identifiers)
The rules for naming constants and variables
• the name can only contain letter, digits and the underscore character (_).
• the first character of the name must be a letter. The underscore is also a
legal first character but its use is not recommended.
• case matters (that is upper- and lowercase letters). Thus, the names count
and Count refer to two different variables.
• C keywords can’t be used as variable names such as int, for, goto, while
and so on.
• should not contain a space
Declare constants and variables.
A variable declaration has the following syntax:
Typename specifies the data type and varname is the variable name
Example:
You can declare multiple variables of same type on one line by
seperating the variable names with commas:
Example:
Typename varname;
int age; /*an integer varibale named age*/
int count, number, start; /*three integer variables*/float percent, total; /*two float variables*/
Declare constants and variables.
Like a variable, a constant is a data storage location used
by your program. Unlike a variable, the value stored in a
constant can‟t be changed during program execution.
Syntax:
OR
Examples:
Typename varname= value
Const Typename varname=value
int count=20;const floatpi=3.14159;
http://modul2poli.blogspot.com/
2/17/2011
11
Identify the scope of constants and
variables.
The scope of a variable refers to the extent to which different parts of a program have access to the variable- in other words, where the variable is visible.
a. External variables
is a variable defined outside of any function. This means outside of main() as well, because main() is a function, too.
sometimes refered to as global variables.
The scope of an external variable is the entire program. This mean that an external variable is visible throughout main() and every other function in the program.
b. Local variables
A local variable is one that is defined within a function.
The scope of a local variable is limited to the function in which it is defined.
Build constants and variables in
programmes.
Example:
#include<stdio.h>
main()
{
float r, area;
float pi=3.14;
printf("\nEnter radius:");
scanf("%f", &r);
area =pi*r*r;
printf("\n\nArea of circle =%.2f\n", area);
return(0);
}
variable
constant
Identify and explain keywords in C
programmes.
Keywords are those words whose meaning
is already defined by compiler.
Cannot used as variable name.
C keywords, also called reserved words, are
listed as below:
Keyword Description
auto The default storage class
break Command that exits for, while, switch, and do...switch statements
unconditionally.
case Command used within the switch statement
char The simplest C data type
const Makes variable value or pointer parameter unmodifiable.
continue Command that resets a for, while, or do...while statement to the next
iteration
default Command used within the switch statement to catch any instances not specified
with a case statement
do used together with while to make another form of repeating statement
double Data type that can hold double-precision floating-point values
else Statement signaling alternative statement to be executed when an if statement
evaluates to FALSE
enum Used to declare and initialize a sequence of integer constants
extern Data modifer indicating that a variable will be declared in another area of the
program
float represents a single precision floating point data type
for Looping command that contains initialization, incrementation, and conditional
sections.
goto Command that causes a jump to a predefined label
if used to change program flow based on a TRUE/FALSE decision
int Data type used to hold integer values
http://modul2poli.blogspot.com/
2/17/2011
12
Keyword Description
long Data type used to larger integer value that int
register Storage modifier that specifies that a variable should be stored in register if
possible
return Command that causes program flow to exit from the current function and return to
the calling function. It can also be used to return a single value
short Data type used to hold integers. It isn’t commonly used, and it’s the same size as
an int on most computers.
signed Modifier used to signify that a variable can have both positive and negative value.
sizeof Operator that returns the size of the item in bytes
static Modifier used to signify that the compiler should retain the variable’s value.
struct Keyword used to combine C variables of any data type into group.
switch Command used to change program flow in a multitude of directions. Used in
conjunction with the case statement
typedef Modifier used to create new names for existing variable and function types.
union Keyword used to allow multiple variables to share the same memory space
unsigned Modifier used to signify that a variable will contain only positive values.
void Keyword used to signify either that a function doesn’t return anything or that a
pointer being used is considered generic or able to point to any data type
volatile Modifier that signifies that a variable can be changed.
while Looping statement that executes a section of code as long as a condition remains
TRUE.
Example: for, if, break
// break loop example
#include <stdio.h>
int main ()
{
int n;
for (n=10; n>0; n--)
{
printf("%d\n",n);
if (n==3)
{
printf("coutdown aborted!\n");
break;
}
}
return 0;
}
Example: switch, case, default#include<stdio.h>
main()
{
int number;printf("Enter number 1 - 3:");
scanf("%d", &number);
switch (number)
{
case 1: printf("Number one\n");
break;
case 2: printf("Number two\n");
break;
case 3: printf("Number three\n");
break;
default : printf ("Number rejected\n");
}
return(0);
}
Basic data types in C.
a. int
b. char
c. float
d. double
http://modul2poli.blogspot.com/
2/17/2011
13
Basic data types in C
a. int• Data type used to hold integer values.• Integers are whole numbers with a range of values• An example of declaring an integer variable called sum is,
b. char• Data type used to hold a single character.• An example of declaring a character variable called letter
is,
int sum;
sum = 20;
char letter;
letter = 'A';
Basic data types in C
c. Float• Data type used to hold Floating point numbers.• used to store fractional numbers (real numbers) with 6 digits of
precision.• An example of declaring a float variable called money is,
d. double• Data type used to hold Double precision floating point number.• When the accuracy of the floating point number is insufficient, we
can use the double to define the number.• An example of declaring a double variable called big is,
float money;
money = 0.12;
double big;
big = 312E+7;
Basic data types in C
Name DescriptionSize
(Byte)Range
char Character 1 signed: -128 to 127int Integer 2 -32768 to +32767
float Floating point number 4 3.4 e-38 to 3.4 e+38
doubleDouble precision floating point number
8 1.7 e-308 to 1.7 e+308
Example:
int quantity;
float price_per_kg;
float price;
Why did we
declare it as int?
Why did we
declare them as
float?
http://modul2poli.blogspot.com/
2/17/2011
14
E3062- Basic Programming 53
Example:
int number1, number2;
number1 = 25;
number2 = 23;
number1 = number2;
…
…
number1 ?
number2 ?
2523
23
E3062- Basic Programming 54
Example:
int quantity;
float price_per_kg, price;
quantity = 2;
price_per_kg = 4.50;
price = quantity * price_per_kg;
…
quantity ?
price_per_kg ?
price ?
4.50
9.00
2
Use data types in C programmes.
#include<stdio.h>main(){int number;float decimal_point_number;char letter;printf("Enter a letter:");scanf("%c", &letter);printf("Enter a whole number:");scanf("%d", &number);printf("Enter a decimal point number:");scanf("%f", &decimal_point_number);printf("\ncharacter=%c",letter);printf("\ninteger=%d",number);printf("\nfloating point number=%f\n",decimal_point_number);return 0;}
Operators and expressions.
An operator is a symbol that instructs C to perform some operation or action, on one or more operands.
An operand is something that an operator acts on. In C, all operands are expressions. C operators fall into several categories:
a. The assignment operator
The assingnment operator is the equal sign (=).
If you write : x=y; in a C program, it doesn‟t mean “x equal to y”. Instead, it means “assigned the value of y to x.
Syntax:
Variable=expression;
http://modul2poli.blogspot.com/
2/17/2011
15
//assignment operator#include <stdio.h>main(){int x, y;x=1;y=2;
printf(“x=%d”,x);
printf(“y=%d”,y);
return 0;}
Example:
Program: Output:
b. Mathematical operators
perform mathematical operations such as additional
adn subtraction.
C has two unary mathematical operators and five
binary mathematical operators.
i. The unary mathematical operators are so
named because they take a single operand.
Operator Symbol Action Example
Increment ++ Increments the operand by one ++x, x++
Decrement -- Decrements by operand by one --x, x--
◦ Unary operator can be placed before its operand
( prefix mode) or after its operand (postfix mode).
Prefix mode: the increment and decrement operator
modify their operand before it‟s used.
Postfix mode: the increment and decrement operator
modify their operand after it‟s used.
Example 1 Example 2
B=3;
A=++B;
/* A contains 4, B
contains 4*/
B=3;
A=B++;
/* A contains 3, B
contains 4*/
Operator Symbol Action Example
Addition + Add two operands x+y
Subtraction - Subtracts the second operand
fromthe first operand
x-y
Multiplication * Multiplies two opeands x*y
Division / Divides the first operand by
the second operand
x/y
Modulus % Gives the remainder when
the first operand is divided
by the second operand
x%y
ii. Binary operators:
http://modul2poli.blogspot.com/
2/17/2011
16
Example:
Example://binary operator#include <stdio.h>main(){int x, y,z;printf("enter an integer value for x:"); scanf("%d",&x);printf("enter an integer value for y:"); scanf("%d",&y);z=x+y; /*the evaluated value of the addition operation
is assigned to the variable z*/printf("sum=%d",z);printf("\n");return 0;
}
Operator Symbol Question asked Example
Equal == Is operand 1 equal to operand 2? x= =y
Greater than > Is operand 1 greater than operand
2?
x>y
Less than < Is operand 1 less than operand 2? x<y
Greater than or
equal to
>= Is operand 1 greater than or equal
to operand 2?
x>=y
Less than or
equal to
<= Is operand 1 less than or equal to
operand 2?
x<=y
Not equal != Is operand 1not equal to operand
2?
x!=y
c. Relational operators• used to compare expressions, asking question
such as, “Is x greater than 100?”.
• A expression containing a relational operator evaluates to either true (1) or flase (0).
Example:#include<stdio.h>
main()
{
int x, y;
printf (“ Enter value of x :”);
scanf (“%d”, &x);
printf (“ Enter value of y :”);
scanf (“%d”, &y);
if (x == y)
printf(“ x is equal to y\n”);
if (x > y)
printf(“ x is larger than y\n”);
if (x < y)
printf(“ x is less than y\n”);
return(0);
}
Operator Symbol Example Evaluates to
AND && exp1 && exp2 True (1) if both exp1 and exp2
are true
OR || exp1 || exp2 True (1) if either exp1 or exp2
is true
NOT ! !exp1 True (1) if exp1 is false
d. Logical operators• Logical operators let you combine two or
more relational expression into a single expression that evaluates to either true or false
http://modul2poli.blogspot.com/
2/17/2011
17
Example:
#include<stdio.h>
main()
{
char x;
printf ("What is the first letter of alphabet?");
printf ("\nEnter you answer:");
scanf ("%c", &x);
if (x=='a'||x=='A')
printf("Your are right\n");
else
printf("Your are wrong\n");
return(0);
}
e. Conditional operator
The conditional operator is ternary operator, meaning that it takes three operands.
Syntax:
If exp1 evaluates to true, the entire expression evaluates to the value of exp2.
If exp1 evaluates to false, the entire expression evaluates to the value of exp3.
exp1? exp2:exp3;
Example
// conditional operator
#include <stdio.h>
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
printf("Larger number=%d",c);
printf("\n");
return 0;
}
OPERATOR PRECEDENCE
• Operator precedence refers to the order in which operators get used.
• An operator with high precedence will get used before an operator with lower precedence.
http://modul2poli.blogspot.com/
2/17/2011
18
Example
#include <stdio.h>
main()
{
int a,b,c,d;
a= 3 * 4 / 2 + 3 - 1;
b= 6 + 2 * 3 - 4 / 2;
c= (6 + 2) * 3 - 4 / 2;
d= 20 / 5 + 5 % 2;
printf("a=%d\n",a);
printf("b=%d\n",b);
printf("c=%d\n",c);
printf("d=%d\n",d);
return 0;
}
End
Escape sequence
The backslash character constant is also known
as the „Escape Sequence‟.
Certain characters such as the backspace and
carriage return are not printable characters and
these characters pose special problems when
printing using text editor.
The backslash character constant is used
together with other character constant when
such problems are encountered.
Must used within “ ”
Escape sequence
Sequence Meaning
\b Backspace
\n Newline
\t Horizontal tab
\” Double quote
\’ Single quote character
\\ Backslash
\a Bell (Alert)
http://modul2poli.blogspot.com/
2/17/2011
1
Input statements are used for accepting data from the user.
Output statements are used for displaying the processed data on the screen.
Output Statement - printf()
Is a function, used as a statement, to display the data on the screen.
Syntax
printf("<string> <format specif ier>",<variable>);
Example 1
printf(“Welcome");
Output
Welcome
Example 2
printf("My age is %d",age);
Output
My age is 16
http://modul2poli.blogspot.com/
2/17/2011
2
Output Statement - puts() Is a function, displays the contents stored in its
parameter on the standard screen.
The standard form for the puts character isputs (str);
“str” is a string variable.
Example 1
puts("Hello World");
Output
Hello World
Input Statement - scanf()
Is a function, used as a statement, to get the value from the user.
Syntaxscanf("<format specifier>",&<variable>);
Examplescanf("%d",&age);
%d format specif ierage variable
Input Statement - gets() Is a function, accepts the name of the string as a
parameter, and fills the string with characters that are input from the keyboard till newline character is encountered.
The standard form of the gets function is gets (str)
"str" is a string variable.
http://modul2poli.blogspot.com/
2/17/2011
3
Format Specified
Defines the data type of the variable to the compiler.
Format Specified Data Type
%d int%f float%c char
Example Of Program #include<stdio.h> main()
{ int event; char heat; float time;
event= 5; heat='C'; time =27.25;
printf("The winning time in heat %c", heat);
printf(" of the event %d was %.2f", event, time); printf(“\n”); return(0); }
Question 1:
Modify the program below to produce the program that only use puts() and gets().
#include<stdio.h>
void main( )
{ char input[80];
printf("Enter some text, then press enter :"); scanf("%s", &input); printf (“\nYour entered: %s", input); printf("\n");
}
input input politeknik
Answer : #include<stdio.h>
void main( )
{ char input[80];
puts("Enter some text, then press enter :"); gets(input); puts(“\nYour entered:"); puts(input);
}
http://modul2poli.blogspot.com/
2/17/2011
4
Question 2:
Write a program to accept the customer id from the user and display the same on the screen.
Answer : /* Program to accept the input f rom the user and display it on
the screen */
#include <stdio.h>
void main() { int cus_id;
printf ("Enter the customer id : "); scanf ("%d", &cus_id);
printf ("\n Customer id is : %d", cus_id); }
http://modul2poli.blogspot.com/
2/17/2011
1
CONTROL STATEMENTSelection, loop, and array structure.
(04 : 09)
5.1 Understand Program Controls Without any logical control structure statement, the instructions were executed in the same
order in which they appeared within the program. Each instruction was executed once and only once. Thus, these programs did not include tests to determine if certain conditions are true or false, they did not require the repeated execution of groups of statements, and did not involve the execution of individual groups of statements on a selective basis.
The ability to control the flow of your program, letting it make decisions on what code to execute, is valuable to the programmer.
For examples, a realistic C program may require that a logical test be carried out at some particular point within the program.
Branching - Depending on the outcome of the logical test, one of several possible
actions will then be carried out.
Selection – A special kind of branching, in which one group of statements is
selected from several available groups.
Looping – In addition, the program may require that a group of instructions be executed
repeatedly, until some logical condition has been satisfied. Sometimes
the required number of repetitions is known in advance and sometimes
the computation continues indefinitely until the logical condition becomes
true.
http://modul2poli.blogspot.com/
2/17/2011
2
a. if A conditional branching statement
The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user's input. For example, by using an if statement to check a user-entered password, your program can decide whether a user is allowed access to the program.
The structure of an if statement is as follows:
if ( expression ) statement
The expression must be
placed in parentheses.
The statement will be executed only if the expression has a nonzero value –true,The statement can be either simple or compound.Often compound statement which may include other control statements
http://modul2poli.blogspot.com/
2/17/2011
3
To have more than one statement execute after an if statement that evaluates to true, use braces, like we did with the body of the main function. Anything inside braces is called a compound statement, or a block. When using if statements, the code that depends on the if statement is called the "body" of the if statement.
For example:
if ( TRUE ) {
/* between the braces is the body of the if statement */
Execute all statements inside the body
}
Example Program : IF Statement
#include <stdio.h>
main ()
{ int age, yrs;
printf("Type in your age: ");
scanf ("%d", &age);
if (age < 18)
{ printf ("You cannot vote yet\n");
yrs = 18 - age;
printf("You can vote in %d years.\n", yrs);
}
if (age > 18)
{ printf ("You can vote now.\n");
}
Return 0;
}
The answers:
http://modul2poli.blogspot.com/
2/17/2011
4
b. if..else
The general form of if statement which includes the else clause is
if ( expression ) statement 1 else statement 2
If the expression has a nonzero value(true), the statement 1 will be executed. Otherwise, statement 2 will be executed.
Sometimes when the condition in an if statement evaluates to false, it would be nice to execute some code instead of the code executed when the statement evaluates to true. The "else" statement effectively says that whatever code after it (whether a single line or code between brackets) is executed if the if statement is FALSE.
# include <stdio.h>
main()
{
int yrs, age;
printf("Type a age: ");
scanf("%d", &age);
if (age < 18)
{ printf("You cannot vote yet\n");
yrs = 18 - age;
printf("You can vote in %d years. \n", yrs);
}
else
{
printf("You can vote now.\n", yrs);
}
return 0;
}
Example Program : IF…Else
The answers :
http://modul2poli.blogspot.com/
2/17/2011
5
c. nested if One property of if –else statement is that they can be nested. This means
that if statement can be target of another if statement.
In a nested else statement is associate with nearest if statement. This association can be change by used of code block. Also you should use proper indenting in your program to make sure your remove any visual ambiguity.
General representation of nested if in C can be –
If (condition1) statement1;
If (condition2) statement2;
If (condition3) statement3;
………………………………………
else statement n+1
else statement n+2
else statement n+3
#include<stdio.h>main(){int number;printf("Type a number:");scanf("%d", &number);
if(number>100)printf("Large\n");
else if (number>0)printf("Not large but positive\n");
else if (number==0)printf("or zero\n");
elseprintf("Negative \n");
return 0;
}
Example Program : Nested If
The answers :
http://modul2poli.blogspot.com/
2/17/2011
6
d. switch..case Switch is a selection statement provided by C. It has a built in multiple –
branch structure . The input value to the switch statement construct is a int or char variable. Note that no float or any other data is allowed.
The input variable is compared against a group of integer constant. All the statements in and after the case in which there is a match is executed
until a break statement is encountered or end of switch is reached. We are also allowed to give a default case which will be executed if no other
statement match is found. Also use of standard indenting is recommended.
General representataion of switch in C can be -
switch ( input) {case constant1:Statement1;break;case constant2:Statement2;break;...Default:Statement n;break;}
#include<stdio.h>
main()
{
char ch;
printf("\n Enter character A, B or C: ");
ch=getchar();
switch(ch)
{
case 'A':
printf("You Entered A");
break;
case 'B':
printf("You Entered B");
break;
case 'C':
printf("You Entered C");
break;
default:
printf("You Did Not Entered A, B or C!\n");
}
return 0;
}
Example Program : Switch …Case
Some of the answers:
http://modul2poli.blogspot.com/
2/17/2011
7
• The switch branches on one value only, whereas the nested if-else tests multiple
logical expressions.
• IF-ELSE can have values based on constraints where SWITCH can have values based on user choice.
• In the if - else, first the condition is verified, then it comes to else. Whereas in the switch - case first it checks the cases and then it switches to that particular case.
• The if statement is used to select among two alternatives. It uses a booleanexpression to decide which alternative to be executed.
5.1.3 Write C program using looping statements.
Loops are used to repeat a block of code. There are three types of loops:
a. do..whileb. whilec. ford. nested loop
http://modul2poli.blogspot.com/
2/17/2011
8
a. do..while
DO..WHILE - DO..WHILE loops are useful for things that want to loop at least once. The structure is
do {} while ( condition );
Notice that the condition is tested at the end of the block instead of the beginning, so the block will be executed at least once. If the condition is true, we jump back to the beginning of the block and execute it again. A do..while loop is almost the same as a while loop except that the loop body is guaranteed to execute at least once. A while loop says "Loop while the condition is true, and execute this block of code", a do..while loop says "Execute this block of code, and then continue to loop while the condition is true".
#include<stdio.h>#include<string.h>main(){char checkword[80] = "Rahsia";char password[80] = "";
do{printf("Enter password: ");scanf("%s", &password);
}while(strcmp(password, checkword));
return 0;}
Note : This example prompts users for a password and continued to prompt them until they enter one that matches the value stored in checkword.
Example Program : Do..While
The answer :
http://modul2poli.blogspot.com/
2/17/2011
9
b. while
The while statement is used to carry out looping operations, in which a group of statement is executed repeatedly, until some condition has been sactisfied.
The general form of the while statement is
while ( condition ) { Code to execute while the condition is true }
Codes must include some feature that eventually alters the value of the expression, thus providing a stopping condition for the loop.
#include<stdio.h>main(){
int x=0; /* Don't forget to declare variables */
while(x<10) { /* While x is less than 10 */printf("%d\n",x); /*Loop prints values 0 to 9*/x++; /* Update x so the condition can be met eventually */
}
return 0;}
The easiest way to think of the loop is that when it reaches the brace at the end it jumps back up to the beginning of the loop, which checks the condition again and decides whether to repeat the block another time, or stop and move to the next statement after the block.
Example Program : While Statement
The answer: :
http://modul2poli.blogspot.com/
2/17/2011
10
c. for FOR – is one of the iteration statement provided by C. It is the most popular of all
iteration statements because it provides unmatched flexibility and power to the program.
Loops generated by for statement is are also called entry controlled or close ended because the condition for iteration of loop is check at the staring of the loop and loop will not execute even once if the condition will to satisfy even once.
for ( variable initialization; condition; increment)
Statement;
For statement declaration as shown above can be divided into 3 parts –1. Variable initialization – In this we initialize the loop control value to a
starting value.2. Condition – In this evaluate the condition for the iteration of the loop and
loop repeat only when this is true.3. Increment – In this determine how the value of loop control value changes
with each iteration of the loop. It can be increment, decrement or any mathematical expression.
Also statement in above form can be a single statement, block statement or at blank statement.
Also note that each part is separated by a semi colon.
#include <stdio.h> int main(){ float meters, feet;printf("Meters to feet\n\n"); for (meters = 0; meters < 10; meters++){ feet = meters/3.28; printf("%.2f %.2f\n", meters, feet);} return 0;}
Example Program 1: For Statement
The answer:
http://modul2poli.blogspot.com/
2/17/2011
11
#include <stdio.h>
main() /* display the numbers 0 through 9 */
{
int x = 0;
for (; x < 10; ) {
printf( "%d\n", x );
x++;
}
return 0;
}
This program is use a for statement in which two of the three expression are omitted.
Example Program 2 : For Statement
The answer:
d. nested loop
These loops are the loops which contain another looping statement in a single loop. These types of loops are used to create matrix. Any loop can contain a number of loop statements in itself. If we are using loop within loop that is called nested loop. In this the outer loop is used for counting rows and the internal loop is used for counting columns.
http://modul2poli.blogspot.com/
2/17/2011
12
#include <stdio.h>
main( ) {
int n, count, loops, loopcount;
float x, average, sum;
/*read in the number of lists */printf("How many lists ? ");scanf("%d", &loops);
/* outer loop (process each list of numbers */for (loopcount = 1; loopcount <= loops; ++loopcount)
{ /* initialize and read in a value for n */
sum= 0;printf("\nList number %d\nHow many numbers ?", loopcount);
scanf("%d", &n);
/*read in the numbers */
for (count =1; count <=n; ++count){ printf("X= ");
scanf("%f", &x);sum += x;
}
/* end inner loop */
/* Calculate the average and display the answer */average = sum/n;printf("\n The average is %f\n", average);
} /*end outer loop*/
return 0;}
Example Program : Nested Loop
The answer:
Multiple loop control variable – more than 1 loop control is used
#include <stdio.h>
main()
{
int i,j;
for (i=0,j=50; i<j; i++, j--) //print numbers 0 to 50
printf( "%d\n", i );
return 0;
}
The answer :
http://modul2poli.blogspot.com/
2/17/2011
13
5.1.4 Compare the differences between the various loop structures.
•In While loop the condition is tested first and then the statements are executed if the condition turns out to be true.
•In do while the statements are executed for the first time and then the conditions are tested, if the condition turns out to be true then the statements are executed again.
•A do while loop runs at least once even though the the condition given is false
•In a while loop the condition is first tested and if it returns true then it goes in the loop - entry control loopIn a do-while loop the condition is tested at the last - exit control loop
• for - Statement for allowing us to repeat certain parts of the program until a specified number of repetitions – allow to determine the required number of repetitions.
5.2 Understand Arrays
What is an array? Array is a very basic data structure provided by every programming language.
Let’s talk about an example scenario where we need to store ten employees’ data in our C/C++ program including name, age and salary. One of the solutions is to declare ten different variables to store employee name and ten more to store age and so on. Also you will need some sort of mechanism to get information about an employee, search employee records and sort them. To solve these types of problem C/C++ provide a mechanism called Arrays.
An array is a data type which contains many variables of the same type. Each element of the array is given a number by which you can access that
element. For an array of 100 elements, the first element is 0 (zero) and the last is 99. This indexed access makes it very convenient to loop through each element of
the array. In C, all arrays are stored in contiguous memory locations. The lowest address corresponds to the first element and the highest address to
the last element. Arrays can be, single dimensional or multidimensional. One of the most common uses of one-dimensional arrays is to represent
strings. These are stored as an array of characters, terminated by a null.
http://modul2poli.blogspot.com/
2/17/2011
14
5.2.1 Describe the steps to define an array.
a. Declaring arrayb. Initializing arrayc. Accessing arrayd. Manipulating arraye. Passing array to function as a parameter
a. Declaring array
The general form of declaring a simple (one dimensional) array is
array_type variable_name[array_size];
in your C program you can declare an array like
int Age[10];
Here array type declares base type of array which is the type of each element in array, it can be characters, integers, f loating-point numbers, etc.
In our example array type is int and its name is Age. Size of the array is defined by array size i.e. 10.
We can access array elements by index, and first item in array is at index 0. First element of array is called lower bound and its always 0. Highest element in array is called upper bound.
http://modul2poli.blogspot.com/
2/17/2011
15
Note: One good practice is to declare array length as a constant identifier. This will minimise the required work to change the array size during program development.
Considering the array we declared above we can declare it like
#define NUM_EMPLOYEE 10
int Age[NUM_EMPLOYEE];
In C programming language upper and lower bounds cannot be changed during the execution of the program, so array length can be set only when the program in written.
String in simplest term is a one dimensional array of characters terminated by a null character (‘\n’).
For safe use size of this string should be one greater than the maximum size string going to be stored in this character array.
String in C is equavialent to a real world sentence made by combination of various characters including spaces.
The general form of declaration of string variable is – char name [size];
Also string manipulation can be done very easily using some predefined function available in header <string.h>.
A character type array can also be initialized within a declaration – always refer as string.
Char text[] = “California”
http://modul2poli.blogspot.com/
2/17/2011
16
C source code below shows the general use of String.
#include<stdio.h>#include<string.h>
main(){
char enter[6] ="Enter";char password[] = "Password";char input[100] = "None";
while (1){printf("\n %s %s: ", enter, password);scanf("%s", &input);if(strcmp(input, "MYPASSWORD")){
printf(" Incorrect Password\n");}else{
printf("\n Welcome to the cyber world.....");break;
}}
return 0;}
The answer:
b. Initializing array
The initializing values are enclosed within the curly braces in the declaration and placed following an equal sign after the array name.
Initialisation of array is very simple in c programming. There are two ways you can initialise arrays.
Declare and initialisearray in one statement. Declare and initialisearray separately. Look at the following C code which demonstrates the declaration and
initialisation of an array.
int Age [5] = {30, 22, 33, 44, 25}; int Age [5]; Age [0]=30; Age [1]=22; Age [2]=33; Age [3]=44; Age [4]=25;
http://modul2poli.blogspot.com/
2/17/2011
17
Array can also be initialised in a ways that array size is omitted, in such case compiler automatically allocates memory to array.
int Age [] = {30, 22, 33, 44, 25}; All individual array elements that are not assigned explicit initial
values will automatically be set to zero. Int digits[3] = {3, 6} – the result on an element basic are as
follows. digits[0] = 3, digits[1] = 6 and digits[2] = 0
c. Accessing array
To access an individual element of an array, use the name of the array name followed by the index of the element in square are brackets. Array indices start at 0 and end at size-1:
array_name[index];
For example, to store the value 75 in the third element of billy, we could write the following statement:
billy[2] = 75;
and, for example, to pass the value of the third element of billy to a variable called a, we could write:
a = billy[2];
http://modul2poli.blogspot.com/
2/17/2011
18
Here is how we can print the value of the second element in the array:
#include <stdio.h>
int main() { short age[4]; age[0]=23; age[1]=34; age[2]=65; age[3]=74;
printf("%d\n", age[1]); return 0; }
The answer:
#include <stdio.h>
int main()
{
short age[4];
age[0]=23;
age[1]=34;
age[2]=65;
age[3]=74;
printf("%d\n", *(age+1));
return 0;
}
The output same as program using pointer to access the array.
d. Manipulating array Each array element occupies consecutive memory locations and array name is a
pointer that points to the first element. Beside accessing array via index we can use pointer to manipulate array.
This program helps you visualize the memory address each array elements and how to access array element using pointer.
#include <stdio.h>
void main()
{
const int size = 5;
int list[size] = {2,1,3,7,8};
int* plist = list;
// print memory address of array elements
for(int i = 0; i < size;i++)
{
printf("list[%d] is in %d\n",i,&list[i]);
}
// accessing array elements using pointer
for(i = 0; i < size;i++)
{
printf("list[%d] = %d\n",i,*plist); /* increase memory address of pointer so it go to the next
element of the array */
plist++;
}
}
The answer:
http://modul2poli.blogspot.com/
2/17/2011
19
e. Passing array to function as a parameter
There are two ways to pass arguments from a function to another functions : by value or by address.
Passing by value means that the value of the variable is passed to the receiving function. C uses the passing by value method for all non-array variables.
When u pass an array to another function, the array is passed by address.
The receiving function then places its receiving parameter array over the address passed. If the receiving function changes one of the variables in the parameter list, the calling function’s argument changes as well.
#include <stdio.h>
void setArray(int array[], int index, int value)
{
array[index] = value;
}
int main(void)
{
int a[1] = {1};
setArray(a, 0, 2);
printf ("a[0]=%d\n", a[0]);
return 0;
}
Example Program : Passing array to function as a parameter
Function parameters of array type may at first glance appear to be an exception to C's pass-by-value rule.
#include <stdio.h>#include <string.h>
char change(char name[]){/*change the string stored at the address pointed to by name*/
strcpy(name, “12345");return 0;
}
main(){
char name[] = "Chris Williams.";printf("You old password is %s", name);change(name);printf("\nFrom now, the password is %s.\n", name);return 0;
}
Program 1Program 2
The answer: The answer:
http://modul2poli.blogspot.com/
2/17/2011
20
5.2.2 Modify a 1-dimension array in C programme.
#include <stdio.h>main(){
int dayNum;char *days[7];days[0] = "Sunday";days[1] = "Monday";days[2] = "Tuesday";days[3] = "Wednesday";days[4] = "Thursday";days[5] = "Friday";days[6] = "Saturday";
printf("Enter a number from 1 to 7: ");scanf("%d", &dayNum);
if (dayNum>=1 && dayNum<=7){ printf("That day is %s\n", days[dayNum -1]); }else{ printf("You didn’t enter a good number.\n"); }
return 0;}
The answer:
5.2.3 Write C programme using array.
#include <stdio.h>
main()
{
int my_array[5], count;
for(count=0;count <= 4;count++)
{
my_array[count] = count*2;
}
for(count=0;count <= 4; count++)
{
printf("Element %d is : %d\n", count, my_array[count]);
}
return 0;
}
Element 0 is : 0
Element 1 is : 2
Element 2 is : 4
Element 3 is : 6
Element 4 is : 8
The program's output would be:
http://modul2poli.blogspot.com/
2/17/2011
21
Multidimensional Arrays
The array we used in the last example was a one dimensional array. Arrays can have more than one dimension, these arrays-of-arrays are called multidimensional arrays. They are very similar to standard arrays with the exception that they have multiple sets of square brackets after the array identifier. A two dimensional array can be though of as a grid of rows and columns.
*Just for information, multidimensional Arrays not in syllabus
#include <stdio.h> const int num_rows = 7; const int num_columns = 5;
int main() {
int box[num_rows][num_columns]; int row, column; for(row = 0; row < num_rows; row++)
for(column = 0; column < num_columns; column++) box[row][column] = column + (row * num_columns);
for(row = 0; row < num_rows; row++) {
for(column = 0; column < num_columns; column++) { printf("%4d", box[row][column]);
} printf("\n"); }
return 0;}
The answer :
http://modul2poli.blogspot.com/
2/25/2011
1
Understand FunctionsA function is a block of code that has a name
and it has a property that it is reusable i.e. it can be executed from as many different points in a C Program as required.
Function groups a number of program statements into a unit and gives it a name.
This unit can be invoked from other parts of a program
A computer program cannot handle all the tasks by it self.
Instead its requests other program like entities – called functions in C – to get its tasks done.
A function is a self contained block of statements that perform a coherent task of same kind.
A function can be accessed from any location within a C Program.
We pass information to the function called arguments specified when the function is called.
The function either returns some value to the point it was called from or returns nothing.
http://modul2poli.blogspot.com/
2/25/2011
2
Structure of a FunctionThere are two main parts of the function
function header & function body.
Function_type function_name(parameter list){
body of the function}
*function_type specifies the type of data that the function returns. Eg : int, float, char, etc.
Example:
int sum(int x, int y) {
int ans = 0; //holds the answer that will be returned
ans = x + y; //calculate the sum
return ans //return the answer
}
Function Header In the first line of the above code
int sum(int x, int y)
It has three main parts:1) The name of the function i.e. sum2) The parameters of the function
enclosed in paranthesis3) Return value type i.e. int
Function BodyWhat ever is written with in { } in the above
example is the body of the function.
{ int ans = 0; ans = x + y; return ans
}
http://modul2poli.blogspot.com/
2/25/2011
3
The Use of Functions
It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later.
The length of the source program can be reduced by using functions at appropriate places. This factor is critical with microcomputers where memory space is limited.
It is easy to locate and isolate a faulty function for further investigation.
A function may be used by many other programs this means that a c programmer can build on what others have already done, instead of starting over from scratch.
A program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated.
Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program
http://modul2poli.blogspot.com/
2/25/2011
4
Types of FunctionThere are basically two types of
functions:
1) Predefined function Library functions
2) User defined function Functions that individually created by the programmer.
The order in which the functions are defined in a program and the order in which they get called need not necessarily be same.
main ( ); {message 1 ( );message 2 ( );}message 2 ( ){printf (“\n I am learning C”);}message 1 ( ){printf ( “\n Hello “);}
A function gets called when the function name is followed by a semicolon.
A function can be called any number of times.
main ( ) {message ( );}
main () {message ( );message ( );}message ( ){printf (“\n Hello”);}
A function can call itself such a process as called “recursion”.
Any C program contains at least one function.
If a program contains only one function, it must be main( ).
There is no limit on the number of functions that might be present in a C program.
http://modul2poli.blogspot.com/
2/25/2011
5
Each function in a program is called in the sequence specified by the function calls in main( )
After each function has done its thing, control returns to the main( ), when main( ) runs out of function calls, the program ends.
Predefined Function The predefined functions used in the C standard
library, and a few of the non-standard functions, include:
Function Purpose
printf used to sends formatted output to the screen.
scanf used to reads formatted input from the keyboard
putchar used to sends a single character to the screen
getchar used to reads a single character from the keyboard
puts used to sends string s to the screen
gets used to read string s from the keyboard
fputc writes one character to a file
fgetc returns one character from a file
Stdio.h
ctype.h
Function Return value
salnum (c) Non- zero if ( c ) is alphanumeric; 0 otherwise
isalpha (c) Non- zero if ( c ) is alphabetic; 0 otherwise
isascii (c) Non- zero if ( c ) is ASCII character; 0 otherwise
iscntrl (c) Non- zero if ( c ) is control character ; 0 otherwise
isdigit (c) Non- zero if ( c ) is a digit; 0 otherwise
isgraph(c) Non- zero if ( c ) is a graphic character(including space); 0
otherwise
islower (c) Non- zero if ( c ) is lowercase letter ; 0 otherwise
isprint (c) Non- zero if ( c ) is printable character ( including space ) ; 0
otherwise
ispunct(c) Non- zero if ( c ) is punctuation character ; 0 otherwise
isspace (c) Non- zero if ( c ) is a space, tab, formfeed or new line
character; 0 otherwise
isupper (c) Non- zero if ( c ) is uppercase letter; 0 otherwise
isxdigit (c) Non- zero if ( c ) is hexadecimal digit ; 0 otherwise
toascii(c) ASCII equavalent
tolower (c) Lowercase equivalent of c if it is latter; unchanged otherwise
toupper (c) Uppercase equivalent of c if it is latter; unchanged otherwise
Function Return value
acos(d) Arc cosine of d
asin(d) Arc sine d
atan(d) Arc sine d
atan2(d1,d2) Arc tangent of d1/d2
ceil(d) Smallest integer greater than d
cos(d) Cosine of d
exp(d) e(i.e.,2.718…) raised to the power d
fabs(d) Absolute value of d
floor(d) Largest integer smaller than d
fmod(d1,d2) Remainder of d1/d2
log(d) Natural logarithm of (d>0)
log10(d) Base logarithm of d (d>0)
pow(d1,d2) D1 raised to the power of d2
sin(d) Sine of d
sinh(d) Hyperbolic sine of d
sqrt(d) Square root of d
tan(d) Tangent of d
tanh(d) Hyperbolic tangent of d
Math.h
http://modul2poli.blogspot.com/
2/25/2011
6
Function Purpose
getch Obtain the next character from the console but
does not echo to the screen
putch Output character to the text window on the
screen
gotoxy Position cursor in text window
clrscr Clear text mode window
Conio.h String.h
User-defined functionC allows programmers to define their own
functions.
Is a self-contained program segment that carries out some specific, well-defined task.
/* convert a lowercase character to uppercase using a programmer-defined function*/
#include <stdio.h>
char lower_to_upper(char c1) /*function definition*/{
char c2;c2=(c1>='a' && c1<='z')? ('A' + c1 - 'a'):c1;return(c2);
}
main(){
char lower, upper;printf("Please enter a lowercese character: ");scanf("%c", &lower);upper = lower_to_upper(lower);printf("\nThe uppercase equivalent is %c\n\n", upper);
}
http://modul2poli.blogspot.com/
2/25/2011
7
Components in the User-
defined Function
There are 4 basic components:
Function prototypes
Function definition
Return statement
Call function
Function PrototypesAll identifiers in C need to be declared
before they are used.
This is true for functions as well as variables.
For functions the declaration needs to be before the first call of the function.
A full declaration includes the return type and the number and type of the arguments.
Have semicolon “;” at the end of the function.
A simple program with a function prototype
/* A simple example of a function prototype allowing the function to be used before it is defined. */
#include <stdio.h> int sum (int, int); int main (void) {
int total; total = sum (2, 3); printf ("Total is %d\n", total); return 0;
} int sum (int a, int b) {
return a + b; }
Function prototype
Having the prototype available before the first use of the function allows the compiler to check that the correct number and type of arguments are used in the function call and that the returned value, if any, is being used reasonably.
The function definition itself can act as an implicit function declaration.
http://modul2poli.blogspot.com/
2/25/2011
8
This was used in the above example and was why sum was put before main.
If the order was reversed the compiler would not recognize sum as a function.
To correct this a prototype could be added before main.
The prototype gives a lot of information about the function.
Function definitionFunction definitions differ from function
declarations in that they supply function bodies — the code that makes up the function.
Function_type function_name(parameter list){
body of the function}
[ data type] function name (argument list) argument declaration; { local variable declarations; statements; [return expression] }
mul(a,b) int a,b; { int y; y=a+b; return y; }
Return statementThe return statement terminates the
execution of a function and returns control to the calling function.
When a return statement is executed, the function is terminated immediately at that point, regardless of whether it's in the middle of a loop, etc.
A return statement can also return a value to the calling function.
http://modul2poli.blogspot.com/
2/25/2011
9
The return statement has the form:
The expression portion of the statement is optional.
If an expression is not specified, the return statement becomes equivalent to:
return [expression];
return void;
Also, reaching the } (right curly brace) that terminates a function is equivalent to executing a return statement without an expression.
In C, if a control path ends in a return statement that returns a value that is of a different type than that specified in the function prototype, a warning may be generated but compilation will continue.
Returning no values - Void
A return statement without an expression can be used only in functions that do not return a value.
This prevents their use in any expression and helps avert accidental misuse.
Before you can use any void function, you must declare its prototype.
#include <stdio.h>
void modify(int a);
main(){
int a=2;printf("\n a=%d (from main, before calling the function)", a);modify(a);printf("\n\n a=%d (from main, after calling the function)", a);
}
void modify(int a){
a *=3;printf("\n\n a=%d (from the function, after being modified)", a);return;
}
Void can be used as function type when defining a function that does not return anything.
http://modul2poli.blogspot.com/
2/25/2011
10
You may also declare main() as void if it does not return a value.
Example:
#include <stdio.h>
void main(void)
{
int x;
for (x=1; x<11; ++x)
printf("\n %d", x*x);
return;
}
Declare main function as void
Return with no value
Returning valuesA return statement with an expression can
be used only in functions returning a value; the value of the expression is returned to the caller of the function.
#include <stdio.h>
int funct1(int count);
main()
{
int a, count;
for(count=1;count<=5;++count)
{
a=funct1(count);
printf("%d\n", a);
}
}
int funct1(int x)
{
int y;
y=x*x;
return (y);
}
Returning the value of y to the caller function
Function prototype
Call the function
#include <stdio.h>
int mul(int a, int b);
void main(void){
int x, y, z;x=10;y=20;z = mul(x, y);printf("%d", mul(x,y));mul(x,y);
}
mul(int a, int b){
return a*b;}
Function prototype
Call the function
Returning the value to the caller
http://modul2poli.blogspot.com/
2/25/2011
11
Call functionA function can be accessed (i.e, called) by
specifying its name, followed by a list of arguments enclosed in parentheses and separated by commas.
In general, subroutines can be passed arguments in one of two ways.
Call by value
Call by reference
Call by ValueThis method copies the value of an
argument into the formal parameter of the subroutine.
In this case, changes made to the parameter have no effect on the argument.
#include <stdio.h>
int sqr(int x);
void main(void){
int t=10;printf("%d %d", sqr(t), t);
}
sqr(int x){
x=x*x;return (x);
}
Call function by the value
In this example, the value of the argument to sqr(),10, is copied into the parameter x.
When the assignment x=x*x takes place, only the local variable x is modified.
The variable t, used to call sqr(), still has the value 10.
Remember that it is a copy of the value of the argument that is passed into the function.
What occurs inside the function has no effect on the variable used in the call.
http://modul2poli.blogspot.com/
2/25/2011
12
Call by ReferenceCall by reference is the second way of
passing arguments to a subroutine.
In this method, the address of an argument is copied into the parameter.
Inside the subroutine, the address is used to access the actual argument used in the call.
This means that changes made to the parameter affect the argument.
You can create a call by reference by passing a pointer to an arguments, instead of the argument itself.
#include <stdio.h>
void swap(int *x, int *y);
void main(void)
{
int i, j;
i=10;
j=20;
printf("i=%d j=%d (from main,before calling the function)", i,j);
swap(&i, &j);
printf("\ni=%d j=%d (from main,after calling the function)", i,j);
}
void swap(int *x, int *y)
{
int temp;
temp=*x; /*save the value at address x*/
*x=*y; /*put y into x*/
*y=temp; /*put x into y*/
}
Pass the addresses of i and j
Example programme using
user-defines function Here is a program that passes an integer i by value, a floating-point x by address, and an
integer array by address (as all arrays should be passed):
#include <stdio.h>
changeSome(int i, f loat *newX, int iAry[4]);
main(){
int i=10;f loat x=20.5;int iAry[] = {10,20,30,40,50};puts("Here are main()'s variables before the function:");printf("i is %d\n", i);printf("x is %.1f\n", x);printf("iAry[0] is %d\n", iAry[0]);printf("iAry[1] is %d\n", iAry[1]);printf("iAry[2] is %d\n", iAry[2]);printf("iAry[3] is %d\n", iAry[3]);printf("iAry[4] is %d\n", iAry[4]);
Function prototype
changeSome(i, &x, iAry);puts("\nmain()'s variables after the function:");printf("i is %d\n", i);printf("x is %.1f\n", x);printf("iAry[0] is %d\n", iAry[0]);printf("iAry[1] is %d\n", iAry[1]);printf("iAry[2] is %d\n", iAry[2]);printf("iAry[3] is %d\n", iAry[3]);printf("iAry[4] is %d\n", iAry[4]);return 0;
}
changeSome(int i, f loat *newX, int iAry[4]){
i=47;*newX=97.6;iAry[0] = 100;iAry[1] = 200;iAry[2] = 300;iAry[3] = 400;iAry[4] = 500;
}
User-defined function
Call the function by value and address
Goes back to DOS
http://modul2poli.blogspot.com/
2/25/2011
13
http://modul2poli.blogspot.com/