Beruflich Dokumente
Kultur Dokumente
http://modul2poli.blogspot.com/
http://modul2poli.blogspot.com/
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.
3
http://modul2poli.blogspot.com/
http://modul2poli.blogspot.com/
10%
20%
10%
50%
10%
http://modul2poli.blogspot.com/
2/17/2011
1.1.1 Term
1.0 Introduction To Programming
programme
Programming
language
programmer
c) A programming 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.
http://modul2poli.blogspot.com/
1
2/17/2011
programming languages.
elementary computer
operations (translated via assemblers)
Example: C++, C , FORTH
http://modul2poli.blogspot.com/
2
2/17/2011
Structured programming
http://modul2poli.blogspot.com/
3
2/17/2011
c. Object-Oriented Programming
Languages
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.
http://modul2poli.blogspot.com/
4
2/17/2011
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 start
var
var
var
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/
5
2/17/2011
b) Modular programming
Advantages of Modular
Programming
http://modul2poli.blogspot.com/
6
2/17/2011
PI = 3.14159265358979
R= 1
PI = 3.14159265358979
C = 2 * PI * R
A = PI * R * R
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
end Function
R= 2
C = 2 * PI * R
area = PI * R * R
A = PI * R * R
end function
sub print_details (R)
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
R= 3
C = 2 * PI * R
C = circumference (R)
A = area (R)
A = PI * R * R
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
end sub
R= 4
print_details 1
C = 2 * PI * R
print_details 2
A = PI * R * R
print_details 3
print_details 4
wscript.echo "Radius " & R & " Circumference " & C & " Area " & A
Here the same functionality is repeated but does works (as can be seen in figure 1). However, the programmer can work more ef ficiently
by using modular programming.
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 fficiency
of both the code and their time.
c)Object oriented
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
Reusability-Cepatkan project
- Improve the quality of
- Easily adjusted
- Flexible
- Easy maintenance
- Reduce the risk for complex projects
http://modul2poli.blogspot.com/
7
2/17/2011
c) Object oriented
is as follows:
var
var
function { ... }
main { ... }
--- Program end
Example 1: Object-oriented
Problem Solving Approach
Step 1: Problem Identification - Compute
the sum of two numbers and print out
the result.
http://modul2poli.blogspot.com/
8
2/17/2011
http://modul2poli.blogspot.com/
9
2/17/2011
PROCESS
2 - Planning variables
location
Variables with a specific type of data to
determine the memory size provided
All variables must be used in the program
prior diishtiharkan
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/
10
2/17/2011
Pseudo code
i. Pseudo code
-Steps problem solving
-Written to spoken language daily
Contoh:Mengira harga
bayarbagi buku
http://modul2poli.blogspot.com/
11
2/17/2011
4-Writing program
http://modul2poli.blogspot.com/
12
2/17/2011
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
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
Problem analysis
Problem 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 problems
Input - 3 numbers
Process - 1. Add 3 numbers
2. 3 Divide the total number to 3
Output - 3 and the average number
http://modul2poli.blogspot.com/
13
2/17/2011
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
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
Flowchart
Pseudocode
IPO Chart(input-process-output
chart)
Structure Chart
http://modul2poli.blogspot.com/
14
2/17/2011
a) Flowchart
Explanation of basic
flowchart symbol:
http://modul2poli.blogspot.com/
15
2/17/2011
ContExplanation of basic
flowchart symbol:
Example Flowchart:
Flowchart to calculate the total of fine for late
returning of library books.
http://modul2poli.blogspot.com/
16
2/17/2011
b)Pseudocode
START
Total=0, Average=0
Input a, b, c
Total = a + b + c
Average = Total / 3
Output a, b, c
Output Average
END
Advantages:
i.
ii.
iii.
Example:
Easily understood.
Easily maintained.
The codes are changeable.
Disadvantages:
Cannot be executed in the computer.
Problem 1
Uncle Ahmad wants to buy 5 cans of paint
http://modul2poli.blogspot.com/
17
2/17/2011
Problem 2
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:
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
http://modul2poli.blogspot.com/
18
2/17/2011
Example 1:
Problem: To calculate the amount of water bill
Example 2:
Problem: To calculate area of a circle
http://modul2poli.blogspot.com/
19
2/17/2011
d)Structure Charts
http://modul2poli.blogspot.com/
20
http://modul2poli.blogspot.com/
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.
http://modul2poli.blogspot.com/
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/
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
+a
-a
Multiplication
a*b
Division
a/b
a%b
Modulo (remainder)
Increment
Decrement
Prefix
++a
Suffix
a++
Prefix
--a
Suffix
a--
http://modul2poli.blogspot.com/
Relational Operator
Operator name
Syntax
Equal to
a == b
Not equal to
a != b
Greater than
a>b
Less than
a<b
a >= b
a <= b
Logical Operator
Operator name
Logical negation
(NOT)
Syntax
!a
a && b
Logical AND
a || b
Logical OR
http://modul2poli.blogspot.com/
Boolean Operator
Operator name
Syntax
Bitwise NOT
~a
Bitwise AND
a&b
Bitwise OR
a|b
Bitwise XOR
a^b
a << b
a >> b
http://modul2poli.blogspot.com/
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
7
http://modul2poli.blogspot.com/
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/
b. Nested selection
When a selection structures 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.
9
http://modul2poli.blogspot.com/
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++) {
10
http://modul2poli.blogspot.com/
Byte
2
2
2
2
4
4
Ranges
-32767 .. 32767
0 .. 65535
-32767 .. 32767
0 .. 65535
-2147483647 .. 2147483647
0 .. 4294967295
11
http://modul2poli.blogspot.com/
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
Char
Unsigned char
Byte
1
1
Ranges
-128 .. 127
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
b. Relational operators
c. Logical operators
12
http://modul2poli.blogspot.com/
Expression
An expression is a
PHRASE,
a sentence fragment.
One simplifies an
expression.
An expression HAS
NO relation symbol.
An equation is a
SENTENCE.
One solves an equation.
An equation HAS a relation
symbol.
Ex.
Ex.
Basic Expression
(Formula)
i = i + j;
i = i j;
i = i * j;
i = i / j;
i = i % j;
i + = j;
i - = j;
i * = j;
i / = j;
i % = j;
13
http://modul2poli.blogspot.com/
http://modul2poli.blogspot.com/
m
m+4
m+6
m+8
m + 10
m + 12
m + 14
m + 16
m + 18
Score [0]
Score [2]
Score [3]
Score [4]
Score [5]
Score [6]
Score [7]
Score [8]
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++)
{
15
http://modul2poli.blogspot.com/
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++;
}
}
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 &
16
http://modul2poli.blogspot.com/
the
other
the
The declaration of two dimension arrays is as follows:
column.
data_type array_name[row_size][column_size];
int m[10][20]
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]
17
http://modul2poli.blogspot.com/
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}}
18
http://modul2poli.blogspot.com/
2/17/2011
Structure Of C Programme
General form of c programs:
3.0 C FUNDAMENTALS
Preprocessor directives
main function heading
{
executable statements;
return value;
}
Structure Of C Programme
#include <stdio.h>
General form:
Example:
Preprocessor directives
#include <stdio.h>
main()
executable statements;
printf(Hello World\n);
return value;
return 0;
}
http://modul2poli.blogspot.com/
1
2/17/2011
main()
curly braces { }
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.
named main.
A function is simply a collection of
commands to perform some tasks.
printf(Hello World\n);
return 0;
http://modul2poli.blogspot.com/
2
2/17/2011
Output
Output:
Compile C programmes
your C program ,
you must run the
c program through
a C compiler to
turn it into
machine language
http://modul2poli.blogspot.com/
3
2/17/2011
Preprocessing
Temporary file
(C++ program)
C++
Preprocessor
C++ Program
C++
Compiler
Executable
Program
#include
instructs the C compiler to add the
http://modul2poli.blogspot.com/
4
2/17/2011
#include
#define
# include file.h
Example
constants or macros.
Syntax:
#define name value
#define
The #define directive can also be used to create function macros.
http://modul2poli.blogspot.com/
5
2/17/2011
stdio.h
Function
printf
scanf
putchar
getchar
puts
gets
fputc
fgetc
Example:
Program:
#include <stdio.h>
main()
{
float y;
int x;
Purpose
used to sends formatted output to the screen.
used to reads formatted input from the keyboard
used to sends a single character to the screen
used to reads a single character from the keyboard
used to sends string s to the screen
used to read string s from the keyboard
writes one character to a file
returns one character from a file
ctype.h
Output:
http://modul2poli.blogspot.com/
6
2/17/2011
Function
Return value
Example:
isascii (c)
iscntrl (c)
isdigit (c)
isgraph(c)
Program:
otherwise
islower (c) Non- zero if ( c ) is lowercase letter ; 0 otherwise
isprint (c)
ispunct(c)
return 0;
}
Output:
ASCII equavalent
math.h
Contain
functions
that
perform
mathematic
operations.
Function
Return value
acos(d)
Arc cosine of d
asin(d)
Arc sine d
atan(d)
Arc sine d
atan2(d1,d2)
Example:
Program:
ceil(d)
cos(d)
Cosine of d
exp(d)
fabs(d)
Absolute value of d
floor(d)
fmod(d1,d2)
Remainder of d1/d2
log(d)
log10(d)
pow(d1,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
Output:
http://modul2poli.blogspot.com/
7
2/17/2011
Example:
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
putch
gotoxy
clrscr
main()
{
char ch;
printf("Enter a string:");
while ((ch=getch())!='\r')
putch(ch);
printf("\nThank you\n");
return 0;
}
Output:
string.h
Program1:
#include < stdio.h >
#include < conio.h >
Program2:
#include < stdio.h >
#include < conio.h >
main()
{
char ch;
printf("Enter a string:");
while ((ch=getch())!='\r')
printf("\nThank you\n");
return 0;
}
Output:
Example:
Program:
Output:
#include <stdio.h>
#include <string.h>
main()
{
char message[20];
strcpy(message, "This is fun!");
printf("message=%s", message);
return 0;
}
http://modul2poli.blogspot.com/
8
2/17/2011
main ( )
Begin block
End block
// statements
http://modul2poli.blogspot.com/
9
2/17/2011
Create comments in
programmes.
Many of todays 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.
Example:
//Welcome program
#include <stdio.h>
main()
{
printf(Welcome to C programming); // welcome message
return 0;
}
and so on.
should not contain a space
Typename varname;
Typename specifies the data type and varname is the variable name
Example:
Example:
int count, number, start; /*three integer variables*/
float percent, total;
/*two float variables*/
OR
Examples:
int count=20;
const float pi=3.14159;
http://modul2poli.blogspot.com/
10
2/17/2011
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.
Example:
#include<stdio.h>
main()
variable
constant
float pi=3.14;
printf("\nEnter radius:");
scanf("%f", &r);
area =pi*r*r;
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.
{
float r, area;
Keyword
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
Description
The default storage class
Command that exits for, while, switch, and do...switch statements
unconditionally.
Command used within the switch statement
The simplest C data type
Makes variable value or pointer parameter unmodifiable.
Command that resets a for, while, or do...while statement to the next
iteration
Command used within the switch statement to catch any instances not specified
with a case statement
used together with while to make another form of repeating statement
Data type that can hold double-precision floating-point values
Statement signaling alternative statement to be executed when an if statement
evaluates to FALSE
Used to declare and initialize a sequence of integer constants
Data modifer indicating that a variable will be declared in another area of the
program
represents a single precision floating point data type
Looping command that contains initialization, incrementation, and conditional
sections.
Command that causes a jump to a predefined label
used to change program flow based on a TRUE/FALSE decision
Data type used to hold integer values
http://modul2poli.blogspot.com/
11
2/17/2011
Keyword
long
register
Description
Data type used to larger integer value that int
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 isnt commonly used, and its 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 variables 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 doesnt 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.
http://modul2poli.blogspot.com/
12
2/17/2011
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,
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,
float money;
money = 0.12;
int sum;
sum = 20;
b. char
Data type used to hold a single character.
An example of declaring a character variable called letter
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,
char letter;
letter = 'A';
double big;
big = 312E+7;
Description
Size
(Byte)
Range
char
Character
int
Integer
-32768 to +32767
float
Floating point
number
Double precision
double floating point
number
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/
13
2/17/2011
Example:
Example:
int quantity;
float price_per_kg, price;
number1 = 25;
number2 = 23;
number1 = number2;
number1
25
23
?
number2
23
?
#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;
}
price_per_kg
price
quantity = 2;
price_per_kg = 4.50;
price = quantity * price_per_kg;
53
quantity
?
2
?
4.50
9.00
?
54
http://modul2poli.blogspot.com/
14
2/17/2011
Example:
Program:
Output:
//assignment operator
#include <stdio.h>
main()
{
int x, y;
x=1;
y=2;
printf(x=%d,x);
printf(y=%d,y);
return 0;
}
b. Mathematical operators
perform mathematical operations such as additional
adn subtraction.
C has two unary mathematical operators and five
binary mathematical operators.
Example 2
B=3;
A=B++;
/* A contains 3, B
contains 4*/
Operator
Symbol
Action
Example
Increment
++
++x, x++
Decrement
--
--x, x--
Operator
Symbol
Action
Example
Addition
Subtraction
+
-
x+y
x-y
Multiplication
Division
*
/
Modulus
x*y
x/y
x%y
http://modul2poli.blogspot.com/
15
2/17/2011
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;
}
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);
}
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).
Operator
Equal
Greater than
Example
x= =y
x>y
x<y
x>=y
x<=y
x!=y
d. Logical operators
Logical operators let you combine two or
more relational expression into a single
expression that evaluates to either true or
false
Operator Symbol Example
Evaluates to
AND
&&
OR
||
exp1 || exp2
NOT
!exp1
http://modul2poli.blogspot.com/
16
2/17/2011
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);
}
Example
// conditional operator
#include <stdio.h>
int main ()
{
int a,b,c;
a=2;
e. Conditional operator
The conditional operator is ternary
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.
b=7;
c = (a>b) ? a : b;
printf("Larger number=%d",c);
printf("\n");
return 0;
}
http://modul2poli.blogspot.com/
17
2/17/2011
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
Escape sequence
Sequence
\b
\n
\t
\
\
\\
\a
Meaning
Backspace
Newline
Horizontal tab
Double quote
Single quote character
Backslash
Bell (Alert)
http://modul2poli.blogspot.com/
18
2/17/2011
Example 1
the screen.
printf(Welcome");
Output
Welcome
Example 2
Syntax
printf("<string> <format specifier>",<variable>);
http://modul2poli.blogspot.com/
1
2/17/2011
Example 1
puts("Hello World");
Output
Hello World
puts (str);
str is a string variable.
Syntax
scanf("<format specifier>",&<variable>);
Example
scanf("%d",&age);
%d f ormat specif ier
age variable
gets (str)
"str" is a string variable.
http://modul2poli.blogspot.com/
2
2/17/2011
Example Of Program
Format Specified
Format Specified
Data Type
%d
%f
%c
int
float
char
Question 1:
Modify the program below to produce the program that only
use puts() and gets().
input
input
#include<stdio.h>
void main( )
{
char input[80];
politeknik
#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);
}
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/
3
2/17/2011
Answer :
Question 2:
#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/
4
2/17/2011
CONTROL STATEMENT
Selection, loop, and array structure.
(04 : 09)
http://modul2poli.blogspot.com/
1
2/17/2011
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
http://modul2poli.blogspot.com/
2
2/17/2011
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
}
main ()
{ int age, yrs;
printf("Type in your age: ");
scanf ("%d", &age);
The answers:
http://modul2poli.blogspot.com/
3
2/17/2011
b. if..else
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.
The general form of if statement which includes the else clause is
The answers :
http://modul2poli.blogspot.com/
4
2/17/2011
c. nested if
One property of if else statement is that they can be nested. This means
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;
The answers :
return 0;
http://modul2poli.blogspot.com/
5
2/17/2011
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;}
case 'B':
printf("You Entered B");
break;
case 'C':
printf("You Entered C");
break;
default:
http://modul2poli.blogspot.com/
6
2/17/2011
logical expressions.
a. do..while
b. while
c. for
d. nested loop
http://modul2poli.blogspot.com/
7
2/17/2011
a. do..while
DO..WHILE - DO..WHILE loops are useful for things that want to loop at least
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".
The answer :
do{
return 0;
}
http://modul2poli.blogspot.com/
8
2/17/2011
b. while
The while statement is used to carry out looping operations, in which a group
The answer:
:
}
return 0;
}
http://modul2poli.blogspot.com/
9
2/17/2011
c. for
FOR is one of the iteration statement provided by C. It is the most popular of all
The answer:
http://modul2poli.blogspot.com/
10
2/17/2011
The answer:
printf( "%d\n", x );
x++;
}
return 0;
}
This program is use a for statement in which two of the three expression are
omitted.
d. nested loop
These loops are the loops which contain another looping
http://modul2poli.blogspot.com/
11
2/17/2011
The answer:
return 0;
}
The answer :
main()
{
int i,j;
for (i=0,j=50; i<j; i++, j--) //print numbers 0 to 50
printf( "%d\n", i );
return 0;
}
http://modul2poli.blogspot.com/
12
2/17/2011
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 loop
In 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.
Lets 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/
13
2/17/2011
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, floating-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/
14
2/17/2011
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];
A character type array can also be initialized within a declaration always refer
as string.
Char text[] = California
http://modul2poli.blogspot.com/
15
2/17/2011
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;
}
}
The answer:
return 0;
}
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 an array.
http://modul2poli.blogspot.com/
16
2/17/2011
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/
17
2/17/2011
#include <stdio.h>
The
output
same as
program
using
pointer to
access the
array.
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:
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;
The answer:
http://modul2poli.blogspot.com/
18
2/17/2011
Program 1
#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;
}
The answer:
#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;
}
The answer:
http://modul2poli.blogspot.com/
19
2/17/2011
The answer:
my_array[count] = count*2;
}
for(count=0;count <= 4; count++)
{
printf("Element %d is : %d\n", count, my_array[count]);
}
return 0;
}
Element
Element
Element
Element
Element
0
1
2
3
4
is : 0
is : 2
is : 4
is : 6
is : 8
http://modul2poli.blogspot.com/
20
2/17/2011
Multidimensional Arrays
The array we used in the last example was a one dimensional array. Arrays can
#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/
21
2/25/2011
Understand Functions
A function is a block of code that has a name
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.
http://modul2poli.blogspot.com/
1
2/25/2011
Structure of a Function
There are two main parts of the function
Example:
Function Header
Function Body
{
It has three main parts:
1) The name of the function i.e. sum
2) The parameters of the function
enclosed in paranthesis
3) Return value type i.e. int
int ans = 0;
ans = x + y;
return ans
}
http://modul2poli.blogspot.com/
2
2/25/2011
http://modul2poli.blogspot.com/
3
2/25/2011
Types of Function
functions:
1) Predefined function Library functions
2) User defined function Functions that
individually created by the programmer.
main ( );
{
message 1 ( );
message 2 ( );
}
message 2 ( )
{
printf (\n I am learning C);
}
message 1 ( )
{
printf ( \n Hello );
}
followed by a semicolon.
main ( )
{
message ( );
}
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/
4
2/25/2011
Predefined Function
Each function in a program is called in the
Function
ctype.h
Return value
Stdio.h
Function
printf
scanf
putchar
getchar
puts
gets
fputc
fgetc
Purpose
used to sends formatted output to the screen.
used to reads formatted input from the keyboard
used to sends a single character to the screen
used to reads a single character from the keyboard
used to sends string s to the screen
used to read string s from the keyboard
writes one character to a file
returns one character from a file
Function
Return value
salnum (c)
acos(d)
Arc cosine of d
isalpha (c)
asin(d)
Arc sine d
isascii (c)
atan(d)
Arc sine d
iscntrl (c)
atan2(d1,d2)
isdigit (c)
ceil(d)
isgraph(c)
cos(d)
Cosine of d
exp(d)
otherwise
islower (c)
fabs(d)
Absolute value of d
isprint (c)
floor(d)
fmod(d1,d2)
Remainder of d1/d2
otherwise
ispunct(c)
log(d)
isspace (c)
log10(d)
character; 0 otherwise
pow(d1,d2)
isupper (c)
sin(d)
Sine of d
isxdigit (c)
sinh(d)
Hyperbolic sine of d
toascii(c)
ASCII equavalent
sqrt(d)
Square root of d
tolower (c)
tan(d)
Tangent of d
toupper (c)
tanh(d)
Hyperbolic tangent of d
Math.h
http://modul2poli.blogspot.com/
5
2/25/2011
String.h
Conio.h
Function
Purpose
getch
putch
gotoxy
clrscr
User-defined function
C allows programmers to define their own
functions.
Is a self-contained program segment that
carries out some specific, well-defined task.
http://modul2poli.blogspot.com/
6
2/25/2011
Function Prototypes
All identifiers in C need to be declared
Function prototype
http://modul2poli.blogspot.com/
7
2/25/2011
Function definition
Function definitions differ from function
Return statement
The return statement terminates the
http://modul2poli.blogspot.com/
8
2/25/2011
optional.
If an expression is not specified, the return
statement becomes equivalent to:
return void;
#include <stdio.h>
void modify(int a)
type when defining a function
{
that does not return anything.
a *=3;
printf("\n\n a=%d (from the function, after being modified)", a);
return;
}
http://modul2poli.blogspot.com/
9
2/25/2011
return a value.
Example:
Returning values
A return statement with an expression can
#include <stdio.h>
void main(void)
Declare main
{
function as void
int x;
for (x=1; x<11; ++x)
printf("\n %d", x*x);
return;
Return with no
}
value
#include <stdio.h>
#include <stdio.h>
int funct1(int count);
main()
{
int a, count;
for(count=1;count<=5;++count)
{
a=funct1(count);
printf("%d\n", a);
Function prototype
Call the
function
}
}
int funct1(int x)
{
int y;
y=x*x;
return (y);
Function
prototype
Call the
function
http://modul2poli.blogspot.com/
10
2/25/2011
Call function
Call by Value
#include <stdio.h>
http://modul2poli.blogspot.com/
11
2/25/2011
You can create a call by reference by passing a pointer to an arguments, instead of the argument itself.
#include <stdio.h>
Call by Reference
Function prototype
void main(void)
{
Pass the addresses
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);
}
of i and j
User-defined function
http://modul2poli.blogspot.com/
12
2/25/2011
http://modul2poli.blogspot.com/
13