ECET 264 C Programming Language with Applications

Similar documents
ECET 264 C Programming Language with Applications

Basic C Program: Print to stdout. Basic C Program. Basic C Program: Print to stdout. Header Files. Read argument and print. Read argument and print

Programming. Data Structure

Pointers (2) Applications

ECET 264 C Programming Language with Applications. C Program Control

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

Introduction to C. Systems Programming Concepts

THE FUNDAMENTAL DATA TYPES

CSE123 LECTURE 3-1. Program Design and Control Structures Repetitions (Loops) 1-1

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

Principles of C and Memory Management

Today. o main function. o cout object. o Allocate space for data to be used in the program. o The data can be changed

First of all, it is a variable, just like other variables you studied

Computer Organization & Systems Exam I Example Questions

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Programming Language A

INTRODUCTION TO C-PROGRAMING LANGUAGE

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

Fundamental of Programming (C)

Beginning C Programming for Engineers

Fundamentals of Programming

Chapter 3. Fundamental Data Types

Chapter 7. Basic Types

UNIVERSITY OF LIMERICK OLLSCOIL LUIMNIGH COLLEGE OF INFORMATICS & ELECTRONICS DEPARTMENT OF ELECTRONIC & COMPUTER ENGINEERING

Day05 A. Young W. Lim Sat. Young W. Lim Day05 A Sat 1 / 14

ISA 563 : Fundamentals of Systems Programming

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

int main(void) { int a, b, c; /* declaration */

Structured Program Development in C

A Short Course for REU Students Summer Instructor: Ben Ransford

A Fast Review of C Essentials Part I

C/Java Syntax. January 13, Slides by Mark Hancock (adapted from notes by Craig Schock)

C/Java Syntax. Lecture 02 Summary. Keywords Variable Declarations Data Types Operators Statements. Functions. if, switch, while, do-while, for

UNIT IV 2 MARKS. ( Word to PDF Converter - Unregistered ) FUNDAMENTALS OF COMPUTING & COMPUTER PROGRAMMING

CS 107 Lecture 3: Integer Representations

Incoming Exam. CS 201 Introduction to Pointers. What is a Pointer? Pointers and Addresses. High Speed Memory (RAM) Size of Variable Types.

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

Main Program. C Programming Notes. #include <stdio.h> main() { printf( Hello ); } Comments: /* comment */ //comment. Dr. Karne Towson University

Lecture 3. More About C

BLM2031 Structured Programming. Zeyneb KURT

Applied Computer Programming

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Work relative to other classes

Low-Level Programming

Structured Programming. Jon Macey

Lecture 02 Summary. C/Java Syntax 1/14/2009. Keywords Variable Declarations Data Types Operators Statements. Functions

UNIT 3 OPERATORS. [Marks- 12]

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Arithmetic Operators. Portability: Printing Numbers

DEPARTMENT OF MATHS, MJ COLLEGE

C: How to Program. Week /Mar/05

Computers Programming Course 5. Iulian Năstac

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

Approximately a Test II CPSC 206

C Pointers. sizeof Returns size of operand in bytes For arrays: size of 1 element * number of elements if sizeof( int ) equals 4 bytes, then

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

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

EL2310 Scientific Programming

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

Lecture 9 - C Functions

Chapter 3 Structured Program Development

Guide for The C Programming Language Chapter 1. Q1. Explain the structure of a C program Answer: Structure of the C program is shown below:

HISTORY OF C LANGUAGE. Facts about C. Why Use C?

C Programming Language (Chapter 2 of K&R) Variables and Constants

Computers Programming Course 6. Iulian Năstac

Bit Manipulation in C

Review Topics. Midterm Exam Review Slides

INTRODUCTION TO COMPUTER SCIENCE - LAB

Week 3 Lecture 2. Types Constants and Variables

P.E.S. INSTITUTE OF TECHNOLOGY BANGALORE SOUTH CAMPUS 1 ST INTERNAL ASSESMENT TEST (SCEME AND SOLUTIONS)

Lecture 02 C FUNDAMENTALS

Introduction to C Language

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

CS 241 Data Organization Binary

Chapter 7. Pointers. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

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

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

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:...

Worksheet 4 Basic Input functions and Mathematical Operators

8. Characters and Arrays

Operators and Expressions:

CS Programming In C

Midterm Exam Review Slides

Fundamentals of Programming

Fundamental of Programming (C)

Introduction to Computing Systems Fall Lab # 3

Programming. Elementary Concepts

Engineering program development 6. Edited by Péter Vass

Number Systems. Binary Numbers. Appendix. Decimal notation represents numbers as powers of 10, for example

Chapter 2 - Introduction to C Programming

Expression and Operator

File Handling in C. EECS 2031 Fall October 27, 2014

Agenda. CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language 8/29/17. Recap: Binary Number Conversion

More about BOOLEAN issues

M4.1-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH C LANGUAGE

CS 61C: Great Ideas in Computer Architecture. Lecture 2: Numbers & C Language. Krste Asanović & Randy Katz

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Types, Operators and Expressions

Transcription:

ECET 264 C Programming Language with Applications Lecture 6 Control Structures and More Operators Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 6 - P. Lin 1 Lecture 6 Control Structures and Operators Review Nested Control Structures Example 1: Nested Control Structures Example 2: Testing ASCII Characters Example 3: Counting Various ASCII Characters More C Operators Bit-wise operators: AND, OR, NOT, EX-OR Truth Tables Example 4: Bit-Operations Example 5: Clear Memory Locations Using EX-OR Operations Conditional Operators Sizeof Operator Example 6: Sizeof Example Example 7: Char and Character Array Size Address and Indirection Operators Example 8: Address Operator and Pointers Summary Lecture 6 - P. Lin 2 1

Example 1 Nested Control Structures Problem Statement Write a C program to produce a summary of the exam results for ten students using nested control structures. If more than 8 students pass, a message of raising tuition is displayed. Analysis Need to include <stdio.h> Read input one at a time (1 passed, 2 failed) Use WHILE control structure Needs two or three counters? Output To display each exam entered, the results, and a message of raising tuition when more than 8 students passed. Lecture 6 - P. Lin 3 Example 1 (continue) Nested Control Structures Formulating Algorithm: Analyze student s exam results and decide if tuition should be raised Define and initialize variables: COUNTERS: passed, failed, student result Input the exam results, count passes and failures while the counter is not exceed 10 Input the next exam result If the student passed, add one to passed COUNTER else add one to failed COUNTER add one to the student COUNTER Print a summary of the exam, and include a message Raise tuition if more than 8 students is passed Lecture 6 - P. Lin 4 2

Example 1 (continue) Nested Control Structures /* Analysis of examination results */ #include <stdio.h> /* function main begins program execution */ int main() { /* initialize variables in definitions */ int passes = 0; /* number of passes */ int failures = 0; /* number of failures */ int student = 1; /* student counter */ int result; /* one exam result */ /* process 10 students using counter-controlled loop */ while (student <= 10) {/* prompt user for input and obtain value fom user */ printf("enter result (1=pass,2=fail): " ); scanf( "%d", &result ); Lecture 6 - P. Lin 5 Example 1 (continue) Nested Control Structures /* if result 1, increment passes */ if ( result == 1 ) { passes = passes + 1; /* end if */ else { /* otherwise, increment failures */ failures = failures + 1; /* end else */ student = student + 1; /*increment student counter */ /* end while */ /* termination phase; display number of passes and failures */ printf( "Passed %d\n", passes ); printf( "Failed %d\n", failures ); Lecture 6 - P. Lin 6 3

Example 1 (continue) Nested Control Structures /* if more than eight students passed, print "raise tuition" */ if ( passes > 8 ) { printf( "Raise tuition\n" ); /* end if */ return 0; /* indicate program ended successfully */ /* end function main */ Lecture 6 - P. Lin 7 Example 1 (continue) Nested Control Structures Lecture 6 - P. Lin 8 4

Example 1 (continue) Nested Control Structures Lecture 6 - P. Lin 9 Example 2 Testing ASCII Characters /* if3.c - Char Class Testing - Testing various ASCII character classes. */ #include <stdio.h> #include <ctype.h> static char s[] = "1aBY4*$%"; /* Character array s[] contains the following characters: l, a, B, Y, 4, *, $, %,, and \0 which is the EOS (End of String Character) */ void main() { char c; int i = 0; while((c = s[i++])!= '\0') { if(islower(c)) { printf("%c = ",c); puts("l_case"); if(isupper(c)) { printf("%c = ",c); puts("u_case"); Lecture 6 - P. Lin 10 5

Example 2 (continue) Testing ASCII Characters if(isgraph(c)) { printf("%c = ",c); puts("printable"); if(isdigit(c)) { printf("%c = ",c); puts("digit"); if(c % 2 == 0) puts("even number"); Lecture 6 - P. Lin 11 Example 2 (continue) Testing ASCII Characters Lecture 6 - P. Lin 12 6

Example 3 Counting Various ASCII Characters /* Counting blanks, digits, newlines, letters and others EOF: end of file character is defined in <stdio.h> as -1 Ctrl Z... MS-DOS system Ctrl D... UNIX system */ /* To run this program to count the ifelse0.c source code under the MS-DOS prompt you type: C:\UNIT3\ifelse0 < ifelse0.c */ #include <stdio.h> void main() { char ch; int b, d, n, l, others; b = d = n = l = others = 0; Lecture 6 - P. Lin 13 Example 3 (continue) Counting Various ASCII Characters puts( Please continue to enter from keyboard; Enter Ctrl Z to exit the loop ); while((ch = getchar())!= EOF) { if (ch == ) ++b; else if (ch >= '0' && ch <= '9') ++d; else if(ch >= 'a' && ch <= 'z' ch >= 'A' && ch <= 'Z') ++l; else if(ch == '\n') ++n; else ++others; printf("blanks = %d\t", b); printf("digits = %d\n", d); printf("newlines = %d\t", n); printf("letters = %d\n", l); printf("others = %d", others); Lecture 6 - P. Lin 14 7

Example 3 (continue) Counting Various ASCII Characters Output: Please continue to enter from keyboard; Enter Ctrl Z to exit the loop 1234 testing testing <Enter> key ^Z blanks = 2 digits = 4 newlines = 1 letters = 14 others = 0Press any key to continue Lecture 6 - P. Lin 15 Bit-wise operators: &,, ^, ~, >>, Bitwise data manipulations are machine dependent Conditional Operators exp1? exp2: exp3; For example (x > 0)? puts( X is positive\n ): puts( X is negative ); Sizeof operator Sizeof(short) is 2byte Sizeof(int) is 4 bytes More C Operators Address operator & address operator for reference to variable directly Lecture 6 - P. Lin 16 8

It works with character and unsigned integer types Bit-wise Operators Applications: Windows operators, computer circuit simulation, digital circuit operations, etc. Operator Meaning & Two input AND gate operation Two input OR gate operation ^ Two input Ex-OR gate operation ~ Complement (NOT) or inverter >> Shift variable s content to the right << Shift variable s content to the left Lecture 6 - P. Lin 17 Truth Tables Input Outputs A B A & B A B A ^B --------------------------------------- 0 0 0 0 0 0 1 0 1 1 1 0 0 1 1 1 1 1 1 0 AND OR EX-OR Lecture 6 - P. Lin 18 9

Bit-wise Operators (continue) Bit-Wise AND Example: If we define bit, b, and c as a unsigned character variables: unsigned char b = 0x2F, c = 0xF3, bit; bit = b & c; /* bit = 0x23 */ In terms of binary numbers: b = 0010 1111 AND & c = 1111 0011 -------------- bit = 0010 0011 Lecture 6 - P. Lin 19 Bit-wise Operators (continue) Bit-wise OR example: unsigned char b = 0x2F, c = 0xF3, bit; bit = b c; /* bit = 0xFF */ In terms of binary numbers: b = 0010 1111 (OR) c = 1111 0011 ---------------------- bit = 1111 1111 Lecture 6 - P. Lin 20 10

Bit-wise Operators (continue) Bit-wise EXOR example: unsigned char b = 0x2F, c = 0xF3, bit; bit = b ^ c; /* bit = 0xDC */ In terms of binary numbers: b = 0010 1111 EXOR ^ c = 1111 0011 --------------- bit = 1101 1100 It is no surprise to see b = b ^ b = 0x00 Lecture 6 - P. Lin 21 Bit-wise Operators (continue) Operator Meaning Example &= bit-wised AND and assign b &= 0x01; b = b & 0x01; = bit-wised OR and assign b = 0x0E; b = b 0x0E; ^= bit-wised EX-OR and assign b ^= a; b =b^ a; Lecture 6 - P. Lin 22 11

Example 4: Bit-Operations /* bit_wised_ops.c */ #include <stdio.h> void main() { unsigned short A_in1 = 1, A_in2 = 0, A_out; unsigned short O_in1 = 1, O_in2 = 0, O_out; unsigned short exor_in1 = 1, exor_in2 = 0, exor_out; unsigned short register1 = 0x0001, register2 = 0x1000; // Not Gate (Inverter) printf("a_in2 = %x\n", A_in2); printf("~a_in2 = %x\n", ~A_in2); // No bit masking A_in2 = 1; printf("a_in2 = %x\n", A_in2); A_in2 = ~A_in2; printf("~a_in2 = %x\n", A_in2); // Masking off bit 15-bit0 A_in2 &= 0x0001; printf("after Maksing: ~A_in2 = %x\n", A_in2); // AND Gate A_out = A_in1 & A_in2; // 2- input AND gate printf("%x & %x = A_out = %x\n", A_in1, A_in2, A_out); printf("\ntruth Table - 2 input AND Gate\n"); printf("--------------------------------- \n"); printf("0 & 0 = %x\n", 0 & 0); printf("0 & 1 = %x\n", 0 & 1); printf("1 & 0 = %x\n", 1 & 0); printf("1 & 1 = %x\n", 1 & 1); Lecture 6 - P. Lin 23 Example 4 Bit-Operations (continue) // OR Gate O_out = O_in1 & O_in2; // 2- input OR gate printf("%x %x = O_out = %x\n", O_in1, O_in2, O_out); printf("\ntruth Table - 2 input OR Gate\n"); printf("--------------------------------- \n"); printf("0 0 = %x\n", 0 0); printf("0 1 = %x\n", 0 1); printf("1 0 = %x\n", 1 0); printf("1 1 = %x\n", 1 1); // EXOR printf("\ntruth Table - 2 input EX-OR Gate\n"); printf("------------------------------- --\n"); printf("0 ^ 0 = %x\n", 0 ^ 0); printf("0 ^ 1 = %x\n", 0 ^ 1); printf("1 ^ 0 = %x\n", 1 ^ 0); printf("1 ^ 1 = %x\n", 1 ^ 1); /* end of main */ Lecture 6 - P. Lin 24 12

Example 4 Bit-Operations (continue) Output A_in2 = 0 ~A_in2 = ffffffff A_in2 = 1 ~A_in2 = fffe After Maksing: ~A_in2 = 0 1 & 0 = A_out = 0 Truth Table - 2 input AND Gate --------------------------------- 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1 1 0 = O_out = 0 Truth Table - 2 input OR Gate --------------------------------- 0 0 = 0 0 1 = 1 1 0 = 1 1 1 = 1 Truth Table - 2 input EX-OR Gate --------------------------------- 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0 Press any key to continue Lecture 6 - P. Lin 25 Example 5 Clear Memory Locations Problem Statement Write a C program to show all possible methods of clearing or resetting integer type numerical variables Analysis Possible integer type numerical variables including char, short, int, and long Analysis (cont.) Memory clearing or resetting methods may include, for example: unsigned short n = 0xFFFF; //or 65535 Method 1, assign zero n = 0; Method 2, subtraction n = n - n; Method 3, using Exclusive OR n ^=n; Lecture 6 - P. Lin 26 13

Example 5 Clear Memory Locations (continue) /* bit_exor_clearm.c */ #include <stdio.h> void main() { unsigned short n1 = 0xFFFF; // 65535 unsigned short n2 = 0x1000; // 4096 unsigned short n3 = 0x0100; // 256 printf("original unsigned short n1 = %d\n", n1); printf("original unsigned short n2 = %d\n", n2); printf("original unsigned short n3 = %d\n", n3); // Method 1 n1 = 0; // Method 2 n2 = n2 - n2; // or n2 -= n2; // Method 3 n3 ^= n3; // or n3 = n3 ^ n3; printf("cleared: unsigned short n1 = %x\n", n1); printf("cleared: unsigned short n2 = %x\n", n2); printf("cleared: unsigned short n3 = %x\n", n3); /* End of main */ OUTPUT Original: unsigned short n1 = 65535 Original: unsigned short n2 = 4096 Original: unsigned short n3 = 256 Cleared: unsigned short n1 = 0 Cleared: unsigned short n2 = 0 Cleared: unsigned short n3 = 0 Press any key to continue Lecture 6 - P. Lin 27 Conditional Operators High-level language: if (a > b) max=a; else max =b; Conditional Operator: exp1? Exp2: exp3; Lecture 6 - P. Lin 28 14

Conditional Operators (continue) Examples: int a = 10, b = -10; max = (a > b)? a: b; /* max = 10*/ min = (a < b)? a: b; /* min = -10 */ v = (5)? 1: 2; // 5 is non-zero, true; v = 1 v = (0)? 1: 2; // 0 is zero, false; v = 2 Lecture 6 - P. Lin 29 sizeof Operator sizeof operator is a unary operator to find the number of bytes for storing the value of a variable in the memory Examples Len = sizeof(short); /* Len= 2, or 2 bytes */ Len = sizeof (n);/ * Len = 4, if n is a 32-bit integer */ Applications: CPU size checking Dynamic memory allocation at run time Data record size calculation etc Lecture 6 - P. Lin 30 15

Example 6 sizeof Problem Statement You are asked to write a simple C program to check the sizes of C data types, including char, short, int, long, float, and double. Analysis sizeof() and printf() functions are needed Correct data type names will be needed Lecture 6 - P. Lin 31 Example 6 (continue) sizeof The program that tell us the sizes of requested data types. /* sizeof_check.c */ #include <stdio.h> void main() { printf("sizeof(char) = %d Bytes\n", sizeof(char)); printf("sizeof(short) = %d Bytes\n", sizeof(short)); printf("sizeof(int) = %d Bytes\n", sizeof(int)); printf("sizeof(long) = %d Bytes\n", sizeof(long)); printf("sizeof(float) = %d Bytes\n", sizeof(float)); printf("sizeof(double) = %d Bytes\n", sizeof(double)); Lecture 6 - P. Lin 32 16

Output Example 6 (continue) sizeof sizeof(char) = 1 Bytes sizeof(short) = 2 Bytes sizeof(int) = 4 Bytes sizeof(long) = 4 Bytes sizeof(float) = 4 Bytes sizeof(double) = 8 Bytes Lecture 6 - P. Lin 33 Example 7 Char and Character Array Size Problem Statement: Write a program that shows and prints the size of a character and a character array. The sizeof operator should be used to evaluate the size of variables or objects and it return a number with the unit of bytes. Output Requirement The output of the program should be textbased, with heading info, and actual byte size for user. Lecture 6 - P. Lin 34 17

Example 7 (continue) Char and Character Array Size Analysis This program will be written using Microsoft Visual C++ 2008 and for running under DOS virtual machine Testing Data We will use the following data for testing: A char variable which contains a character T, and a character array which contains a string T which contains two characters, namely, T and a null character \0. Format Specifiers: %c for printing signal character %d -- for printing a decimal number %s -- for printing a string of characters Lecture 6 - P. Lin 35 Example 7 (continue) Char and Character Array Size /* charstr.c */ #include <stdio.h> void main() { char ch = 'T'; /*Define a single character variable ch*/ /*Evaluate the size of character type variable ch*/ /*The ch variable is a local variable within the main()*/ printf("sizeof(ch) = %d\n", sizeof(ch)); /* Evaluate the size of a string constant "T"*/ printf("%s\n", "T"); Lecture 6 - P. Lin 36 18

Example 7 (continue) Char and Character Array Size /*To display a double quote, a back slash is needed*/ /*Because a pair of double quote is used to enclose*/ /* the format string in the printf() function */ printf("sizeof(\"t\") = %d\n",sizeof("t")); Output: sizeof(ch) = 1 T sizeof( T") = 2 Lecture 6 - P. Lin 37 Address and Indirection Operators & Obtain address of a variable * Access the contents of a memory (using pointer or indirection) Examples: int a = 10; int *ptr; /* define a pointer variable called ptr of pointer type */ ptr = &a; /* assign the address of a variable to pointer ptr */ (*ptr)++; /* Access memory directory using pointer variable, a = 11 after this line */ Lecture 6 - P. Lin 38 19

Example 8 Address Operator and Pointers /* pointer1.c - This program explains how to use address operator and pointers. */ #include <stdio.h> void main() { int a = 10; int *ptr; /*A variable that holds the address of another r variable */ ptr = &a; printf("a = %d\n", a); printf("(*ptr) = %d\n", (*ptr)); (*ptr)++; printf("(*ptr)++ = %d\n", (*ptr)); printf("&a = %x\n", &a); printf("ptr = %x\n", ptr); Lecture 6 - P. Lin 39 Example 9 8 (continue) Address Operator and Pointers Lecture 6 - P. Lin 40 20

Summary Review Nested Control Structures More C Operators Bit-wise operators Conditional Operators sizeof operator Address operator C Examples Next More C Program Control Lecture 6 - P. Lin 41 Question? Answers lin@ipfw.edu Lecture 6 - P. Lin 42 21