SlideShare a Scribd company logo
Introduction to C Programming
Chapter 1.1
What is a program?
• A list of instructions.
• Written in a programming language (c, c++, java).
• Determines the behavior of a machine
(computer, robot).
Programming Language
• A machine language that has its own set of
grammatical rules.
• It is used to instruct a machine to perform
specific tasks.
History
• C was developed in 1972 by Dennis Ritchie at
Bell Laboratories.
• Based on a programming language called B
(which is derived from BCPL language).
• C was designed and developed for the
development of UNIX operating system.
• C has been widely used to develop many type
of application software from a basic to
operating system.
History
Development stages of C program
c-programming
Editing
• Process of writing the C source code.
• Using editor program (i.e. vi and emacs for
Linux, Notepad for Windows)
• Software package provides programming
environment
– Integrated editor
– Managing and maintaining source code
– i.e. C++ Builder, Code::Blocks, Dev-C++, Microsoft
Visual Studio
Pre-processing and Compiling
• Pre-processing – performs directives such as
inclusion of header files and substitution.
• Compiling – process of translating the source
code (programming language) to machine
code (machine language).
Linking
• Process of combining generated object files.
• Add required codes from C standard library.
• Produce an executable file.
Executing
• Run the program to check whether it produce
the desired output.
• Testing stage where you check the output of
your program.
• The program does not produces the suppose
output, then you have made logic (semantic)
error.
C Program Layout
• C program consists of two sections:
– Pre-processor directives
– Main function
pre-processor directives
main()
{
statements
}
Pre-processor section
Main function section
Pre-processor Directives
• Specify what compiler should do before
compilation.
• Include header files.
• Header file keep information about the library
functions (printf, scanf).
• Pre-processor directives begins with the #
symbol.
Main Function
• The program starts its execution.
• Define the program definition.
An Example of C Program
Sample output:
C program example
An Example of C Program
• A comment, not actually part of the program.
• Provide information on what the program
does.
• Begin with /* and end with */ or written
as //.
• Good habit to include comments.
• Keep inform what are the code actually doing.
An Example of C Program
• Important line in C
• Symbol # indicates that this is a pre-processor
directive
• Include stdio.h header file in our program
• stdio.h contains information on
input/output routines.
• We are using the printf() function from
stdio.h
An Example of C Program
• Defines the start of the function main().
• Keyword int signifies main function returns
an integer value.
• The () is where we specify information to be
transferred to function main().
An Example of C Program
• The portion that begins with { and ends
with } is called block or body.
• Within the block is where we write the
statements.
An Example of C Program
• Function printf() instructs the computer
to display characters or a string enclosed by
the double quotes on the monitor screen.
• A string is a combination of numerous
characters.
An Example of C Program
• Function main() is defined to return a value
of integer type.
• return 0 is needed to indicate that the
program has terminated successfully.
Flow Chart
• Sequence flow
Flow Chart
• Looping flow
Flow Chart
• Combination
flow
Exercise
Draw a flowchart to solve below problem:
Prepare cupcakes. Ingredients are flour, yeast,
and sugar. Make sure you taste the dough
before baking process.
Find solution to calculate the average marks for
100 of student. Then, display the average
value.
Variables, Keywords and
Operators
Chapter 1.2
• Every variable has name, type and value.
• Variable name / Identifier :
 Must start with character or underscore ( _ ), cannot
start with number or symbol and not a keyword .
 Must not include any space and it is letter case
sensitive.
 Eg: stud1, Stud1, stud_name, _student (valid)
@stud, stud name, 1stud (invalid)
• Variable type :
 Based on the data type – integer, floating point
numbers and characters.
 The value can be change any time.
 Whenever a new value is placed into a variable, it
replaces the previous value.
Variables
• Variable must be declare / initialize before it can be used
in the next line of statements.
• Variable declaration :
 To declare a variable with a name and suitable data
type.
 Eg: int student; int staff;
double x, y;
• Variable initialization :
 To declare a variable and assign a certain value to
the varible.
 Eg: int student=5; int staff=1;
double x=1.12;
double y=9.999;
Variables
• Integer:
 Whole number (decimal).
 Positive, negative or zero : 25, 0, -9.
 Variable declaration: int x;
• Floating point numbers:
 double / float
 Variable declaration: double y;
float z;
• Characters:
 A character is a single letter, digit, symbol or space. Eg:
‘m’,‘B’,‘#’,‘3’,‘=’,‘@’,‘ ’.
 A string is series of characters .
Eg: “student” ,“F#”,“$35”,
“class_93”,“ALI BABA”.
Data Types
• Special words reserved for C.
• Cannot be used as variable names.
• Eg: data types (int,void,const,static)
instruction statements (if,for,case,
break,return,include)
Keywords
• Constant name is declared just like variable name.
• Constant value cannot be changed after its declaration.
• 2 ways for constant declaration :
 const double pi = 3.147; or
 #define pi 3.147
Constants
• To assign a value to a variable.
• Is a binary operator (at least has two operands).
• Variable that receiving the value is on the left.
• Eg: int num;  num
(in memory)
num=3; 
• num is assigned to value of 3.
• Arithmetic operation  c = a + b
• Multiple assignment  x = y = z = 7
• Compound assignment  +=,–=,*=,/=,%=
 sum += 5
sum = sum+5
Assignment Operator
3
• x % y produces remainder when x / y.
• Eg: 5/3=1,5%3=2.
Arithmetic Operators
Operators Symbol
Addition +
Substraction -
Multiplication *
Division /
Modulus %
• Used to compare numerical values .
Operator Symbol
Less than <
Less than or equal to <=
Greater than >
Greater than or
equal to
>=
Equal to ==
Not equal to !=
Relational Operators
Also
known as
Equality
Operators
Expression Value
!1 0
!0 1
Expression Value
0 && 0 0
0 && 1 0
1 && 0 0
1 && 1 1
Expression Value
0 || 0 0
0 || 1 1
1 || 0 1
1 || 1 1
Operators Symbol
NOT !
AND &&
OR ||
Logical Operators
• Increment operator  ++
 add 1
• Decrement operator  --;
subtract 1
• These operators can be used as prefix (+
+a/--a) or postfix (a++/a--).
• Prefix increase/decrease the operand
before it is used.
• Postfix  increase/decrease the operand
after it is used.
Increment and
Decrement Operators
• Example 1.2.1
int y,c,x;
y=5,c=1,x=3;
c++;
x+=2;
--y;
y=c++;
y=++x;
Increment and
Decrement Operators
5 1 3
5 2 5
4 2 5
2 2 5
6 3 6
5
y
1
c
3
x (in memory)
Highest Precedence
parenthesis,
logical op.
( ) !
arithmetic op. * / %
arithmetic op. + -
relational op. < <= > >=
equality op. == !=
logical op. &&
logical op. ||
Lowest Precedence
Operator Precedence
• Example 1.2.2
7 % 3 + 4 * 2 – (1 + 12) / 4
• Example 1.2.3
x > 5 || y < 7 && z != 2
let x=4 ,y =5,z=9.
Operator Precedence
• Example 1.2.2
7 % 3 + 4 * 2 – (1 + 12) / 4
= 7 % 3 + 4 * 2 – 13 / 4
= (7 % 3)+(4 * 2)–(13 / 4)
= 1 + 8 – 3
= 6
Operator Precedence
• Example 1.2.3
x > 5 || y < 7 && z != 2
let x=4 ,y =5,z=9.
– x > 5 returns False (0)
– y < 7 returns True (1)
– z != 2 returns True (1)
=(x > 5)||(y < 7)&&(z != 2)
= 0 || 1 && 1
= 0 || (1 && 1)
= 0 || 1
= 1
Operator Precedence
Input Output Operation
Chapter 2
Input Output Device
• Input devices are used to perform the input
operation.
• Eg: keyboard, mouse, microphone, scanner.
• Output devices are used to perform the
output operation.
• Eg: monitor, printer, speaker.
Input Output Operation
• Input operation in basic C programming is to
get input data from the keyboard using
scanf statement.
• While output operation is to display the data
at the monitor screen using printf
statement.
scanf
Input Output Operation
printf
get input data
from the
keyboard
display the
data at the
monitor
46
Formatting Output with printf
• printf
– Precise output formatting
• Conversion specifications: flags, field widths, precisions, etc.
– Can perform rounding, aligning columns, right/left justification,
inserting literal characters, exponential format, hexadecimal format,
and fixed width and precision
• Format
– printf( format-control-string, other-arguments );
– Format control string: describes output format
– Other-arguments: correspond to each conversion specification in
format-control-string
• Each specification begins with a percent sign(%), ends with
conversion specifier
47
Printing Integers
• Integer
– Whole number (no decimal point): 25, 0, -9
– Positive, negative, or zero
– Only minus sign prints by default
Conversion Specifier Description
d Display a signed decimal integer.
i Display a signed decimal integer. (Note: The i and d specifiers
are different when used with scanf.)
o Display an unsigned octal integer.
u Display an unsigned decimal integer.
x or X Display an unsigned hexadecimal integer. X causes the digits 0-9
and the letters A-F to be displayed and x causes the digits 0-9 and
a-f to be displayed.
h or l (letter l) Place before any integer conversion specifier to indicate that a
short or long integer is displayed respectively. Letters h and l
are more precisely called length modifiers.
49
Printing Floating-Point Numbers
• Floating Point Numbers
– Have a decimal point (33.5)
– f – print floating point with at least one digit to left of
decimal
Printing Strings and Characters
• c
– Prints char argument
– Cannot be used to print the first character of a string
• s
– Requires a pointer to char as an argument
– Prints characters until NULL ('0') encountered
– Cannot print a char argument
• Remember
– Single quotes for character constants ('z')
– Double quotes for strings "z" (which actually contains
two characters, 'z' and '0')
51
Printing with Field Widths and
Precisions
• Field width
– Size of field in which data is printed
– If width larger than data, default right justified
• If field width too small, increases to fit data
• Minus sign uses one character position in field
– Integer width inserted between % and conversion
specifier
– %4d – field width of 4
52
• Precision
– Meaning varies depending on data type
– Integers (default 1)
• Minimum number of digits to print
– If data too small, prefixed with zeros
– Floating point
• Number of digits to appear after decimal (e and f)
– For g – maximum number of significant digits
– Strings
• Maximum number of characters to be written from
string
– Format
• Use a dot (.) then precision number after %
%.3f
53
• Field width and precision
– Can both be specified
• %width.precision
%5.3f
– Negative field width – left justified
– Positive field width – right justified
– Precision must be positive
– Can use integer expressions to determine field
width and precision values
54
Printing Literals and Escape
Sequences
• Printing Literals
– Most characters can be printed
– Certain "problem" characters, such as the
quotation mark "
– Must be represented by escape sequences
• Represented by a backslash  followed by an escape
character
55
• Table of all escape sequences
Escape sequence Description
' Output the single quote (') character.
" Output the double quote (") character.
? Output the question mark (?) character.
 Output the backslash () character.
a Cause an audible (bell) or visual alert.
b Move the cursor back one position on the current line.
f Move the cursor to the start of the next logical page.
n Move the cursor to the beginning of the next line.
r Move the cursor to the beginning of the current line.
t Move the cursor to the next horizontal tab position.
v Move the cursor to the next vertical tab position.
scanf Statement
• Input operation in basic C programming is to
get input data from the keyboard using
scanf statement.
• While output operation is to display the data
at the monitor screen using printf
statement.
57
Formatting Input with Scanf
• scanf
– Input formatting
– Capabilities
• Input all types of data
• Input specific characters
• Skip specific characters
• Format
– scanf(format-control-string, other-arguments);
– Format-control-string
• Describes formats of inputs
– Other-arguments
• Pointers to variables where input will be stored
– Can include field widths to read a specific number of characters from
the stream
58
Formatting Input with Scanf
Conversion specifier Description
Integers
d Read an optionally signed decimal integer. The corresponding
argument is a pointer to integer.
o Read an octal integer. The corresponding argument is a pointer to
unsigned integer.
x or X Read a hexadecimal integer. The corresponding argument is a
pointer to unsigned integer.
Floating-point numbers
f Read a floating-point value. The corresponding argument is a
pointer to a floating-point variable.
Characters and strings
c Read a character. The corresponding argument is a pointer to
char, no null ('0') is added.
s Read a string. The corresponding argument is a pointer to an array
of type char that is large enough to hold the string and a
terminating null ('0') character—which is automatically added.
Exercise
What data types would you use to hold the
following data?
Customer name
Your house number
A price
Car registrations
The time
A six digit number
Write C statements to declare them all.
Selection Structure
Chapter 3.1
Introduction
• Ability to change the flow of program
execution.
• Allows the program to decide an action based
upon user's input or other processes.
if Selection Statement
• Primary tool of selection structure.
• The condition is TRUE – execute the
statement.
• The condition is FALSE – skip the
statement.
if Selection Statement
if ( condition )
Execute this statement if
condition is TRUE
i.e.
if (5 < 10)
printf("Five is less than ten");
• Evaluate the statement, "is five less than ten"
Example
Sample output:
Enter a number between -10 and 10: 6
6 is a positive number
if else Selection Statement
• Execute certain
statement if the
condition is false
• The condition is TRUE –
execute the statement A
• The condition is FALSE –
execute the statement B
if else Selection Statement
if ( condition )
Statement A;
else
Statement B;
i.e.
if ( 5 < 10 )
printf("Five is less than ten");
else
printf("Five is greater than
ten");
Example
Sample output:
Enter a number between -10 and 10: -2
-2 is a negative number
if else if Selection Statement
• Test additional conditions
• Works the same way as normal if statement
Example
Sample output:
Please enter your age: 58
You are old
More than one statement
• Multiple statements within selection structure
• Use braces { }
• Block of code
if ( condition ) {
Statement 1
Statement 2
…
Statement N
}
Nested if Selection Structure
• if within an if is called
nested if
if ( condition 1 )
Statement A;
if ( condition 2 )
Statement C;
else
Statement D;
else
Statement B;
Example
Sample output:
Enter a number between -10 and 10: 6
6 is a positive number
6 is an even number
switch Selection Statement
• Substitutes for long if statements
• Select from multiple options
• Consists of a series of case label sand optional
default case
• Compares the value of variable or expression
with values specified in each case
switch Selection Statement
switch (variable ){
case value 1:
Statement A;
break;
case value 2:
Statement B;
break;
...
default:
Statement N;
break;
}
Example
Exercise
Write a program that asks the user to enter two
integers, obtains the numbers from the user,
then prints the larger number followed by the
words “is larger.” If the numbers are equal, print
the message “These numbers are equal.” Use
only the single-selection form of the if statement
you learned in this chapter.
Draw a flowchart for this task:-
Obtains two integer numbers from the keyboard,
and display which is larger of the two numbers.
Exercise
Write a program that asks the user to enter two
integers, obtains the numbers from the user,
then prints the larger number followed by the
words “is larger.” If the numbers are equal, print
the message “These numbers are equal.” Use
only the single-selection form of the if statement
you learned in this chapter.
Draw a flowchart for this task:-
Obtains two integer numbers from the keyboard,
and display which is larger of the two numbers.
Exercise
Using ‘switch’ and ‘case statement’, write a
program determine whether the number we
key in is odd or even and that print out
adjacent “*” sign same as that number.
(Example: For number 6, we will print out
****** ).
Repetition Structure
Chapter 3.2
Introduction
• What if we want to display numbers from 1 to
100?
• What if we want to repeat a thousand times of
10 statements?
• It is possible to do it, but it is not a convenience
and it would take a long time to complete
• Ability to specify repetition of compound
statements is as important in programming –
Loop
Introduction
• Two types of loop:
– Finite loop
– Infinite loop
• Finite (counter-controlled) loop is a repetition
in which it will continue looping until certain
condition is met
• Infinite loop has no certain condition in which
it will continue looping forever
Introduction
• Three requirements of defining a definite loop
1.counter initialization
2.increment of counter
3.loop condition
• while, do while and for loop
while Repetition Structure
• Allows the repetition of a set
of statements execution to
continue for as long as a
specified condition is TRUE
• When the condition becomes
false, the repetition
terminates
while Repetition Structure
while ( condition ) {
statements;
}
while ( a < b ) {
printf("a is less than bn");
}
Example
• Test the condition
• Execute statements within
while loop’s block
• Jump back to the top and re-
test the condition
Example
Sample output:
0
1
2
…
9
do while Repetition Structure
• Condition is tested at the end of
the block instead of at the
beginning
• Block will be executed at least
once
do while Repetition Structure
do {
statements;
} while ( condition );
do {
printf("a is less than bn");
} while ( a < b );
Example
• Execute statements within do
while loop’s block
• Test the condition
• Jump back to the top and re-
execute statements
Example
Sample output:
0
1
2
…
9
for Repetition Structure
• for loop combines the loop control
parameters into single statement
• Loop control parameters – variable
initialization, variable update and loop
condition
for Repetition Structure
for ( a; b; c ) {
statements;
}
• a (variable initialisation) is evaluated once only -
before entering the loop
• b (condition) determines whether or not the
program loops
• c (variable update) is evaluated after an iteration
of the loop – loop counter
Example
• Initializes count equals
to zero
• Test the condition
• Execute statements
within for loop’s block
• Jump back to the top
and re-test the
condition
Example
Sample output:
0
1
2
…
9
Nested Loop
• A loop within a loop
Loop1
Loop2
statement
return
return
Example
Sample output:
1 1
2 3
3 6
Infinite Loop
• Loops forever
• Contains no condition
• Condition that can never be satisfied
Example
break and continue Statements
• Can be executed in while, do while and
for statement
• Used to alter the flow of control
Example
• Causes an immediate exit from that
statement
• Skip the remaining statements
• Performs the next iteration of the loop
Example
Exercise
Use a loop to produce the following output:
a) 12345678910
b) 3, 8, 13, 18, 23
c) 20, 14, 8, 2, -4, -10
Write a program that will display all odd
numbers between 1 to 40.
Functions
Chapter 4
Introduction
• Mini-program where a group of statements
are executed.
• Programmer-defined functions.
• Break a large program into smaller sets of
statements according to their tasks.
Benefits of Function
• To make program more manageable
– divide-and-conquer approach (construct a
program from smaller components/modules.
• Software reusability
– reuse existing functions for new programs
• Avoid repeating code
c-programming
Sequence of Execution
3 Elements of Function
• Function definition
• Function prototype / declaration
• Calling function
Function Definition
• Specifies the specification of a function
– return value type, function name, arguments.
• Defines the operation to be performed when
a function is invoked.
Function Definition
return_value_type function_name(parameter_list)
{
statements;
}
function body
function header
Function Definition
return_value_type function_name(parameter_list)
{
statements;
}
 Specifies the type of the value returned by the function
 Data types of return value : int (default),char, float, double
 If function does not has any return value : void
o List of variable names received by the function from the caller –
arguments (data input)
o parameter_list : (parameter_type parameter name)
o parameter_type: int ,char, float, double
o If function does not has any parameter_list : (void) or ()
Function Prototype
• To declare function if the function definition is
written below the main function.
• Otherwise, no need function prototype.
(function definition above the main function)
• Almost similar with function definition header,
but must be written before the main function
with semicolon at the end of statement.
Function Prototype
return_value_type function_name(parameter_list);
 Specifies the type of the value returned by the function
 Data types of return value : int (default),char, float, double
 If function does not has any return value : void
o List of variable names received by the function from the caller –
arguments (data input)
o parameter_list : (parameter_type )
o parameter_type: int ,char, float, double
o If function does not has any parameter_list : (void) or ()
Calling Function
• Two ways to invoke/call function
– Call-by-value
– Call-by-reference.
• Calling function statement is written in the
caller function (main function).
Call-by-value VS Call-by-reference
Call-by-value
• Copies of the
arguments’ value are
made and passed to the
called function
• Changes to the copy do
not effect an original
variable’s value
• Available in C language
Call-by-reference
• References of
the arguments’
value are passed
to the called
function
• Called function
can modify the
original
variable’s value
• Possible to
simulate
Example 1
#include<stdio.h>
void function_name(void);
int main() {
statements;
function_name();
return 0;
}
void function_name(void) {
statements;
}
Function prototype
Function definition
Calling function
Example 2
#include<stdio.h>
double function_name(int,double);
int main() {
int p1, double p2;
statements;
function_name(p1,p2);
return 0;
}
double function_name(int pm1,double pm2) {
statements;
}
Function prototype
Function definition
Calling function
Example 3
Sample output:
Call-by-value
----------------------
Before func1 is called
n1 = 5
In func1
n1 = 10
After func1 is called
n1 = 5
Example 4
Sample output:
Enter base and power: 5 4
The result is 625.
function prototype
function definition
function call
Scope Variable
• Variables declared in function main() are
known only within function main() – not
accessible outside of the block
• It is applied to variables defined within a block
that is inside other block
• But variables defined in the outer block are
accessible in the inner block
Scope Variable
• Variable a is declared in
main()
• Variable b is declared
within while loop block
(inner block)
• a is the outer block
variable therefore it is
accessible within inner
block
• b is not accessible in the
outer block because it is
while loop variable
Scope Variable
num2 is not accessible in func()
num2 is considered undeclared in func()
num2 is accessible in main() only
num2 is declared in main()
Global Variable
• Variables declared outside any function is
called global variables
• Global variables are variables that can be
accessed in any function
• Normally they are declared before function
main()
Global Variable
num2 is a global variable
num2 is accessible in func()
Recursive Function
• Function that calls itself either directly or
indirectly through another function
Example 5
Sample output:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
Exercise
• Write a program that utilizes a function with
parameters. The program reads 3 integer
numbers from the user and sends the 3 input
to the function. The function finds the
smallest value between the 3 integer numbers
and return the value to the main function.
Enter three inter numbers:
30
80
20
Smallest value: 20
Exercise
• Consider the following program, what is the
value of num1 and num2 after each statement
is executed?
num1 num2
2
1
1 3
1 7
1 21
num1 num2
1 void funcA(int);
2 int funcB(int);
3 int num2 = 2;
4
5 int main(void)
6 {
7 int num1 = 1;
8
9 num2 = funcB(num1);
10 funcA(num1);
11 funcA(num2);
12
13 return 0;
14 }
15 void funcA(int num1)
16 {
17 num1 = num1 + num2;
18 num2 = num1 + num2;
19 }
20 int funcB(int num1)
21 {
22 num1 = num1 + num2;
23 return num1;
24 }
Arrays
Chapter 5
Introduction
• A group of memory locations that have the
same name and the same type.
• Allows to store a sequence of values.
Introduction cont.• First element in an array is the
zeroth element, a[0]
• In the example to the right:_
Second element is a[1]= 6. Element
two is a[2]=11. Different way of
statement resulting in different
meaning!
• If b=2 and c=4, then
a[b+c] =a[b+c]+2;
a[2+4] =a[2+4]+2;
a[6] = a[6]+2;
a[6] = 10;
Defining and Initializing
of One Dimentional Array
• int a[5];
• int a[5] = {0}; //all elements equal zero
• int a[5] = {10, 20, 30, 40, 50};
• int a[5] = {10, 20, 30, 40, 50, 60}; //error
• float a[5] = {1.1, 2.2, 3.3, 4.4, 5.5};
• char a[6] = {'h', 'e', 'l', 'l', 'o'};
Note: a[5] carries the value ‘/0’, more on
this later.
Example
Input/Output
• Declare an integer array named a with 10 elements
int a[10];
• Input an integer into 6th
element
scanf("%d ", &a[5]);
• Output the content of 6th
element
printf("a[5] is %d.n ", a[5]);
Character Arrays
• Store characters
• Character arrays are capable of storing strings
• Revise: %c for characters ( eg. A, b, c, D )
%s for strings ( eg. hi, welcome, good )
Character Arrays
• char string[]="hello";
• Initializes the elements of array string to the
individual characters in the string “hello”
• string "hello" has 5 characters plus a special string
termination character called null character '0'
Character Arrays
char x[]={'h', 'e', 'l', 'l', 'o', '0'};
• x[0] = 'h'
• x[1] = 'e'
• x[2] = 'l'
• x[3] = 'l'
• x[4] = 'e‘
• x[5] = '0'
Input/Output
• Declare a char array named string1 with 20 elements
char string1[20];
• Input a string into the array
scanf("%s", string1);
• Output the array’s content
printf("The content is %s.n",
string1);
• Function scanf will read characters until a space, tab,
newline or EOF is encountered
c-programming
Passing Arrays to Functions
• Modify the elements in function body is
modifying the actual elements of the array
Cont.
int array[30]; //array declaration
void func(int array[]) {
… //function prototype
}
func(array) //call function
the passed array
Passing Elements to Functions
• Passing an individual array elements are like
passing a variable
• The actual value is not modified
Cont.
int array[30];
void func(int e) {
…
}
func(array[5])
the passed element
variable e copies the value of array element
Passing Elements to
Functions
Two Dimensional Array
• To represent table of values consisting of
information arranged in rows and columns
Defining and Initializing
• int a[2][3];
• int a[2][3] = {{1, 2, 3}, {2, 3, 4}};
1st
Row 2nd
Row
• Eg. int b[3][4];
Example
Exercise
• Write a program to print the values of each
element of a 3-by-2 array using nested loop..
Initialize the array as:
{12.0,14.2},{13.0,16.5},{10.5,11.0}
Pointers
Chapter 6
Introduction
• Pointers are variables whose values are
memory addresses
• A pointer contains an address of a variable
that contains a specific value
Introduction cont.
• Count directly
references a variable
that contains the value
5
• Pointer indirectly
references a variable
that contains the value
5 (indirection)
5
count
5
countPointer
Declaring and Initializing
• A pointer of type int is a
pointer to a variable
type int
• int y = 5;
• int *yPtr;
• yPtr = &y;
• & returns the address
of its operand
5
yyPtr
5
Location
60000
60000
Location
50000
Using Pointers
• * (indirection) operator returns the value of
the object a pointer refers to
• Assume y = 5
• yPtr = &y;
• z = *yPtr + 5;
• *yPtr = 7;
• z = *yPtr + 5;
• yPtr = &z;
c-programming
c-programming
Call-by-reference
• The original variable address is passed to the
function by using & operator.
• Ability to access the variables directly and to
modify them if required.
Example
num1 = 3 - before
Value returned: 9
num1 = 3 - after
num2 = 5 - before
num2 = 25 - after
& (address) operator is specified
a pointer
numRef = numRef * numRef
Pointers and Arrays
• Any operation that can be achieved by array
subscripting can also be done with pointers
Cont.
• bPtr = &b[0];
• bPtr+1 points to next element
• bPtr+i points i elements after
bPtr
• bPtr-i points i elements before
bPtr
• bPtr+i is the address of b[i]
• *(bPtr+i) is the content of b[i]
b
0 1 2 3 4
bPtr bPtr+1
Arrays of Pointers
• Since pointers are variables
• Can be stored in arrays
• Array of memory addresses
Example
Sample output:
3
5
10
Pointers to Functions
• A pointer to a function contains the
address of the function
• Similarly, a function called through
a pointer must also passes the
number and type of the arguments
and the type of return value that is
expected
Example
Exercise
• Consider the following statements, what is the
value of px and py after each statement is
executed?
px py
0 x 00FC24BB
0 x 00AACCDD
0 x 00EE58FA
0 x 00EE58FA
Given:
address x = 0 x 00FC24BB
address y = 0 x 00AACCDD
address z = 0 x 00EE58FA
px py
1 int x, y, z;
2 int *px, *py, *pz;
3
4 x = 5;
5 y = 10;
6 px = &x;
7 py = &y;
8 z = 15;
9 py = &z;
10 px = py
Working with Files
Opening a File
• FILE pointer which will let the program
keep track of the file being accessed
• FILE *fp;
• Function fopen use to open a file
• fp = fopen("filename", "mode");
Filename
• Use double backslashes rather than a
single backslash (in the case of string
literal)
– "c:test.txt" – t is considered as
escape sequence
– "c:test.txt" – correct way to specify
backslash
Modes
• r - open for reading
• w - open for writing
• a - open for appending
Example
• FILE *p1, *p2;
• p1 = fopen("data", "r");
• p2 = fopen("results", "w");
Closing a File
• A file must be closed as soon as all
operations on it have been completed
• fclose(p1);
• fclose(p2);
Get a character from file
• fgetc (file);
• Returns the character currently pointed by
the internal file position indicator of the
specified file
Example
• FILE *fptr;
• fptr = fopen("logfile.txt",
"r");
• char inpF;
• inpF = fgetc(fptr);
Get string from File
• fgets(char *str, int num, file);
• Reads characters from file until
– (num-1) characters have been read or
– a newline or
– End-of-File is reached
– whichever comes first.
• A null character is automatically appended
in str after the characters read to signal
the end of the C string.
Example
• FILE *fptr;
• fptr = fopen("logfile.txt",
"r");
• char inpF[20] = " ";
• fgets(inpF, 20, fptr);
Write character to file
– fputc(int character, file);
– Writes a character to the file and advances the
position indicator
Example
• FILE *fptr = NULL;
• fptr = fopen("logfile.txt",
"a");
• char outF = 'A';
• fputc(outF, fptr);
Write string to file
• fputs(const char * str, FILE * stream);
• Writes the string pointed by str to the file
Example
• FILE *fptr = NULL;
• fptr = fopen("logfile.txt",
"a");
• char outF[20] = "Hello
Worldn";
• fputs(outF, fptr);
Read formatted data from file
• fscanf(file, fmt-control-string, var);
• Reads data from the file and stores them
according to the parameter format into
variables
Example
• FILE *fptr = NULL;
• fptr = fopen("logfile.txt",
"r");
• char inpF[20] = " ";
• fscanf(fptr, "%s", inpF);
Write formatted output to file
• fprintf(file, fmt-control-string, var);
• Writes to the specified file a sequence of
data formatted as the format argument
specifies
Example
• FILE *fptr = NULL;
• fptr = fopen("logfile.txt", "a");
• int n = 1;
• char name[20] = "Muhammad";
• fprintf (fptr, "Name %d - %sn", n,
name);

More Related Content

What's hot (20)

PPTX
File in C language
Manash Kumar Mondal
 
PPTX
C programming
Jigarthacker
 
PPTX
Function in C program
Nurul Zakiah Zamri Tan
 
PPTX
C functions
University of Potsdam
 
PPTX
C if else
Ritwik Das
 
PDF
C programming
Rounak Samdadia
 
PPTX
Functions in c
sunila tharagaturi
 
PPTX
Unit 3. Input and Output
Ashim Lamichhane
 
PPT
C++ Functions
sathish sak
 
PPTX
Pointers in c++
Vineeta Garg
 
PDF
Introduction to c++ ppt
Prof. Dr. K. Adisesha
 
PPTX
Loops in C Programming Language
Mahantesh Devoor
 
PDF
Introduction to c++ ppt 1
Prof. Dr. K. Adisesha
 
PDF
Character Array and String
Tasnima Hamid
 
PPTX
Functions in c language
tanmaymodi4
 
PPTX
Data Type in C Programming
Qazi Shahzad Ali
 
PPT
C program
AJAL A J
 
PDF
Object oriented programming c++
Ankur Pandey
 
PPTX
Type casting in c programming
Rumman Ansari
 
File in C language
Manash Kumar Mondal
 
C programming
Jigarthacker
 
Function in C program
Nurul Zakiah Zamri Tan
 
C if else
Ritwik Das
 
C programming
Rounak Samdadia
 
Functions in c
sunila tharagaturi
 
Unit 3. Input and Output
Ashim Lamichhane
 
C++ Functions
sathish sak
 
Pointers in c++
Vineeta Garg
 
Introduction to c++ ppt
Prof. Dr. K. Adisesha
 
Loops in C Programming Language
Mahantesh Devoor
 
Introduction to c++ ppt 1
Prof. Dr. K. Adisesha
 
Character Array and String
Tasnima Hamid
 
Functions in c language
tanmaymodi4
 
Data Type in C Programming
Qazi Shahzad Ali
 
C program
AJAL A J
 
Object oriented programming c++
Ankur Pandey
 
Type casting in c programming
Rumman Ansari
 

Similar to c-programming (20)

PPT
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
PDF
2 EPT 162 Lecture 2
Don Dooley
 
PPTX
Team-7 SP.pptxdfghjksdfgduytredfghjkjhgffghj
bayazidalom983
 
PPT
Unit i intro-operators
HINAPARVEENAlXC
 
PPTX
C programming language
Abin Rimal
 
PPT
Ch2 introduction to c
Hattori Sidek
 
PPTX
Each n Every topic of C Programming.pptx
snnbarot
 
PPTX
c_pro_introduction.pptx
RohitRaj744272
 
PPTX
c programming session 1.pptx
RSathyaPriyaCSEKIOT
 
PPT
Introduction to C Programming
MOHAMAD NOH AHMAD
 
PPT
Unit 4 Foc
JAYA
 
PPTX
dinoC_ppt.pptx
DinobandhuThokdarCST
 
PPTX
comp 122 Chapter 2.pptx,language semantics
floraaluoch3
 
PDF
learn basic to advance C Programming Notes
bhagadeakshay97
 
PPTX
Overview of C Mrs Sowmya Jyothi
Sowmya Jyothi
 
PDF
java or oops class not in kerala polytechnic 4rth semester nots j
ishorishore
 
PDF
C intro
SHIKHA GAUTAM
 
PDF
The New Yorker cartoon premium membership of the
shubhamgupta7133
 
PPT
Introduction to C
Janani Satheshkumar
 
PPT
Fundamental of C Programming Language and Basic Input/Output Function
imtiazalijoono
 
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
2 EPT 162 Lecture 2
Don Dooley
 
Team-7 SP.pptxdfghjksdfgduytredfghjkjhgffghj
bayazidalom983
 
Unit i intro-operators
HINAPARVEENAlXC
 
C programming language
Abin Rimal
 
Ch2 introduction to c
Hattori Sidek
 
Each n Every topic of C Programming.pptx
snnbarot
 
c_pro_introduction.pptx
RohitRaj744272
 
c programming session 1.pptx
RSathyaPriyaCSEKIOT
 
Introduction to C Programming
MOHAMAD NOH AHMAD
 
Unit 4 Foc
JAYA
 
dinoC_ppt.pptx
DinobandhuThokdarCST
 
comp 122 Chapter 2.pptx,language semantics
floraaluoch3
 
learn basic to advance C Programming Notes
bhagadeakshay97
 
Overview of C Mrs Sowmya Jyothi
Sowmya Jyothi
 
java or oops class not in kerala polytechnic 4rth semester nots j
ishorishore
 
C intro
SHIKHA GAUTAM
 
The New Yorker cartoon premium membership of the
shubhamgupta7133
 
Introduction to C
Janani Satheshkumar
 
Fundamental of C Programming Language and Basic Input/Output Function
imtiazalijoono
 
Ad

Recently uploaded (20)

PDF
NTPC PATRATU Summer internship report.pdf
hemant03701
 
PPTX
Seminar Description: YOLO v1 (You Only Look Once).pptx
abhijithpramod20002
 
PPTX
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
PPTX
Unit_I Functional Units, Instruction Sets.pptx
logaprakash9
 
PPT
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
PPTX
Alan Turing - life and importance for all of us now
Pedro Concejero
 
PPTX
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
PPT
FINAL plumbing code for board exam passer
MattKristopherDiaz
 
DOCX
Engineering Geology Field Report to Malekhu .docx
justprashant567
 
PDF
bs-en-12390-3 testing hardened concrete.pdf
ADVANCEDCONSTRUCTION
 
PDF
LLC CM NCP1399 SIMPLIS MODEL MANUAL.PDF
ssuser1be9ce
 
PDF
William Stallings - Foundations of Modern Networking_ SDN, NFV, QoE, IoT, and...
lavanya896395
 
PPTX
Distribution reservoir and service storage pptx
dhanashree78
 
PPTX
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
PDF
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
PPTX
UNIT 1 - INTRODUCTION TO AI and AI tools and basic concept
gokuld13012005
 
PDF
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
PDF
Digital water marking system project report
Kamal Acharya
 
PDF
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
PDF
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
NTPC PATRATU Summer internship report.pdf
hemant03701
 
Seminar Description: YOLO v1 (You Only Look Once).pptx
abhijithpramod20002
 
Introduction to Internal Combustion Engines - Types, Working and Camparison.pptx
UtkarshPatil98
 
Unit_I Functional Units, Instruction Sets.pptx
logaprakash9
 
Footbinding.pptmnmkjkjkknmnnjkkkkkkkkkkkkkk
mamadoundiaye42742
 
Alan Turing - life and importance for all of us now
Pedro Concejero
 
Numerical-Solutions-of-Ordinary-Differential-Equations.pptx
SAMUKTHAARM
 
FINAL plumbing code for board exam passer
MattKristopherDiaz
 
Engineering Geology Field Report to Malekhu .docx
justprashant567
 
bs-en-12390-3 testing hardened concrete.pdf
ADVANCEDCONSTRUCTION
 
LLC CM NCP1399 SIMPLIS MODEL MANUAL.PDF
ssuser1be9ce
 
William Stallings - Foundations of Modern Networking_ SDN, NFV, QoE, IoT, and...
lavanya896395
 
Distribution reservoir and service storage pptx
dhanashree78
 
OCS353 DATA SCIENCE FUNDAMENTALS- Unit 1 Introduction to Data Science
A R SIVANESH M.E., (Ph.D)
 
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
UNIT 1 - INTRODUCTION TO AI and AI tools and basic concept
gokuld13012005
 
20ES1152 Programming for Problem Solving Lab Manual VRSEC.pdf
Ashutosh Satapathy
 
Digital water marking system project report
Kamal Acharya
 
Tesia Dobrydnia - An Avid Hiker And Backpacker
Tesia Dobrydnia
 
Submit Your Papers-International Journal on Cybernetics & Informatics ( IJCI)
IJCI JOURNAL
 
Ad

c-programming

  • 1. Introduction to C Programming Chapter 1.1
  • 2. What is a program? • A list of instructions. • Written in a programming language (c, c++, java). • Determines the behavior of a machine (computer, robot).
  • 3. Programming Language • A machine language that has its own set of grammatical rules. • It is used to instruct a machine to perform specific tasks.
  • 4. History • C was developed in 1972 by Dennis Ritchie at Bell Laboratories. • Based on a programming language called B (which is derived from BCPL language). • C was designed and developed for the development of UNIX operating system. • C has been widely used to develop many type of application software from a basic to operating system.
  • 8. Editing • Process of writing the C source code. • Using editor program (i.e. vi and emacs for Linux, Notepad for Windows) • Software package provides programming environment – Integrated editor – Managing and maintaining source code – i.e. C++ Builder, Code::Blocks, Dev-C++, Microsoft Visual Studio
  • 9. Pre-processing and Compiling • Pre-processing – performs directives such as inclusion of header files and substitution. • Compiling – process of translating the source code (programming language) to machine code (machine language).
  • 10. Linking • Process of combining generated object files. • Add required codes from C standard library. • Produce an executable file.
  • 11. Executing • Run the program to check whether it produce the desired output. • Testing stage where you check the output of your program. • The program does not produces the suppose output, then you have made logic (semantic) error.
  • 12. C Program Layout • C program consists of two sections: – Pre-processor directives – Main function pre-processor directives main() { statements } Pre-processor section Main function section
  • 13. Pre-processor Directives • Specify what compiler should do before compilation. • Include header files. • Header file keep information about the library functions (printf, scanf). • Pre-processor directives begins with the # symbol.
  • 14. Main Function • The program starts its execution. • Define the program definition.
  • 15. An Example of C Program Sample output: C program example
  • 16. An Example of C Program • A comment, not actually part of the program. • Provide information on what the program does. • Begin with /* and end with */ or written as //. • Good habit to include comments. • Keep inform what are the code actually doing.
  • 17. An Example of C Program • Important line in C • Symbol # indicates that this is a pre-processor directive • Include stdio.h header file in our program • stdio.h contains information on input/output routines. • We are using the printf() function from stdio.h
  • 18. An Example of C Program • Defines the start of the function main(). • Keyword int signifies main function returns an integer value. • The () is where we specify information to be transferred to function main().
  • 19. An Example of C Program • The portion that begins with { and ends with } is called block or body. • Within the block is where we write the statements.
  • 20. An Example of C Program • Function printf() instructs the computer to display characters or a string enclosed by the double quotes on the monitor screen. • A string is a combination of numerous characters.
  • 21. An Example of C Program • Function main() is defined to return a value of integer type. • return 0 is needed to indicate that the program has terminated successfully.
  • 25. Exercise Draw a flowchart to solve below problem: Prepare cupcakes. Ingredients are flour, yeast, and sugar. Make sure you taste the dough before baking process. Find solution to calculate the average marks for 100 of student. Then, display the average value.
  • 27. • Every variable has name, type and value. • Variable name / Identifier :  Must start with character or underscore ( _ ), cannot start with number or symbol and not a keyword .  Must not include any space and it is letter case sensitive.  Eg: stud1, Stud1, stud_name, _student (valid) @stud, stud name, 1stud (invalid) • Variable type :  Based on the data type – integer, floating point numbers and characters.  The value can be change any time.  Whenever a new value is placed into a variable, it replaces the previous value. Variables
  • 28. • Variable must be declare / initialize before it can be used in the next line of statements. • Variable declaration :  To declare a variable with a name and suitable data type.  Eg: int student; int staff; double x, y; • Variable initialization :  To declare a variable and assign a certain value to the varible.  Eg: int student=5; int staff=1; double x=1.12; double y=9.999; Variables
  • 29. • Integer:  Whole number (decimal).  Positive, negative or zero : 25, 0, -9.  Variable declaration: int x; • Floating point numbers:  double / float  Variable declaration: double y; float z; • Characters:  A character is a single letter, digit, symbol or space. Eg: ‘m’,‘B’,‘#’,‘3’,‘=’,‘@’,‘ ’.  A string is series of characters . Eg: “student” ,“F#”,“$35”, “class_93”,“ALI BABA”. Data Types
  • 30. • Special words reserved for C. • Cannot be used as variable names. • Eg: data types (int,void,const,static) instruction statements (if,for,case, break,return,include) Keywords
  • 31. • Constant name is declared just like variable name. • Constant value cannot be changed after its declaration. • 2 ways for constant declaration :  const double pi = 3.147; or  #define pi 3.147 Constants
  • 32. • To assign a value to a variable. • Is a binary operator (at least has two operands). • Variable that receiving the value is on the left. • Eg: int num;  num (in memory) num=3;  • num is assigned to value of 3. • Arithmetic operation  c = a + b • Multiple assignment  x = y = z = 7 • Compound assignment  +=,–=,*=,/=,%=  sum += 5 sum = sum+5 Assignment Operator 3
  • 33. • x % y produces remainder when x / y. • Eg: 5/3=1,5%3=2. Arithmetic Operators Operators Symbol Addition + Substraction - Multiplication * Division / Modulus %
  • 34. • Used to compare numerical values . Operator Symbol Less than < Less than or equal to <= Greater than > Greater than or equal to >= Equal to == Not equal to != Relational Operators Also known as Equality Operators
  • 35. Expression Value !1 0 !0 1 Expression Value 0 && 0 0 0 && 1 0 1 && 0 0 1 && 1 1 Expression Value 0 || 0 0 0 || 1 1 1 || 0 1 1 || 1 1 Operators Symbol NOT ! AND && OR || Logical Operators
  • 36. • Increment operator  ++  add 1 • Decrement operator  --; subtract 1 • These operators can be used as prefix (+ +a/--a) or postfix (a++/a--). • Prefix increase/decrease the operand before it is used. • Postfix  increase/decrease the operand after it is used. Increment and Decrement Operators
  • 37. • Example 1.2.1 int y,c,x; y=5,c=1,x=3; c++; x+=2; --y; y=c++; y=++x; Increment and Decrement Operators 5 1 3 5 2 5 4 2 5 2 2 5 6 3 6 5 y 1 c 3 x (in memory)
  • 38. Highest Precedence parenthesis, logical op. ( ) ! arithmetic op. * / % arithmetic op. + - relational op. < <= > >= equality op. == != logical op. && logical op. || Lowest Precedence Operator Precedence
  • 39. • Example 1.2.2 7 % 3 + 4 * 2 – (1 + 12) / 4 • Example 1.2.3 x > 5 || y < 7 && z != 2 let x=4 ,y =5,z=9. Operator Precedence
  • 40. • Example 1.2.2 7 % 3 + 4 * 2 – (1 + 12) / 4 = 7 % 3 + 4 * 2 – 13 / 4 = (7 % 3)+(4 * 2)–(13 / 4) = 1 + 8 – 3 = 6 Operator Precedence
  • 41. • Example 1.2.3 x > 5 || y < 7 && z != 2 let x=4 ,y =5,z=9. – x > 5 returns False (0) – y < 7 returns True (1) – z != 2 returns True (1) =(x > 5)||(y < 7)&&(z != 2) = 0 || 1 && 1 = 0 || (1 && 1) = 0 || 1 = 1 Operator Precedence
  • 43. Input Output Device • Input devices are used to perform the input operation. • Eg: keyboard, mouse, microphone, scanner. • Output devices are used to perform the output operation. • Eg: monitor, printer, speaker.
  • 44. Input Output Operation • Input operation in basic C programming is to get input data from the keyboard using scanf statement. • While output operation is to display the data at the monitor screen using printf statement.
  • 45. scanf Input Output Operation printf get input data from the keyboard display the data at the monitor
  • 46. 46 Formatting Output with printf • printf – Precise output formatting • Conversion specifications: flags, field widths, precisions, etc. – Can perform rounding, aligning columns, right/left justification, inserting literal characters, exponential format, hexadecimal format, and fixed width and precision • Format – printf( format-control-string, other-arguments ); – Format control string: describes output format – Other-arguments: correspond to each conversion specification in format-control-string • Each specification begins with a percent sign(%), ends with conversion specifier
  • 47. 47 Printing Integers • Integer – Whole number (no decimal point): 25, 0, -9 – Positive, negative, or zero – Only minus sign prints by default
  • 48. Conversion Specifier Description d Display a signed decimal integer. i Display a signed decimal integer. (Note: The i and d specifiers are different when used with scanf.) o Display an unsigned octal integer. u Display an unsigned decimal integer. x or X Display an unsigned hexadecimal integer. X causes the digits 0-9 and the letters A-F to be displayed and x causes the digits 0-9 and a-f to be displayed. h or l (letter l) Place before any integer conversion specifier to indicate that a short or long integer is displayed respectively. Letters h and l are more precisely called length modifiers.
  • 49. 49 Printing Floating-Point Numbers • Floating Point Numbers – Have a decimal point (33.5) – f – print floating point with at least one digit to left of decimal
  • 50. Printing Strings and Characters • c – Prints char argument – Cannot be used to print the first character of a string • s – Requires a pointer to char as an argument – Prints characters until NULL ('0') encountered – Cannot print a char argument • Remember – Single quotes for character constants ('z') – Double quotes for strings "z" (which actually contains two characters, 'z' and '0')
  • 51. 51 Printing with Field Widths and Precisions • Field width – Size of field in which data is printed – If width larger than data, default right justified • If field width too small, increases to fit data • Minus sign uses one character position in field – Integer width inserted between % and conversion specifier – %4d – field width of 4
  • 52. 52 • Precision – Meaning varies depending on data type – Integers (default 1) • Minimum number of digits to print – If data too small, prefixed with zeros – Floating point • Number of digits to appear after decimal (e and f) – For g – maximum number of significant digits – Strings • Maximum number of characters to be written from string – Format • Use a dot (.) then precision number after % %.3f
  • 53. 53 • Field width and precision – Can both be specified • %width.precision %5.3f – Negative field width – left justified – Positive field width – right justified – Precision must be positive – Can use integer expressions to determine field width and precision values
  • 54. 54 Printing Literals and Escape Sequences • Printing Literals – Most characters can be printed – Certain "problem" characters, such as the quotation mark " – Must be represented by escape sequences • Represented by a backslash followed by an escape character
  • 55. 55 • Table of all escape sequences Escape sequence Description ' Output the single quote (') character. " Output the double quote (") character. ? Output the question mark (?) character. Output the backslash () character. a Cause an audible (bell) or visual alert. b Move the cursor back one position on the current line. f Move the cursor to the start of the next logical page. n Move the cursor to the beginning of the next line. r Move the cursor to the beginning of the current line. t Move the cursor to the next horizontal tab position. v Move the cursor to the next vertical tab position.
  • 56. scanf Statement • Input operation in basic C programming is to get input data from the keyboard using scanf statement. • While output operation is to display the data at the monitor screen using printf statement.
  • 57. 57 Formatting Input with Scanf • scanf – Input formatting – Capabilities • Input all types of data • Input specific characters • Skip specific characters • Format – scanf(format-control-string, other-arguments); – Format-control-string • Describes formats of inputs – Other-arguments • Pointers to variables where input will be stored – Can include field widths to read a specific number of characters from the stream
  • 58. 58 Formatting Input with Scanf Conversion specifier Description Integers d Read an optionally signed decimal integer. The corresponding argument is a pointer to integer. o Read an octal integer. The corresponding argument is a pointer to unsigned integer. x or X Read a hexadecimal integer. The corresponding argument is a pointer to unsigned integer. Floating-point numbers f Read a floating-point value. The corresponding argument is a pointer to a floating-point variable. Characters and strings c Read a character. The corresponding argument is a pointer to char, no null ('0') is added. s Read a string. The corresponding argument is a pointer to an array of type char that is large enough to hold the string and a terminating null ('0') character—which is automatically added.
  • 59. Exercise What data types would you use to hold the following data? Customer name Your house number A price Car registrations The time A six digit number Write C statements to declare them all.
  • 61. Introduction • Ability to change the flow of program execution. • Allows the program to decide an action based upon user's input or other processes.
  • 62. if Selection Statement • Primary tool of selection structure. • The condition is TRUE – execute the statement. • The condition is FALSE – skip the statement.
  • 63. if Selection Statement if ( condition ) Execute this statement if condition is TRUE i.e. if (5 < 10) printf("Five is less than ten"); • Evaluate the statement, "is five less than ten"
  • 64. Example Sample output: Enter a number between -10 and 10: 6 6 is a positive number
  • 65. if else Selection Statement • Execute certain statement if the condition is false • The condition is TRUE – execute the statement A • The condition is FALSE – execute the statement B
  • 66. if else Selection Statement if ( condition ) Statement A; else Statement B; i.e. if ( 5 < 10 ) printf("Five is less than ten"); else printf("Five is greater than ten");
  • 67. Example Sample output: Enter a number between -10 and 10: -2 -2 is a negative number
  • 68. if else if Selection Statement • Test additional conditions • Works the same way as normal if statement
  • 69. Example Sample output: Please enter your age: 58 You are old
  • 70. More than one statement • Multiple statements within selection structure • Use braces { } • Block of code if ( condition ) { Statement 1 Statement 2 … Statement N }
  • 71. Nested if Selection Structure • if within an if is called nested if if ( condition 1 ) Statement A; if ( condition 2 ) Statement C; else Statement D; else Statement B;
  • 72. Example Sample output: Enter a number between -10 and 10: 6 6 is a positive number 6 is an even number
  • 73. switch Selection Statement • Substitutes for long if statements • Select from multiple options • Consists of a series of case label sand optional default case • Compares the value of variable or expression with values specified in each case
  • 74. switch Selection Statement switch (variable ){ case value 1: Statement A; break; case value 2: Statement B; break; ... default: Statement N; break; }
  • 76. Exercise Write a program that asks the user to enter two integers, obtains the numbers from the user, then prints the larger number followed by the words “is larger.” If the numbers are equal, print the message “These numbers are equal.” Use only the single-selection form of the if statement you learned in this chapter. Draw a flowchart for this task:- Obtains two integer numbers from the keyboard, and display which is larger of the two numbers.
  • 77. Exercise Write a program that asks the user to enter two integers, obtains the numbers from the user, then prints the larger number followed by the words “is larger.” If the numbers are equal, print the message “These numbers are equal.” Use only the single-selection form of the if statement you learned in this chapter. Draw a flowchart for this task:- Obtains two integer numbers from the keyboard, and display which is larger of the two numbers.
  • 78. Exercise Using ‘switch’ and ‘case statement’, write a program determine whether the number we key in is odd or even and that print out adjacent “*” sign same as that number. (Example: For number 6, we will print out ****** ).
  • 80. Introduction • What if we want to display numbers from 1 to 100? • What if we want to repeat a thousand times of 10 statements? • It is possible to do it, but it is not a convenience and it would take a long time to complete • Ability to specify repetition of compound statements is as important in programming – Loop
  • 81. Introduction • Two types of loop: – Finite loop – Infinite loop • Finite (counter-controlled) loop is a repetition in which it will continue looping until certain condition is met • Infinite loop has no certain condition in which it will continue looping forever
  • 82. Introduction • Three requirements of defining a definite loop 1.counter initialization 2.increment of counter 3.loop condition • while, do while and for loop
  • 83. while Repetition Structure • Allows the repetition of a set of statements execution to continue for as long as a specified condition is TRUE • When the condition becomes false, the repetition terminates
  • 84. while Repetition Structure while ( condition ) { statements; } while ( a < b ) { printf("a is less than bn"); }
  • 85. Example • Test the condition • Execute statements within while loop’s block • Jump back to the top and re- test the condition
  • 87. do while Repetition Structure • Condition is tested at the end of the block instead of at the beginning • Block will be executed at least once
  • 88. do while Repetition Structure do { statements; } while ( condition ); do { printf("a is less than bn"); } while ( a < b );
  • 89. Example • Execute statements within do while loop’s block • Test the condition • Jump back to the top and re- execute statements
  • 91. for Repetition Structure • for loop combines the loop control parameters into single statement • Loop control parameters – variable initialization, variable update and loop condition
  • 92. for Repetition Structure for ( a; b; c ) { statements; } • a (variable initialisation) is evaluated once only - before entering the loop • b (condition) determines whether or not the program loops • c (variable update) is evaluated after an iteration of the loop – loop counter
  • 93. Example • Initializes count equals to zero • Test the condition • Execute statements within for loop’s block • Jump back to the top and re-test the condition
  • 95. Nested Loop • A loop within a loop Loop1 Loop2 statement return return
  • 97. Infinite Loop • Loops forever • Contains no condition • Condition that can never be satisfied
  • 99. break and continue Statements • Can be executed in while, do while and for statement • Used to alter the flow of control
  • 100. Example • Causes an immediate exit from that statement
  • 101. • Skip the remaining statements • Performs the next iteration of the loop Example
  • 102. Exercise Use a loop to produce the following output: a) 12345678910 b) 3, 8, 13, 18, 23 c) 20, 14, 8, 2, -4, -10 Write a program that will display all odd numbers between 1 to 40.
  • 104. Introduction • Mini-program where a group of statements are executed. • Programmer-defined functions. • Break a large program into smaller sets of statements according to their tasks.
  • 105. Benefits of Function • To make program more manageable – divide-and-conquer approach (construct a program from smaller components/modules. • Software reusability – reuse existing functions for new programs • Avoid repeating code
  • 108. 3 Elements of Function • Function definition • Function prototype / declaration • Calling function
  • 109. Function Definition • Specifies the specification of a function – return value type, function name, arguments. • Defines the operation to be performed when a function is invoked.
  • 111. Function Definition return_value_type function_name(parameter_list) { statements; }  Specifies the type of the value returned by the function  Data types of return value : int (default),char, float, double  If function does not has any return value : void o List of variable names received by the function from the caller – arguments (data input) o parameter_list : (parameter_type parameter name) o parameter_type: int ,char, float, double o If function does not has any parameter_list : (void) or ()
  • 112. Function Prototype • To declare function if the function definition is written below the main function. • Otherwise, no need function prototype. (function definition above the main function) • Almost similar with function definition header, but must be written before the main function with semicolon at the end of statement.
  • 113. Function Prototype return_value_type function_name(parameter_list);  Specifies the type of the value returned by the function  Data types of return value : int (default),char, float, double  If function does not has any return value : void o List of variable names received by the function from the caller – arguments (data input) o parameter_list : (parameter_type ) o parameter_type: int ,char, float, double o If function does not has any parameter_list : (void) or ()
  • 114. Calling Function • Two ways to invoke/call function – Call-by-value – Call-by-reference. • Calling function statement is written in the caller function (main function).
  • 115. Call-by-value VS Call-by-reference Call-by-value • Copies of the arguments’ value are made and passed to the called function • Changes to the copy do not effect an original variable’s value • Available in C language Call-by-reference • References of the arguments’ value are passed to the called function • Called function can modify the original variable’s value • Possible to simulate
  • 116. Example 1 #include<stdio.h> void function_name(void); int main() { statements; function_name(); return 0; } void function_name(void) { statements; } Function prototype Function definition Calling function
  • 117. Example 2 #include<stdio.h> double function_name(int,double); int main() { int p1, double p2; statements; function_name(p1,p2); return 0; } double function_name(int pm1,double pm2) { statements; } Function prototype Function definition Calling function
  • 118. Example 3 Sample output: Call-by-value ---------------------- Before func1 is called n1 = 5 In func1 n1 = 10 After func1 is called n1 = 5
  • 119. Example 4 Sample output: Enter base and power: 5 4 The result is 625. function prototype function definition function call
  • 120. Scope Variable • Variables declared in function main() are known only within function main() – not accessible outside of the block • It is applied to variables defined within a block that is inside other block • But variables defined in the outer block are accessible in the inner block
  • 121. Scope Variable • Variable a is declared in main() • Variable b is declared within while loop block (inner block) • a is the outer block variable therefore it is accessible within inner block • b is not accessible in the outer block because it is while loop variable
  • 122. Scope Variable num2 is not accessible in func() num2 is considered undeclared in func() num2 is accessible in main() only num2 is declared in main()
  • 123. Global Variable • Variables declared outside any function is called global variables • Global variables are variables that can be accessed in any function • Normally they are declared before function main()
  • 124. Global Variable num2 is a global variable num2 is accessible in func()
  • 125. Recursive Function • Function that calls itself either directly or indirectly through another function
  • 126. Example 5 Sample output: 0! = 1 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120
  • 127. Exercise • Write a program that utilizes a function with parameters. The program reads 3 integer numbers from the user and sends the 3 input to the function. The function finds the smallest value between the 3 integer numbers and return the value to the main function. Enter three inter numbers: 30 80 20 Smallest value: 20
  • 128. Exercise • Consider the following program, what is the value of num1 and num2 after each statement is executed? num1 num2 2 1 1 3 1 7 1 21
  • 129. num1 num2 1 void funcA(int); 2 int funcB(int); 3 int num2 = 2; 4 5 int main(void) 6 { 7 int num1 = 1; 8 9 num2 = funcB(num1); 10 funcA(num1); 11 funcA(num2); 12 13 return 0; 14 } 15 void funcA(int num1) 16 { 17 num1 = num1 + num2; 18 num2 = num1 + num2; 19 } 20 int funcB(int num1) 21 { 22 num1 = num1 + num2; 23 return num1; 24 }
  • 131. Introduction • A group of memory locations that have the same name and the same type. • Allows to store a sequence of values.
  • 132. Introduction cont.• First element in an array is the zeroth element, a[0] • In the example to the right:_ Second element is a[1]= 6. Element two is a[2]=11. Different way of statement resulting in different meaning! • If b=2 and c=4, then a[b+c] =a[b+c]+2; a[2+4] =a[2+4]+2; a[6] = a[6]+2; a[6] = 10;
  • 133. Defining and Initializing of One Dimentional Array • int a[5]; • int a[5] = {0}; //all elements equal zero • int a[5] = {10, 20, 30, 40, 50}; • int a[5] = {10, 20, 30, 40, 50, 60}; //error • float a[5] = {1.1, 2.2, 3.3, 4.4, 5.5}; • char a[6] = {'h', 'e', 'l', 'l', 'o'}; Note: a[5] carries the value ‘/0’, more on this later.
  • 135. Input/Output • Declare an integer array named a with 10 elements int a[10]; • Input an integer into 6th element scanf("%d ", &a[5]); • Output the content of 6th element printf("a[5] is %d.n ", a[5]);
  • 136. Character Arrays • Store characters • Character arrays are capable of storing strings • Revise: %c for characters ( eg. A, b, c, D ) %s for strings ( eg. hi, welcome, good )
  • 137. Character Arrays • char string[]="hello"; • Initializes the elements of array string to the individual characters in the string “hello” • string "hello" has 5 characters plus a special string termination character called null character '0'
  • 138. Character Arrays char x[]={'h', 'e', 'l', 'l', 'o', '0'}; • x[0] = 'h' • x[1] = 'e' • x[2] = 'l' • x[3] = 'l' • x[4] = 'e‘ • x[5] = '0'
  • 139. Input/Output • Declare a char array named string1 with 20 elements char string1[20]; • Input a string into the array scanf("%s", string1); • Output the array’s content printf("The content is %s.n", string1); • Function scanf will read characters until a space, tab, newline or EOF is encountered
  • 141. Passing Arrays to Functions • Modify the elements in function body is modifying the actual elements of the array
  • 142. Cont. int array[30]; //array declaration void func(int array[]) { … //function prototype } func(array) //call function the passed array
  • 143. Passing Elements to Functions • Passing an individual array elements are like passing a variable • The actual value is not modified
  • 144. Cont. int array[30]; void func(int e) { … } func(array[5]) the passed element variable e copies the value of array element
  • 146. Two Dimensional Array • To represent table of values consisting of information arranged in rows and columns
  • 147. Defining and Initializing • int a[2][3]; • int a[2][3] = {{1, 2, 3}, {2, 3, 4}}; 1st Row 2nd Row
  • 148. • Eg. int b[3][4];
  • 150. Exercise • Write a program to print the values of each element of a 3-by-2 array using nested loop.. Initialize the array as: {12.0,14.2},{13.0,16.5},{10.5,11.0}
  • 152. Introduction • Pointers are variables whose values are memory addresses • A pointer contains an address of a variable that contains a specific value
  • 153. Introduction cont. • Count directly references a variable that contains the value 5 • Pointer indirectly references a variable that contains the value 5 (indirection) 5 count 5 countPointer
  • 154. Declaring and Initializing • A pointer of type int is a pointer to a variable type int • int y = 5; • int *yPtr; • yPtr = &y; • & returns the address of its operand 5 yyPtr 5 Location 60000 60000 Location 50000
  • 155. Using Pointers • * (indirection) operator returns the value of the object a pointer refers to • Assume y = 5 • yPtr = &y; • z = *yPtr + 5; • *yPtr = 7; • z = *yPtr + 5; • yPtr = &z;
  • 158. Call-by-reference • The original variable address is passed to the function by using & operator. • Ability to access the variables directly and to modify them if required.
  • 159. Example num1 = 3 - before Value returned: 9 num1 = 3 - after num2 = 5 - before num2 = 25 - after & (address) operator is specified a pointer numRef = numRef * numRef
  • 160. Pointers and Arrays • Any operation that can be achieved by array subscripting can also be done with pointers
  • 161. Cont. • bPtr = &b[0]; • bPtr+1 points to next element • bPtr+i points i elements after bPtr • bPtr-i points i elements before bPtr • bPtr+i is the address of b[i] • *(bPtr+i) is the content of b[i] b 0 1 2 3 4 bPtr bPtr+1
  • 162. Arrays of Pointers • Since pointers are variables • Can be stored in arrays • Array of memory addresses
  • 164. Pointers to Functions • A pointer to a function contains the address of the function • Similarly, a function called through a pointer must also passes the number and type of the arguments and the type of return value that is expected
  • 166. Exercise • Consider the following statements, what is the value of px and py after each statement is executed? px py 0 x 00FC24BB 0 x 00AACCDD 0 x 00EE58FA 0 x 00EE58FA
  • 167. Given: address x = 0 x 00FC24BB address y = 0 x 00AACCDD address z = 0 x 00EE58FA px py 1 int x, y, z; 2 int *px, *py, *pz; 3 4 x = 5; 5 y = 10; 6 px = &x; 7 py = &y; 8 z = 15; 9 py = &z; 10 px = py
  • 169. Opening a File • FILE pointer which will let the program keep track of the file being accessed • FILE *fp; • Function fopen use to open a file • fp = fopen("filename", "mode");
  • 170. Filename • Use double backslashes rather than a single backslash (in the case of string literal) – "c:test.txt" – t is considered as escape sequence – "c:test.txt" – correct way to specify backslash
  • 171. Modes • r - open for reading • w - open for writing • a - open for appending
  • 172. Example • FILE *p1, *p2; • p1 = fopen("data", "r"); • p2 = fopen("results", "w");
  • 173. Closing a File • A file must be closed as soon as all operations on it have been completed • fclose(p1); • fclose(p2);
  • 174. Get a character from file • fgetc (file); • Returns the character currently pointed by the internal file position indicator of the specified file
  • 175. Example • FILE *fptr; • fptr = fopen("logfile.txt", "r"); • char inpF; • inpF = fgetc(fptr);
  • 176. Get string from File • fgets(char *str, int num, file); • Reads characters from file until – (num-1) characters have been read or – a newline or – End-of-File is reached – whichever comes first. • A null character is automatically appended in str after the characters read to signal the end of the C string.
  • 177. Example • FILE *fptr; • fptr = fopen("logfile.txt", "r"); • char inpF[20] = " "; • fgets(inpF, 20, fptr);
  • 178. Write character to file – fputc(int character, file); – Writes a character to the file and advances the position indicator
  • 179. Example • FILE *fptr = NULL; • fptr = fopen("logfile.txt", "a"); • char outF = 'A'; • fputc(outF, fptr);
  • 180. Write string to file • fputs(const char * str, FILE * stream); • Writes the string pointed by str to the file
  • 181. Example • FILE *fptr = NULL; • fptr = fopen("logfile.txt", "a"); • char outF[20] = "Hello Worldn"; • fputs(outF, fptr);
  • 182. Read formatted data from file • fscanf(file, fmt-control-string, var); • Reads data from the file and stores them according to the parameter format into variables
  • 183. Example • FILE *fptr = NULL; • fptr = fopen("logfile.txt", "r"); • char inpF[20] = " "; • fscanf(fptr, "%s", inpF);
  • 184. Write formatted output to file • fprintf(file, fmt-control-string, var); • Writes to the specified file a sequence of data formatted as the format argument specifies
  • 185. Example • FILE *fptr = NULL; • fptr = fopen("logfile.txt", "a"); • int n = 1; • char name[20] = "Muhammad"; • fprintf (fptr, "Name %d - %sn", n, name);