You are on page 1of 127

C/C++ Program Compilation

Before
Machine Languages Assembly Languages High Level Languages ..
JUIT Waknaghat 2

Creating, Compiling and Running Your Program


The stages of developing your C program are as follows.

Creating the program


Create a file containing the complete program, such as myprog.c. You can use any ordinary editor with which you are familiar to create the file. The filename must by convention end ``.c'' (full stop, lower case c), e.g. myprog.c or progtest.c. The contents must obey C syntax.

Compilation
There are many C compilers around. The cc being the default Sun compiler. The GNU C compiler gcc is popular and available for many platforms. PC users may also be familiar with the Borland bcc compiler. For the sake of compactness in the basic discussions of compiler operation we will simply refer to the Borland bcc compiler -- other compilers can simply be substituted in place of bcc unless otherwise stated.

Contd
To Compile your program simply press the Alt+F9. If there are syntax errors in your program (such as mistyping, misspelling one of the key words or omitting a semi-colon), the compiler will detect and report them. There may, of course, still be logical errors that the compiler cannot detect. You may be telling the computer to do the wrong operations.

Running the program


The next stage is to actually run your executable program. To run an executable in Windows, you press the Ctrl+F9. This executes your program, printing any results to the screen. At this stage there may be run-time errors, such as division by zero, or it may become evident that the program has produced incorrect output. If so, you must return to edit your program source, and recompile it, and run it again.

The C Compilation Model


We will briefly highlight key features of the C Compilation model here.

The Preprocessor
The Preprocessor accepts source code as input and is responsible for
removing comments interpreting special preprocessor directives denoted by #. For example
#include -- includes contents of a named file. Files usually called header files. e.g #include <math.h> -- standard library maths file. #include <stdio.h> -- standard library I/O file #define -- defines a symbolic name or constant. Macro substitution. #define MAX_ARRAY_SIZE 100

C Compiler
The C compiler translates source to assembly code.
The source code is received from the preprocessor.

Assembler
The assembler creates object code. On a WINDOWS system you may see files with a .OBJ suffix (on MSDOS) to indicate object code files.

Link Editor
If a source file references library functions or functions defined in other source files the link editor combines these functions (with main()) to create an executable file. External Variable references resolved here also.

Using Libraries
C is an extremely small language. Many of the functions of other languages are not included in C.
e.g. No built in I/O, string handling or maths functions.

What use is C then?


C provides functionality through a rich set function libraries. As a result most C implementations include standard libraries of functions for many facilities ( I/O etc.). A programmer can also develop his or her own function libraries.

C Programming
An introduction

History
The initial development of C occurred at AT&T Bell Labs between 1969 and 1973. It is developed in 1972 by Dennis Ritchie The origin of C is closely tied to the development of the Unix operating system, It was named "C" because many of its features were derived from an earlier language called "B", which according to Ken Thompson was a stripped-down version of the BCPL (Basic Combined Programming Language).
JUIT Waknaghat 16

Philosophy
In computing, C is a general-purpose, block structured, procedural, imperative computer programming language It was designed to be compiled using a relatively straightforward compiler, to provide low-level access to memory, to provide language constructs that map efficiently to machine instructions, and to require minimal run-time support. Although C was designed for implementing system software, it is also widely used for developing application software.
JUIT Waknaghat 17

Programming
Programming - scheduling, or performing a task or an event. Computer Programming - creating a sequence of steps for a computer to follow in performing a task. Programming Language - a set of rules, symbols, and special words used to construct a computer program. Programming language rules consist of:
Rules of Syntax which specify how valid instructions are written in the language. Rules of Semantics which determine the meaning of the instructions (what the computer will do).
JUIT Waknaghat 18

A SIMPLE C PROGRAM
The following program is written in the C programming language. #include <stdio.h> main() { printf ("Programming in C is easy.\n"); }
Sample Program Output: Programming in C is easy. _
JUIT Waknaghat 19

A NOTE ABOUT C PROGRAMS


In C, lowercase and uppercase characters are very important! All commands in C must be in lowercase. The C programs starting point is identified by the word main()
This informs the computer as to where the program actually starts.

The brackets that follow the keyword main indicate that there are no arguments supplied to this program (this will be examined later on).
JUIT Waknaghat 20

Contd
The two braces, { and }, signify the begin and end segments of the program. The purpose of the statment :

#include <stdio.h>
is to allow the use of the printf statement to provide program output. Text to be displayed by printf() must be enclosed in double quotes . The program has only one statement printf("Programming in C is easy.\n")
JUIT Waknaghat 21

Contd
printf() is actually a function in C that is used for printing variables and text. Where text appears in double quotes "", it is printed without modification. There are some exceptions however. This has to do with the \ and % characters. These characters are modifier's, and for the present the \ followed by the n character represents a newline character.
JUIT Waknaghat 22

Contd

Another important thing to remember is that all C statements are terminated by a semi-colon ;

JUIT Waknaghat

23

Summary of major points


program execution begins at main() keywords are written in lower-case statements are terminated with a semi-colon text strings are enclosed in double quotes C is case sensitive, use lower-case and try not to capitalise variable names \n means position the cursor on the beginning of the next line printf() can be used to display text to the screen the curly braces { } define the beginning and end of a program block
JUIT Waknaghat 24

CLASS EXERCISE 1
Q1.1. What is the output of following program ?

#include <stdio.h> main() { printf("Programming in C is easy.\n"); printf("And so is Pascal.\n"); }


JUIT Waknaghat 25

ANSWER 1.1

Programming in C is easy. And so is Pascal. _

JUIT Waknaghat

26

Q1.2 What is the output of following program ?

#include <stdio.h> main() { printf("The black dog was big. "); printf("The cow jumped over the moon.\n"); }
JUIT Waknaghat 27

ANSWER 1.2

The black dog was big. The cow jumped over the moon. _

JUIT Waknaghat

28

Q1.3 Try and work out what the following program displays, #include <stdio.h> main() {
printf("Hello...\n..oh my\n...when do i stop?\n");

JUIT Waknaghat

29

ANSWER 1.3 Hello... ..oh my ...when do i stop? _


JUIT Waknaghat 30

KEYWORDS
Keywords are words reserved by C so they cannot be used as variables.
Keywords
auto break case char const default do double else enum extern float goto if int long register return short signed sizeof static
JUIT Waknaghat

struct switch typedef union unsigned void volatile while


31

continue for

Variables & Data Types


Declaring a variable reserves enough bytes in RAM memory to store value of the declared type. A data type is a set of values and a set of operations on values.The values and operations go together. You can think of them as a unit . The objects of a data type can be variables or constants.
JUIT Waknaghat 32

Contd
C provides the programmer with FOUR basic data types These are: integer character float double

JUIT Waknaghat

33

Contd
The basic format for declaring variables is

data_type var, var, ... ;


where data_type is one of the four basic types, an integer, character, float, or double type.

JUIT Waknaghat

34

DATA TYPE

DESCRIPTION

MEMORY REQUIRMENT 2 bytes(-32767 32767) 4 bytes 4 bytes (1E-37 to 1E+37) 1 byte


(-127 to 127)

int Long int float char double

Integer quantity Integer quantity A number containing a decimal point Any character

A number containing a 8 bytes decimal point but here we can have more significant figures.

JUIT Waknaghat

35

Contd
User defined variables must be declared before they can be used in a program. Get into the habit of declaring variables using lowercase characters. Remember that C is case sensitive, so even though the two variables listed below have the same name, they are considered different variables in C.
sum Sum
JUIT Waknaghat 36

Contd
The declaration of variables is done after the opening brace of main(), e.g. #include <stdio.h> main() {

int sum;
sum = 500 + 15; printf("The sum of 500 and 15 is %d\n", sum); }
JUIT Waknaghat 37

More about printf()


Now lets look more closely at the printf() statement. It has two arguments, separated by a comma. Lets look at the first argument: "The sum of 500 and 15 is %d\n" The % sign is a special character in C. It is used to display the value of variables. When the program is executed, C starts printing the text until it finds a % character. If it finds one, it looks up for the next argument (in this case sum), displays its value, then continues on.
JUIT Waknaghat 38

Contd
The d character that follows the % indicates that a decimal integer is expected. So, when the %d sign is reached, the next argument to the printf() routine is looked up (in this case the variable sum, which is 515), and displayed. The \n is then executed which prints the newline character.
JUIT Waknaghat 39

Some of the formatters for printf are


1. Cursor Control Formatters \n new line \t tab \r carriage return \f form feed \v vertical tab
JUIT Waknaghat 40

Contd
2. Variable Formatters %d decimal integer %c character %s string or character array %f float %e As a float in scientific notation

JUIT Waknaghat

41

Formatted Output
Control strings can also contain:
characters that will be printed on the screen as they appear. Format specifications that define the output format for display of each item. Escape sequence characters such as \n, \t, \r.

JUIT Waknaghat

42

Formatting Output with printf


Format
printf( format-control-string, other-arguments);
Format control string: describes output format,
Ordinary characters: copy to output stream: printf(this is an output\n); Conversion specifications: leading with character % Format:

%-w.plx

[-]: optional left justification, if exists [w]: optional minimal width (wider if necessary). The padding character is blank normally and zero if the field width was specified with a leading zero [.]: optional separates field w and p
JUIT Waknaghat 43

Contd
[p]: optional maximum field width for a string
precision of floating number

[l]: long integer [x]:d decimal signed integer


i decimal signed integer (the d and i specifiers are different when used in scanf) u decimal unsigned integer x hexadecimal unsigned integer (0 9 and a f) X unsigned hexadecimal integer (0 9 and A F) h or l length modifiers; place before any integer conversion specifier to indicate that a short or long integer is displayed respectively

JUIT Waknaghat

44

Contd
o octal unsigned integer f floating pointer number g either f or e, whichever is shorter c single character s character string e exponential floating pointer number Other-arguments: correspond to each conversion specification in format-control-string, such as variables

JUIT Waknaghat

45

Printing Integers
Whole number (no decimal point): 25, 0, -9 Positive, negative, or zero Only minus sign prints by default
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 /* Fig 9.2: fig09_02.c */ /* Using the integer conversion specifiers */ #include <stdio.h> main() { printf( printf( printf( printf( printf( printf( printf( printf( printf( printf( printf(

"%d\n", 455 ); "%i\n", 455 ); /* i same as d in printf */ "%d\n", +455 ); "%d\n", -455 ); "%hd\n", 32000 ); "%ld\n", 2000000000 ); "%o\n", 455 ); "%u\n", 455 ); "%u\n", -455 ); "%x\n", 455 ); "%X\n", 455 );

455 455 455 -455 32000 2000000000 707 455 65081 1c7 1C7

Program Output

JUIT Waknaghat

46

Printing Floating-Point Numbers


Floating Point Number
Have a decimal point (33.5) Exponential notation (computer's version of scientific notation)
150.3 is 1.503 x 10 in scientific 150.3 is 1.503E+02 in exponential (%E stands for exponent) Can use %e or %E

Example:
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15

/* Fig 9.4: fig09_04.c */ /* Printing floating-point numbers with floating-point conversion specifiers */ #include <stdio.h> main() {

Program Output
1.234568e+006

%f : print floating point with at least one digit to left of decimal %g (or G) : prints in f or e with no trailing zeros (1.2300 becomes 1.23) Use exponential if exponent less than -4, or greater than or equal to precision (6 digits by default)

printf( "%e\n", 1234567.89 );

printf( "%e\n", +1234567.89 ); 1.234568e+006 printf( "%e\n", -1234567.89 ); -1.234568e+006 printf( "%E\n", 1234567.89 ); printf( "%f\n", 1234567.89 ); printf( "%g\n", 1234567.89 ); printf( "%G\n", 1234567.89 );
1.234568E+006 1234567.890000 1.23457e+006 1.23457E+006

16 17 return 0; 18 } JUIT Waknaghat

47

Printing Strings and Characters


%c
Prints char argument Cannot be used to print the first character of a string
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* Fig 9.5: fig09_05c */ /* Printing strings and characters */ #include <stdio.h> main() { char character = 'A'; char string[] = "This is a string";

%s
Requires a pointer to char as an argument (line 8) Cannot print a char argument Prints characters until NULL ('\0') encountered Single quotes for character constants ('z') Double quotes for strings "z" (which actually contains two characters, 'z' and '\0')

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

return 0; } A This is a string This is a string This is also a string

Program Output

JUIT Waknaghat

48

Other Conversion Specifiers


%p

%n

Displays pointer value (address) Stores number of characters already output by current printf statement Takes a pointer to an integer as an argument Nothing printed by a %n specification Every printf call returns a value

%%

Number of characters output Negative number if error occurs

Prints a percent sign


JUIT Waknaghat 49

Flags

Using Flags in the printf FormatControl String


Supplement formatting capabilities Place flag immediately to the right of percent sign Several flags may be combined Flag Description Left justify the output within the specified field.

- (minus sign)

+ (plus sign) Display a plus sign preceding positive values and a minus sign preceding negative values. space Print a space before a positive value not printed with the + flag Prefix 0 to the output value when used with the octal conversion specifier Prefix 0x or 0X to the output value when used with the hexadecimal conversion specifiers x or X Force a decimal point for a floating point number printed with e, E, f, g, or G that does not contain a fractional part. (Normally the decimal point is only printed if a digit follows it.) For g and G specifiers, trailing zeros are not eliminated. Pad a field with leading zeros
JUIT Waknaghat 50

0 (zero)

Example:
1 /* Fig 9.11: fig09_11.c */ 2 /* Right justifying and left justifying values */ 3 #include <stdio.h> 4 5 int main() 6 { 7 printf( "%10s%10d%10c%10f\n\n", "hello", 7, 'a', 1.23 ); 8 printf( "%-10s%-10d%-10c%-10f\n", "hello", 7, 'a', 1.23 ); 9 return 0; 10 }

JUIT Waknaghat

51

Program Output:

hello7a1.230000

hello7a1.230000

JUIT Waknaghat

52

Output of Integer Numbers


The format specification is %wd where w specifies the minimum field width for the output. If the number is greater than w, it will be printed in full. The number is written right-justified in the given field width.
JUIT Waknaghat 53

Example
printf(%d,9876) printf(%6d,9876) printf(%2d,9876) printf(%-6d,9876)
9 8 7 9 6 8 7 6

9 8 7 6
9 0 8 0 7 9 6 8 7 6

printf(%06d,9876)

JUIT Waknaghat

54

Output of Real Numbers


The format specification is % w.pf where w indicates the min. no. of positions that are used for the display of the value and p indicates the number of digits to be displayed after the decimal point. The value is rounded to p decimal places. It is printed right-justified.

JUIT Waknaghat

55

Example
printf(%7.4f,98.7654) printf(%7.2f,98.7654) printf(%-7.2f,98.7654) printf(%f,98.7654) 9 9 8 8 9 8 . 9 . . 7 8 7 7 6 . 7 6 5 4 5 7 4 7

printf(%10.2e,98.7654)
printf(%11.4e,-98.7654) 9

9
.

8 8

e + 0 1
e + 0 1
56

8 7 6 5

JUIT Waknaghat

MORE ABOUT VARIABLES


Variables must begin with a character or underscore, and may be followed by any combination of characters, underscores, or the digits 0 - 9. The following is a list of valid variable names: summary exit_flag I Jerry7 Number_of_moves _valid_flag
JUIT Waknaghat 57

Contd
You should ensure that you use meaningful names for your variables. The reasons for this are:
meaningful names for variables are self documenting (see what they do at a glance) they are easier to understand there is no correlation with the amount of space used in the .EXE file makes programs easier to read
JUIT Waknaghat 58

CLASS EXERCISE 3
Q3.1 Why are the variables in the following list invalid, value$sum exit flag 3lotsofmoney char
JUIT Waknaghat 59

ANSWER 3.1
value$sum contains a $ exit flag contains a space 3lotsofmoney begins with a digit char is a reserved keyword

JUIT Waknaghat

60

COMMENTS
The addition of comments inside programs is desirable. These may be added to C programs by enclosing them as follows:

/* bla bla bla bla bla bla */


Note that the /* opens the comment field and */ closes the comment field. Comments may span multiple lines.
JUIT Waknaghat 61

Contd
Comments may not be nested one inside another. For e.g. /* this is a comment. /* this comment is inside */ wrong */ In the above example, the first occurrence of */ closes the comment statement for the entire line, meaning that the text wrong is interpreted as a C statement or variable, and in this example, generates an error.
JUIT Waknaghat 62

What Comments Are Used For


Documentation of variables and their usage Explaining difficult sections of code Describes the program, author, date, modification changes, revisions etc Copyrighting

JUIT Waknaghat

63

PREPROCESSOR STATEMENTS
Note that preprocessor statements begin with a # symbol, and are NOT terminated by a semi-colon. Preprocessor statements are handled by the compiler (or preprocessor) before the program is actually compiled. In general, preprocessor constants are written in UPPERCASE
JUIT Waknaghat 64

Contd
The define statement is used to make programs more readable. Consider the following examples:
#define TRUE 1 #define FALSE 0 #define NULL 0 #define AND & #define OR | #define EQUALS ==
JUIT Waknaghat 65

HEADER FILES
Header files contain definitions of functions and variables which can be incorporated into any C program by using the pre-processor #include statement. Standard header files are provided with each compiler, and cover a range of areas, string handling, mathematical, data conversion, printing and reading of variables.
JUIT Waknaghat 66

Contd
To use any of the standard functions, the appropriate header file should be included. This is done at the beginning of the C source file. For example, to use the function printf() in a program, the line #include <stdio.h> should be at the beginning of the source file, because the definition for printf() is found in the file stdio.h
JUIT Waknaghat 67

Contd
All header files have the extension .h and generally reside in the /include subdirectory.

The use of angle brackets <> informs the compiler to search the compilers include directory for the specified file. The use of the double quotes " around the filename inform the compiler to search in the current directory for the specified file. #include "mydec.h"

JUIT Waknaghat

68

CONSTANTS
INTEGER CONSTANTS FLOATING POINT CONSTANTS CHARACTER CONSTANTS STRING CONSTANTS
JUIT Waknaghat 69

INTEGER & FLOATING CONSTANTS


it is an integer valued number. It consist of any sequence of digits ranging from 0-9. Examples12245, 743 Illegal characters 13,654 36.0 Floating point constant It contains either a decimal point or an exponent Examples1.23 , 827.602, 2E-8
JUIT Waknaghat 70

Class Exercise 4
Determine which of the following are valid integer constants. 0.5 12345 27,234 9.3e-12 9.345
JUIT Waknaghat 71

Character& string constants


A character constant is a single character enclosed in apostrophe (i.e. single quotation mark)

E.g. A v 3
Note- character constant have integer values. its given a code by ASCII

String constants
It includes any number of consecutive characters enclosed in quotation marks

green hello world


JUIT Waknaghat 72

Note
Note there is difference between A and A A -a character constant has a corresponding integer values A it does not have any integer value

JUIT Waknaghat

73

Class Exercise 5
Determine which of following are valid string constants 1) red,white,blue 2) red, white blue 3) name: 4) new york , ny 10020 Determine which of the following are valid character constants a t $ xyz
JUIT Waknaghat 74

ARITHMETIC OPERATORS
The symbols of the arithmetic operators are:Operation Oper ator
*
/ + ++ -%

Comment
sum = sum * 2;
sum = sum / 2; sum = sum + 2; sum = sum -2;

Value of Value of Sum before sum after

Multiply
Divide Addition Subtraction Increment Decrement Modulus

4
4 4 4 4 4 4

8
2 6 2 5 3 1
75

++sum;
--sum; sum = sum %3;
JUIT Waknaghat

ARITHMATIC OPERATION
Operands that differ in type may undergo type conversions before expression takes on its final value. If one operand is an integer and another is a floating point number then we express final result in floating value. If both operands are in integer then final result is also an integer value.

operation K(int) K(float) 12/5 12.0/5 12/5.0 12.0/5.0 2 2 2 2 2.0 2.4 2.4 2.4

JUIT Waknaghat

76

CLASS EXERCISE 6
Q6.1 What is the output of the following program?
#include <stdio.h> main() { int value1, value2, sum; value1 = 35; value2 = 18; sum = value1 + value2; printf("The sum of %d and %d is %d\n", value1, value2, sum); }
JUIT Waknaghat 77

ANSWER 6.1

The sum of 35 and 18 is 53 _

JUIT Waknaghat

78

CLASS EXERCISE 6.2


Q6.2 What is the output of the following program?
#include <stdio.h> main() { int sum = 50; float modulus; modulus = sum % 10; printf("The modulus); }

%%

of %d by 10 is %f \n", sum,

JUIT Waknaghat

79

ANSWER 6.2

Sample Program Output:

The % of 50 by 10 is 0.000000

JUIT Waknaghat

80

Q 6.3 Find the equivalent arithmetic statement: 1. X+=3.0 2. voltage/=sqrt(2)

JUIT Waknaghat

81

ANSWER 6.3
Statement Equivalent -------------------------------------------------------x+=3.0 x=x+3.0; voltage/=sqrt(2) voltage=voltage/sqrt(2);

JUIT Waknaghat

82

PRE/POST INCREMENT/DECREMENT OPERATORS

PRE means do the operation first followed by any assignment operation. POST means do the operation after any assignment operation. Consider the following statements
++count; /* PRE Increment, means add one to count */ count++; /* POST Increment, means add one to count */
JUIT Waknaghat 83

Example
Lets examine what happens when we use the operator along with an assignment operation. Consider the following program,
#include <stdio.h> main() { int count = 0, loop; loop = ++count; /* same as count = count + 1; loop = count; */ printf ("loop = %d, count = %d\n", loop, count); loop = count++; /* same as loop = count; count = count + 1; */ printf("loop = %d, count = %d\n", loop, count); }
JUIT Waknaghat 84

OUTPUT
Sample Program Output: loop = 1, count = 1 loop = 1; count = 2 Note If the operator precedes (is on the left hand side) of the variable, the operation is performed first, so the statement. loop = ++count; really means increment count first, then assign the new value of count to loop.
JUIT Waknaghat 85

Increment / Decrement Operators


Invalid cases
++3 ++(x+y+z) ++x++ 3++ (x+y+z)++ --x---3 --(x+y+z) ++x-3-(x+y+z)---x++

Note: Can not increment or decrement constant and expression i ++j or i + ++j i -j (WRONG) i + -j i - --j

i - ++j

(OK)

Example: i - - j (valid, second is Unary - ) i + + j (invalid, no + Unary)


JUIT Waknaghat 86

Other Examples
Simple cases
++i; i++; (i = i + 1; or i += 1;) --i; i--; (i = i - 1; or i -= 1;) Example: i = 5; i++; (or ++i;)
printf(%d, i) 6

i = 5; i--; (or --i;) printf(%d, i) 4


JUIT Waknaghat 87

Complicated cases
i = 5; j = 5 + ++i; i = 5; j = 5 + i++; i = 5; j = 5 + --i; i 6 j 11

10

i = 5; j = 5 + i--;
JUIT Waknaghat

10

88

Type casting
Sometimes it is important to guarantee that a value is stored as a real number, even if it is in fact a whole number. A common example is where an arithmetic expression involves division. When applied to two values of type int, the division operator "/" signifies integer division, so that (for example) 7/2 evaluates to 3. In this case, if we want an answer of 3.5, we can simply add a decimal point and zero to one or both numbers - "7.0/2", "7/2.0" and "7.0/2.0" all give the desired result.
JUIT Waknaghat 89

Contd
However, if both the numerator and the divisor are variables, this trick is not possible. Instead, we have to use a type cast. For example, we can convert "7" to a value of type double using the expression "static_cast<double>(7)". Hence in the expression
answer = static_cast<double>(numerator) / denominator
JUIT Waknaghat 90

Contd
the "/" will always be interpreted as real-number division, even when both "numerator" and "denominator" have integer values. Other type names can also be used for type casting. For example, "static_cast<int>(14.35)" has an integer value of 14.
JUIT Waknaghat 91

KEYBOARD INPUT
There is a function in C which allows the programmer to accept input from a keyboard. The following program illustrates the use of this function:

JUIT Waknaghat

92

Example
#include <stdio.h> main() /* program which introduces keyboard input */ { int number; printf("Type in a number \n"); scanf("%d", &number); printf("The number you typed was %d\n", number); }
JUIT Waknaghat 93

ANSWER
Sample Program Output: Type in a number 23 The number you typed was 23 _

JUIT Waknaghat

94

More about scanf()


The scanf routine, which accepts the response, has two arguments. The first ("%d") specifies what type of data type is expected (ie char, int, or float). The second argument (&number) specifies the variable into which the typed response will be placed. In this case the response will be placed into the memory location associated with the variable number.
JUIT Waknaghat 95

Formatting Input with Scanf


scanf
Input formatting Capabilities Input all types of data Input specific characters Skip specific characters Format scanf(format-control-string, other-arguments); Format-control-string: describes formats of inputs

%*wlx
[*]: optional conversion only, result is not stored [w]: optional minimum width (wider if necessary). The padding character is blank normally and zero if the field width was specified with a leading zero [l]: long integer [x]: see the table next page Other-arguments Pointers to variables where input will be stored ( address of variables) Can include field widths to read a specific number of characters from the stream
JUIT Waknaghat 96

FORMATTERS FOR scanf()


Conversion specifier Description

Integers
d i Read an optionally signed decimal integer. The corresponding argument is a pointer to integer Read an optionally signed decimal, octal, or hexadecimal integer. The corresponding argument is a pointer to integer. Read an octal integer. The corresponding argument is a pointer to unsigned integer. Read an unsigned decimal integer. The corresponding argument is a pointer to unsigned integer. Read a hexadecimal integer. The corresponding argument is a a pointer to unsigned integer. Place before any of the integer conversion specifiers to indicate that a short or long integer is to be input. JUIT Waknaghat 97

o u x or X h or l

Contd
Floating-point Number
e,E,f,g,G I or L Read a floating point value. The corresponding argument is a pointer to a floating point variable. Place before any of the floating point conversion specifiers to indicate that a double or long double value is to be input

Characters and strings c


Read a character. The corresponding argument is a pointer to char no null (\0) is added Read a string. The corresponding argument is a pointer to an array of type char that is large enough to hold the string and a terminating null (\0) character which is automatically added.
JUIT Waknaghat 98

Contd
Scan set
scan char

Scan a string for a set of characters that are stored in an array.

Miscellaneous
p

Read an address of the same form produced when an address is output with %p in a printf statement Store the number of characters input so far in this scanf. The corresponding argument is a pointer to integer Skip a percent sign (%) in the input
JUIT Waknaghat 99

Formatting Input with 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
JUIT Waknaghat 100

Example
1 /* Fig 9.20: fig09_20.c */ 2 /* Reading characters and strings */ 3 #include <stdio.h> 4 5 main() char x, y[ 9 ]; printf( "Enter a string: " ); scanf( "%c%s", &x, y ); printf( "The input was:\n" ); printf( "the character \"%c\" ", x ); printf( "and the string \"%s\"\n", y ); return 0;
JUIT Waknaghat 101

6 {
7 8 9 10 11 12 13 14 15 16 17 }

Program Output

Enter a string: Sunday The input was: the character "S" and the string "unday"

JUIT Waknaghat

102

Other Input / Output


puts(line)
Example:

Print a string to standard output and append a newline


puts(12345);

putchar(c) gets(line)

Print a character to standard output


putchar(A);
char buf[128];

Example:
Example:

Read a string from standard input (until a newline is entered)

gets(buf); /* space is OK, and the \n wont be read in */ Newline will be replaced by \0

getchar()
Example:

Get a character from standard input


int c;

c = getchar();

/* c must be int */

In-memory Format Conversion


sprintf(string, control, variables); sscanf(string, control, address-of-variables); Example: sprintf(buf, project%03d%02d.dat,year,month); Sscanf(buf, project%03d%02d,&year,&month);

JUIT Waknaghat

103

Operator Precedence
Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: (a + b + c ) / 3
Operator(s) Operation(s) Order of evaluation (precedence)

()

Parentheses

Evaluated first. If the parentheses are nested, the expression in the innermost pair is evaluated first. If there are several pairs of parentheses on the same level (i.e., not nested), they are evaluated left to right.

*, /, or %

Multiplication, Evaluated second. If there are several, they are Division, evaluated left to right. Modulus Addition Subtraction Evaluated last. If there are several, they are evaluated left to right.
JUIT Waknaghat 104

+ or -

Precedence Table
This following slide lists C operators in order of precedence (highest to lowest). Their associativity indicates in what order operators of equal precedence in an expression are applied.

JUIT Waknaghat

105

Operator
()
[] . ->

Description
Parentheses (function call) (see Note 1)
Brackets (array subscript) Member selection via object name Member selection via pointer

Associativity

left-to-right

++ -++ -+ ! ~ (type) * & sizeof * / %

Postfix increment/decrement (see Note 2)


Prefix increment/decrement Unary plus/minus Logical negation/bitwise complement Cast (change type) Dereference Address Determine size in bytes Multiplication/division/modulus left-to-right right-to-left

+ << >> < <= > >=

Addition/subtraction
Bitwise shift left, Bitwise shift right Relational less than/less than or equal to Relational greater than/greater than or equal to
JUIT Waknaghat

left-to-right
left-to-right left-to-right
106

== !=

Relational is equal to/is not equal to

left-to-right

&
^ | && || ?: =

Bitwise AND
Bitwise exclusive OR Bitwise inclusive OR Logical AND Logical OR Ternary conditional Assignment

left-to-right
left-to-right left-to-right left-to-right left-to-right right-to-left right-to-left

+= -= *= /=
%= &= ^= |= <<= >>= ,

Addition/subtraction assignment Multiplication/division assignment


Modulus/bitwise AND assignment Bitwise exclusive/inclusive OR assignment Bitwise shift left/right assignment Comma (separate expressions)
JUIT Waknaghat

left-to-right
107

Example

Order in which a second-degree polynomial is evaluated.


JUIT Waknaghat 108

THE RELATIONAL OPERATORS


Binary Operators == != < > Result is a integer: <= >= 1 means TRUE 0 means FALSE No logical type variable and constants No space between the operators

Example:

Meaning
equal not equal greater less greater equal less equal

C
== != > < >= <=

Expression
5 5 5 5 5 5 == 3 != 3 > 3 < 3 >= 3 <= 3

Result
0 1 1 0 1 0 1 0
109

0==0 int i=10, j=10, k=1; i + j <= 3 + k


JUIT Waknaghat

Contd
These allow the comparison of two or more variables.
Standard algebraic equality operator or relational operator
Equality Operators

C equality or relational operator


== !=

Example of C Meaning of C condition condition

= not =
Relational Operators

x == y x != y x > y x < y x >= y x <= y

x is equal to y x is not equal to y x is greater than y x is less than y x is greater than or equal to y x is less than or equal to y
110

> < >= <=

> < >= <=

JUIT Waknaghat

Example
1 /* Fig. 2.13: fig02_13.c 2 Using if statements, relational 3 operators, and equality operators */ 4 #include <stdio.h> 5 6 /* function main begins program execution */ 7 int main( void ) 8 { 9 int num1; /* first number to be read from user */ 10 int num2; /* second number to be read from user */ 11 12 printf( "Enter two integers, and I will tell you\n" ); 13 printf( "the relationships they satisfy: " ); 14 15 scanf( "%d%d", &num1, &num2 ); /* read two integers */ 16 Checks if num1 is equal to num2 17 if ( num1 == num2 ) { 18 printf( "%d is equal to %d\n", num1, num2 ); 19 } /* end if */ 20 Checks if num1 is not equal to num2 21 if ( num1 != num2 ) { 22 printf( "%d is not equal to %d\n", num1, num2 ); 23 } /* end if */ 24 Checks if num1 is less than num2 25 if ( num1 < num2 ) { 26 printf( "%d is less than %d\n", num1, num2 ); 27 } /* end if */ 28 JUIT Waknaghat 111

29 30 31 32 33 34 35 36 37 38 39 40 41

if ( num1 > num2 ) { } /* end if */ if ( num1 <= num2 ) { } /* end if */

Checks if num1 is greater than num2

printf( "%d is greater than %d\n", num1, num2 );

Checks if num1 is less than or equal to num2

printf( "%d is less than or equal to %d\n", num1, num2 );

if ( num1 >= num2 ) { Checks if num1 is greater than equal to num2 printf( "%d is greater than or equal to %d\n", num1, num2 ); } /* end if */ return 0; /* indicate that program ended successfully */

42 43 } /* end function main */ 43 } /* end function main */

(continued on next slide )

JUIT Waknaghat

112

Output
Enter two integers, and I will tell you the relationships they satisfy: 3 7 3 is not equal to 7 3 is less than 7 3 is less than or equal to 7 Enter two integers, and I will tell you the relationships they satisfy: 22 is not equal to 12 22 is greater than 12 22 is greater than or equal to 12 Enter two integers, and I will tell you the relationships they satisfy: 7 is equal to 7 7 is less than or equal to 7 7 is greater than or equal to 7

JUIT Waknaghat

113

Assignment operators
In C, the = symbol is an assignment operator. It causes the computer to evaluate the expression to the right of the = and assign the value of the expression to the variable to the left of the =. So lets say that x is an integer. the statement "x = 5;" will set the value of the variable named x to 5.
JUIT Waknaghat 114

Confusing Equality (==) and Assignment (=) Operators


Dangerous error
Does not ordinarily cause syntax errors Any expression that produces a value can be used in control structures Nonzero values are true, zero values are
false

Example using ==:


if ( payCode == 4 ) printf( "You get a bonus!\n" );

Checks payCode, if it is 4 then a bonus is awarded


JUIT Waknaghat 115

Contd
Example, replacing == with =:
if ( payCode = 4 ) printf( "You get a bonus!\n" );

This sets payCode to 4 4 is nonzero, so expression is true, and bonus awarded no matter what the payCode was

Logic error, not a syntax error


JUIT Waknaghat 116

Common Programming Error


Using operator == for assignment or using operator = for equality is a logic error.

JUIT Waknaghat

117

Confusing Equality (==) and Assignment (=) Operators


lvalues
Expressions that can appear on the left side of an equation Their values can be changed, such as variable names
x = 4;

rvalues
Expressions that can only appear on the right side of an equation Constants, such as numbers
Cannot write 4 = x; Must write x = 4;

lvalues can be used as rvalues, but not vice versa


y = x;

JUIT Waknaghat

118

Good Programming Practice


When an equality expression has a variable and a constant, as in x == 1, some programmers prefer to write the expression with the constant on the left and the variable name on the right (e.g. 1 == x as protection against the logic error that occurs when you accidentally replace operator == with =.
JUIT Waknaghat 119

Logical (Boolean) Operators


Binary Operators && (and) || (OR) Unary Operator ! (not) Operand must be int
Use float or double, the result may not predictable nonzero (TRUE) zero (FALSE)
Example: Expression 5||3 5||0 5&&3 5&&0 i&&j (if i=0, j=0) i&&j+1 (if i=5, j=0) !5 !0 !i (if i=5) Result 1 1 1 0 0 1 0 1 0

Result is int
1 (TRUE) 0 (FALSE) Express connected by && or || are evaluated from left to right, and evaluation stops as soon as the truth or falsehood of the result is known. i.e. expr1 && expr2 is not equal to expr2 && expr1. This is called short-circuit evaluation. inward == 0 normally be written as !inward (3 < 7) < 5 1<5 1 Example: 1 && 0 0 3<7<5 3 < 7 && 7 < 5 JUIT Waknaghat 120

Logical (Boolean) Operators


AND && OR ||

input1 Input2 output 0 0 1 1 0 1 0 1 0 0 0 1

input1 0
0 1 1

Input2 output 0
1 0 1

0
1 1 1
121

JUIT Waknaghat

Not symbol !
input output

0 1

1 0

JUIT Waknaghat

122

CLASS EXERCISE 7
Suppose i, j,k are integer variables whose value is 1,2,3. what are the values of following logical expressions i<j (i+j)>=k (j+k)>(i+5) k !=3 J==2
JUIT Waknaghat 123

Answer
Expression interpretation i<j (i+j)>=k (j+k)>(i+5) k !=3 J==2 True True False False True
JUIT Waknaghat

value 1 1 0 0 1
124

Conditional (ternary) Operator


Syntax expr1 ? expr2 : expr3
If expr1 0, then execute expr2 and ignore expr3 If expr1 = 0, then execute expr3 and ignore expr2 Example: x = i+j ? i+1 : j+1
Example:

x = 5 ? 4 : 2;
Example:

/* x = 4 */

j = 4; i = 2 x = i+j ? i+1 : j-1


Example: Example:

/* x = 3 */

l = a > b ? a : b; /* the larger of a and b */ max =(a > b)?((a>c)?a:c):(b>c)?b:c);


/* the maximum number among a, b, and c */ Example:

x = a > 0 ? a: -a; /* the absolute value of a */


JUIT Waknaghat 125

sizeof Operator
Syntax
sizeof(expr)
The number of bytes occupied by expr For most computers
sizeof(3) 2 or 4 (bytes) (depending on16 bit CPU or 32 bit CPU), where 3 is an integer sizeof(3L) 4 (long int) sizeof(3.0) 8 (double float) Example: double i; printf(%d,sizeof(i)); 8

Usually, this operator is used to get the size of an organized variable (like struct, union, ) This is one of a few functions that are built-in. No #include is required.
JUIT Waknaghat 126

Address Operator
Syntax

&var
Get the address of the variable & means the address of var Type of var may be
(a) fundamental data type (b) organized data type

Example: int i=100; printf(%d %d, &i, i);

JUIT Waknaghat

127

You might also like