0% found this document useful (0 votes)
39 views78 pages

02 - Introduction To C Programming

The document discusses C programming basics including data types, input/output statements, operators, and common errors. It provides examples of writing simple C programs to print "Hello World" and explains key aspects like including header files, the main function, printf statements, comments, and returning values. Code snippets and explanations are given for declaring integer, floating point, and other variable types in C.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
39 views78 pages

02 - Introduction To C Programming

The document discusses C programming basics including data types, input/output statements, operators, and common errors. It provides examples of writing simple C programs to print "Hello World" and explains key aspects like including header files, the main function, printf statements, comments, and returning values. Code snippets and explanations are given for declaring integer, floating point, and other variable types in C.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 78

Dr.

Nur Hafizah Ghazali


adilahhanin@unimap.edu.my
1. C Program structures & data types
2. Input & output statements
3. Basic Operator
4. Logic & comparison
5. Programming Errors

2
Example 1
• Write an algorithm that display a message to the screen as
“Hello World!”.

Pseudo Code Flow Chart


Begin
• Begin
• Print Message Print “Hello World!”
• End

End

3
Example 1
• Write a C program that display a message to the screen as
“Hello World!”.
Simple C Program

Flow Chart #include<stdio.h>

Begin int main(void)


{

printf(“Welcome to C!");
Print “Welcome to C!”
return 0;

End

4
1 /* Figure 1 prog01.c
2 First program in C */
3 #include<stdio.h>
4
5 /* function main begin program execution */
6 int main(void)
7 {
8 printf(“Welcome to C!\n”);
9 return 0;
10 /* indicate that the program ends successfully */
11 } /* end function main */
12

5
1 /* Figure 1 prog01.c
2 First program in C */
3 #include<stdio.h>
4
5 /* function main begin program execution */
6 int main(void)
7 {
8 printf(“Welcome to C!\n”);
9 return 0;
10 /* indicate that the program ends successfully */
11
12 } /* end function main */

6
• Starts with /* and terminates with */
OR
• Character // starts a line comment, if several lines,
each line must begin with //
Example : // comment1
// comment2
• Ignored by compiler
• Help other people read and understand the program
• Comments cannot be nested /* /* */*/
– /* some comment /* trying to nest other comment */ inside */
– WRONG!! 7
1 /* Figure 1 prog01.c
2 First program in C */
3 #include<stdio.h>
4
5 /* function main begin program execution */
6 int main(void)
7 {
8 printf(“Welcome to C!\n”);
9 return 0;
10 /* indicate that the program ends successfully */
11
12 } /* end function main */

8
• An instruction to pre-processor
• Standard library header: <stdio.h> , <math.h>
• E.g.

#include <stdio.h> /* for standard input/output */


#include <stdlib.h> /* Conversion number-text vise-
versa, memory allocation, random numbers */
#include <string.h> /* string processing */

9
1 /* Figure 1 prog01.c
2 First program in C */
3 #include<stdio.h>
4
5 /* function main begin program execution */
6 int main(void)
7 {
8 printf(“Welcome to C!\n”);
9 return 0;
10 /* indicate that the program ends successfully */
11
12 } /* end function main */

10
C programs contain one or more functions, exactly one of
which must be main
Braces ( { and } ) indicate a block
The bodies of all functions must be contained in braces
At a minimum, the main() function looks like this:
main()
{

}
11
1 /* Figure 1 prog01.c
2 First program in C */
3 #include<stdio.h>
4
5 /* function main begin program execution */
6 int main(void)
7 {
8 printf(“Welcome to C!\n”);
9 return 0;
10 /* indicate that the program ends successfully */
11
12 } /* end function main */

12
• printf()
– Instructs computer to print the
string of characters within
quotes (“ ”)
• Entire line called a statement
– All statements must end with a
semicolon (;)
• \n is an escape sequence
 moves the cursor to the new
line

13
1 /* Figure 1 prog01.c
2 First program in C */
3 #include<stdio.h>
4
5 /* function main begin program execution */
6 int main(void)
7 {
8 printf(“Welcome to C!\n”);
9 return 0;
10 /* indicate that the program ends successfully */
11
12 } /* end function main */

14
– A way to exit a function
– return 0, in this case, means that the program
terminated normally

15
/*First program in C*/
#include<stdio.h>

/*Program execution begins with main function*/


int main(void)
{

/*Display Welcome to C*/ printf starts printing from


printf("Welcome "); where the statement ended, so
printf("to C!\n"); the text is printed on one line

/* Indicates program ended succesfully */


return 0;
Note:
}/* end function main */ printf(“Welcome
to C!\n");

 this is WRONG:
16
/*First program in C*/
#include<stdio.h>

/*Program execution begins with main function*/


int main(void)
{ newline character moves the cursor to the
next line
/*Display Welcome to C*/
printf("Welcome\nto\nC!\n");

/* Indicates program ended succesfully */


return 0;
Note: In general, it’s better programming
}/* end function main */ practice to put newlines only at the end, not
in the middle, because in the middle they can
be difficult for programmers to see.
printf( “ Welcome \n ”);
printf(“ to \n ”);
printf(“ C! \n ”); 17
• Using open source IDE
platform (Code Block)
to write C program
• Using open source IDE
platform (Code Block)
to write C program
• Run and execute the
program by clicking
“Build and Run”
button
my_program.c 1. Write text of program (source code) using an
1 #include <stdio.h> editor such as gedit, save as file e.g.
2 /* The simplest C Program */ my_program.c
3 int main()
4{ 2. Run the compiler to convert program from source
5 printf(“Hello World\n”) to an “executable” or “binary”:
6 return 0; $ gcc –o my_program my_program.c
7} $ ./my_program
$ gcc -o my_program
$ gcc my_program.c
my_program.c
$ ./a.out
$ gcc my_program.c
my_program.c: In function `main':
my_program.c :5: parse error before
3. Compiler gives errors and warnings; edit source
`return' file, fix it, and re-compile

./my_program
4. Run it and see if it works 
$ ./my_program
Hello World!
Hello World
20
$▌
21
• C has a concept of 'data types' which are used to define a variable
before its use
• Data types determine the following:
• Type of data stored
• Number of bytes it occupies in memory
• Range of data
• Operations that can be performed on the data
• C has the following basic built-in data types
• int
• float
• double
• char

22
• Modifiers alter the meaning of the base type to
more precisely fit a specific need
• C supports the following modifiers along with data
types:
• short
• long
• signed
• unsigned

23
• int is used to define integer numbers (whole
numbers, both positive and negative)
• An example of an integer value is 5, 6, 100,
2500.
• An example of declaring an integer variable
called age is
int age;

24
• long int - allowing an integer to be stored in more
memory locations thereby increasing its effective range so
that very large integers can be stored

• short int - may or may not have a smaller range


than normal int variables, however will not take up more
bytes than int

• unsigned (positive values only) - negative integers


cannot be assigned to unsigned integers, only a range of
positive values

25
• float is used to define floating point
numbers, both positive and negative
• Typical floating point values are 1.73 and
1.932e5 (1.932 x 105).
• An example of declaring a float variable called
x is
float x;

26
• double is used to define BIG floating point
numbers, both positive and negative, which
have a higher precision than float variables.

• An example of declaring a double variable


called voltage :
double voltage;

27
• The three C floating point types are:
• float
• double
• long double

• In general, the accuracy of the stored real values


increases as you move down the list

28
• char defines characters
• Example of characters:
– Numeric digits: 0 - 9
– Lowercase/uppercase letters: a - z and A - Z
– Space (blank)
– Special characters: , . ; ? “ / ( ) [ ] { } * & % ^ < > etc
• An example of declaring a character variable called
letter: The declared character must be
char letter = ‘U’; enclosed within a single quote!

29
l Processor works with finite-sized data
l All data implemented as a sequence of bits
l Bit = 0 or 1
l Byte = 8 bits
Type Bytes Range Precision
char 1 0 -> +255 -
int 4 -2,147,483,648 -> -
+2,147,483,647
short int 2 -32,768 -> +32,767 -
long int 4 -2,147,483,648 -> -
+2,147,483,647
float 4 1.2E-38 to 3.4E+38 6 decimal
double 8 2.3E-308 to 1.7E+308 15 decimal
long double 10 3.4E-4932 to 1.1E+4932 19 decimal
30
31
32
• Variables: locations in memory where a value can
be stored
• A quantity that can change during program
execution
• Hold the data in your program
• All variables in C must be declared before use
• If an executable statement references and
undeclared variable it will produce a syntax
(compiler) error

33
• Identifiers: Variable names
• Valid : dA, dB, dSum, Root, _getchar, __sin, x1, x2,
x_1
• Invalid: 324, short, price$, My Name
• case sensitive (a1 and A1 is different!)
• can consist of capital letters[A..Z], small letters[a..z],
digit[0..9], and underscore character (_) that does not
begin with a digit
• First character MUST be a letter or an underscore
• No blanks
• Reserved words cannot be identifiers
34
• Reserved words / Keywords are reserved identifiers that
have strict meaning to the C compiler.

35
Variable names(identifiers) according to Hungarian notation
• Begin variable names with lowercase letters
• Start with an appropriate prefix that indicates the data
type
• After the prefix, the name of variable should have one or
more words
• The first letter of each word should be in upper case
• The rest of the letter should be in lower case
• The name of variable should clearly convey the purpose of
the variable

36
Prefix Data Type Example
i int and unsigned int iTotalScore
f float fAverageScore
d double dHeight
l long and unsigned long lFactorial
c signed char and unsigned char cProductCode
ai Array of integer aiStudentId
af Array of float afWeight
ad Array of double adAmount
al Array of long integer alSample
ac Array of characters acMaterial
37
• float fIncome; float fIncome, fNet_income;
float fNet_income;
• double dBase, dHeight, dArea;
• int iIndex =0, iCount =0;
• char cCh=‘a’, cCh2;
• const float fEpf = 0.1, fTax = 0.05;

Declare and initialize

Named constant declared and initialized

38
 Variables may be given initial values, or initialized, when
declared. Examples:

length
int length = 7 ; 7

diameter
float diameter = 5.9 ; 5.9

initial
char initial = ‘A’ ; ‘A’

39
• A constant is a named or unnamed value, which does not
change during the program execution
• The C language supports two types of constants
– declared constants
• const double dPi=3.141592
• const int iDegrees=360;
• const char cQuit=‘q’;

– defined constants : You may also associate


constant using #define preprocessor directive
• #define N 3000
• #define FALSE 0
• #define PI 3.14159
40
41
• Example of printf() statement
printf(“Sum is %d\n",dSum);
Output:
Sum is 66
• When the printf is executed, it starts printing the until it
encounters a % character (conversion specifier)
– The %d means decimal integer will be printed
– dSum specifies what integer will be printed
• Calculations can be performed inside printf statements
printf( "Sum is %d\n", integer1 + integer2 );

42
• scanf is a function in C which allows the programmer to
accept input from user usually from a keyboard.
scanf(“%d” , &dA );
• This scanf statement has two arguments
%d - indicates data should be a decimal integer
&dA - location in memory to store variable
& - have to be included with the variable name in scanf
statements
When executing the program the user responds to the scanf
statement by inserting a number, then pressing the enter (return)
key

43
• Common Conversion Identifier used in printf and
scanf functions.

printf scanf
int %d %d
float %f %f
double %f %lf
char %c %c
string %s %s

44
#include<stdio.h> Output for the source code:
int main()
{
int a=7; 7
printf("%d\n”,a); 7
printf("%3d\n”,a); 007
printf("%03d\n”,a);
return 0;
}

45
#include<stdio.h> Output for the source code:
int main()
{ 7
int a=7; 7
printf("%d\n”,a); 0 0 7
printf("%3d\n”,a);
printf("%03d\n”,a);
%d : Print as decimal integer
return 0;
%3d : Print three digits (positions)
}
%03d : Print the output with a width of
three digits, but fill the space with 0

46
#include<stdio.h> Output for the source code:
int main()
15.350000
{
float a=15.35; 15.3500
printf("%f\n”,a); 15.35
printf("%.4f\n”,a);
printf("%4.2f\n”,a);
%f print as a floating point
return 0;
%.4f print as a floating point with a
} precision of four characters after
the decimal point
%4.2f print as a floating point at least 4
wide and a precision of 2

47
48
Types of operators are:
– Arithmetic operators : unary and binary
(+ , - , * , / , %)‫‏‬
– Relational operators
(> , < , == , >= , <=, !=)‫‏‬
– Logical operators
(AND - && , OR - ||)‫‏‬
– Compound assignment operators
(+=, -=, *=, /=, %=)‫‏‬

49
• Used to execute mathematical equations
• The result is usually assigned to a data storage
(variable) using assignment operator ( = )‫‏‬
• E.g. sum = marks1 + marks2;

50
• 2 types of arithmetic operators in C:
– Unary operators are operators that require only
one operand.
• Example:
second = + first;

– Binary operators are operators that require two


operands.
• Example:
third = first + second;

51
• Prefix/Postfix Increment
– a++ : return the current value of a and then increment
the value of a. (a = a + 1)
– ++a : increment the value of a before returning the
value a.
Example: Example:
int a=9; int a=9;
printf(“%d\n”, a++); printf(“%d\n”, ++a);
printf(“%d”, a); printf(“%d”, a);
Output: Output:
9 10
10 10
52
a b
Before: int a=2, b; 2 ?

b = ++a; b = a++;
increments a by 1 and assign value of variable a
assign value of variable a to variable b and
to variable b. increments a by 1.

a b a b
After: 3 3 3 2

53
int i, j=10;

++ Or --
Equivalent Statements i value j value
Statement
i = j;
i = j++; 10 11
j = j + 1;
j = j + 1;
i = ++j; 11 11
i = j ;
i = j ;
i = j--; 10 9
j = j – 1;
j = j – 1;
i = --j; 9 9
i = j ;

54
• Operator precedence
– Some arithmetic operators act before others (i.e.,
multiplication before addition)
• Use parenthesis when needed
– Example: Find the average of three variables a, b and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3

55
56
Pseudo Code Flow Chart
Begin
• Begin
• Input A and B Input A,B
• Calculate A + B
• Print result of SUM Calculate A + B
• End
Print SUM

End

57
1 #include<stdio.h>
2
Data Types Flow Chart
3 int main(void)
4 {
5 int dA,dB,dSum; Variables
6 Begin
7 printf(“Input first integer \n”);
8 scanf(“ %d”, &dA); Read
Input A,B
9 input
10 printf(“Input second integer \n”);
11 scanf(“ %d”, &dB);
12 Addition operation
13 dSum= dA + dB; Calculate A + B
14
Display Output
15 printf(“Sum is %d \n”, dSum); Print SUM
16
17 return 0;
End 58
18 }
1 #include<stdio.h>
2
3 int main(void)
4 {
5 int dA,dB,dSum;
6
7 printf(“Input first integer \n”);
Output:
8 scanf(“ %d”, &dA);
9 Input first integer
10 printf(“Input second integer \n”); 39
11 scanf(“ %d”, &dB);
Input second integer
12
13 dSum= dA + dB; 27
14 Sum is 66
15 printf(“Sum is %d \n”, dSum);
16
17 return 0;
59
18 }
1 #include<stdio.h>
2
3 int main(void)
4 {
5 float fA,fB,fAverage;
6
7 printf(“Input first number \n”);
8 scanf(“ %f”, &fA);
9
10 printf(“Input second number \n”);
11 scanf(“ %f”, &fB);
12
13 dAverage= (fA + fB)/2;
14
15 printf(“Average is %f \n”, fAverage);
16
17 return 0;
60
18 }
61
• To perform decisions
– Example : Printing "pass" or "fail" given
the value of a test grade
• Relational operator:
>, < >=, <=, == , !=
• Used to control the flow of a program

62
Standard algebraic C relational Example of C Meaning of C condition
relational operator operator condition
= == x == y x is equal to y
≠ != x != y x is not equal to y
> > x>y x is greater than y
< < x<y x is less than y
x is greater than or equal
>= >= x >= y
to y
<= <= x <= y x is less than or equal to y

63
Relational operators use mathematical comparison (operation)
on two data, but give logical output

Example 1 : if b is greater than 10,


if (b > 10)‫‏‬
Example 2 : while b is not equal to 10,
while (b != 10)‫‏‬
Example 3 : if mark is equal to 60, print “Pass”,
if (mark == 60)
print (“Pass”);

DO NOT confuse :
== (relational operator)
= (assignment operator)‫‏‬
64
Logical operator:
AND &&
OR ||
Logical operators are manipulation of logic

Example:
if ((midterm > 60) && (finalexam>50))‫‏‬
printf(“Pass\n”);

i. if ((midterm < 60) || (finalexam < 50))


printf(“Fail\n”);
65
Expression 1 Expression 2 Expression 1 &&
Expression 2
True True True
True False False
False True False
False False False

66
Expression 1 Expression 2 Expression 1 ||
Expression 2
True True True
True False True
False True True
False False False

67
• To calculate value from expression and store it
in variable, we use assignment operator (=)‫‏‬
• Compound assignment operator combines
binary operator with assignment operator
• E.g. val +=one; is equivalent to val = val + one;
• E.g. count = count -1; is equivalent to
count -=1;
count--;
--count;

68
Operators Precedence
! + - (unary operators) first
* / % second
+ - (binary operators) third
< <= >= > fourth
== != fifth
&& sixth
|| seventh
= last
69
70
• Debugging  Process removing errors from a
program

• Three (3) kinds of errors:


– Syntax error
– Run-time errors
– Logic Error/Design Error

71
Syntax error
– Mistakes caused by violating “grammar” of C
– C compiler can easily diagnose during
compilation
– statement cannot be translated and program
cannot be executed

72
Syntax error

No semicolon ;

73
Run-time error
C compiler cannot recognize during compilation
An attempt to perform an invalid operation, detected
during program execution.
Occurs when the program directs the computer to
perform an illegal operation, such as dividing a
number by zero.
The computer will stop executing the program, and
displays a diagnostic message indicates the line where
the error was detected

74
Run-time error

Run-time error

75
Logic Error
– Most difficult error to recognize and correct - it
does not cause run-time error and does not display
message errors.
– Program compiled and executed successfully but
answer wrong

76
Logic Error

Printing the wrong


variables

77
END

78

You might also like