Introduction to C Programming II & Formatted Input/Output Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.

Slides:



Advertisements
Similar presentations
Character Arrays (Single-Dimensional Arrays) A char data type is needed to hold a single character. To store a string we have to use a single-dimensional.
Advertisements

Dale Roberts Basic I/O – printf() CSCI 230 Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Department of.
Lecture 2 Introduction to C Programming
1 Lecture 7  Fundamental data types in C  Data type conversion:  Automatic  Casting  Character processing  getchar()  putchar()  Macros on ctype.h.
1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
Chapter 9 Formatted Input/Output Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
 2007 Pearson Education, Inc. All rights reserved C Formatted Input/Output.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
C Formatted Input/Output /* Using Integer Conversion Specifiers */ #include int main ( ) { printf( "%d\n", 455 ); printf( "%i\n", 455 ); printf( "%d\n",
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Basic Elements of C++ Chapter 2.
C Programming. Chapter – 1 Introduction Study Book for one month – 25% Learning rate Use Compiler for one month – 60%
C - Input & Output When we are saying Input that means to feed some data into program. This can be given in the form of file or from command line. C programming.
CS 161 Introduction to Programming and Problem Solving Chapter 13 Console IO Herbert G. Mayer, PSU Status 9/8/2014 Initial content copied verbatim from.
Chapter 18 I/O in C. Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display Standard C Library I/O commands.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Streams Streams –Sequences of characters organized.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 9 - Formatted Input/Output Outline 9.1Introduction.
C Programming Lecture 3. The Three Stages of Compiling a Program b The preprocessor is invoked The source code is modified b The compiler itself is invoked.
CMPE13 Cyrus Bazeghi Chapter 18 I/O in C. CMPE Standard C Library I/O commands are not included as part of the C language. Instead, they are part.
Chapter 5: Data Input and Output Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills
1 IPC144 Session 11 The C Programming Language. 2 Objectives To format a #define statement correctly To use a #define statement in a C program To construct.
Chapter 9 Formatted Input/Output. Objectives In this chapter, you will learn: –To understand input and output streams. –To be able to use all print formatting.
Chapter 9 Formatted Input/Output Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
EPSII 59:006 Spring Introduction In this lecture  Formatted Input/Output scanf and printf  Streams (input and output) gets, puts, getchar, putchar.
Chapter 9 - Formatted Input/Output Outline 9.1Introduction 9.2Streams 9.3Formatting Output with printf 9.4Printing Integers 9.5Printing Floating-Point.
CP104 Introduction to Programming File I/O Lecture 33 __ 1 File Input/Output Text file and binary files File Input/output File input / output functions.
C Tokens Identifiers Keywords Constants Operators Special symbols.
Sales person receive RM200/week plus 9% of their gross sales for that week. Write an algorithms to calculate the sales person’s earning from the input.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Chapter 18 I/O in C.
Structure of a C program Preprocessor directive (header file) Program statement } Preprocessor directive Global variable declaration Comments Local variable.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Chapter-4 Managing input and Output operation.  Reading, processing and writing of data are three essential functions of a computer program.  Most programs.
Programming Fundamentals. Summary of previous lectures Programming Language Phases of C++ Environment Variables and Data Types.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
CCSA 221 Programming in C INPUT AND OUTPUT OPERATIONS IN C – PART 1 1.
Chapter 18 I/O in C Original slides from Gregory Byrd, North Carolina State University Modified slides by C. Wilcox, Y. Malaiya Colorado State University.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 2.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Pointers and Arrays Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
Chapter 9 - Formatted Input/Output
Chapter Topics The Basics of a C++ Program Data Types
Chapter 1.2 Introduction to C++ Programming
ECE Application Programming
Standard Input - Output
Input/output.
Basic Elements of C++.
TMF1414 Introduction to Programming
Chapter 18 I/O in C.
Introduction to C CSE 2031 Fall /3/ :33 AM.
Plan of the Day: More on type conversions scanf printf format strings
By: Syed Shahrukh Haider
Basic Elements of C++ Chapter 2.
Input and Output Lecture 4.
Input/Output Input/Output operations are performed using input/output functions Common input/output functions are provided as part of C’s standard input/output.
توابع ورودي-خروجي.
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
I/O in C Lecture 6 Winter Quarter Engineering H192 Winter 2005
Chapter 9 - Formatted Input/Output
Chapter 18 I/O in C.
Chapter 18 I/O in C.
Introduction to C EECS May 2019.
Introduction to C Programming
Introduction to C CSE 2031 Fall /15/2019 8:26 AM.
Presentation transcript:

Introduction to C Programming II & Formatted Input/Output Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013

3 Learning Outcomes At the end of this session, student will be able to: Define element and structure of C programming language (LO1 & LO2) T Algorithm and Programming

4 Variable Identifier for storing data/information Each variable has its name, address (L-value), type, size and data (R-value) Data or variable value can be modified at run time Declaration format: ; = ; Example: int a, b, c, total; float salary, bonus; int num_students = 20; T Algorithm and Programming

5 Variable Example: char ch=65 T Algorithm and Programming 65 Memory address ch name value Range of value: -128 – 127

6 Variable Variable Declaration: –Variable can be declared at every statement block –Block statement or compound statement is statement exists between { and } sign –Example: T Algorithm and Programming int x; int y; int z; or: int x, y, z; or: int x; int y; int z;

7 Data Type In C, there are 5 data types and 4 modifiers Data types: –Character  char –Integer  int –Floating point  float –Double floating point  double –Void  void Modifiers: -signed -unsigned -long -short T Algorithm and Programming

8 Data Type Data type in C is a combination of basic data type and its modifier Example: signed char unsigned int long int etc. T Algorithm and Programming

9 Data Type Data type and its range on TURBO C 2.0 (DOS) T Algorithm and Programming DATA TYPESYNTAXMEMORYRANGE characterunsigned char1 byte0 to 255 char1 byte-128 to 127 integerunsigned int2 byte0 to int2 byte to short int1 byte-128 to 127 unsigned long4 byte0 to long4 byte to float 4 byte3.4E-38 to 3.4E+38 double8 byte1.7E-308 to 1.7E+308 long double16 byte3.4E-4932 to 1.1E+4932

10 Data Type Why char data range between -128 to 127 ? 1 Byte = 8-bit to (MSB=>0 = Positive value) to (MSB=>1 = Negative value) T Algorithm and Programming MSB = Most Significant Bit (most left) Total = -1Total =

11 Data Type Beside used in function identifier type as no return value, keyword void also used as data type in variable. Void data type: is data type that can be transform into any data type (will be discussed later in pointer) T Algorithm and Programming

12 Casting Casting is a process to convert data type in C Syntax : (data type) Example : int x; float f = 3.134; x = (int) f; T Algorithm and Programming casting

13 Symbolic Constant Symbolic constant is an identifier which only have R- Value, and its value is unchangeable at runtime Symbolic constant does not have address (L-Value) Symbolic constant declaration does not need memory allocation To declare symbolic constant, can be done by using pre- processor directive #define or keyword const Example : const float Pi=3.14; #define Pi 3.14 T Algorithm and Programming

14 Symbolic Constant T Algorithm and Programming #define Pi 3.14 int main() { Pi=3.1475; //Error return 0; } int main() { const float Pi=3.14; Pi=3.1475; //Error return 0; } #define Pi 3.14 int main() { float PHI=3.14; PHI = ; //OK (variable) Pi=3.1475; //Error return 0; }

15 Constant Constant / symbolic constant does not have address (only value) and its value can not be changed at run time. Constant type:  Integer constant  -5  Floating-point constant  3.14  Character constant  'C' '1' '$'  Escape sequence  \n \t \''  String constant  ''BiNus'' † Symbolic constant  #define PHI 3.14  const float PHI=3.14;  'H‘is a character constant  ''H'‘is a string constant  1is a integer constant  '1‘is a character constant  const float Pi= ; Pi is a symbolic constant T Algorithm and Programming

16 Program Example Addition of two numbers Data has put on the memory. Result of the addition saved on the memory (variable) T Algorithm and Programming /* Addition Program */ /*comments */ int x,y,z;/*Global variable*/ int main() {/*start main program*/ x = 20;/*Statement 1*/ y = 30;/*Statement 2*/ z = x + y;/*Statement 3*/ return 0;/*Statement 4*/ }/*end of main program*/

17 Program Example Calculating area of a circle Radius value input from keyboard. Print out the result. T Algorithm and Programming /* Program circle area */ #include const float Pi = 3.14; /*Constant declaration*/ int main() /*start main program*/ { float r; /*local variable*/ float area; scanf(“%f”,&r); /*r input from keyboard*/ area = Pi * r * r; printf(“ Circle area = %5.2f”, area);/*print out to screen*/ return (0); }/*end of main program*/

18 Sizeof sizeof is an operator to find out size of a data type in C language Syntax: sizeof expression Example : sizeof(int) = 4 => Dev-V (Windows) sizeof(int) = 2 => Turbo C ver 2.0 (DOS) T Algorithm and Programming

19 Suffix C provides suffix for floating point constant: – F or f for float data type – L or l for long double data type – Default double data type Example : – 3.14  (double) – 3.14f  (float) – 3.14L  (long double) T Algorithm and Programming

20 Suffix C provides suffix for a constant integer: –U or u for unsigned integer –L or l for long integer –UL or ul or LU or lu for unsigned long integer –Default integer Example : – 174  (integer) – 174u  (unsigned integer) – 174L  (long integer) – 174ul  (unsigned long integer) T Algorithm and Programming

21 Suffix Some compilers will give warning for differ in data type, as can be seen from the following example Visual C++: Example : float x; x = 3.14; warning: truncation from 'const double' to 'float’ How to deal with the issue? You may use casting or suffix float x; x = (float)3.14;// casting x = 3.14f;// or suffix T Algorithm and Programming

22 Suffix T Algorithm and Programming #include int main() { printf(“Size of Floating Point Constant :\n"); printf(" – using suffix f = %d\n",sizeof(3.14f)); printf(" – without suffix = %d\n",sizeof(3.14)); printf(" – using suffix L = %d\n",sizeof(3.14L)); getch(); return 0; } Output: Size of Floating Point Constant : - using suffix f= 4 - without suffix= 8 - using suffix L= 12

23 Output Operation To show data on the display screen/monitor. Some of standard library function in C : printf(); putchar(); putch(); puts(); etc. T Algorithm and Programming

24 Output Operation: printf function To display some data on the standard output, using certain format Standard output is the monitor. Syntax: printf(const char *format[,argument, …]); Header file : stdio.h T Algorithm and Programming

25 Output Operation: printf() function T Algorithm and Programming /* A first program in C */ #include void main() { printf (“Welcome to C!\n”); } /*Printing on one line with two printf statements*/ #include int main(void){ printf (“Welcome”); printf (“to C!\n”); return 0; }

26 Output Formatting Output also has formatted specification: %[flags][width][.precision] type T Algorithm and Programming width : number of columns provided precision : digit number flags : can be changed into: none: right justify - : left justify -+: for positive & negative value type : d –or- i : signed decimal o: unsigned octal u: unsigned decimal x: unsigned hexadecimal f: floating point e: floating point (exponent) c: single character s: string %: % character p: pointer

27 Output Formatting For long data type, add l at the front of data type: –long double  ( “ %lf “) –unsigned long int  ( “ %lu “) –long int  ( “ %ld “) T Algorithm and Programming

28 Output Example Example 1: printf (“%6d”, 34);….34 printf (”%-6d”, 34);34…. Example 2 printf (“%10s”, “BINUS”);…..BINUS printf (“%-10s”, “BINUS”);BINUS….. printf (“%8.2f”, );….3.14 printf (“%-8.3f”, );3.141… T Algorithm and Programming

29 Output Example Example 3: printf ("%c\n",65); // print A printf ("%x\n",'A'); // print 41 printf ("%o\n",65); // print 101 printf ("%+d\n",34);// print +34 printf ("%+d\n",-45);// print -45 printf ("%e\n",3.14);// print e+000 T Algorithm and Programming

30 Output Example Example 4: T Algorithm and Programming #include int main(){ char ss[]="Selamat Datang"; printf(" \n"); printf("%.10s di Binus\n",ss); printf("%10s di Binus\n",ss); printf("%-10s di Binus\n",ss); printf("%.20s di Binus\n",ss); printf("%20s di Binus\n",ss); printf("%-20s di Binus\n",ss); printf("%20.10s di Binus\n",ss); printf("%-20.10s di Binus\n",ss); return 0; }

31 Output Example Example 4: T Algorithm and Programming Output: Selamat Da di Binus Selamat Datang di Binus Selamat Da di Binus

32 Output Operation: putchar() function Syntax: int putchar(int c) Functionality: –Displaying character on the monitor at cursor position. After display, cursor will move to the next position –Return EOF if error, and return the displayed character after successfully done –putchar is a macro similar to : putc(c, stdout ) –Header File : stdio.h Example : char ch=’A’; putchar(ch); T Algorithm and Programming

33 Output Operation: putch() function Syntax: int putch(int ch) Functionality: –Display ASCII character to the monitor without moving cursor to its next position –Return EOF if error, and return the displayed character after successfully done –Header file : conio.h Example : char ch=’b’; putch(ch); T Algorithm and Programming

34 Output Operation: puts() function Syntax: int puts(const char *str); Functionality : –Display string to the monitor and move the cursor to new line –Return non-negative value when successful and EOF if error –Header file: stdio.h Example : puts(”Welcome”); puts(”to Binus”); Output on monitor: Welcome to Binus T Algorithm and Programming

35 Input Operation Standard library function that is related to input operations are: scanf(); getchar(); getch(); getche(); gets(); etc. Input operation: function/operation of getting the data into the memory using standard I/O devices (keyboard, disk, etc.) T Algorithm and Programming

36 Input Operation: scanf() function Header file: stdio.h Format: int scanf( const char *format [,argument]... ); All the argument type are pointers (address of a variable) To get the address of a variable use “&” sign Example : int aValue; scanf(”%d”,&aValue); Input format: ”%type” where type can be substituted with one of the following list: (next page) T Algorithm and Programming

37 Input Operation: scanf() function Format Type: T Algorithm and Programming TypeUsed to scan d u x e, f, g C integer unsigned integer hexadecimal floating point single character s O […] [^..] string ended with whit space data unsigned octal string ended with non of the value inside [...] string ended with the value inside [...]

38 Input Operation: scanf() function If exist an x integer variable, state the difference of x and &x? Answer: x : 234 &x : T Algorithm and Programming Variable Name X Address Value 234

39 Input Operation: scanf() function scanf() function returns an integer that stated how many fields are successfully assigned Example : int x,y,z,w; x = scanf("%d %d %d",&y,&z,&w); –Input three values of integer 6 7 8, then x = 3; –Input four values then x = 3 (successfully assign 3 variables y z w) T Algorithm and Programming

40 Input Operation: scanf() function T Algorithm and Programming /* Program Calculating rectangle area v1*/ #include int main(){ int width, height, area; scanf(”%d”,&width); scanf(”%d”,&height); area = width*height; return(0); } /* Program Calculating rectangle area v2*/ #include int main(){ int width, height, area; scanf(“%d %d”,&width, &height); area = width * height; return(0); } scanf() function can use more than one argument

41 Input Operation: scanf() function T Algorithm and Programming /* Program different argument*/ #include int main() { int number; char initial; float money; scanf(“%d %c %f”,&number, &initial, &money); //other statements return(0); } Data type for each variable in the function argument can be different

42 Input Operation: scanf() function Getting string data from keyboard using scanf() using format: %s Example : char ss[40]; scanf(”%s”, ss); Note for the example above, as the ss variable is a pointer than we need not putting extra & sign (&ss) in the function argument (pointer will be discussed later separately) String takes only till the first whitespace found T Algorithm and Programming

43 Input Formatting Space char, tab, linefeed, carriage-return, form-feed, vertical-tab, and new-line entitle ”white-space characters” Example : –Using previous example, if a string “good morning every one” entered then ss value will only contain “good” T Algorithm and Programming

44 Input Formatting & Example To get string that ended with certain character for example Enter, use scanf() with format: [^\n] Example 1: char ss[40]; scanf(”%[^\n]”,ss); Using the previous example, if a string “good morning every one” then ENTER, the ss variable will contain “good morning every one” T Algorithm and Programming

45 Input Formatting & Example Example 2: char ss[40]; scanf(”%[a-z]”, ss); Using the example above, if the string is: then ENTER, ss variable will only contain: http. This is caused by character (:) is not within a to z, thus (:) accounted as the end of the string T Algorithm and Programming

46 Input Formatting & Example Example 3 : int x; scanf("%o", &x); Using the above code, if input value: 44 followed by enter then x will contain: 36 in decimal, as 44 is an octal number system T Algorithm and Programming

47 Input Formatting & Example Example 4: int x; scanf("%x", &x); Using the above code, if input value: 44 followed by enter then x will contain: 68 in decimal, as 44 is a hexadecimal number system T Algorithm and Programming

48 Input Operation: getchar() function Syntax: int getchar(void); Functionality: –Return the next ASCII character from keyboard buffer –Shown on the monitor screen –Awaiting for ENTER pressed –Header file: stdio.h Example : char ch; ch = getchar(); T Algorithm and Programming

49 Input Operation: getch() function Syntax: int getch(void); Functionality: –return a character from keyboard buffer –not shown on the monitor (no echo) –not wait for ENTER pressed –suitable for password –Header file: conio.h Example : char ch; ch = getch(); T Algorithm and Programming

50 Input Operation: getche() function Syntax: int getche(void) Functionality : –return a character from keyboard buffer –character shown on monitor (echo) –not wait for ENTER –Header file: conio.h Example : char ch; ch = getche(); T Algorithm and Programming

51 Input Operation: gets() function Syntax: char *gets(char *buffer) Functionality : –read a string from keyboard till find new-line and save in buffer –new-line will later on replace with null character –will return NULL if error and return its argument (buffer) if success Example : char buffer[40]; char *ptr; ptr = gets(buffer); T Algorithm and Programming

52 Exercise 1.int x,y,z,w; x=scanf("%d %d %d",&y,&z,&w); a.What happen if input was 2 integer values from the keyboard? b.What is x value if 3 character values given as the input? 2.char ss1[40]; char ss2[40]; x=scanf(”%s %s”,ss1,ss2); a.What is ss1 and ss2, if the input from keyboard is ”Good morning everyone” ? b.What is x if the input : ”Class 1PAT” ? T Algorithm and Programming

53 Exercise 3.char ss[40]; scanf(”%4s”, ss); What is ss value, if the input : ”Good morning” ? 4.char ch; ch = getchar(); What is ch value, if the input : Binus ? 5.char ch1, ch2; ch1 = getchar(); // input word “Binus” here! ch2 = getchar(); What is the value of ch1 and ch2, if the input : Binus ? T Algorithm and Programming

54 Exercise 6.Create a program in C to receive input from standard input (keyboard) for the following data: –Assignment Score –Mid Exam Score –Final Exam Score Calculate and display Final Score using : Final Score = 20%*Assignment + 30%*Mid + 50%*Final T Algorithm and Programming

55 Exercise 7. #include int main() { char name[40]; int nim; char gender; printf(“Name:"); scanf("%[^\n]",name); printf(“StudentNum :"); scanf("%d",&nim); printf(“Gender (M/F):"); gender=getchar(); return 0; } After entering name and student number, program will exit to prompt. gender=getchar() seems to be never executed. Explain why? T Algorithm and Programming

56 Exercise 8. #include int main(){ char ss[]="10 % 3 = 1\n"; char str[]= “ Welcome to Binus everyone\n"; printf(ss); printf("%s",ss); printf(str); printf("%s",str); return 0; } What is the output of the above code ? T Algorithm and Programming

57 Summary Syntax for Output: printf, putchar, putch, puts Syntax for Input: scanf, getchar, getch, getche, gets The screen (DOS mode) divided into row and column, normally max column = 80 and max row = 25 T Algorithm and Programming

58 References Paul J. Dietel,Harvey M. Deitel, C : how to program. PEAPH. New Jersey. ISBN: Chapter 1 & 2 Writing Your First C Program: Data Types and Names in C: T Algorithm and Programming

59 References Paul J. Dietel,Harvey M. Deitel, C : how to program. PEAPH. New Jersey. ISBN: Chapter 9 Reading from and Writing to Standard I/O: Intro to File Input/Output in C: T Algorithm and Programming

60 END T Algorithm and Programming