Outline. Computer Programming. Preprocessing in C. File inclusion. Preprocessing in C

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

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

UNIT- 3 Introduction to C++

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

Computers Programming Course 5. Iulian Năstac

Fundamentals of Programming

Fundamental of Programming (C)

UNIT 3 OPERATORS. [Marks- 12]

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

Unit 4. Input/Output Functions

Goals of C "" The Goals of C (cont.) "" Goals of this Lecture"" The Design of C: A Rational Reconstruction"

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

Computers Programming Course 6. Iulian Năstac

Arithmetic Operators. Portability: Printing Numbers

Work relative to other classes

The Design of C: A Rational Reconstruction (cont.)

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

Reserved Words and Identifiers

Lecture 4. Console input/output operations. 1. I/O functions for characters 2. I/O functions for strings 3. I/O operations with data formatting

Should you know scanf and printf?

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

EDIABAS BEST/2 LANGUAGE DESCRIPTION. VERSION 6b. Electronic Diagnostic Basic System EDIABAS - BEST/2 LANGUAGE DESCRIPTION

Introduction to C Language

THE FUNDAMENTAL DATA TYPES

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

ANSI C Programming Simple Programs


Fundamental of Programming (C)

CSCI 171 Chapter Outlines

The Design of C: A Rational Reconstruction (cont.)" Jennifer Rexford!

Lecture 3. More About C

Course Outline Introduction to C-Programming

XC Specification. 1 Lexical Conventions. 1.1 Tokens. The specification given in this document describes version 1.0 of XC.

C - Basic Introduction

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

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:

Computer System and programming in C

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

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

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

Continued from previous lecture

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

Unit 4 Preprocessor Directives

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

Fundamentals of Programming. Lecture 11: C Characters and Strings

Advanced C Programming Topics

Basic Types and Formatted I/O

Java Notes. 10th ICSE. Saravanan Ganesh

EECS2031. Modifiers. Data Types. Lecture 2 Data types. signed (unsigned) int long int long long int int may be omitted sizeof()

Operators in java Operator operands.

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

Model Viva Questions for Programming in C lab

C++ Programming Basics

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

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

Fundamentals of Programming

Mechatronics and Microcontrollers. Szilárd Aradi PhD Refresh of C

Basic Elements of C. Staff Incharge: S.Sasirekha

Introduction. Following are the types of operators: Unary requires a single operand Binary requires two operands Ternary requires three operands

Week 3 More Formatted Input/Output; Arithmetic and Assignment Operators

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

Lecture 02 C FUNDAMENTALS

Introduction to C++ Introduction and History. Characteristics of C++

The C++ Language. Arizona State University 1

Chapter 7. Basic Types

Types, Operators and Expressions

Operators and Expressions in C & C++ Mahesh Jangid Assistant Professor Manipal University, Jaipur

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

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

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

Language Reference Manual simplicity

Introduction to Computing Lecture 03: Basic input / output operations

SWEN-250 Personal SE. Introduction to C

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

Problem Solving and 'C' Programming

Contents. Preface. Introduction. Introduction to C Programming

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

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

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

UNIT IV INTRODUCTION TO C

BİL200 TUTORIAL-EXERCISES Objective:

LEXICAL 2 CONVENTIONS

The Design of C: A Rational Reconstruction: Part 2

Java enum, casts, and others (Select portions of Chapters 4 & 5)

Informatics Ingeniería en Electrónica y Automática Industrial

Basics of Programming

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

6.096 Introduction to C++ January (IAP) 2009

C Programming. Course Outline. C Programming. Code: MBD101. Duration: 10 Hours. Prerequisites:

Standard File Pointers

Console Input and Output

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

Appendix. Grammar. A.1 Introduction. A.2 Keywords. There is no worse danger for a teacher than to teach words instead of things.

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

Basic C Programming (2) Bin Li Assistant Professor Dept. of Electrical, Computer and Biomedical Engineering University of Rhode Island

Fundamental of C programming. - Ompal Singh

Pointers cause EVERYBODY problems at some time or another. char x[10] or char y[8][10] or char z[9][9][9] etc.

A Fast Review of C Essentials Part I

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

Princeton University Computer Science 217: Introduction to Programming Systems The Design of C

Transcription:

Outline Computer Programming The greatest gift you can give another is the purity of your attention. Richard Moss Preprocessing in C Function vs macro Conditional compilation Constant identifiers Standard I/O getch, getche, putch (non-portable) gets, puts scanf, printf sscanf, sprintf getchar, putchar Expressions Definition Evaluation T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 1 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 2 Preprocessing in C Preprocessing occurs before compilation Text substitution in source code according to directives Directives are preceded by the sharp character, i.e. # Preprocessing ensures: Source file inclusion (typically header files) Macro definition and invocation Conditional compilation T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 3 Preprocessing in C. File inclusion The inclusion directive is specified as: #include <file_specifier> or #include file_specifier The directive is replaced by the specified file Notes: An included file may contain include directives Include directives are placed at the top of a file, for visibility of definitions in the whole file Include directives are widely used for large programs Examples #include <stdlib.h> #include my_header.h T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 4

Preprocessing in C. Symbolic constant and macro definitions Directive used is #define Defining a symbolic constant is a special case of macro definition #define name character_sequence During preprocessing, name is replaced by character_sequence character_sequence may be more than one line long; continuation using \ as the last character Replacement continues till a directive #undef name or the EOF is met Preprocessing in C. Symbolic constant examples Examples: #define ALPHA 20 #define BETA ALPHA+80 Note: with this definitions x=3*beta is replaced by x=3*20+80 if that is not the intended behavior, BETA should be defined as #define BETA (ALPHA+80) Name is replaced by the character sequence which starts with the first non-whitespace T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 5 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 6 Preprocessing in C. Macro definitions A macro definition resembles a function definition, i.e. #define name(p1, p2,..., pn) text where name = macro name p1, p2,..., pn = macro parameters text = substitution text Notes Formal parameters are replaced by actual parameters in replacement text text may spread over multiple lines. Continuation with \ as last character Macro substitution is also called expansion A symbolic constant is actually a parameter less macro Invocation is similar with function invocation, i.e. name(p_actual1, p_actual2,..., p_actualn) T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 7 Preprocessing in C. Macro definition examples Swapping two variables: Definition #define SWAP(vartype, a, b) (vartype t;\ t=a; a=b; b=t; ) Invocation SWAP(int, x, y) SWAP(double, u, v) Calculate the absolute value Definition #define ABS(x) ( (x) < 0? (x) : (x) ) Invocation k= ABS(a - b); Expansion. Note that x is replaced by a - b k= ( (a - b) < 0? (a b) : (a b) ); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 8

Preprocessing in C. Function vs. macro Differences between functions and macro definitions Function invocation involves a call and execution of statements of function body Upon function invocation parameter type is also considered Macro invocation means expansion, i.e. replacement of invocation with macro text. Thus statements in a macro are generated for each invocation and compiled. Hence, macros should be used for small size computations Upon macro invocation, a formal parameter is replaced by the character sequence corresponding to the actual parameter. Formalactual parameter correspondence is purely positional Processing time is shorter when using macros (function invocation requires overhead) Note. C++ also has inline functions, based on a principle similar to macros with the difference that type is also considered T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 9 Preprocessing in C. Conditional compilation Conditional compilation facilitates development, mainly testing Directives for conditional compilation: #if: #if expr #if expr text text1 #else text2 where expr is a constant expression which can be evaluated by the preprocessor, text1, text2, text are portions of source code Effect: if expr is not zero text (text1) are compiled (not text2). Otherwise only text2 (for second form) and processing continues after T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 10 Preprocessing in C. Conditional compilation Directives for conditional compilation: #ifdef: #ifdef name text #ifdef name text1 #else text2 where name is a constant which is tested if defined; text1, text2, text are portions of source code Effect: if name is defined text (text1) are compiled (not text2). Otherwise only text2 (for second form) and processing continues after Preprocessing in C. Conditional compilation Directives for conditional compilation: #ifndef: #ifndef name text #ifndef name text1 #else text2 where name is a constant which is tested if not defined; text1, text2, text are portions of source code Effect: if name is undefined text (text1) are compiled (not text2). Otherwise only text2 (for second form) and processing continues after T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 11 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 12

Preprocessing in C. Conditional compilation #ifdef and #ifndef are used to avoid multiple inclusions. Thus at the beginning of each header file sequences similar to the following can be present (excerpt from stdio.h): #ifndef _STDIO_H_ #define _STDIO_H_... /* _STDIO_H_ */ Note. A number of predefined names exist, e.g.: MSDOS if operating system is MSDOS DATE date of compilation CDECL -indicates that function calls follow C conventions STDC - defined if strict C ANSI rules must be followed FILE - name of currently compiled file T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 13 Preprocessing in C. Declaring constant identifiers #error: causes a compilation error with a message given as a parameter to it. E.g. #ifndef cplusplus #error This program should be compiled with C++\ compilers Constant declaration: type const identifier=value; or const type identifier=value; Examples: int const alpha=10; double const beta=20.5; or const int alpha=10; const double beta=20.5; T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 14 Standard I/O functions If interactive processing, then: The standard terminal is the terminal used to run the program. Three files are attached to it: Input file (stdin) Output file (stdout) Error file (stderr) C/C++ do not have statements for reading and writing. I/O operations are achieved by functions with prototypes in stdio.h Note: conio.h is an extension, it is NOT part of the standard Non-portable functions: getch, getche, putch Character oriented getch: reads without echoing a character from stdin getche: similar, but echoes its input For both execution waits for a new character to become available putch: prints the character whose ASCII code is its parameter Printable characters have codes in the range [32, 126] Prototypes in conio.h: int getch(void); int getche(void); int putch(int ch); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 16

Non-portable functions: getch, getche, putch Example: #include <conio.h> /* non-portable! */ int main(void) { putch( \r ); putch( \n ); /* CR+LF */ putch(getch()); putch( \r ); putch( \n ); /* CR+LF */ putch(getche()); getch(); return 0; } T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 17 gets: Function gets Reads characters from the stream stdin up to the next newline character, and stores them in the string given as argument The newline character is discarded. If gets encounters a read error or end-of-file, it returns a null pointer; otherwise it returns its argument. Warning: The gets function is very dangerous because it provides no protection against overflowing the string s. The GNU library includes it for compatibility only. You should always use fgets or getline instead. Prototype: char *gets(char *s); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 18 puts: Functions gets Writes the string given as an argument to the stream stdout followed by a newline. The terminating null character of the string is not written. puts is the most convenient function for printing simple messages. Returns the code of the last output character Prototype: int puts(const char *s); Functions gets and puts. Example #include <stdio.h> #include <stdlib.h> int main(void) { char s[200]; printf( \ninput a character string and press Enter\n ); gets(s); /* the character string is stored at the address where s points */ printf( \nthe string you input is:\n ); puts(s); system( PAUSE ); return 0; } T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 19 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 20

scanf Function scanf reads formatted input from the stream stdin under the control of the template string given as its first argument. The next arguments are optional arguments, and are pointers to the places which receive the resulting values. The return value is normally the number of successful assignments. If an end-of-file condition is detected before any matches are performed, including matches against whitespace and literal characters in the template, then EOF is returned. Prototype: int scanf(const char *template, pointer ); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 21 Function scanf. Template string A scanf template string contains format specifiers A scanf template string has the general form: % flags width type conversion In more detail, an input conversion specification consists of an initial '%' character followed in sequence by: An optional flag character, *, which says to ignore the text read for this specification. An optional decimal integer that specifies the maximum field width. Reading of characters from the input stream stops either when this maximum is reached or when a non-matching character is found, whichever happens first. Most conversions discard initial whitespace characters (those that don't are explicitly documented), and these discarded characters don't count towards the maximum field width. String input conversions store a null character to mark the end of the input; the maximum field width does not include this terminator. An optional type modifier character. A character that specifies the conversion to be applied. T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 22 Table of input conversions (1) %d %i %o %u %x, %X Function scanf. Table of output conversions I %e, %f, %g, %E, %G Matches an optionally signed integer written in decimal. Matches an optionally signed integer in any of the formats that the C language defines for specifying an integer constant. Matches an unsigned integer written in octal radix. Matches an unsigned integer written in decimal radix Matches an unsigned integer written in hexadecimal radix. Matches an optionally signed floating-point number. T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 23 Table of input conversions (2) %s %[ %c %p %n %% Function scanf. Table of output conversions II Matches a string containing only non-whitespace characters Matches a string of characters that belong to a specified set. Matches a string of one or more characters; the number of characters read is controlled by the maximum field width given for the conversion. Matches a pointer value in the same implementationdefined format used by the %p output conversion for printf. This conversion doesn't read any characters; it records the number of characters read so far by this call. Matches an literal % given in the input stream T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 24

Scan sets Function scanf. Scan sets Set of characters enclosed in square brackets [] Preceded by % sign Scans input stream, looking only for characters in scan set Whenever a match occurs, stores character in specified array Stops scanning once a character not in the scan set is found Inverted scan sets Use a caret ^: "%[^aeiou]" Causes characters not in the scan set to be stored Skipping characters Include character to skip in format control Or, use * (assignment suppression character) Skips any type of character without storing it T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 25 Function scanf. Examples Usage examples for scanf Read a character char ch; scanf( %c, &ch); Read a character string char s[40]; scanf( %s, s); Read three integers with values in decimal, octal, and hexadecimal respectively int a, b, c; scanf( %d %o %x, &a, &b, &c); Read reals of type float, double, long double float x; double y; long double z; scanf( %f %lf %Lf, &x, &y, &z); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 26 printf Function printf prints the optional arguments under the control of the template string template to the stream stdout. returns the number of characters printed, or a negative value if there was an output error. Prototype: int printf (const char *template,...) expression_list ); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 27 Function printf. Template string I A printf template string contains format specifiers A printf template string has the general form: % param-no $ flags width. precision type conversion In more detail, an output conversion specification consists of an initial % character followed in sequence by: An optional specification of the parameter used for this format. Normally the parameters to the printf function are assigned to the formats in the order of appearance in the format string. The param-no part of the format must be an integer in the range of 1 to the maximum number of arguments present to the function call. Zero or more flag characters that modify the normal behavior of the conversion specification. An optional decimal integer that specifies the minimum field width. This is a minimum value; if the normal conversion produces more characters than this, the field is not truncated. Normally, the output is right-justified within the field. You can also specify a field width of *. This means that the next argument in the argument list (before the actual value to be printed) is used as the field width. The value must be an int. If the value is negative, this means to set the flag and to use the absolute value as the field width. T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 28

Function printf. Template string II printf template string format specifiers (cont d) An optional precision to specify the number of digits to be written for the numeric conversions. If the precision is specified, it consists of a period (.) followed optionally by a decimal integer (which defaults to zero if omitted). You can also specify a precision of *. This means that the next argument in the argument list (before the actual value to be printed) is used as the precision. The value must be an int, and is ignored if it is negative. If you specify * for both the field width and precision, the field width argument precedes the precision argument. C library versions other than GNU may not recognize this syntax. An optional type modifier character, which is used to specify the data type of the corresponding argument if it differs from the default type. (For example, the integer conversions assume a type of int, but you can specify h, l, or L for other integer types.) A character that specifies the conversion to be applied. Conversion characters are the same as for scanf, except for %[ which is not used here T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 29 Table of output conversions (1) %d %i %u %o %x %X %f %e, %E, %g, %G Function printf. Table of output conversions I Print an integer as a signed decimal number. Print an integer as an unsigned decimal number. Print an integer as an unsigned octal number. Print an integer as an unsigned hexadecimal number. %x uses lower-case letters and %X uses upper-case. Print a floating-point number in normal (fixed-point) notation Print a floating-point number in exponential notation. %e uses lower-case letters and %E uses upper-case. Print a floating-point number in either normal or exponential notation, whichever is more appropriate for its magnitude. %g uses lower-case letters and %G uses upper-case. T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 30 Table of output conversions (2) %a %A %c %s %p %n Function printf. Table of output conversions II Print a floating-point number in a hexadecimal fractional notation which the exponent to base 2 represented in decimal digits. %a uses lower-case letters and %A uses upper-case. Print a single character. Print a string. Print the value of a pointer. Get the number of characters printed so far. Function printf. Flags for integer conversions Modifier flags for integer conversions: : Left-justify the result in the field (instead of the normal right-justification). +: For the signed %d and %i conversions, print a plus sign if the value is positive. #: For %o conversion, forces the leading digit to be 0, as if by increasing the precision. For %x or %X, prefixes a leading 0x or 0X to the result. Doesn't do anything useful for the %d, %i, or %u conversions. 0: Pad the field with zeros instead of spaces. The zeros are placed after any indication of sign or base. This flag is ignored if the flag is also specified, or if a precision is specified. T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 31 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 32

Function printf. Example: integer Example of integer numbers printing (from libc help) Values printed are, in order: 0, 1, -1, 100000 Specifier: " %5d %-5d %+5d %+-5d % 5d %05d %5.0d %5.2d %d \n Output: 0 0 +0 +0 0 00000 00 0 1 1 +1 +1 1 00001 1 01 1-1 -1-1 -1-1 -0001-1 -01-1 100000 100000 +100000 +100000 100000 100000 100000 100000 100000 Specifier: " %5u %5o %5x %5X %#5o %#5x %#5X %#10.8x \n" Output: 0 0 0 0 0 0 0 00000000 1 1 1 1 01 0x1 0X1 0x00000001 100000 303240 186a0 186A0 0303240 0x186a0 0X186A0 0x000186a0 Function printf. Flags for integer conversions Modifier flags for floating point number conversions : Left-justify the result in the field. Normally the result is rightjustified. +: Always include a plus or minus sign in the result. If the result doesn't start with a plus or minus sign, prefix it with a space instead. Since the + flag ensures that the result includes a sign, this flag is ignored if you supply both of them. #: Specifies that the result should always include a decimal point, even if no digits follow it. For the %g and %G conversions, this also forces trailing zeros after the decimal point to be left in place where they would otherwise be removed. 0: Pad the field with zeros instead of spaces; the zeros are placed after any sign. This flag is ignored if the '-' flag is also specified. A type modifier is supported: L An uppercase L specifies that the argument is a long double. T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 33 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 34 Function printf. Example: floating point Example of floating number printing (from libc help) Values printed are, in order:0, 0.5, 1, -1, 100, 1000, 10000, 12345, 100000, 123456 Specifier: " %13.4a %13.4f %13.4e %13.4g \n" Output: 0x0.0000p+0 0.0000 0.0000e+00 0 0x1.0000p-1 0.5000 5.0000e-01 0.5 0x1.0000p+0 1.0000 1.0000e+00 1-0x1.0000p+0-1.0000-1.0000e+00-1 0x1.9000p+6 100.0000 1.0000e+02 100 0x1.f400p+9 1000.0000 1.0000e+03 1000 0x1.3880p+13 10000.0000 1.0000e+04 1e+04 0x1.81c8p+13 12345.0000 1.2345e+04 1.234e+04 0x1.86a0p+16 100000.0000 1.0000e+05 1e+05 0x1.e240p+16 123456.0000 1.2346e+05 1.235e+05 printf. Printing literals and escape sequences Escape sequence Description \' Output the single quote (') character. \" Output the double quote (") character. \? Output the question mark (?) character. \\ Output the backslash (\) character. \a Cause an audible (bell) or visual alert. \b Move the cursor back one position on the current line. \f Move the cursor to the start of the next logical page. \n Move the cursor to the beginning of the next line. \r Move the cursor to the beginning of the current line. \t Move the cursor to the next horizontal tab position. \v Move the cursor to the next vertical tab position. T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 35 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 36

scanf and printf example #include <stdio.h> #include <stdlib.h> int main(void) { int a, e1, e2; float b, c, d; printf( \ninput an integer value a= ); scanf( %d, &a); printf( \ninput a real value b= ); scanf( %f, &b); c=a+b; e1=a+b; d=a*b; e2=a+b; printf( \nc=%d+%.3f=%.3f d=%d*%.3f=%.3f\n, a, b, c, a, b, d); printf( \ne1=%d+%f=%d e2=%d*%f=%d\nnote that truncation\ occurs\n, a, b, e1, a, b, e2); system( Pause ); return 0; } T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 37 sscanf and sprintf Have an extra parameter: the address of the memory area (a buffer) containing the input (ASCII) to be converted sscanf converts the content of that area instead of stdin sprintf outputs to that area instead of stdout Prototypes (found in stdio.h) int sscanf(const char *buffer, const char *template, pointer ); int sprintf(const char *buffer, const char *template, variable_list); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 38 sscanf and sprintf example #include <stdio.h> #include <stdlib.h> int main(void) { char s[100], q[100]; int a, b; float c, d; printf( \ninput the values for a and c on a single line\nseparated by a space, then press Enter\n ); gets(s); /* a string containing a and c is found at address s */ sscanf(s, %d %f, &a, &c); printf( \na=%4d c=%8.3f\n, a, c); sprintf(q, \na=%4d c=%8.3f\n, a, c); /* q contains a string which includes the values of a and c */ sscanf(q, %d %f, &b, &d); /* now b=a and d=c */ printf( \na=%4d c=%8.3f\n, b, d); system( Pause ); return 0; } T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 39 Macros getchar and putchar getchar reads a single character from stdin. Returns the ASCII code of the character or -1 when EOF is encountered putchar writes a single character, given as an argument, to stdout. Returns the value of the character given as an argument Prototypes: int getchar(void); int putchar (int c); Usage example #include <stdio.h> #include <stdlib.h> int main(void) { putchar( \r ); putchar( \n ); /* begin new line */ putchar(getchar(())) putchar( \r ); putchar( \n ); /* begin new line */ system( Pause ); return 0; } T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 40

Expressions Expression=one or more operands joined by operators An operand can be: A numeric or a character constant A symbolic constant A simple variable identifier An array identifier A structure identifier A type identifier A function identifier An indexed variable A component of a structure A function call An expression enclosed between parenthesis Expressions An operand Has a type and a value An operator Can be unary or binary Unary: applied to a single operand Binary: applied to both preceding and following operand Does not have any effect on character string constants T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 41 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 42 Expressions. Operators Operators are grouped in classes Arithmetic operators: unary + and binary + * / % Relation operators < <= > >= Equality operators ==!= Logic operators: negation!, and &&, or Bitwise operators: one s complement ~, left shift <<, right shift >>, and &, or, exclusive or ^ Assignment operators: assignment =; compound assignment: op= where op is an arithmetic or bitwise operator. The effect is: v op = operand v = v op operand Expressions. Operators Operators are grouped in classes (cont d) Increment/decrement operators: ++, Type cast operators: (type) operand Size operator: sizeof(variable), sizeof(type ) Referencing operator: &identifier Parenthesis operator: () [] Conditional operator:? : (expression? exp1: exp2) Comma operator:, Dereferencing operators: *,., -> C++ specific: Memory allocation/free: new/delete Resolution: :: T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 43 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 44

Expression evaluation What is taken into account: Operator priority Operator associativity for equal priority Default conversion rule Descending order of type priority: long double double float unsigned long long unsigned int Expression evaluation The result of evaluating relational expressions is true or false. False is represented by zero, true by non-zero Increment and decrement operators can be prefix (++operand) or postfix (operand--) Prefix: in evaluation the value after increment/decrement is used, e.g. x=10; y=++x; /* y=11 and x=11 */ Postfix: the value before increment/decrement is used in evaluation x=10; z=x++; /* z=10 and x=11 */ Comma operator. The expressions are evaluated strictly left to right and their values discarded, except for the last one, whose type and value determine the result of the overall expression. Usage examples (for decomposition of complex evaluations): y=((c=(a<0)? a: a), (d=(b<0)? -b: b), (c>d)? c: d); alpha = ((a1=x+y+z), (a2=x+y+w), (a1*a2+10)); T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 45 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 46 Logical operators. Truth tables Truth table for the && (logical AND) operator. expression1 expression2 0 0 0 0 nonzero 0 nonzero 0 0 nonzero nonzero 1 expression1 && expression2 Truth table for the logical OR ( ) operator. expression1 expression2 expression1 0 0 0 0 nonzero 1 nonzero 0 1 nonzero nonzero 1 Truth table for operator! (logical negation). expression 0 1 nonzero 0 expression2! expression T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 47 Level 17 17 16 16 16 16 16 14 Operator precedence and associativity Operator(s) Description Associativity :: global scope (unary) :: class scope (binary) ->. member selectors [ ] array index ( ) function call ( ) type construction sizeof size in bytes ++ -- increment, decrement ~ bitwise NOT! logical NOT + - unary plus, minus * & dereference, address-of ( ) cast new delete free store management ->*.* member pointer selectors T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 48

Operator precedence and associativity Summary Level 13 12 11 10 9 8 7 6 5 4 3 2 Operator(s) * / % + - << >> < <= > >= ==!= & ^ &&? : = *= /* %= += -= <<= >>= &= = ^= Description multiplicative operators arithmetic operators bitwise shift relational operators equality, inequality bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical OR arithmetic if assignment operators Associativity Preprocessing in C Function vs. macro Conditional compilation Constant identifiers Standard I/O getch, getche, putch (non-portable) gets, puts scanf, printf sscanf, sprintf getchar, putchar Expressions Definition Evaluation 1, comma operator T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 49 T.U. Cluj-Napoca - Computer Programming - lecture 4 - M. Joldoş 50