C Programming Basics

Similar documents
Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics

Chapter Overview. More Flow of Control. Flow Of Control. Using Boolean Expressions. Using Boolean Expressions. Evaluating Boolean Expressions

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Fundamental of Programming (C)

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

C: How to Program. Week /Mar/05

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants

Chapter 3. More Flow of Control

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018

Data types, variables, constants

Fundamentals of Programming

C OVERVIEW. C Overview. Goals speed portability allow access to features of the architecture speed

Full file at

A complex expression to evaluate we need to reduce it to a series of simple expressions. E.g * 7 =>2+ 35 => 37. E.g.

Lecture 3. More About C

Chapter 2 - Introduction to C Programming

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

Basics of Java Programming

Programming and Data Structures

Using Boolean Expressions. Multiway Branches. More about C++ Loop Statements. Designing Loops. In this chapter, you will learn about:

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Programming for Engineers Introduction to C

9/5/2018. Overview. The C Programming Language. Transitioning to C from Python. Why C? Hello, world! Programming in C

Programming Lecture 3

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

The C Programming Language. (with material from Dr. Bin Ren, William & Mary Computer Science)

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

UNIT- 3 Introduction to C++

The C++ Language. Arizona State University 1

BASIC ELEMENTS OF A COMPUTER PROGRAM

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

3. Java - Language Constructs I

1 Lexical Considerations

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Full file at

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

2. Numbers In, Numbers Out

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Introduction to C Programming. Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan

Reserved Words and Identifiers

UIC. C Programming Primer. Bharathidasan University

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

Computer System and programming in C

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Statements. Control Flow Statements. Relational Operators. Logical Expressions. Relational Operators. Relational Operators 1/30/14

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

2. Numbers In, Numbers Out

Information Science 1

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Full file at C How to Program, 6/e Multiple Choice Test Bank

CS313D: ADVANCED PROGRAMMING LANGUAGE

3. Java - Language Constructs I

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University

Lexical Considerations

C++ Programming: From Problem Analysis to Program Design, Third Edition

Chapter 12 Variables and Operators

A Fast Review of C Essentials Part I

By the end of this section you should: Understand what the variables are and why they are used. Use C++ built in data types to create program

Operators. Java operators are classified into three categories:

QUIZ: What value is stored in a after this

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Course Outline. Introduction to java

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

Use of scanf. scanf("%d", &number);

Lexical Considerations

CPE 101, reusing/mod slides from a UW course (used by permission) Lecture 5: Input and Output (I/O)

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting

The SPL Programming Language Reference Manual

Lecture 3 Tao Wang 1

3. Types of Algorithmic and Program Instructions

DEPARTMENT OF MATHS, MJ COLLEGE

Programming in C and Data Structures [15PCD13/23] 1. PROGRAMMING IN C AND DATA STRUCTURES [As per Choice Based Credit System (CBCS) scheme]

Objectives. In this chapter, you will:

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Lesson 3 Introduction to Programming in C

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

printf( Please enter another number: ); scanf( %d, &num2);

Lecture 2. Examples of Software. Programming and Data Structure. Programming Languages. Operating Systems. Sudeshna Sarkar

Variables and literals

LECTURE 3 C++ Basics Part 2

Flow Control. CSC215 Lecture

n Group of statements that are executed repeatedly while some condition remains true

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Operators And Expressions

Display Input and Output (I/O)

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

Transcription:

CSE 2421: Systems I Low-Level Programming and Computer Organization C Programming Basics Presentation B Read/Study: Reek 3.1-3.4, 4, and 5, Bryant 2.1.1-2.1.5 Gojko Babić 08/29/2017 C Programming Language C is a language for expressing common ideas in programming in a way that most people are comfortable with, since it is procedural not object oriented (as Java) Portable, versatile, simple, straight-forward, and has many important, yet subtle, details Reasonably close to the machine: allows direct manipulation of memory via pointers provide language constructs that map efficiently to machine instructions, not to byte code (as Java does) requires minimal run-time support appropriate for writing device drives, operating systems C has the best combination of speed, low memory use, lowlevel access to the hardware, and popularity. Presentation B 2 1

C Keywords You shouldn't use them for any other purpose in a C program. But, they are allowed only within double quotation marks, i.e. as a part of string literal. g. babic Presentation B 3 C Variables and Identifiers C variables are names for memory locations we write a value in them and change the value stored but we cannot erase the memory location, since some value is always there Variables names are called identifiers Choosing variable names first character must be a letter or the underscore remaining characters must be letters, numbers or underscore character Keywords (also called reserved words) are used by the C language and cannot be used as identifiers g. babic Presentation B 4 2

Declaring Variables in C Before use, variables must be declared Examples: int number; double weight, total; int for signed integer and could store 3, 102, 3211, -456, etc. double or float for rational numbers with a fractional component and could store 1.34, 4.0, -345.6, etc. Declaration at the beginning Immediately prior to use int main() int main() int score1, score2; int sum, score1, score2; int sum; sum = score1 + score2; sum = score1 + score 2; return 0; return 0; g. babic Presentation B 5 Assignment Statements An assignment statement changes the value of a variable total = weight + number; total is set to the sum weight and number Assignment statements (as many others) end with a semicolon The single variable to be changed is always on the left of the assignment operator = On the right of the assignment operator can be Constants age = 21; Variables my_cost = your_cost; Expressions circumference = diameter * 3.14159; The = operator in is not an equal sign, e.g. this legal number = number + 3; g. babic Presentation B 6 3

Initializing Variables Declaring a variable does not give it a value Giving a variable its first value is initializing the variable Variables can be initialized in assignment statements double mpg; mpg = 26.3; // declare the variable // initialize the variable Declaration and initialization can be combined using two methods: double mpg = 26.3, area = 0.0, volume; int number = -20, i, j; g. babic Presentation B 7 Integers and Real Numbers Numbers of type int are stored as exact values Type int does not contain decimal points Examples: 34-45 1 89 Numbers of type double (or float) may be stored (sometimes) as approximate due to limitations on a number of significant digits that can be represented. Type double or float can be written in two ways: conventional notation Examples: 34.1 23.0034-1.0 89.9 exponent or scientific notation Examples: 3.41e1 means 34.1 3.67e17 means 367000000000000000.0-5.89e-6 means -0.00000589 g. babic Presentation B 8 4

Machine has word size Nominal size of integer-valued data Including addresses Machine Word Some current machines use 32 bits (4 bytes) words Limits addresses to 4G-1; Why? Becoming too small for memory-intensive applications High-end systems use 64 bits (8 bytes) words Potential address space 1.8 X 10 19 bytes x86-64 machines support 48-bit addresses: 256 Terabytes Machines support multiple data formats Fractions or multiples of word size Always integral number of bytes bryant Presentation B 9 Word-Oriented Memory Organization 32-bit 64-bit words words Bytes Address Address specifies a byte locations Address of first byte in word Addresses of successive words differ by 4 (32-bit) or 8 (64-bit) bryant Presentation B Addr = 0000?? Addr = 0004?? Addr = 0008?? Addr = 0012?? Addr = 0000?? Addr = 0008?? 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 0010 0011 0012 0013 0014 0015 5

C Basic Data Types Four basic data types in C integers, floating-point values, pointers, and aggregate types: arrays and structures. C Data Type Typical 32-bit Intel IA32 x86-64 char 1 1 1 short int 2 2 2 int 4 4 4 Sizes of all data types are given in bytes long int 4 4 8 long long int 8 8 8 float (6-7 digit precision) 4 4 4 double (15 digit precision) 8 8 8 long double 8 10/12 10/16 pointer 4 4 8 bryant Presentation B 11 (ClassEx1) Example with Basic I/O #include<stdio.h> Example run: int main() alpha ~/Cse2421> ClassEx1 Enter integer and real: 34 7.987 i1= 34 f1=7.987000 int i1; New i1= 17 f1=7.99 float f1; alpha ~/Cse2421> printf("enter integer and real: "); scanf ("%d %f", &i1, &f1); // do not forget & before variables printf ("i1= %d f1=%f", i1, f1); // no & i1=f1 +10; printf ("\nnew i1= %d f1=%.2f", i1, f1); /* f1 will be printed with 2 decimals */ g. babic Presentation B 12 6

Arithmetic Operators Arithmetic is performed with operators: + for addition, - for subtraction, * for multiplication, / for division An operand is a number or variable used by the operator Arithmetic operators can be used with any numeric type including char Result of an operator depends on the types of operands If both operands are int, the result is int If one or both operands are float, the result is float e.g., division with at least one operator of type float produces the expected results. float divisor = 3, dividend = 5, quotient; quotient = dividend / divisor; quotient = 1.6666 Result is the same if either dividend or divisor is int Integer division by zero? Float/double division by zero? g. babic Presentation B 13 Division of Integers Be careful with the division operator! Integer division discards the fractional part! int / int produces an integer result (true for variables or numeric constants) int dividend = 5, divisor = 3; float quotient; quotient = dividend / divisor; The value of quotient is 1.0, not 1.666 % operator gives the remainder from integer division int dividend=5, divisor=3, remainder; remainder = dividend % divisor The value of remainder is 2 Arithmetic operators have the usual algebraic precedence with left to right evaluation in the case of the same precedence. g. babic Presentation B 14 7

Use spacing to make expressions readable. x+y*z or x + y * z Arithmetic Expressions Use parentheses to alter the order of operations x + y * z ( y is multiplied by z first) (x + y) * z ( x and y are added first) Some expressions occur so often that C contains to shorthand operators for them: count = count + 2; count += 2; Similar operators: -=, *=, /=, %= Increment operator ++ adds 1 to the value of a variable x++; is equivalent to x = x + 1; Decrement operator -- subtracts 1 from the value of a variable x--; is equivalent to x = x 1; g. babic Presentation B 15 Arithmetic Expressions: Examples g. babic Presentation B 16 8

Introductory Assignment B Write C program (Size.c), that prints sizes in bytes of all C data types (given in B11) in a system the program would run. Compile your code once as usual and once with switch m32. When you run each of two executable codes, you should be getting different outputs. In file Readme provide outputs of your program and comment them. Hint: Read Reek sections 5.1.1-5.1.7 Before Wednesday class, submit Size.c (at the beginning provide compilation commands used) and Readme using the following: submit c2421ac int2 Size.c Readme Turn in a hard copies of Size.c and Readme at the beginning of the class on Wednesday. g. babic Presentation B 17 Relational Operators g. babic Presentation B 18 9

Used to compare two values > >= < <= ==!= Relational Operators (cont.) Precedence order given above; then left to right. Arithmetic operators have higher precedence than relational operators. When you perform comparison with the relational operators, the operator will return 1 if the comparison is true, or 0 if the comparison is false. e.g. the check 2 == 2 evaluates to 1. e.g. printf( %d, 2==1); what will be printed? g. babic Presentation B 19 While Loop The Expression is checked first and only if true the body is executed. The Expression is checked again after the body has been executed and only if true the body is executed again. Expression Expression g. babic Presentation B 20 10

(ClassEx2) Example: While Loop /* print Fahrenheit-Celsius table for fahr = 0, 20,..., 300 where the conversion factor is C = (5/9) x (F-32) */ int main() float celsius; int fahr, lower, upper, step; lower =0; // lower limit of temperature scale upper = 300; // upper limit step = 20; // step size fahr = lower; while (fahr <= upper) celsius = 5 * (fahr-32) / 9; // problem? printf("%d %.2f\n", fahr, celsius); fahr = fahr + step; return 0; Presentation B 21 C does not have a Boolean type and int is used instead C treats integer 0 as FALSE and any non-zero value as TRUE Example: i = 0; while (i 10) /*body*/ i=i+1; // probably found inside the body The body will execute until the variable i takes on the value 10 at which time the expression (i 10) will become false (i.e. 0). g. babic Boolean Type Presentation B 22 11

Logical (Boolean) Operators Logical Operators are: &&,, and! and, or, and not (logical negate), respectively Boolean expressions are evaluated using values from the truth tables below g. babic Presentation B 23 Logical Expression Logical expressions can be combined into complex expressions && is and operator true only if both expressions are true e.g.: ( (2 < x) && (x < 7) ) True only if x is between 2 and 7; inside parentheses are optional but enhance meaning is or operator true if either or both expressions are true e.g: ( ( x = = 1) ( x = = y) ) True if x contains 1 or/and if x contains the same value as y! is not operator negates any Boolean expression!(x = = y) True if x is NOT equal to y! operator may make expressions difficult to understand, thus use only when appropriate Relational operators have higher precedence than logical operators && and II and lower precedence than! g. babic Presentation B 24 12

Short-Circuit Evaluation Some Boolean expressions do not need to be completely evaluated, e.g. the value of the expression (x >= 0) && ( y > 1) or (x >= 0) ( y > 1) can be determined by evaluating only (x >= 0) C uses the above approach called short-circuit evaluation Short-circuit evaluation can be used to prevent run time errors, such as in this example: if ((kids!= 0) && (pieces / kids >= 2) ) printf( \neach child may have two pieces! ); If the value of kids is zero, short-circuit evaluation prevents evaluation of (pieces / 0 >= 2), since integer division by zero causes a run-time error. g. babic Presentation B 25 Problems with! The expression (! time > limit ), with limit = 60, is evaluated as (!time) > limit If time is an int with value 36, what is!time? False! Or zero since it will be compared to an integer The expression is further evaluated as: 0 > limit false The intent of the previous expression was most likely the expression (! ( time > limit) ) which evaluates as: (! ( false) ) true Before using the! operator see if you can express the same idea more clearly without the! operator g. babic Presentation B 26 13

If-Else Statement Expression Expression g. babic Presentation B 27 Keywords that are very important to looping are break and continue. break will exit the most immediately surrounding loop regardless of what the conditions of the loop are. break is useful if we want to exit a loop under special circumstances. continue is another keyword that controls the flow of loops. If you are executing a loop and hit a continue statement, the loop will stop its current iteration, update itself (in the case of FOR loops) and begin to execute again from the top. Essentially, the continue statement is saying "this iteration of the loop is done, let's continue with the loop without executing whatever code comes after me. g. babic Break and Continue Statements Presentation B 28 14

(ClassEx3) Example: if-else, break & continue #include <stdio.h> Guessing a factor of MAGIC integer #define MAGIC 100 int main() int i=5, fact, quotient, success=0; while (i--) // What is this? printf("guess a factor of MAGIC larger than 1: "); scanf("%d",&fact); if (fact<2) printf("you provided illegal number. Try again.\n"); continue; quotient = MAGIC % fact; if (0==quotient) printf("you got it!\n"); success=1; break; else printf("sorry,you missed it. Try again.\n"); if (success==0)printf ("You exhausted all your tries"); g. babic Presentation B 29 For Loop For loop is designed for tasks such as adding numbers in a given range and sometimes it is more convenient to use than a while loop But, a for loop does not do anything a while loop cannot do sum = 0; n = 1; while(n <= 10) // this while loop adds numbers 1 to 10 sum = sum + n; n++; sum = 0; for (n = 1; n <= 10; n++) //this for loop does the same as above sum = sum + n; The for loop uses the same components as the while loop but in a more compact form. g. babic Presentation B 30 15

For Loop with a Multistatement Body All expressions inside for statement often contain more complex expressions: for (x = sqrt(y); x < z+ 1000; x= pow(y,3.3)).. pow and sqrt are two functions from math library g. babic Presentation B 31 (ClassEx1A) Example with Basic I/O #include<stdio.h> int main() Cse2421> ClassEx1A Enter one integer and one rational: 201 34.055 int i1; i1dec= 201 i1hex= C9 f1=34.055000 float f1; Newi1dec= 44 Newi1hex = 2C f1=34.06 printf("enter one integer and one rational: "); scanf ("%d %f", &i1, &f1); // do not forget & before variables printf ("i1dec= %d i1hex= %X f1=%f", i1, i1, f1); // no & i1=f1 +10; printf ("\nnewi1dec= %d Newihex= %X f1=%.2f", i1, i1, f1); g. babic Presentation B 32 16

Goto Statement Goto plus a labeled statement goto label ; label: statement ; A statement labeled with label is meaningful only to a goto statement and in any other context, a labeled statement is executed without regard to its label, i.e. it is ignored. A label must reside in the same function as goto and can appear before only one statement in the same function. The set of label names following a goto has its own name space so the names do not interfere with other identifiers. It is good programming style to use the break and continue statement in preference to goto whenever possible. However, since the break statement only exits from one level of the loop, a goto may be necessary for exiting a loop from within a deeply nested loop. Presentation B 33 #include <stdio.h> int main() int i, j; for ( i = 0; i < 10; i++ ) Example: goto Statement In this example, a goto statement transfers control to the point labeled stop when i equals 5. printf( "Outer loop executing. i = %d\n", i ); for ( j = 0; j < 3; j++ ) printf( " Inner loop executing. j = %d\n", j ); if ( i == 5 ) goto stop; printf( "Loop exited. i = %d\n", i ); // This will never execute stop: printf( "Jumped to stop. i = %d\n", i ); return 0; Presentation B 34 17

Common Pitfalls Using = instead of == Example: if ( x == 3) // This is probably correct The compiler will also accept the following: if (x = 3) // This is probably wrong? but stores 3 in x instead of comparing x and 3 and since the result is 3 (non-zero), the expression is always true. Also, be careful translating inequalities to C e.g. if x < y < z should be translated into C as if ( ( x < y ) && ( y < z ) ) NOT as if ( x < y < z ) and compiler will not indicate an error g. babic Presentation B 35 (CommonPitfals) Common Pitfalls Program #include <stdio.h> void main() int x=2, y=15, z=9; printf("x= %d y= %d z= %d\n", x, y, z); if(x=5) printf("x equals 5\n"); if(x<y<z) printf("x<y<z true"); else printf("x<y<z not true"); printf("\nx= %d y= %d z= %d\n", x, y, z); Output: x= 2 y= 15 z= 9 x equals 5 x<y<z true x= 5 y= 15 z= 9 g. babic Presentation B 36 18

Do-While Loop A do-while loop is executed at least once. The body of the loop is first executed. The expression is checked after the body has been executed. Expression Expression g. babic Presentation B 37 Char Data Type Declare a variable letter of type char: char letter; This type variables are mostly used to store ASCII characters Character constants are enclosed in single quotes char letter = 'a ; // internally 97 Variables of type char are 8-bit integers, that can be used in any type of expression (arithmetic, relational or logical) as 32- bit integers we have used so far, e.g. letter=letter-32; // letter now has value 65 == A Always keep in mind distinction between a and a. 'a' is a value of type character "a" is a string of 2 characters containing character a followed by null character. g. babic Presentation B 38 19

(CharRead) Scanf and Printf with Char Variable int main() char c1, c2; printf("enter two chars:"); scanf("%c %c", &c1, &c2); printf("c1%%c= %c c1%%d= %d c2%%c= %c c2%%d= %d", c1, c1, c2, c2); alpha ~/Cse2421> CharRead Enter two chars:3 8 c1%c= 3 c1%d= 51 c2%c= 8 c2%d= 56 Note: scanf takes the first character entered (even if it is whitespace, because of no space in front) for its first char variable and then for the second char variable (because of a space between two %c) skips all whitespace characters until printable character is found. g. babic Presentation B 39 (CharRead2) Scanf and Printf with Char Variable int main() char c1, c2; printf("enter two chars:"); scanf("%c%c", &c1, &c2); printf("c1%%c= %c c1%%d= %d c2%%c= %c c2%%d= %d", c1, c1, c2, c2); alpha ~/Cse2421> CharRead2 Enter two chars:3 8 c1%c= 3 c1%d= 51 c2%c= c2%d= 32 Note: scanf takes the first character entered (even if it is whitespace, because of no space in front) for its first char variable and then for the second char variable (because of no space between two %c) the next character even if it is whitespace character. g. babic Presentation B 40 20

Introductory Assignment C Since C does not have exponentiation operator, your assignment is to write a C program (in file power.c), that accepts on input a rational number X (0<=X<=100.) and an integer A (0 <= A <=30) and then it calculates and prints results of X A as float. Check if each inputs is in a range. You may use the function pow only to check correctness of results your program provides. In file Readme provide outputs of your program for small, medium and large numbers and comment them. Before Thursday class, submit power.c and Readme using: submit c2421ac int3 power.c Readme Turn in a hard copy of the power.c and Readme at the beginning of Thursday class. g. babic Presentation B 41 (CharRead1) Scanf and Printf with Char Variable #include<stdio.h> int main() char c1, c2, c3; alpha ~/Cse2421> CharRead1 Enter two chars:1 2 3 c1%c= 1 c1%d= 49 c2%c= 2 c2%d= 50 Enter one more char: c3%c= c3%d= 32 printf("enter two chars:"); scanf("%c %c", &c1, &c2); printf("c1%%c= %c c1%%d= %d c2%%c= %c c2%%d= %d", c1, c1, c2, c2); printf("\nenter one more char:"); scanf("%c", &c3); printf("\nc3%%c= %c c3%%d= %d", c3, c3); g. babic Presentation B 42 21

Switch Statement switch (expression) case constant_1: Statement_Sequence_1 case constant_2: Statement_Sequence_2... case constant_n: Statement_Sequence_n default: Default_Statement_Sequence The expression must return one of integer types, including char. The value returned is compared to the constant values after each case and when a match is found, the sequence for that case is executed, following by execution of all sequences below that one. If no match, default sequence executed. 43 Usual Usage of Switch Statement switch (expression) case constant_1: Statement_Sequence_1 break; case constant_2: Statement_Sequence_2 break;... case constant_n: Statement_Sequence_n break; default: Default_Statement_Sequence The break statement ends the switch-statement Note: Default case is always optional; If there is no default, nothing happens when there is no match. g. babic Presentation B 44 22

(Switch) Example: Switch char grade; printf("enter your midterm grade:"); scanf("%c", &grade); switch (grade) case 'A': printf("excellent."); break; case 'B': printf("very good."); break; case 67: printf("passing."); break; case 'D': case 'F': printf("not good, study more."); break; default: printf("that is not a possible grade."); g. babic Presentation B 45 Precedence Rules Within a pair of parenthesis, the precedence of operations is: relational operations relational operations Operators with higher precedence performed first Binary operators with equal precedence performed left to right Unary operators of equal precedence are performed right to left The expression (x+1) > 2 (x + 1) < -3 is equivalent to ( (x + 1) > 2) ( ( x + 1) < -3) and is also equivalent to x + 1 > 2 x + 1 < - 3 g. babic Presentation B 46 23

More on Increment Operator i++ returns the current value of i, then increments i; an expression using i++ will use the value of i BEFORE it is incremented ++i increments i first and returns the new value of i; an expression using ++i will use the value of number AFTER it is incremented i has the same value after either version! Example: int i1 = 3, i2; i2 = 2 * (i1++); printf( i1= %d i2= %d, i1, i2); Output i1= 4 i2= 6 i1 = 3; i2 = 2 * (++i1); printf( i1= %d i2= %d, i1, i2); Output i1= 4 i2= 8 Same applies to the decrement operator -- g. babic Presentation B 47 Nested if-else statements Consider the following example: if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) printf( Fuel very low. Caution!\n ); else printf("fuel over 3/4. Don't stop now!\n ); This would compile and run, but produce wrong results. The compiler pairs the "else" with the nearest previous "if Correct would be (using braces): if (fuel_gauge_reading < 0.75) if (fuel_gauge_reading < 0.25) prinff("fuel very low. Caution!\n ); else printf("fuel over 3/4. Don't stop now!\n ); g. babic Presentation B 48 24

More Boolean Examples Operator Operator's Name Example Result && AND 3>2 && 3>1 1(true) && AND 3>2 && 3<1 0(false) && AND 3<2 && 3<1 0(false) OR 3>2 3>1 1(true) OR 3>2 3<1 1(true) OR 3<2 3<1 0(false)! NOT!(3==2) 1(true)! NOT!(3==3) 0(false)! ( 2 0 ) Answer: 0! ( 2 5 && 0 ) Answer: 0 (and is evaluated before or)! ( ( 2 5 ) && 0 ) Answer: 1 (Parenthesis are useful) Presentation B 49 Named Constants and Constant Variables Number constants used throughout a program may be difficult to find and change when needed Constants may be named using #define directive, so they have meaning and allow us to change all occurrences simply by changing the value of the constant Example: # define MAX_ELEMENTS 100 //no semicolon declares named conctant MAX_ELEMENTS equal to 100 It is common to name constants with all capitals, they are usually declared outside main block. const int Window = 10; declares int variable named Window that can t be changed by the program (although it is a variable) Useful for using at places where only variables can be used, e.g. function declarations and function call g. babic Presentation B 50 25

Introductory Assignment D A number x is said to be prime if x is at least 2, and the only proper factors of x are itself and 1. So the first few primes are 2, 3, 5, 7, 11, 13, 17, 19, 23, etc. 4 or 6 or 8 isn't prime, since each is divisible by 2. And so on. In this assignment, you are to code a program prime.c to do the following: Prompt the user for input of a positive integer (call it X) greater than 1 and less than 100,000. Check if input is in a range. Generate and print all prime numbers between 2 and X (both inclusive). For example if the user enters 42 then the output should be: 2 3 5 7 11 13 17 19 23 29 31 37 41 There are 13 prime numbers from 2 to 42 In file Readme provide output of your program for one large number on input. Submit before Friday class: submit c2421ac int4 prime.c Readme Turn in a hard copy of prime.c at the beginning of Friday class. g. babic Presentation B 51 26