Assoc. Prof. Dr. Tansu FİLİK

Size: px
Start display at page:

Download "Assoc. Prof. Dr. Tansu FİLİK"

Transcription

1 Assoc. Prof. Dr. Tansu FİLİK

2 Previously on Bil 200 Operators Logical and arithmetic operators Control Structures if-else mechanism

3 Low-level I/O They are fast! Might be useful for console applications. But they are a little bit difficult to use properly because of the strange behavior of console stream (keyboard buffer).

4 Low-level I/O - getchar getchar ( ) ; This is a primitive function used for entering a single character. char az; az = getchar ( );

5 Low-level I/O - putchar putchar ( ) ; This is a primitive function used for writing a character. char az; az = getchar ( ); putchar( az );

6 Low-level I/O char c1, c2, c3; c1= g ; c2= < ; c3= \n ; printf( %c%c%c,c1,c2,c3); putchar(c1); putchar(c2); putchar(c3);... > > g< >

7 ... printf( Type 2 characters and press enter: ); scanf( %c%c,&c1,&c2); putchar(c1); putchar(c2); printf( \ntype 2 characters and press enter: ); getchar();/*why? Try without this*/ c1=getchar(); c2=getchar(); /*We read 3 chars from buffer*/ putchar(c1); putchar(c1); Getchar functions do not start execution before an <enter> is pressed.

8 Run: xp<enter> (Type x and p, press enter) Memory block: x p \n Now 2 more getchar() read 2 characters from buffer: x p \n Keyboard buffer position is here! vs<enter> (Type v and s, press enter) Memory block: x p \n v s \n

9 In this position, if we read two more characters: a=getchar(); b=getchar(); x p \n v s \n Caution: You may think that we first read x and p, then v and s. But the last two characters would be <enter> and v! If you read two more chars, they would be s and <enter>! In order to free keyboard buffer after reading (to eliminate <enter> effects, use fflush(stdin).

10 ... printf( \ntype 2 characters and press enter: ); fflush(stdin); /* What?? */ c1=getche(); /* Try with getch() */ c2=getche(); putchar(c1); putchar(c2); /* Works faster than printf( %c%c,c1,c2); and takes less memory */

11 getc() getc ( *file ) ; This function, resembles getchar(), but this one can read from a file, too. char ch; ch = getc (stdin) ; /* input from keyboard */ ch = getc (fileptr) ;/* input from file */

12 putc() putc ( char, *file ) ; This function resembles putchar ( ), but it can write to files, too. char ch; ch = getc (stdin) ; /* read from keyboard */ putc (ch, stdout) ; /* write to screen */ putc (ch, fileptr) ; /* write to file */

13 Control Structures if-else mechanism

14 Control structures: if-else mechanism if else if else Multiple if-else statements can be used as: if (this logical expression1 is true ) statement1 ; else if (this logical expression2 is true ) statement2 ; else if (this logical expression3 is true ) statement3 ; else statement4 ;

15 Control structures: if-else mechanism Example: Number comparison #include <stdio.h> void main ( ) { int a, b ; printf ("a ve b için değer girin ") ; scanf ("%d %d", &a, &b ) ; if ( a < b ) printf ("a küçüktür b'den\n") ; else if ( a = = b ) printf (" a b'ye eşittir\n") ; else printf ("a, b'den büyüktür\n") ;

16 Control structures: if-else mechanism Nested if statements If-else does not have to be regularly listed. The C compiler matches an else statement to the nearest if statement. You have to be careful about logical construction of the program, and using { parentheses. if (nem < 20) if (sicaklik <= 0) printf("soğuk ve kuru bir gün."); if (ruzgar < 10) printf("ne güzel, rüzgar yok"); else printf("nem düşük ve 0 dereceden yüksek"); else if (nem < 60) if (sicaklik <= 0) printf("soguk ve orta nemli."); else printf("0'dan büyük, orta nem oranı.");

17 Introduction to Programming Languages Control structures: if-else mechanism

18 Introduction to Programming Languages Control structures: if-else mechanism

19 Control structures: if-else mechanism Short-cut comparison: sonuc=(condition)? (true statement) : (false statement); Boolean expression if if output else output

20 Control structures: if-else mechanism Short-cut comparison: float diff1,diff2, min, x1=100.0, x2=90.0, x3=10.0; diff1=(x1>x2)? (x1-x2) : (x2-x1); min=(x1>x2)? ( (x2>x3)? x3 : x2 ) : ( (x1>x3)? x3 : x1 )

21 Control structures: switch case structure switch case structure Multiple choice menu selection

22 Control structures: switch case structure Inside an algorithm, if there are more than two possible values of a variable according to which the program will flow, multiple menu selection is the appropriate mechanism. In the algorithm, each different value will invoke a different set of commands. Similar to a list of if-else statements, we have the switch-case structure which is suitable for this.

23 Control structures: switch case structure Layout: switch ( integer test variable ) { case value1 : commands ; case value2 : commands ; case value3 : commands ; default : commands ;

24 Control structures: switch case structure switch phrase shows the beginning of the structure (using something like goto label). It works with integers only. All values in case parts must be integer values. Remember that char and long int are also integers. There must be constant values in case parts. Do not put expressions there. There is no need for { after case.

25 Control structures: switch case structure In if-else-if-else-if-else... style, the if part works until the else or. Conversely, once a case is true, all the lines after the case line gets executed. switch(variable) { case 0: case 1: printf("merhaba\n"); printf("%d\n", degisken); scanf("%f", &a); printf("hello\n");...

26 switch case structure - Example Write a program which reads individual letter grades of a student. Consequently, it will display the following corresponding messages: A: "Çok güzel" B: "Güzel" C: "Fena Değil" D: "İyi değil" F: "Çok kötü" Write the program both with if-else, and switchcase.

27 switch case structure - Example Algorithm Print "Notunuzu giriniz" Read not switch(not) { case 'A': yaz "Çok güzel" case 'B': yaz "güzel" case 'C': yaz "fena değil" case 'D': yaz "iyi değil" case 'F': yaz "kötü" #include <stdio.h> void main ( ) { Solution Code char not ; printf ("Notunuzu girin:") ; not = getchar ( ) ; switch(not) { case 'A': printf("çok güzel\n"); case 'B': printf("güzel\n"); case 'C': printf("fena değil\n"); case 'D': printf("iyi değil\n"); case 'F': printf("kötü\n");

28 switch case structure - Example Program Output While running the program, if you enter A, the output is as follows: Çok güzel güzel fena değil iyi değil Kötü What is wrong here? switch(not) { case 'A': printf("çok güzel\n"); case 'B': printf("güzel\n"); case 'C': printf("fena değil\n"); case 'D': printf("iyi değil\n"); case 'F': printf("kötü\n");

29 switch case structure - Example Correction The errors in the program must be eliminated by using a control statement which skips all cases after a case is selected. We use "break". Break goes out of the structure when encountered. The structures include loops, nested loops, switch-cases, etc. It goes out of the next or the next control statement. Usage: break;

30 switch case structure - Example Correction Codes switch(not) { case 'A': printf("çok güzel\n"); break; case 'B': printf("güzel\n"); break; case 'C': printf("fena değil\n"); break; case 'D': printf("iyi değil\n"); break; case 'F': printf("kötü\n"); While running the program, if you enter A, the output is as follows: Çok güzel

31 Control structures: switch case structure Schematic layout true case a case a action(s) break true case b case b action(s) break... false false true case z case z action(s) break false default action(s)

32 switch case structure - Example switch(val) { case 1: case 3: case 5: printf( Tek sayi\n ); break; case 2: case 4: case 6: printf( Cift sayi\n ); break; default: printf( Sayi 1 6 arasinda degil. ); Deliberately missed breaks

33 switch case structure - Exercise The meteorology department wishes to write a program to convert numerical humidity values into meaningful English words. The user enters numbers between 0 and 100 to indicate humidity rate. The following rule converts the rate into words. The program must output the corresponding words. 20% or less Too dry" 21% - 40%: Dry" 41% - 60%: Moderately dry" 61% - 80%: Moderately humid" 81% or more: Humid" Write a program which asks user the humidity rate and writes the words using switch-case structures.

34 Control structures: switch case structure Notes on Switch Case Do not use double or float variables in switch. Only integers are used. After the case label, use as many statements as you can. Using the default: label is helpful in finding the logical mistakes of the program. The most common mistake is forgetting break. Be careful about this (as long as you do not deliberately take it out).

35 Control structures: Loops while, do-while, for loops

36 Control structures: Loops Repeat structures Repeat structures cause the code blocks to re-run. The re-run condition is decided according to the truth of a condition expression. There are number counting loops (for) for running the loop a number of times, or while or do-while types of loops which re-run as long as something is true.

37 Control structures: Loops Repeat structures for and while loops check the truth of a logical expression before entering the loop. do-while loop first enters the loop, and then checks whether a condition is true or not to re-run.

38 Control structures: Loops while loop Similar to if, it can be used in two ways: while ( true logical expression ) statement ; while (true logical expression) { statement1 ; statement2 ; Unlike if, it not only works for once if expression is true, but it works as long as expression stays true..

39 Control structures: Loops while loop examples: #include <stdio.h> main() { int i = 10; while ( i > 0 ) { printf("hello %d\n", i ); i = i -1; #include <stdio.h> Hello 10 Hello 9 Hello 8 Hello 7 Hello 6 Hello 5 Hello 4 Hello 3 Hello 2 Hello 1 main() { int i = 0; do { printf("hello %d\n", i ); i = i -1; while (i > 0)

40 Control structures: Loops #include <stdio.h> void main ( ) { int not ; not = -1 ; while (not!= 0) { printf ("sınav sonucu : >") ; scanf ("%d", &not) ; if (not >= 90) printf ("Notunuz[%d]=A\n", not) ; else if (not >= 80) printf ("Notunuz[%d]=B\n", not) ; else if (not >= 70) printf ("Notunuz[%d]=C\n", not) ; else if (not >= 60) printf ("Notunuz[%d]=D\n", not) ; else if (not!= 0) printf ("Notunuz[%d]=F\n", not) ; else printf ("Çıkıyoruz\n\n") ;

41 Control structures: Loops while loop Exercise: Write program find guessed number that asks user to input numbers until the user determines the number of the computer. Program must guide user by saying less and more.

42 Control structures: Loops do-while loop do statement; while ( true logical expression ); do { statement1 ; statement2 ; while ( true logical expression );

43 Control structures: Loops #include <stdio.h> void main ( ) { int not; do { printf ("sınav sonucu : >") ; scanf ("%d", &not) ; if (not >= 90) printf ("Notunuz[%d]=A\n", not) ; else if (not >= 80) printf ("Notunuz[%d]=B\n", not) ; else if (not >= 70) printf ("Notunuz[%d]=C\n", not) ; else if (not >= 60) printf ("Notunuz[%d]=D\n", not) ; else if (not!= 0) printf ("Notunuz[%d]=F\n", not) ; else printf ("Çıkıyoruz\n\n") ; while (not!= 0)

44 Control structures: Loops for loop (generic) A disturbingly general loop structure. statement and expression can be anything. The whole program, no matter how ridiculous, can be written inside a single for loop.

45 Control structures: Loops for loop for( initial statements;logical expression;updates) { statements; initial statements can be used as the first commands and assignments before running the loop. These statements work only for once. You can use several statements separated by,.

46 Control structures: Loops for loop for( initial statements;logical expression;updates) { statements; updates get executed after the statements in the block are executed. There may be several updates separated by,.

47 Control structures: Loops for loop for( initial statements;logical expression;updates) { statements; After the updates, the logical expression is checked. If it is true, the loop continues.

48 Control structures: Loops for loop for (statement1;statement2;statement3) { statements ; statement1 initializes the for loop. It may be a mathematical assignment, or several commands. It runs only once.

49 Control structures: Loops for loop for (statement1;statement2;statement3) { statements ; statement2 checks for the truth of an expression. That expression can be anything that determines the continuity or stop condition.

50 Control structures: Loops for loop for (statement1;statement2;statement3) { statements ; statement3 makes the final changes to the control variables. These changes and variables can be completely different than the ones in statement1, or the body statements.

51 int gun, saat, dakika; for(gun=1; gun<=3; gun++) printf( gun=%d\n,gun); for(saat=5; saat>2; saat--) { dakika=60*saat; printf( S:%d D:%d\n,saat,dakika);

52 Control structures: Loops for loop : Notes for is an extremely flexible structure. The statement1-3 parts may be completely empty, leaving everything inside the body. Yet, do not forget to use ;. Skipping the first and third statements actually turn the for loop into a while loop. Without the second statement (in the middle), you cannot determine when to terminate the loop. In this case, you must use break somewhere inside the body to check for a termination situation. The first and third statements can contain multiple commands. Using such a style, you can write single line for loops, even without a body part.

53 Control structures: Loops for loop : Example for(;;) { < - > printf( Bir sayi girin (çıkış için 0): ); scanf( %d,&number); if(number==0) break; for(number=1;number!=0;) { printf( Bir sayi girin (çıkış için 0): ); scanf( %d,&number); < - > for(number=1;number!=0; printf( Bir sayi girin (çıkış için 0): ),scanf( %d,&number));

54 Control structures: Loops for while statement1 ; while ( expression2 ) { statements ; statement3 ; for ( statement1;expression2;statement3 ) { statements ;

55 Control structures: Loops for loops : Example #include <stdio.h> void main ( ) { int k, n ; for( k = 1, n = 12 ; k<9 && n>6 ; k++, n--) { printf ("k=%d, n=%d\n", k, n ) ;

56 Control structures: Loops Exercises: What is the value of x when the following statement is complete? for (x = 0 ; x < 100 ; x++) ; What is the value of ctr when the following statement is complete? for (ctr = 2 ; ctr < 10 ; ctr += 3) ; How many X s does the following print? for (x = 0; x < 10; x++) for (y = 5; y > 0; y--) printf("x");

57 Control structures: Loops Loop termination The keyword break can be used for terminating the loop. If the loop is nested, it terminates the current block. The keyword continue is used for skipping until the end of the loop block, but the block does not terminate. Depending on the algorithm, you may use combinations of these keywords.

58 Control structures: Loops Loop termination: break: exit loop In the following program, break causes the loop to finish when value of x becomes 5. void main() { int x = 0; for( ; ; ) { /* infinite loop */ if(x == 5) break; printf("x = %d\n", x); x++;

59 Control structures: Loops Example: Nested for loops Consider formula: x 2 + y 2 = z 2. Here, x, y, and z are integers. As an example, for 3,4,5 triangle, = 5 2. We wish to obtain others. Brute force method: We may check all integer x-y couples and see if an integer z can be obtained.

60 Control structures: Loops Example: Nested for loops #include <stdio.h> #define N 20 void main(void) { int i,j,k, karetoplam; for (i=1; i <= N; i++) { for (j=1; j <= N; j++) { karetoplam = i * i + j * j; /* x2 + y2 */ /* is there a suitable z for the x and y? */ for(k = 1 ; k <= N; k++ ) { if (karetoplam == k * k) { printf("%5d %5d %5d\n", i, j, k);

61 Control structures: Loops Example: Nested for loops

62 Control structures: Loops Exercises: Can you write the previous program using only two nested loops? Think of a way to eliminate repetitions in the loop. In this way, once is determined, the program will not output

63 Control structures: Loops Exercises: Write a program in which you can enter a string into a string variable using for loop and getchar. Whenever an enter is pressed, the new string must be available for printing with printf( %s,..). Find a simple program that converts lowercase letters to uppercase ones inside a string. Do not use long lists of if-else or switch-case. Do not use ready C functions either. You do not need to know ASCII codes of letter, either. Be smart.

Assoc. Prof. Dr. Tansu FİLİK

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Previously on Bil 200 Low-Level I/O getchar, putchar, getc, putc Control Structures if-else, switch-case, loops (while, dowhile, for loops) for loop (generic) A disturbingly

More information

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries

Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Computer Programming 5th Week loops (do-while, for), Arrays, array operations, C libraries Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil 200 Low-Level I/O getchar, putchar,

More information

Computer Programming 3 th Week Variables, constant, and expressions

Computer Programming 3 th Week Variables, constant, and expressions 3 th Week Variables, constant, and expressions Hazırlayan Asst. Prof. Dr. Tansu Filik Previously on Bil 200 Unitary operations (applied to single variable, +.-,++,--) Type casting Operation/Operator precedence

More information

Assoc. Prof. Dr. Tansu FİLİK

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Midterm Exam - 1 Midterm Exam - 1 126 students Curve: 49,78 Computer Programming Arrays Arrays List of variables: [ ] Computer Programming

More information

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

Chapter 2. Section 2.5 while Loop. CS 50 Hathairat Rattanasook Chapter 2 Section 2.5 while Loop CS 50 Hathairat Rattanasook Loop Iteration means executing a code segment more than once. A loop is an iterative construct. It executes a statement 0..n times while a condition

More information

Assoc. Prof. Dr. Tansu FİLİK

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Computer Programming Previously on Bil 200 Introduction to pointers String (character array) Static and automatic variables static and automatic variables, and scope Rem: Static

More information

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

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code CS102: Standard I/O Our next topic is standard input and standard output in C. The adjective "standard" when applied to "input" or "output" could be interpreted to mean "default". Typically, standard output

More information

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010

Computer Programming: Skills & Concepts (CP1) Files in C. 18th November, 2010 Computer Programming: Skills & Concepts (CP1) Files in C 18th November, 2010 CP1 26 slide 1 18th November, 2010 Today s lecture Character oriented I/O (revision) Files and streams Opening and closing files

More information

Computer Programming: Skills & Concepts (CP) Files in C

Computer Programming: Skills & Concepts (CP) Files in C CP 20 slide 1 Tuesday 21 November 2017 Computer Programming: Skills & Concepts (CP) Files in C Julian Bradfield Tuesday 21 November 2017 Today s lecture Character oriented I/O (revision) Files and streams

More information

LESSON 4. The DATA TYPE char

LESSON 4. The DATA TYPE char LESSON 4 This lesson introduces some of the basic ideas involved in character processing. The lesson discusses how characters are stored and manipulated by the C language, how characters can be treated

More information

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch

Flow of Control. Selection. if statement. True and False in C False is represented by any zero value. switch Flow of Control True and False in C Conditional Execution Iteration Nested Code(Nested-ifs, Nested-loops) Jumps 1 True and False in C False is represented by any zero value The int expression having the

More information

Assoc. Prof. Dr. Tansu FİLİK

Assoc. Prof. Dr. Tansu FİLİK Assoc. Prof. Dr. Tansu FİLİK Bil 200 Week -2 Previously on Bil 200 Programming Languages (Machine Code, Assembly code, high-level languages) Compiler (translator) Software development (components of algorithm)

More information

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

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University Unit 1 Programming Language and Overview of C 1. State whether the following statements are true or false. a. Every line in a C program should end with a semicolon. b. In C language lowercase letters are

More information

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

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath UNIT - I Introduction to C Programming Introduction to C C was originally developed in the year 1970s by Dennis Ritchie at Bell Laboratories, Inc. C is a general-purpose programming language. It has been

More information

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment. Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special

More information

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 07: Data Input and Output Readings: Chapter 4 Input /Output Operations A program needs

More information

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

The C Programming Language Part 2. (with material from Dr. Bin Ren, William & Mary Computer Science) The C Programming Language Part 2 (with material from Dr. Bin Ren, William & Mary Computer Science) 1 Overview Input/Output Structures and Arrays 2 Basic I/O character-based putchar (c) output getchar

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture 04 Programs with IO and Loop We will now discuss the module 2,

More information

Control Structure: Selection

Control Structure: Selection Control Structure: Selection Knowledge: Understand various concepts of selection control structure Skill: Be able to develop a program containing selection control structure Selection Structure Single

More information

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

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

Chapter 5: Control Structures

Chapter 5: Control Structures Chapter 5: Control Structures In this chapter you will learn about: Sequential structure Selection structure if if else switch Repetition Structure while do while for Continue and break statements S1 2017/18

More information

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode STUDENT OUTLINE Lesson 8: Structured Programming, Control Structures, if- Statements, Pseudocode INTRODUCTION: This lesson is the first of four covering the standard control structures of a high-level

More information

WARM UP LESSONS BARE BASICS

WARM UP LESSONS BARE BASICS WARM UP LESSONS BARE BASICS CONTENTS Common primitive data types for variables... 2 About standard input / output... 2 More on standard output in C standard... 3 Practice Exercise... 6 About Math Expressions

More information

Tail recursion. Decision. Assignment. Iteration

Tail recursion. Decision. Assignment. Iteration Computer Programming Tail recursion. Decision. Assignment. Iteration Marius Minea marius@cs.upt.ro 7 October 2014 Two ways of writing recursion unsigned max(unsigned a, unsigned b) { return a > b? a :

More information

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

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information Laboratory 2: Programming Basics and Variables Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information 3. Comment: a. name your program with extension.c b. use o option to specify

More information

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur Lecture 18 Switch Statement (Contd.) And Introduction to

More information

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

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 Overview The C Programming Language Part 2 Input/Output Structures and Arrays (with material from Dr. Bin Ren, William & Mary Computer Science) 1 2 character-based putchar (c) output getchar () input formatted

More information

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

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2 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 information

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

C Program. Output. Hi everyone. #include <stdio.h> main () { printf ( Hi everyone\n ); } C Program Output #include main () { printf ( Hi everyone\n ); Hi everyone #include main () { printf ( Hi everyone\n ); #include and main are Keywords (or Reserved Words) Reserved Words

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

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

sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ; INPUT AND OUTPUT IN C Function: printf() library: sends the formatted data to the standard output stream (stdout) int printf ( format_string, argument_1, argument_2,... ) ; format_string it is

More information

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:

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: Q1. Explain the structure of a C program Structure of the C program is shown below: Preprocessor Directives Global Declarations Int main (void) Local Declarations Statements Other functions as required

More information

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

CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting CpSc 1111 Lab 4 Part a Flow Control, Branching, and Formatting Your factors.c and multtable.c files are due by Wednesday, 11:59 pm, to be submitted on the SoC handin page at http://handin.cs.clemson.edu.

More information

C: How to Program. Week /Mar/05

C: How to Program. Week /Mar/05 1 C: How to Program Week 2 2007/Mar/05 Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers

More information

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

C Fundamentals & Formatted Input/Output. adopted from KNK C Programming : A Modern Approach C Fundamentals & Formatted Input/Output adopted from KNK C Programming : A Modern Approach C Fundamentals 2 Program: Printing a Pun The file name doesn t matter, but the.c extension is often required.

More information

The Design of C: A Rational Reconstruction: Part 2

The Design of C: A Rational Reconstruction: Part 2 The Design of C: A Rational Reconstruction: Part 2 1 Continued from previous lecture 2 Agenda Data Types Operators Statements I/O Facilities 3 Operators Issue: What kinds of operators should C have? Thought

More information

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions. Introduction In the programs that we have dealt with so far, all statements inside the main function were executed in sequence as they appeared, one after the other. This type of sequencing is adequate

More information

Continued from previous lecture

Continued from previous lecture The Design of C: A Rational Reconstruction: Part 2 Jennifer Rexford Continued from previous lecture 2 Agenda Data Types Statements What kinds of operators should C have? Should handle typical operations

More information

Computer Programming 6th Week Functions (Function definition, function calls),

Computer Programming 6th Week Functions (Function definition, function calls), Computer Programming 6th Week Functions (Function definition, function calls), Hazırlayan Asst. Prof. Dr. Tansu Filik Computer Programming Previously on Bil-200 loops (do-while, for), Arrays, array operations,

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 3 Constants, Variables, Data Types, And Operations Department of Computer Engineering

More information

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

بسم اهلل الرمحن الرحيم بسم اهلل الرمحن الرحيم Fundamentals of Programming C Session # 10 By: Saeed Haratian Fall 2015 Outlines Examples Using the for Statement switch Multiple-Selection Statement do while Repetition Statement

More information

Euclid s algorithm, 133

Euclid s algorithm, 133 Index A Algorithm computer instructions, 4 data and variables, 5 develop algorithm, 6 American Standard Code for Information Interchange (ASCII) codes, 141 definition, 142 features, 142 Arithmetic expressions

More information

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files

CS113: Lecture 7. Topics: The C Preprocessor. I/O, Streams, Files CS113: Lecture 7 Topics: The C Preprocessor I/O, Streams, Files 1 Remember the name: Pre-processor Most commonly used features: #include, #define. Think of the preprocessor as processing the file so as

More information

Chapter 2 - Introduction to C Programming

Chapter 2 - Introduction to C Programming Chapter 2 - Introduction to C Programming 2 Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic

More information

Decision Making -Branching. Class Incharge: S. Sasirekha

Decision Making -Branching. Class Incharge: S. Sasirekha Decision Making -Branching Class Incharge: S. Sasirekha Branching The C language programs presented until now follows a sequential form of execution of statements. Many times it is required to alter the

More information

Introduction to C Programming

Introduction to C Programming 1 2 Introduction to C Programming 2.6 Decision Making: Equality and Relational Operators 2 Executable statements Perform actions (calculations, input/output of data) Perform decisions - May want to print

More information

More examples for Control statements

More examples for Control statements More examples for Control statements C language possesses such decision making capabilities and supports the following statements known as control or decision-making statements. 1. if statement 2. switch

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 5 Structured Program Development Department of Computer Engineering How to develop

More information

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

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers

Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers Computer Programming: 7th Week Functions, Recursive Functions, Introduction to Pointers Hazırlayan Asst. Prof. Dr. Tansu Filik Introduction to Programming Languages Previously on Bil-200 Functions: Function

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 5 - Structured Program Development Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad How to develop a program? Requirements Problem Analysis

More information

Presented By : Gaurav Juneja

Presented By : Gaurav Juneja Presented By : Gaurav Juneja Introduction C is a general purpose language which is very closely associated with UNIX for which it was developed in Bell Laboratories. Most of the programs of UNIX are written

More information

Multiple Choice Questions ( 1 mark)

Multiple Choice Questions ( 1 mark) Multiple Choice Questions ( 1 mark) Unit-1 1. is a step by step approach to solve any problem.. a) Process b) Programming Language c) Algorithm d) Compiler 2. The process of walking through a program s

More information

ROCK PAPER SCISSORS Rock Paper Scissors Lab Project Using C or C++

ROCK PAPER SCISSORS Rock Paper Scissors Lab Project Using C or C++ ROCK PAPER SCISSORS Rock Paper Scissors Lab Project Using C or C++ Copyright 2014 Dan McElroy Project Definition Truth Tables Topics Covered Keyboard Character Input (C and C++) Converting Characters to

More information

Iteration. Side effects

Iteration. Side effects Computer programming Iteration. Side effects Marius Minea marius@cs.upt.ro 17 October 2017 Assignment operators We ve used the simple assignment: lvalue = expression lvalue = what can be on the left of

More information

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead. Chapter 9: Rules Chapter 1:Style and Program Organization Rule 1-1: Organize programs for readability, just as you would expect an author to organize a book. Rule 1-2: Divide each module up into a public

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

Standard I/O in C and C++

Standard I/O in C and C++ Introduction to Computer and Program Design Lesson 7 Standard I/O in C and C++ James C.C. Cheng Department of Computer Science National Chiao Tung University Standard I/O in C There three I/O memory buffers

More information

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes

CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes CpSc 1011 Lab 5 Conditional Statements, Loops, ASCII code, and Redirecting Input Characters and Hurricanes Overview For this lab, you will use: one or more of the conditional statements explained below

More information

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA

7/21/ FILE INPUT / OUTPUT. Dong-Chul Kim BioMeCIS UTA 7/21/2014 1 FILE INPUT / OUTPUT Dong-Chul Kim BioMeCIS CSE @ UTA What s a file? A named section of storage, usually on a disk In C, a file is a continuous sequence of bytes Examples for the demand of a

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 3 - Constants, Variables, Data Types, And Operations Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline C Program Data types Variables

More information

University of California San Diego Department of Electrical and Computer Engineering. ECE 15 Midterm Exam

University of California San Diego Department of Electrical and Computer Engineering. ECE 15 Midterm Exam University of California San Diego Department of Electrical and Computer Engineering ECE 15 Midterm Exam Tuesday, February 17, 2015 12:30 p.m. 1:50 p.m. Room 109, Pepper Canyon Hall Name Class Account:

More information

Strings. Daily Puzzle

Strings. Daily Puzzle Lecture 20 Strings Daily Puzzle German mathematician Gauss (1777-1855) was nine when he was asked to add all the integers from 1 to 100 = (1+100)+(2+99)+... = 5050. Sum all the digits in the integers from

More information

Fundamentals of Programming

Fundamentals of Programming Fundamentals of Programming Lecture 4 Input & Output Lecturer : Ebrahim Jahandar Borrowed from lecturer notes by Omid Jafarinezhad Outline printf scanf putchar getchar getch getche Input and Output in

More information

THE FUNDAMENTAL DATA TYPES

THE FUNDAMENTAL DATA TYPES THE FUNDAMENTAL DATA TYPES Declarations, Expressions, and Assignments Variables and constants are the objects that a prog. manipulates. All variables must be declared before they can be used. #include

More information

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

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University ITC213: STRUCTURED PROGRAMMING Bhaskar Shrestha National College of Computer Studies Tribhuvan University Lecture 08: Control Statements Readings: Chapter 6 Control Statements and Their Types A control

More information

CSE 5A Introduction to Programming I (C) Homework 4

CSE 5A Introduction to Programming I (C) Homework 4 CSE 5A Introduction to Programming I (C) Homework 4 Read Chapter 7 Due: Friday, October 26 by 6:00pm All programming assignments must be done INDIVIDUALLY by all members of the class. Start early to ensure

More information

Fundamental of Programming (C)

Fundamental of Programming (C) Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi CE 43 - Fall 97 Lecture 4 Input and Output Department of Computer Engineering Outline printf

More information

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

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

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

UNIT IV-2. The I/O library functions can be classified into two broad categories:

UNIT IV-2. The I/O library functions can be classified into two broad categories: UNIT IV-2 6.0 INTRODUCTION Reading, processing and writing of data are the three essential functions of a computer program. Most programs take some data as input and display the processed data, often known

More information

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

CSE 1001 Fundamentals of Software Development 1. Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 CSE 1001 Fundamentals of Software Development 1 Identifiers, Variables, and Data Types Dr. H. Crawford Fall 2018 Identifiers, Variables and Data Types Reserved Words Identifiers in C Variables and Values

More information

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng Slide Set 2 for ENCM 335 in Fall 2018 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary September 2018 ENCM 335 Fall 2018 Slide Set 2 slide

More information

BSM540 Basics of C Language

BSM540 Basics of C Language BSM540 Basics of C Language Chapter 4: Character strings & formatted I/O Prof. Manar Mohaisen Department of EEC Engineering Review of the Precedent Lecture To explain the input/output functions printf()

More information

Structured programming

Structured programming Exercises 2 Version 1.0, 22 September, 2016 Table of Contents 1. Simple C program structure................................................... 1 2. C Functions..................................................................

More information

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from

INTRODUCTION TO C++ PROGRAM CONTROL. Dept. of Electronic Engineering, NCHU. Original slides are from INTRODUCTION TO C++ PROGRAM CONTROL Original slides are from http://sites.google.com/site/progntut/ Dept. of Electronic Engineering, NCHU Outline 2 Repetition Statement for while do.. while break and continue

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

C-LANGUAGE CURRICULAM

C-LANGUAGE CURRICULAM C-LANGUAGE CURRICULAM Duration: 2 Months. 1. Introducing C 1.1 History of C Origin Standardization C-Based Languages 1.2 Strengths and Weaknesses Of C Strengths Weaknesses Effective Use of C 2. C Fundamentals

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Fundamentals of Programming Session 8

Fundamentals of Programming Session 8 Fundamentals of Programming Session 8 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

Data Types. Data Types. Integer Types. Signed Integers

Data Types. Data Types. Integer Types. Signed Integers Data Types Data Types Dr. TGI Fernando 1 2 The fundamental building blocks of any programming language. What is a data type? A data type is a set of values and a set of operations define on these values.

More information

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

Overview of C, Part 2. CSE 130: Introduction to Programming in C Stony Brook University Overview of C, Part 2 CSE 130: Introduction to Programming in C Stony Brook University Integer Arithmetic in C Addition, subtraction, and multiplication work as you would expect Division (/) returns the

More information

Data Type Fall 2014 Jinkyu Jeong

Data Type Fall 2014 Jinkyu Jeong Data Type Fall 2014 Jinkyu Jeong (jinkyu@skku.edu) 1 Syntax Rules Recap. keywords break double if sizeof void case else int static... Identifiers not#me scanf 123th printf _id so_am_i gedd007 Constants

More information

Question 1. Part (a) [2 marks] error: assignment of read-only variable x ( x = 20 tries to modify a constant) Part (b) [1 mark]

Question 1. Part (a) [2 marks] error: assignment of read-only variable x ( x = 20 tries to modify a constant) Part (b) [1 mark] Note to Students: This file contains sample solutions to the term test together with the marking scheme and comments for each question. Please read the solutions and the marking schemes and comments carefully.

More information

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

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are: LESSON 1 FUNDAMENTALS OF C The purpose of this lesson is to explain the fundamental elements of the C programming language. C like other languages has all alphabet and rules for putting together words

More information

Storage class and Scope:

Storage class and Scope: Algorithm = Logic + Control + Data Data structures and algorithms Data structures = Ways of systematically arranging information, both abstractly and concretely Algorithms = Methods for constructing, searching,

More information

Lecture 6. Statements

Lecture 6. Statements Lecture 6 Statements 1 Statements This chapter introduces the various forms of C++ statements for composing programs You will learn about Expressions Composed instructions Decision instructions Loop instructions

More information

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15

Day14 A. Young W. Lim Tue. Young W. Lim Day14 A Tue 1 / 15 Day14 A Young W. Lim 2017-12-26 Tue Young W. Lim Day14 A 2017-12-26 Tue 1 / 15 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-12-26 Tue 2 / 15 Based

More information

Data types, variables, constants

Data types, variables, constants Data types, variables, constants Outline 2.1 Introduction 2.2 A Simple C Program: Printing a Line of Text 2.3 Another Simple C Program: Adding Two Integers 2.4 Memory Concepts 2.5 Arithmetic in C 2.6 Decision

More information

ECET 264 C Programming Language with Applications. C Program Control

ECET 264 C Programming Language with Applications. C Program Control ECET 264 C Programming Language with Applications Lecture 7 C Program Control Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Lecture 7 - Paul I. Lin

More information

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

2/29/2016. Definition: Computer Program. A simple model of the computer. Example: Computer Program. Data types, variables, constants Data types, variables, constants Outline.1 Introduction. Text.3 Memory Concepts.4 Naming Convention of Variables.5 Arithmetic in C.6 Type Conversion Definition: Computer Program A Computer program is a

More information

Programming for Engineers Introduction to C

Programming for Engineers Introduction to C Programming for Engineers Introduction to C ICEN 200 Spring 2018 Prof. Dola Saha 1 Simple Program 2 Comments // Fig. 2.1: fig02_01.c // A first program in C begin with //, indicating that these two lines

More information

Other Loop Options EXAMPLE

Other Loop Options EXAMPLE C++ 14 By EXAMPLE Other Loop Options Now that you have mastered the looping constructs, you should learn some loop-related statements. This chapter teaches the concepts of timing loops, which enable you

More information

PROGRAMMING IN HASKELL. Chapter 10 - Interactive Programming

PROGRAMMING IN HASKELL. Chapter 10 - Interactive Programming PROGRAMMING IN HASKELL Chapter 10 - Interactive Programming 0 Introduction To date, we have seen how Haskell can be used to write batch programs that take all their inputs at the start and give all their

More information

Introduction. C provides two styles of flow control:

Introduction. C provides two styles of flow control: Introduction C provides two styles of flow control: Branching Looping Branching is deciding what actions to take and looping is deciding how many times to take a certain action. Branching constructs: if

More information

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14

Day14 A. Young W. Lim Thr. Young W. Lim Day14 A Thr 1 / 14 Day14 A Young W. Lim 2017-11-02 Thr Young W. Lim Day14 A 2017-11-02 Thr 1 / 14 Outline 1 Based on 2 C Strings (1) Characters and Strings Unformatted IO Young W. Lim Day14 A 2017-11-02 Thr 2 / 14 Based

More information

Computers Programming Course 7. Iulian Năstac

Computers Programming Course 7. Iulian Năstac Computers Programming Course 7 Iulian Năstac Recap from previous course Operators in C Programming languages typically support a set of operators, which differ in the calling of syntax and/or the argument

More information

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

n Group of statements that are executed repeatedly while some condition remains true Looping 1 Loops n Group of statements that are executed repeatedly while some condition remains true n Each execution of the group of statements is called an iteration of the loop 2 Example counter 1,

More information

BİL200 TUTORIAL-EXERCISES Objective:

BİL200 TUTORIAL-EXERCISES Objective: Objective: The purpose of this tutorial is learning the usage of -preprocessors -header files -printf(), scanf(), gets() functions -logic operators and conditional cases A preprocessor is a program that

More information