Top Banner
ENG1410 C Programming: Topic #3 “C: Important Constructs” S. Areibi School of Engineering University of Guelph
42

ENG1410 C Programming: Topic #3 “C: Important Constructs”

Dec 31, 2021

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: ENG1410 C Programming: Topic #3 “C: Important Constructs”

ENG1410C Programming: Topic #3“C: Important Constructs”

S. AreibiSchool of EngineeringUniversity of Guelph

Page 2: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Topics

Introduction to Programming Conditions & Decisions in C .. Repetitions & Loops in C .. Arrays and strings in C .. Functions in C ..

Page 3: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Textbook Resources

Chapter #1, Chapter #2, Chapter #3

Page 4: ENG1410 C Programming: Topic #3 “C: Important Constructs”

C Example: Decisions

Page 5: ENG1410 C Programming: Topic #3 “C: Important Constructs”

The If Statement

Syntax: if (expression) statement; If the expression is true (not zero), the statement is executed. If the expression is false, it is not executed.

You can group multiple expressions together with braces:if (expression) {statement 1;statement 2;statement 3;

}

5

Page 6: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Conditional Statements

Example:if (age < 0) {

printf ("warning: negative age\n");age = -age;

}

Syntax:if (condition) statementif (condition) statement else statement

Rules:• the condition is an int ! (no booleans)• parentheses required around conditional expression• use curly braces to make a compound statement

6

Page 7: ENG1410 C Programming: Topic #3 “C: Important Constructs”

• The flowchart segment below shows a decision structure with only one action to perform. It is expressed as an if statement in C code.

if (x < y)

a = x * 2;

Flowchart C Code

YESNOx < y?

Calculate a as x times 2.

Decision Structure

7

Page 8: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Alternative Decision Structure

8

• The flowchart segment below shows a decision structure with two actions to perform.

• It is expressed as an if-else statement in C code.

Page 9: ENG1410 C Programming: Topic #3 “C: Important Constructs”

The If/Else Statement o Syntax: if (expression)

statement_1;else

statement_2;o If the expression is true, statement_1 will be

executed, otherwise, statement_2 will be.

9

if (myVal < 3) printf (“myVal is less than 3.\n”);

else printf (“myVal is greater than or

equal to 3.\n”);

Page 10: ENG1410 C Programming: Topic #3 “C: Important Constructs”

The flowchart segment below shows how a decision structure is expressed in C as an if/else statement.

YESNOx < y?

Calculate a as x times 2.

Calculate a as x plus y.

if (x < y) /* Yes */

a = x * 2;

Else /* No */

a = x + y;

Flowchart C Code

10

Decision Structure

Page 11: ENG1410 C Programming: Topic #3 “C: Important Constructs”

More ConditionalsExample:

if (x < 0)printf ("x is less than 0\n");

else if (x == 0)printf ("x is equal to 0\n");

elseprintf ("x is greater than 0\n");

11

1. When x < 0 the system will print x is less than 0 and exit

2. When x >= 0 the system will check the next two statements

3. If x == 0 the system will print x is equal to 0

4. If x != 0 the system will print x is greater than 0

Page 12: ENG1410 C Programming: Topic #3 “C: Important Constructs”

CASEyears_employed

1 2 3 Other

bonus = 100 bonus = 200 bonus = 400 bonus = 800

If years_employed = 1, bonus is set to 100

If years_employed = 2, bonus is set to 200

If years_employed = 3, bonus is set to 400

If years_employed is any other value, bonus is set to 800

Case Structure

12

Page 13: ENG1410 C Programming: Topic #3 “C: Important Constructs”

The switch constructs has the following form:

switch(condition){

case template_1 : statement(s);break;

case template_2 : statement(s);break;

case template_3 : statement(s);break;

……case template_n : statement(s);

break;

default : statement(s);}next_statement;

Switch/Case Statement

13

Page 14: ENG1410 C Programming: Topic #3 “C: Important Constructs”

C Example: Repetition

Page 15: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Looping Construct

As long as the condition is true continue to execute the statements

15

Page 16: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Loops

• flow control– break – exit innermost loop– continue – perform next iteration of loop

• Note, all these forms permit one statement to be executed. By enclosing in brackets we create a block of statements.

for (i = 0; i < MAXVALUE; i++) {dowork();

}

while (c != 12) {dowork();

}

do {dowork();

} while (c < 12);

16

Page 17: ENG1410 C Programming: Topic #3 “C: Important Constructs”

• The flowchart segment below shows a repetition structure expressed in C++ as a while loop.

while (x < y)

x++;

Flowchart C Code

x < y? Add 1 to xYES

Repetition Structure

17

Page 18: ENG1410 C Programming: Topic #3 “C: Important Constructs”

While Loops

Example:/* print "hi" forever */while (1)printf ("hi");

Syntax:while (condition)statement

Rules (again):• the condition is an int ! (no booleans)• parentheses required around conditional expression• use curly braces to make a compound statement

18

Page 19: ENG1410 C Programming: Topic #3 “C: Important Constructs”

• The action performed by a repetition structure must eventually cause the loop to terminate. Otherwise, an infinite loop is created.

• In this flowchart segment, x is never changed. Once the loop starts, it will never end.

• QUESTION: How can this flowchart be modified so it is no longer an infinite loop?

x < y? Display xYES

Controlling a Repetition Structure

19

Page 20: ENG1410 C Programming: Topic #3 “C: Important Constructs”

ANSWER:By adding an action within the repetition that changes the value of x.

x < y? Display x Add 1 to xYES

Controlling a Repetition Structure

20

Page 21: ENG1410 C Programming: Topic #3 “C: Important Constructs”

The For Loopo Syntax: for (initialization; test; increment) {statements;}o The for loop will first perform the initialization. Then, as

long is test is TRUE, it will execute statements. After each execution, it will increment.

21

Page 22: ENG1410 C Programming: Topic #3 “C: Important Constructs”

The For Loopo Syntax: for (initialization; test; increment)

{statements;}o The for loop will first perform the

initialization. Then, as long is test is TRUE, it will execute statements. After each execution, it will increment.

for (cntr = 0; cntr < 3; cntr = cntr + 1) {printf(“ Counter = %d\n”, cntr);

}

Counter = 0;Counter = 1;Counter = 2;

22

Page 23: ENG1410 C Programming: Topic #3 “C: Important Constructs”

For LoopsExample:

/* print "hi" three times */int i; /* i continues to exist when loop ends */for (i = 0; i < 3 ; i++)printf ("hi");

Syntax:for (statement1; condition; statement2)statement3;

Equivalent to:statement1;while (condition) {statement3;statement2;

}

23

Page 24: ENG1410 C Programming: Topic #3 “C: Important Constructs”

For Loop Example/* print squares up to 100 */main ( ){

int j, up = 100;for (j = 0; j * j <= up; j++)printf ("%d \n", j * j);

}

24

Note:• can’t do: for (int j = 0; ...• waste of one multiplication per iteration

Page 25: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Example (cont’d)

/* print squares up to 100 */void main ( ){

int j, up = 100, sq;for (j = 0; (sq = j * j) <= up; j++)printf ("%d \n", sq);

}

25

Note:• recall equivalence to a while loop: condition is evaluated before the loop body

Page 26: ENG1410 C Programming: Topic #3 “C: Important Constructs”

#include <stdio.h>int main (){

int i, j;for (i = 0; i < 10; i++){

printf ("\n");for (j = 0; j < i+1; j++ )

printf ( "A");}printf("\n");return 0;

}

Loop within a Loop

26

Page 27: ENG1410 C Programming: Topic #3 “C: Important Constructs”

C Example: Arrays

Page 28: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Definition – Array

28

• A collection of objects of the same type stored contiguously in memory under one name

• May be type of any kind of variable• May even be collection of arrays!

• For ease of access to any member of array• For passing to functions as a group

Page 29: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Arraysint years[45];float temperatures [11];void main () {years[0] = 2000;temperatures[11] = -45.67;

}

Rules:• indices start at zero• maximum valid index is the size of the array minus 1• but C lets you go beyond the declared boundaries• temperatures[11] is illegal

29

Page 30: ENG1410 C Programming: Topic #3 “C: Important Constructs”

CharactersCharacters

char a, b, c1, c2;a = '0'; b = '\037'; c1 = 'K'; c2 = c1 + 1;

• Assigns values: 48, 31, 75, 76• The sequences '0',...,'9', 'a',...,'z', 'A',...,'Z' contain characters numbered consecutively

Castingprintf ("%c %d\n", c1, (int) c1);

• Outputs: K 75

A character constant is enclosed in single quotes.

Note

30

Page 31: ENG1410 C Programming: Topic #3 “C: Important Constructs”

StringsStrings are '\0'-terminated arrays of char :

char s[3] = "hi"; /* invisible '\0' */char t[3] = {'h', 'i', '\0'};

String operations#include <string.h>strlen ("there"); /* returns 5 */strcpy (s, t); /* copy t to s */strcmp (s, t) /* alphabetical comparison */

Use single quotes for character constants. Use double quotes for string constants.

Note

31

Page 32: ENG1410 C Programming: Topic #3 “C: Important Constructs”

C Example: Functions

Page 33: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Basics of FunctionsDefinition: A function in C programming language is a set of statements that take inputs from the caller of the function, it performs some computation and produces some output. The results may be returned to the caller of a function.

Syntax:Return_type function_name (set_of_inputs);

33

Name of the functionVariable Type it intends to return

Inputs that might be provided to the function

Page 34: ENG1410 C Programming: Topic #3 “C: Important Constructs”

/* Increment; takes an integer argument and * returns the argument plus one.*/

int incr (int i){int j;j = i + 1;return j;

}

main () {int k, m = 4;k = incr(m);printf ("k = %d, m = %d\n", k, m);

}

Functions

34

output: k = 5, m = 4

Page 35: ENG1410 C Programming: Topic #3 “C: Important Constructs”

More about Functions

• might have no return type, and no return statement:void printhi (){printf ("hi\n");

}

• parameters are copied and can be modifiedint incr (int i){i++;return i;

}

• default (unspecified) return type is int

35

Page 36: ENG1410 C Programming: Topic #3 “C: Important Constructs”

/* Program to calculate the product of two numbers */

#include <stdio.h>int product(int x, int y);int main (){

int a,b,c;/* Input the first number */printf ("Enter a number between 1

and 100: ");scanf ("%d", &a);

/* Input the second number */printf ("Enter another number

between 1 and 100: ");scanf ("%d", &b);

/* Calculate and display the product */c = product (a, b);printf ("%d times %d = %d \n", a, b, c);return 0;

}

/* Functions returns the product of its two arguments */

int product (int x, int y){

return (x*y);}

Functions

36

Page 37: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Variables within Functions

void no_incr (int i){

i++;}

void main () {int x = 5;no_incr(x);printf ("%d\n", x);

}

But this does not work:

37

Page 38: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Summary

Page 39: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Summary

There are several structures that are used in many programming languages including “C” that allow to build more complex and sophisticated applications.

The constructs include:a. Decision making with “If-else” and “case” statements b. Looping using “for” and “while”, “do while”c. Modular programming structures in the form of

“Functions”d. Abstract data types using “Arrays” and “Strings”.

39

Page 40: ENG1410 C Programming: Topic #3 “C: Important Constructs”

Resources

Page 41: ENG1410 C Programming: Topic #3 “C: Important Constructs”

C: Resourceso YouTube:

https://www.youtube.com/watch?v=3pwxRgJQW54 https://www.youtube.com/watch?v=3lQEunpmtRA

o Documents: https://en.wikibooks.org/wiki/A_Little_C_Primer/C_Control_Constructs https://webdocs.cs.ualberta.ca/~tony/C201/Lectures/LecNotes/Lec04/lec-04.sli.html

o Examples: https://ict.senecacollege.ca/~btp100/pages/content/const.html

o Test Yourself: https://www.javatpoint.com/c-quiz https://www.tutorialspoint.com/cprogramming/cprogramming_online_quiz.htm https://data-flair.training/blogs/online-c-programming-test/

41

Page 42: ENG1410 C Programming: Topic #3 “C: Important Constructs”