You are on page 1of 58

ENG 054: COMPUTING ENGINEERING II

Chapter 3 : Introduction to C Programming

Objectives :
1. To know basic structure of C programming 2. To introduce the concepts of - data types - variables - constants - C operators 3. To introduce standard input & output function
2

Introduction
C programming language
Structured and disciplined approach to program design

Example of C program
#include <stdio.h> int main(void) { printf("Welcome to C !\n"); return 0; }
output

Structure of a C Program
Preprocessor directive

#include <stdio.h> Header file int main() { int num1; Variable Declaration scanf(%d,&num1 ); Statement @Program Body printf(You key in %d\n,num1); return 0; }
output
5

Structure of a C Program
//Written by: Rosmiza Wahida /*This program is to calculate the area of a cylinder*/ #include <stdio.h> #define pi 3.142 float A_cyl; int main() { float radius, height; printf(Please enter radius: ); scanf(%f,&radius); printf(Please enter height: ); scanf(%f,&height); A_cyl = 2*pi*radius*height; printf(Area for the cylinder is %f , A_cyl); return 0; }
Global declaration Comments

Preprocessor directive

main() function

Local declaration

Statements

C Program Structure
Preprocessor Directive The first line of the program contains a preprocessor directive, indicated by pound sign (#): #include. Format or syntax of this directive must be exact No space between # and include

This causes the preprocessor the first tool to examine source code as it is compiled. #include <stdio.h> allow standard input/output operations or function such as printf(), scanf()

C Program Structure
Header Files Have the extention .h and the fullfilename follows from the preprocessor directive (# include) (<stdio.h>) standard input/output header .This header contains information used by the compiler when compiling calls to standard input/output library functions such as printf and scanf in your program. Details in the later chapter int main (void) is a part of every C program. The parentheses after main indicate that main is a program building block called a function. C programs contain one or more functions, exactly one of 8 which must be main

C Program Structure
int main (void) int main(): int means that main "returns" an integer value

The void in parentheses here means that main does not receive any information. Braces ({ and }) indicate a block - beginning and ending function The bodies of all functions must be contained in braces Function contains
Declaration /variable declaration (local declaration) Data that youll be using in the function Also called local declaration (learn in details on topic :function) because only visible to the function that contain them Statement @ Program body Instructions to the computer to do something
9

C Program Structure
printf("Welcome to C !\n"); Code to print a line of text Instructs computer to perform an action

Specifically, prints the string of characters within quotes ( )


Entire line called a statement

All statements must end with a semicolon (;)

10

C Program Structure
printf("Welcome to C !\n");

backslash (\) is called an escape character Indicates that printf should do something out of the ordinary When encountering a backslash in a string, the compiler looks ahead at the next character and combines it with the backslash to form an escape sequence. The escape sequence n means newline. When a newline appears in the string output by a printf, the newline causes the cursor to position to the beginning of the next line on the screen.

11

C Program Structure
Some common escape sequences.

return the integer value 0, which is interpreted by the run-time system as an exit code indicating successful execution.

12

C Program Structure
Comments You insert comments to document programs and improve program readability. Comments do not cause the computer to perform any action when the program is run.

Comments are ignored by the C compiler and do not cause any machine-language object code to be generated. Comments also help other people read and understand your program.

13

C Program Structure
Comments Two format i) Block comment Uses opening and closing comment token ( one or more symbols that compiler understood when it interpret codes Opening token (/* ) and closing token (*/) Use for long comment ii) Line comment Uses two slashes (//) Does not require an end-of-comment token Use for short comment-single line Comments cannot be nested (comments inside comments)
14

C Program Structure
Example of comments

15

Structure of a C Program

16

Identifiers
Allows programmers to name data and other objects in the program- variable, constant, function etc. Can use any capital letter A through Z, lowercase letters a through z, digits 0 through 9 and also underscore ( _ ) Rules for identifier The first character must be alphabetic character or underscore It must consists only of alphabetic characters, digits and underscores, cannot contain spaces It cannot duplicate any reserved word C is case-sensitive; this means that NUM1, Num1, num1, and NuM1 are four completely different words.
17

Identifiers
Valid names
A student_name _aSystemName pi al stdntNm _anthrSysNm PI

Invalid names
$sum // $ is illegal 2names // cant start with 2 stdnt Nmbr // cant have space int // reserved word

Examples of valid and invalid names

18

Reserved word/ Keyword


Special words reserved for C Cannot be used as identifiers or variable names All reserves word appear in lowercase.

C and C++ Reserved Words auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

19

Data types
Data type defines a set of value and operations that can be applied on those values Set of values for each type is known as the domain for the type Functions also have types which is determined by the data it returns

20

Data types
C contains five standard types
void int : Integer :e.g. 1244,-87 char : Character :a, A double : Floating-point: 0.5678, -3.25 float : Floating-point (less precision)

They serves as the basic building blocks for derived types (complex structures that are built using the standard types) Derived types are pointer, enumerated type, union, array, structure and class
21

Data types
void Has no values and operations Both set of values are empty char Any value that can be represented in the computers alphabet (Note the symbols ) A char is stored in a computers memory as an integer representing the ASCII code A character in C can be interpreted as a small integer(between 0 and 255). For this reason, C treats a character like integer.
22

Data types
Integer A number without a fraction part C supports three different sizes of integer

short int int long int


Type Byte Size

short int unsigned short int int unsigned int long int
unsigned long int

2 2 2 2 4
4

Minimum Value -32,768 0

Maximum Value

32,767 65,535 32,767 65,535 2,147,483,647


4,294,967,295
23

-32,768 0 -2,147,483,648
0

Data types
Float A number with fractional part such as 43.32 C supports three types of float float double long double
Type
float double long double

Byte Size
4 8 16

Precision
6 15 19

Range
10-37 ..1038 10-307 ..10308 10-4931 ..104932
24

Variables
Variable names correspond to locations in the computer's memory Every variable has a name, a data type, a size and a value

A variable is created via a declaration where its name and type are specified.
E.g: int integer1, integer2, sum;

Whenever a new value is placed into a variable (through scanf, for example), it replaces (and destroys) the previous value
25

Variables
Declaration of variables Variables: locations in memory where a value can be stored int means the variables can hold integers (-1, 3, 0, 47) Variable names (identifiers) integer1, integer2, sum Identifiers: consist of letters, digits (cannot begin with a digit, cannot contain space) and underscores( _ ) Case sensitive Declarations appear before executable statements If an executable statement references and undeclared variable it will produce a syntax 26 (compiler) error

Variables

long int

Variables in memory
27

Variables Declaration
Variable declaration syntax : data type variable name Examples: short int maxItems; // word separator : capital

long int national_debt;


float payRate; double tax;

// word separator : _
// word separator : capital

char code;
int a, b; // equivalent to int a; int b;
28

Variable initialization
Initializer establishes the first value that the variable will contain To initialize a variable when it is defined, the identifier is followed by the assignment operator (=) and then the initializer which is the value the variable is to have when the functions starts int count = 0; int count , sum = 0; Only sum is initialize. int count=0 , sum = 0; OR int count =0; int sum = 0;
29

Constants
Data values that cannot be changed during the execution of a program Types of constant Integer constant Float constant Numbers with decimal part Character constant Enclosed between two single quotes () String constant A sequence of zero or more characters enclosed in double quotes ( ) Symbolic constant Define constant and memory constant
30

Constants
Three different ways Literal constants An unnamed constant used to specify data If the data cannot be changed, we can simply code the data value itself in a statement
E.g A // a char literal 5 // a numeric literal 5 a+5 // numeric literal 3.1435 // a float literal Hello // a string literal

31

Constants
Defined constant Another way to designate a constant is to use the preprocessor command define Like other preprocessor commands, it is also prefaced with the pound sign (#)

Placed at the beginning of a program to make it easy to find and change


E.g #define pi 3.142

The way define work is that the expressions that follows the name (3.142) replaces the name wherever it is found in the program (like search and replace command)
32

Constants
Defined constant Another way to designate a constant is to use the keyword const E.g const int a = 1;

33

Arithmetic Operators
Few symbols in assignment statements which have been used in programs Assume int a=4, b= 5, d;
C Operation Addition Substraction Arithmetic Operator + C Expression d=a+b d=b-2 Value of d after assignment 9 3

Multiplication
Division Modulus

*
/ %

d=a*b
d = a/2 d = b%3

20
2 2
34

Assignment Operator
Assume int x = 4, y=5, z=8;
Assignment Operator += -= *= /= %= Sample Expression x += 5 y -= x x *= z z /=2 y %=x Similar Expression x=x+5 y=y-x x = x*z z = z/2 y = y%x Value of variable after assignment x=9 y=1 x=32 z=4 y=1
35

Increment and decrement Operator


Preincrementing (predecrementing) a variable causes the variable to be incremented (decremented) by 1, then the new value of the variable is used in the expression in which it appears.
Postincrementing (postdecrementing) the variable causes the current value of the variable to be used in the expression in which it appears, then the variable value is incremented (decremented) by 1.

36

Increment and decrement Operator


Operator Called Sample Expression Similar Expression Explanation

++

preincrement

++a

a = a +1 a += 1

Increment a by 1, then use the new value of a in expression in which a reside

++

postincrement

a++

a = a +1 a += 1

Use the current value of a in the expression which a reside, then increment a by 1

--

predecrement

--a

a = a -1 a -= 1

Decrement a by 1, then use the new value of a in expression in which a reside

--

postdecrement

a--

a = a -1 a -= 1

Use the current value of a in the expression which a reside, then decrement a by 1 37

Increment and decrement Operator


If c equals 5, then printf( "%d", ++c ); Prints 6 printf( "%d", c++ ); Prints 5 In either case, c now has the value of 6 When variable not in an expression Preincrementing and postincrementing have the same effect ++c; printf( %d, c ); Has the same effect as c++; printf( %d, c );
38

Relational And Equality Operator


int y=6, x=5;
Relational Operators > < >= Sample Expression Value

y>x y<2 x>=3

T (1) F (0) T (1)

<=

y<=x

F (0)

Equality Operators == !=

Sample Expression x==5 y!=6

Value T(1) F(0)


39

Logical Operator
(learn in details on next chapter) Logical Operators Called Sample Operation

&& || !

AND OR NOT

expression1 && expression 2 expression1 | | expression2 ! expression

Example : Assume int x = 50


Sample Expression Expression !Expression

!(x==60)
!(x!=60)

0 (False)
1 (True)

1 (True)
0 (False)
40

Logical Operator &&(AND)


(learn in details on next chapter)

Example : Assume int x = 4, y=5, z=8;


Expression1 Sample Expression ( y > 10) && ( z < =x ) 0 (False) 0 (False) Expression2 Expression1 && Expression2 0 (False)

( z < = y) && ( x = = 4) ( y ! = z) && ( z < x ) ( z > = y ) && ( x ! = 3)

0 (False) 1 (True) 1 (True)

1 (True) 0 (False) 1 (True)

0 (False) 0 (False) 1 (True)


41

Logical Operator - || (OR)


(learn in details on next chapter)

Example : Assume int x = 4, y=5, z=8;

Expression1 Sample Expression ( y > 10) || ( z < =x ) 0 (False)

Expression2

Expression1 && Expression2 0 (False)

0 (False)

( z < = y) || ( x = = 4) ( y ! = z) || ( z < x ) ( z > = y ) || ( x ! = 3)

0 (False) 1 (True) 1 (True)

1 (True) 0 (False) 1 (True)

1 (True) 1 (True) 1 (True)


42

Operator Precedence
Operators () ++ - - + - ! Associative Left to right Right to left

* / %
+ < <= > >= = = != && || = *= += - = /= %=

Left to right
Left to right Left to right Left to right Left to right Left to right Right to left
43

Operator Precedence
Example 1: int a=10, b=20, c=15, d=8; Example 2: int a=15, b=6, c=5, d=4;

a*b/(-c*31%13)*d
1. a*b/(-15*31%13)*d 2. a*b/(-465%13)*d

d *= ++b a/3 + c
1. d *= ++b a/3+ c 2. d*=7- a/3+c

3. a*b/(-10)*d
4. 200/(-10)*d 5. -20*d 6. -160

3. d*=7- 5+c
4. d*=2 + c 5. d*= 7 6. d = d*7 7. d = 28
44

Standard Input & Output Function


We can identify functions to perform special task like getting input and display the output. printf(): Function for printing text, values, etc.

scanf(): Function for reading a value. It will wait for the user to enter a value
Must include <stdio.h> header file. This is to allow standard input/output operations or function such as printf(), scanf()

45

scanf()

Standard Input Function

scanf() is in fact a call to a standard library function

Syntax of scanf():
scanf(FormatControlString, InputList); e.g. int age;

scanf(%d, &age);
FormatControlString must consist of format specifiers only

Each element in InputList must be an address to a memory location for which it must be made into an address by prefixing the variable name by an ampersand character & (address operator)
46

Common scanf() Format Specifiers


Specifies the argument type
Data Type int %d Format Specifiers

float
double char string

%f
%lf %c %s

47

scanf() Function
Example scanf( "%d", &integer1 ); Obtains a value from the user scanf ()uses standard input (usually keyboard) This scanf() statement has two arguments %d - indicates data should be a decimal integer &integer1 - location in memory to store variable When executing the program the user responds to the scanf statement by typing in a number, then pressing the enter (return) key

48

Example scanf()
double height; int year; scanf(%lf, &height); scanf(%d, &year); scanf(%lf, height); /* This is an error!! */

49

Inputting Multiple Values with a Single scanf()


int height; char ch; double weight; scanf(%d %c %lf, &height, &ch , &weight);

Put space between the specifiers ** Note : It is always better to use multiple scanf()s, where each reads a single value

50

Standard Output Function


Output :printf()

printf() is in fact a call to a standard library function


Two Syntax of printf():
printf(FormatControlString); e.g. printf(Hello\n); printf(FormatControlString Format specifier, PrintList); e.g. int year=2006; printf(Year is %d, year);
Specifier for printing an integer value To read the value of an integer from this variable
51

Common Output Format Specifiers


Specifies the argument type
Data Type int float double char string %d %f %lf %c %s Format Specifiers

52

printf()Function
Example printf( "Sum is %d\n", sum ); %d means decimal integer will be printed sum specifies what integer will be printed

53

Different Ways of Formatting printf()


Display normal message printf("Hello Welcome to C"); Display space printf("\tWelcome"); Display new line printf("\n"); Printing value of variable printf("Addition of two Numbers : %d",sum); Printing value of the calculation printf("Addition of two Numbers : %d", num1+num2);
54

Different Ways of Formatting printf()


Multiple format specifier printf("I Love %c %s",'c',"Programming"); Display integer in different styles
printf(\n%d",1234); printf(\n%3d",1234); printf(\n%6d",1234); printf(\n%-6d",1234); printf(\n%06d",1234); Output 1234 1234 1234 1234 001234

55

Different Ways of Formatting printf()


Display fraction number in different styles
printf("\n%f",1234.12345); printf("\n%.4f",1234.12345); printf("\n%3.2f",1234.12345); printf("\n%-15.2f",1234.12345); printf("\n%15.2f",1234.12345);
Output 1234.123450 1234.1235 1234.12 1234.12 1234.12

56

Different Ways of Formatting printf()


Display fraction number in different styles char str[]="Programming"; // Length = 11 printf("\n%s",str); // Display Complete String printf("\n%10s",str); // 10 < string Length, thus display Complete String printf("\n%15s",str); // Display Complete String with RIGHT alignment printf("\n%-15s",str); // Display Complete String with LEFT alignment printf("\n%15.5s",str); //Width=15 and show only first 5 characters with RIGHT alignment printf("\n%-15.5s",str); //Width=15 and show only first 5 characters with LEFT alignment Output Programming Programming Programming Programming Progr Progr
57

1 /* Fig. 2.5: fig02_05.c 2 Addition program */ 3 #include <stdio.h> 4 5 int main() 6 { 7 int integer1, integer2, sum; declaration */ 8 9 printf( "Enter first integer\n" ); prompt */ 10 scanf( "%d", &integer1 ); an integer */ "Enter second integer\n" ); 11 printf( prompt */ 12 scanf( "%d", &integer2 ); an integer */ 13 sum = integer1 + integer2; assignment of "Sum */ %d\n", sum ); 14 printf( sum is print sum */ 15 16 return 0; /* indicate that program successfully */ 17 } Enter first integer 45 Enter second integer 72 Sum is 117

/*

1. Initialize variables 2. Input

/* /* read /* /* read /* /*

2.1 Sum 3. Print

ended

Program Output
58

You might also like