Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Similar documents
Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

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

Unit 4. Input/Output Functions

CS Basics 14) C: Additional features

Fundamental of Programming (C)

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Fundamentals of Programming

CSC 1107: Structured Programming

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

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

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ;

CS Basics 15) Compiling a C prog.

CSC 1107: Structured Programming

Fundamental of Programming (C)

Should you know scanf and printf?

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

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

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

Standard I/O in C and C++

Fundamentals of Programming

Fundamentals of Programming. Lecture 11: C Characters and Strings

UNIT-I Input/ Output functions and other library functions

Dept. of CSE, IIT KGP

1/31/2018. Overview. The C Programming Language Part 2. Basic I/O. Basic I/O. Basic I/O. Conversion Characters. Input/Output Structures and Arrays

Advanced C Programming Topics

Console Input and Output

ANSI C Programming Simple Programs

Course Outline Introduction to C-Programming

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

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

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

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach

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:

THE FUNDAMENTAL DATA TYPES

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

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

C Input/Output. Before we discuss I/O in C, let's review how C++ I/O works. int i; double x;

C-programming. Goal To give basic knowledge of the C language. Some previous experiences in programming are assumed. Litterature

VARIABLES AND CONSTANTS

C - Basic Introduction

Work relative to other classes

Computer Programming CS F111

Stream Model of I/O. Basic I/O in C

Lecture 2: C Programming Basic

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); }

Continued from previous lecture

Lecture 02 C FUNDAMENTALS

Introduction to Programming

Input/output functions

Programming in C. Session 2. Seema Sirpal Delhi University Computer Centre

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

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

Chapter 2. Section 2.5 while Loop. CS 50 Hathairat Rattanasook

Input/output functions

CMPT 102 Introduction to Scientific Computer Programming. Input and Output. Your first program

Input / Output Functions

INTRODUCTION TO C++ C FORMATTED INPUT/OUTPUT. Dept. of Electronic Engineering, NCHU. Original slides are from

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

LESSON 4. The DATA TYPE char

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

C programming basics T3-1 -

SWEN-250 Personal SE. Introduction to C

The Design of C: A Rational Reconstruction: Part 2

Structured Programming. Dr. Mohamed Khedr Lecture 4

BASIC ELEMENTS OF A COMPUTER PROGRAM

Lecture 3. More About C

Midterm Exam. CSCI 2132: Software Development. March 4, Marks. Question 1 (10) Question 2 (10) Question 3 (10) Question 4 (10) Question 5 (5)

C: How to Program. Week /Mar/05

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

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

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

CC112 Structured Programming

Contents. A Review of C language. Visual C Visual C++ 6.0

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

Introduction to C Language

Structured programming

C Programming

C Tutorial: Part 1. Dr. Charalampos C. Tsimenidis. Newcastle University School of Electrical and Electronic Engineering.

BSM540 Basics of C Language

Tail recursion. Decision. Assignment. Iteration

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

Course organization. Course introduction ( Week 1)

Formatted Input/Output

1. History of C. 2. Characteristics of C. 3. Basic structure of C programs INTRODUCTION TO C

Computer System and programming in C

Number Systems, Scalar Types, and Input and Output

Formatting functions in C Language

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

C Course. IIT Kanpur. Lecture 3 Aug 31, Rishi Kumar <rishik>, Final year BT-MT, CSE

IECD Institute for Entrepreneurship and Career Development Bharathidasan University, Tiruchirappalli 23.

Operators and Control Flow. CS449 Fall 2017

printf("%c\n", character); printf("%s\n", "This is a string"); printf("%s\n", string); printf("%s\n",stringptr); return 0;

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

C Programming Multiple. Choice

Programming and Data Structures

بسم اهلل الرمحن الرحيم

(2½ Hours) [Total Marks: 75

Topic 6: A Quick Intro To C

Lab Session # 1 Introduction to C Language. ALQUDS University Department of Computer Engineering

Transcription:

Control Structures for C CS Basics 10) C Control Structures Emmanuel Benoist Fall Term 2016-17 Data Input and Output Single character In and Output Writing output data Control Statements Branching Looping More branching Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 1 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2 Functions for Data Input and Output Data Input and Output getchar() Read one character putchar() Write one character scanf() Read : integers, strings, floating point numbers, hexadecimal,... printf() Write: Integers (decimal / hexadecimal / octal), strings, floating point numbers, characters,... gets() Read a string puts() Write a string Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 3 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 4

Outline of a typical C program #include <stdio.h> main(){ char c,d; /* declarations */ float x,y; int i,j,k;... c=getchar(); /* character input */ scanf("%f", &x) /* floating point input */... putchar(d); /* character output*/ printf("%3d %7.4f",k, y); /* numerical output */ Single character In and Output Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 5 Single character Input Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 6 Single character output Function getchar() Part of the standard I/O library Returns one character from a standard input (stdin) character variable = getchar(); char c;... c = getchar(); The putchar() function Writes on stdout the character given as argument char c; c= a ; putchar(c); End of file character EOF is returned at end of file EOF is a constant defined in stdio.h Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 7 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 8

Entering input data The scanf() function Reads input from standard input Parse inputs in variables scanf(control string, arg1, arg2,..., argn Arguments represent pointers (i.e. addresses) where the values can be stored. char str1[20]; int i1; float f1;... scanf("%s %d %f", str1,&i1,&f1); Formats for scanf Integers %d integers %ld long int %hd short int Unsigned integers %u integer %hu unsigned short %lu unsigned long int %x hexadecimal %X hexadecimal (capitals) Floats %f float %lf double %Lf long double Arrays are addresses (address of the first element) Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 9 Scanf Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 10 Using scanf with format Scan three numbers /* 1 Scanf */ int i1; double d1; char c1; puts("type an integer, a float and a char"); scanf(" %d %lf %c",&i1,&d1,&c1); printf(" i1=%d, d1=%lf c1=%c\n",i1,d1,c1); /* if input is : 1234 10.5 T Output is i1=1234, d1=10.500000 c1=t */ Define the length to be parsed One can set for each item, the number of chars parsed int i2; double d2; char c2; puts("type an integer (3 digits), a float (5 chars) and a char"); scanf(" %3d %5lf %c",&i2,&d2,&c2); printf(" i2=%d, d2=%lf c2=%c\n",i2,d2,c2); /* if input is : 1234 10.5 T Output is: i2=123, d2=4.000000 c2=1 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 11 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 12

sscanf() (String Scan Format) Similar to scanf() Scan not from stdin, but rather from a given string String can be read using gets() char line[256]; int i=0; int a,b,c,d; while(gets(line)){ sscanf(line,"%d %d %d %d",&a,&b,&c,&d); printf("%d + %d + %d + %d = %d\n",a,b,c,d,(a+b+c+ d)); Writing output data Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 13 The printf() function Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 14 Field width and precision specification Format an output using a string syntax printf(control string, arg1, arg2, arg3,..., argn) Each arg correspond to one expression in control string an expression starts with % Possible conversion characters c single character d signed decimal integer e floating-point number with an exponent f floating-point number without exponent g use e or f type depending on value i signed decimal integer o octal integer s string u unsigned decimal integer x hexadecimal integer Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 15 One can state the size of the generated string Two numbers: minimal length of generated string. precision Minimal length If the content is not long enough, the rest is filed with spaces Precision For strings : Maximum number of characters For floating point numbers: number of decimal places Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 16

length. precision /* 1 Printf */ double d1 = 101.593039; printf("%f %.2f %.0f %2.2f \n",d1,d1,d1,d1); /* Output: 101.593039 101.59 102 101.59 */ /* 2 Printf */ char line[]="abcdefghijklmnop"; printf("%10s %15s %15.5s %.10s\n",line,line,line, line); /* Output: ABCDEFGHIJKLMNOP ABCDEFGHIJKLMNOP ABCDE ABCDEFGHIJ */ printf() Flags Each character group can include a flag - left justified + a sign will precede each numerical data item. 0 zeros appear instead of blangs (blank space) a blank space will preced each positive number. # (with o- and x-type) octal and hexa numbers are preceded by 0 and 0x, respectively # (with e-, f- and g-type) Decimal point must be present even if not required for g it prevents any truncation of zeros. Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 17 Flags: Flags change the way expressions are printed int i1 = 1234; double x = 12.0, y = -3.3; printf(":%6d %7.0f %10.1e:\n",i1,x,y); printf(":%-6d %-7.0f %-10.1e:\n",i1,x,y); printf(":%+6d %+7.0f %+10.1e:\n",i1,x,y); printf(":%-+6d %-+7.0f %-+10.1e:\n",i1,x,y); printf(":%7.0f %#7.0f %7g %#7g:\n",x,x,y,y); /* Output: : 1234 12-3.3e+00: :1234 12-3.3e+00 : : +1234 +12-3.3e+00: :+1234 +12-3.3e+00 : : 12 12. -3.3-3.30000: */ Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 18 Functions: gets() and puts() Read a string from stdin : gets() Get a String Populate a string given as argument Write a string to stdout : puts() Put a String Write the string given as input to standard output #include <stdio.h> main(){ char line[80]; puts("hello, what is your name?"); gets(line); printf("hello "); puts(line); Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 19 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 20

Typical interactive program #include <stdio.h> main(){ char name[80]; int nbmarks,i; float mark, sum, avg; puts("hello, what is your name?"); /* scan a line : everything not \n */ scanf(" %[^\n]",name); printf("number of marks?"); scanf(" %d",&nbmarks); for(i=0;i<nbmarks;i++){ printf("enter Mark %d:",(i+1)); scanf(" %f",&mark); sum += mark; avg = sum / nbmarks; printf("%s, your average mark is: %.1f \n",name,avg); Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 21 Control Statements Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 22 Branching: IF, ELSE Branching Similar to Java if (expression) statement 1 else statement 2 If expression is true, statement 1 is executed, (and not statement 2) If expression is false, statement 2 is executed (and not statement 1) s if (status == S ) tax = 0.20 * pay; else tax = 0.14 * pay; Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 23 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 24

Branching (Cont.) Statement can contain more than one instruction if(circle){ scanf("%f",&radius); area = PI * radius * radius; printf("area of the circle = %f \n",area); else { scanf("%f %f", &length, &width); area = length * width; printf("area of rectangle = %f",area); Looping Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 25 Looping: the WHILE statement Similar to Java while (expression) statement The statement will be executed as long as the expression is true while (digit <=9) { printf("%d\n", digit); ++digit; Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 27 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 26 WHILE (Cont.) : compute average of marks #include <stdio.h> main(){ char name[80]; int nbmarks,i=0; float mark, sum, avg; puts( Hello, what is your name? ); / scan a line : everything not \n / scanf( %[ˆ\n],name); printf( Number of marks? ); scanf( %d,&nbmarks); while (i<nbmarks){ i++; printf( Enter Mark %d:,(i)); scanf( %f,&mark); sum += mark; avg = sum / nbmarks; printf( %s, your average mark is: %.1f \n,name,avg); Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 28

More Looping: DO... WHILE do statement while(expression) Executes statement as long as expression is true The statement is executed at least once, since expression is evaluated afterwards. do printf("%d\n",digit++); while(digit <= 9); DO... WHILE (Cont.) Transform a string in uppercase 1 char line[80]; int i = 0, size=0; /* Scan one line (until a \n is read) */ puts("type a line (to be transformed in uppercase): "); scanf("%[^\n]",line); do ++size; while(line[size]!=0); do { putchar(toupper(line[i])); i++; while (i<size); putchar( \n ); 1 Need the library <ctype.h> Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 29 Loops with FOR Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 30 FOR (cont.) for (expression 1; expression 2; expression 3) statement expression 1 : is used to initialize some parameter expression 2 : represents the condition that must be true for the loop to continue execution expression 3 : used to alter the value of the parameter for(digit = 0; digit <=9; ++digit){ printf("%d\n",digit); Visit a string for(i=0;i<size;i++){ putchar(toupper(line[i])); putchar( \n ); Compute an average for(i=0;i<nbmarks;i++){ printf("enter Mark %d:",(i+1)); scanf(" %f",&mark); sum += mark; avg = sum / nbmarks; Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 31 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 32

More branching The SWITCH statement Cause a particular group of statements to be chosen from several available groups Similar to Java switch (expression) { case expression 1: statement 1 statement 2 case expression 2: statement 3... case expression n: statement m-1 default: statement m Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 33 SWITCH (Cont.) expression is evaluated expression 1 to expression n must represent constant, integer-valued expressions: either an integer constant or a character constant. control is transfered, to the first expression that matches expression if the statement does not contain a break the statements following the matched expression are executed. Default case The case default matches any value of expression. Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 35 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 34 SWITCH : example Ask for a letter puts( Enter one letter for a color (RWB): ); char choice; choice = getchar(); switch(choice){ case r : case R : printf( RED ); case w : case W : printf( White ); case b : case B : printf( Blue ); default: printf( Not a valid color ); Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 36

The BREAK statement BREAK (Cont.) Is used to terminate a loop or exit from a SWITCH Can be used within for, while, do - while or switch (switch) case B : printf("blue"); with while int val, exponent; int i=0; int res = 1; puts("type value and exponent:"); scanf(" %d %d",&val,&exponent); while(1){ if(i++ == exponent){ res *= val; printf("%d power %d = %d\n",val,exponent,res); Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 37 The CONTINUE statement Is used to bypass the remainder of the current pass throug a loop The loop does not terminate The remaining loop statements are skipped and the computation proceeds to the next pass through the loop BREAK: go out of loop CONTINUE: go to the next pass of the loop for(i=0; i< 10; i++){ puts("type a number:"); scanf("%d",&val); if(val<0){ /* A negative number does not have a sqrt*/ continue; double res = sqrt(val*1.0); printf("square root of %d is %lg\n",val,res); Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 38 The GOTO statement Very simplar to JMP in Assembly Go from one place to a label Label must be in the same function (we see functions next week) The label must be unique inside the function goto label and somewhere else in function label: statement Take care not to allow to go into label Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 39 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 40

: GOTO Goto error message if an error occures for(i=0; i< 10; i++){ puts("type a number:"); scanf("%d",&val); if(val<0){ /* A negative number does not have a sqrt*/ goto errornegativenumber; double res = sqrt(val*1.0); printf("square root of %d is %lg\n",val,res); return; errornegativenumber:{ printf("negative number do not have any root"); Conclusion Input and Output Read a string, parse it Print out formated output More about files and other functions later Control statement Similar to Java Some controls are low level SWITCH (with integers) GOTO (similar to assembly language) Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 41 Bibliography Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 42 This course corresponds to chapters 4, (5) and 6 of the course book: Schaum s OuTlines, Programming with C (second edition), Byron Gottfied, Mc Graw-Hill, 1996 Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 43