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.
Cont’d
• 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
16
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
17
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
18
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).
18JUIT Waknaghat
19
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.
_
19JUIT Waknaghat
20
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).
20JUIT Waknaghat
21
Cont’d• 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")
21JUIT Waknaghat
22
• 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.
Cont’d
22JUIT Waknaghat
23
• Another important thing to remember is that all C statements are terminated
by a semi-colon ;
Cont’d
23JUIT Waknaghat
24
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
24JUIT Waknaghat
25
CLASS EXERCISE 1Q1.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");
}
25JUIT Waknaghat
26
ANSWER 1.1
Programming in C is easy.
And so is Pascal.
_
26JUIT Waknaghat
27
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");
}
27JUIT Waknaghat
28
ANSWER 1.2
The black dog was big. The cow jumped over the moon.
_
28JUIT Waknaghat
29
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");
}
29JUIT Waknaghat
30
ANSWER 1.3
Hello...
..oh my
...when do i stop?
_
30JUIT Waknaghat
3131
KEYWORDS • Keywords are words reserved by C so
they cannot be used as variables.Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while JUIT Waknaghat
32
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.
32JUIT Waknaghat
33
Cont’d• C provides the programmer with FOUR
basic data types • These are:
– integer–character– float–double
33JUIT Waknaghat
34
Cont’d
• 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.
34JUIT Waknaghat
35
DATA TYPE DESCRIPTION MEMORY REQUIRMENT
int Integer quantity 2 bytes(-32767 32767)
Long int Integer quantity 4 bytes
float A number containing a decimal point
4 bytes(1E-37 to 1E+37)
char Any character 1 byte (-127 to 127)
double A number containing a decimal point but here we can have more significant figures.
8 bytes
35JUIT Waknaghat
36
Cont’d• 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
36JUIT Waknaghat
37
Cont’d• 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); }
37JUIT Waknaghat
38
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.
38JUIT Waknaghat
39
Cont’d
• 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.
39JUIT Waknaghat
40
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
40JUIT Waknaghat
41
Cont’d
2. Variable Formatters
%d decimal integer
%c character
%s string or character array
%f float
%e As a float in scientific notation
41JUIT Waknaghat
42
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
43
Formatting Output with printf• Formatprintf( 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
44
Cont’d–[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
45
Cont’d
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
46
Printing Integers– Whole number (no decimal point): 25, 0, -9– Positive, negative, or zero– Only minus sign prints by default
1 /* Fig 9.2: fig09_02.c */2 /* Using the integer conversion specifiers */3 #include <stdio.h>45 main()6 { 7 printf( "%d\n", 455 );8 printf( "%i\n", 455 ); /* i same as d in printf */9 printf( "%d\n", +455 );10 printf( "%d\n", -455 );11 printf( "%hd\n", 32000 );12 printf( "%ld\n", 2000000000 );13 printf( "%o\n", 455 );14 printf( "%u\n", 455 );15 printf( "%u\n", -455 );16 printf( "%x\n", 455 );17 printf( "%X\n", 455 );18 1920 }
455455455-45532000200000000070745565081 1c71C7
Program Output
Example:
JUIT Waknaghat
47
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– %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)
1 /* Fig 9.4: fig09_04.c */2 /* Printing floating-point numbers with 3 floating-point conversion specifiers */45 #include <stdio.h>67 main()8 { 9 printf( "%e\n", 1234567.89 );
10 printf( "%e\n", +1234567.89 );
11 printf( "%e\n", -1234567.89 );
12 printf( "%E\n", 1234567.89 );
13 printf( "%f\n", 1234567.89 );
14 printf( "%g\n", 1234567.89 );
15 printf( "%G\n", 1234567.89 );
1617 return 0;18 }
1.234568e+0061.234568e+006-1.234568e+0061.234568E+0061234567.8900001.23457e+0061.23457E+006
Program Output
Example:
JUIT Waknaghat
48
Printing Strings and Characters• %c
– Prints char argument– Cannot be used to print
the first character of 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')
1 /* Fig 9.5: fig09_05c */2 /* Printing strings and characters */3 #include <stdio.h>45 main()6 { 7 char character = 'A';8 char string[] = "This is a string";91011 printf( "%c\n", character );12 printf( "%s\n", "This is a string" );13 printf( "%s\n", string );141516 return 0;17 }
AThis is a stringThis is a stringThis is also a string
Program Output
Example:
JUIT Waknaghat
49
Other Conversion Specifiers• %p
– Displays pointer value (address)• %n
– 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
50
Using Flags in the printf Format-Control String
• Flags– Supplement formatting capabilities– Place flag immediately to the right of percent sign– Several flags may be combined
Flag Description
- (minus sign)
Left justify the output within the specified field.
+ (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.
0 (zero) Pad a field with leading zerosJUIT Waknaghat
51
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
52
Program Output:
hello7a1.230000
hello7a1.230000
JUIT Waknaghat
53
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
54
Example
• printf(“%d”,9876)
• printf(“%6d”,9876)
• printf(“%2d”,9876)
• printf(“%-6d”,9876)
• printf(“%06d”,9876)
9 8 7 6
9 8 7 6
9 8 7 6
9 8 7 6
0 0 9 8 7 6
JUIT Waknaghat
55
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
56
Example
printf(“%7.4f”,98.7654)
printf(“%7.2f”,98.7654)
printf(“%-7.2f”,98.7654)
printf(“%f”,98.7654)
printf(“%10.2e”,98.7654)
printf(“%11.4e”,-98.7654)
9 8 . 7 6 5 4
9 8 . 7 7
9 8 . 7 7
9 8 . 7 6 5 4
9 . 8 8 e + 0 1
- 9 . 8 7 6 5 + 0 1eJUIT Waknaghat
57
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
57JUIT Waknaghat
58
Cont’d• 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
58JUIT Waknaghat
59
CLASS EXERCISE 3
Q3.1 Why are the variables in the following list invalid,
• value$sum • exit flag • 3lotsofmoney • char
59JUIT Waknaghat
60
ANSWER 3.1
• value$sum contains a $ • exit flag contains a space • 3lotsofmoney begins with a digit • char is a reserved keyword
60JUIT Waknaghat
61
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.
61JUIT Waknaghat
62
Cont’d• 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.
62JUIT Waknaghat
63
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
63JUIT Waknaghat
64
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
64JUIT Waknaghat
65
Cont’d• 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 ==
65JUIT Waknaghat
66
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.
66JUIT Waknaghat
67
Cont’d• 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
67JUIT Waknaghat
68
Cont’d• 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"
68JUIT Waknaghat
69
CONSTANTS
• INTEGER CONSTANTS
• FLOATING POINT CONSTANTS
• CHARACTER CONSTANTS
• STRING CONSTANTS
JUIT Waknaghat
70
INTEGER & FLOATING CONSTANTS
• it is an integer valued number.• It consist of any sequence of digits ranging from 0-9.Examples-12245, 743Illegal characters 13,654 36.0
Floating point constantIt contains either a decimal point or an exponentExamples-1.23 , 827.602, 2E-8
JUIT Waknaghat
71
Class Exercise 4
Determine which of the following are valid integer constants.
0.51234527,2349.3e-129.345
JUIT Waknaghat
72
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 constantsIt includes any number of consecutive characters enclosed in
quotation marks“green”“hello world”
JUIT Waknaghat
73
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
74
Class Exercise 5
Determine which of following are valid string constants1) ‘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
75
ARITHMETIC OPERATORS • The symbols of the arithmetic operators
are:-
75
OperationOperator Comment
Value of Sum before
Value of sum after
Multiply * sum = sum * 2; 4 8
Divide / sum = sum / 2; 4 2
Addition + sum = sum + 2; 4 6
Subtraction - sum = sum -2; 4 2
Increment ++ ++sum; 4 5
Decrement -- --sum; 4 3
Modulus % sum = sum %3; 4 1
JUIT Waknaghat
76
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 2 2.0
12.0/5 2 2.4
12/5.0 2 2.4
12.0/5.0 2 2.4
JUIT Waknaghat
77
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);
}
77JUIT WaknaghatJUIT Waknaghat
78
ANSWER 6.1
The sum of 35 and 18 is 53
_
78JUIT WaknaghatJUIT Waknaghat
79
CLASS EXERCISE 6.2Q6.2 What is the output of the following
program?
#include <stdio.h> main() { int sum = 50; float modulus; modulus = sum % 10;
printf("The %% of %d by 10 is %f \n", sum, modulus);
}
JUIT Waknaghat
80
ANSWER 6.2
Sample Program Output:
The % of 50 by 10 is 0.000000
JUIT Waknaghat
81
Q 6.3 Find the equivalent arithmetic statement:
1. X+=3.0
2. voltage/=sqrt(2)
JUIT Waknaghat
82
ANSWER 6.3
Statement Equivalent
--------------------------------------------------------
x+=3.0 x=x+3.0;
voltage/=sqrt(2) voltage=voltage/sqrt(2);
JUIT Waknaghat
83
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
84
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
85
OUTPUTSample 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
86
Increment / Decrement Operators
• Invalid cases++3 3++ --3 3--++(x+y+z) (x+y+z)++ --(x+y+z) (x+y+z)--++x++ --x-- ++x-- --x++
Note: Can not increment or decrement constant and expression
i ++j or i –-j (WRONG)i + ++j i + –-j i - --j i - ++j
(OK)
Example:i - - j (valid, second – is Unary - )
i + + j (invalid, no + Unary)JUIT Waknaghat
87
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) 6i = 5;
i--; (or --i;) printf(“%d”, i) 4
JUIT Waknaghat
88
– Complicated casesi = 5; i jj = 5 + ++i;
i = 5;j = 5 + i++;
i = 5;j = 5 + --i;
i = 5;j = 5 + i--;
JUIT Waknaghat
6 11
6 10
4 9
4 10
89
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
90
Cont’d
• 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 expressionanswer = static_cast<double>(numerator) / denominator
JUIT Waknaghat
91
Cont’d• 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
92
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
93
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
94
ANSWER
Sample Program Output:
Type in a number 23
The number you typed was 23
_
JUIT Waknaghat
95
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
96
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
97
Conversion specifier Description
Integersd
i
o
u
x or X
h or l
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.
FORMATTERS FOR scanf()
JUIT Waknaghat
98
Floating-point Numbere,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
s
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.
Cont’d
JUIT Waknaghat
99
Scan setscan char Scan a string for a set of characters that are stored
in an array.
Miscellaneousp
n
%
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
Cont’d
JUIT Waknaghat
100
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 itJUIT Waknaghat
101
1 /* Fig 9.20: fig09_20.c */
2 /* Reading characters and strings */
3 #include <stdio.h>
4
5 main()
6 {
7 char x, y[ 9 ];
8
9 printf( "Enter a string: " );
10 scanf( "%c%s", &x, y );
11
12 printf( "The input was:\n" );
13 printf( "the character \"%c\" ", x );
14 printf( "and the string \"%s\"\n", y );
15
16 return 0;
17 }
Example
JUIT Waknaghat
102
Program Output
Enter a string: SundayThe input was:the character "S" and the string "unday"
JUIT Waknaghat
103
Other Input / Outputputs(line) Print a string to standard output and append a newline
Example: puts(“12345”);putchar(c) Print a character to standard output
Example: putchar(‘A’);
gets(line) Read a string from standard input (until a newline is entered)Example: char buf[128];
gets(buf); /* space is OK, and the ‘\n’ won’t be read in */
– Newline will be replaced by ‘\0’
getchar() Get a character from standard input Example: 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
104
Operator Precedence
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,Division, Modulus
Evaluated second. If there are several, they are evaluated left to right.
+ or - Addition Subtraction
Evaluated last. If there are several, they are evaluated left to right.
Some arithmetic operators act before others (i.e., multiplication before addition)
Use parenthesis when neededExample: Find the average of three variables a, b and c
Do not use: a + b + c / 3 Use: (a + b + c ) / 3
JUIT Waknaghat
105
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
106
Operator Description Associativity
() Parentheses (function call) (see Note 1) left-to-right
[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)
++ -- Prefix increment/decrement right-to-left
+ - Unary plus/minus
! ~ Logical negation/bitwise complement
(type) Cast (change type)
* Dereference
& Address
sizeof Determine size in bytes
* / % Multiplication/division/modulus left-to-right
+ - Addition/subtraction left-to-right
<< >> Bitwise shift left, Bitwise shift right left-to-right
< <= Relational less than/less than or equal to left-to-right
> >= Relational greater than/greater than or equal to
JUIT Waknaghat
107
== != Relational is equal to/is not equal to left-to-right
& Bitwise AND left-to-right
^ Bitwise exclusive OR left-to-right
| Bitwise inclusive OR left-to-right
&& Logical AND left-to-right
|| Logical OR left-to-right
?: Ternary conditional right-to-left
= Assignment 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) left-to-right
JUIT Waknaghat
108
Example
Order in which a second-degree polynomial is evaluated. JUIT Waknaghat
109
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 operatorsExample:
Meaning C Expression Resultequalnot equalgreaterlessgreater equalless equal
==!=><>=<=
5 == 35 != 35 > 35 < 35 >= 35 <= 3
1
0
0==0int i=10, j=10, k=1;
i + j <= 3 + kJUIT Waknaghat
01
1
0
1
0
110
Cont’d• These allow the comparison of two or more variables.
Standard algebraic equality operator or relational operator
C equality or relational operator
Example of C condition
Meaning of C condition
Equality Operators = == x == y x is equal to y
not = != x != y x is not equal to y Relational Operators > > x > y x is greater than y
< < x < y x is less than y
>= >= x >= y x is greater than or equal to y
<= <= x <= y x is less than or equal to y
JUIT Waknaghat
111
Example1 /* 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 17 if ( num1 == num2 ) { 18 printf( "%d is equal to %d\n", num1, num2 ); 19 } /* end if */ 20 21 if ( num1 != num2 ) { 22 printf( "%d is not equal to %d\n", num1, num2 ); 23 } /* end if */ 24 25 if ( num1 < num2 ) { 26 printf( "%d is less than %d\n", num1, num2 ); 27 } /* end if */ 28
Checks if num1 is equal to num2
Checks if num1 is not equal to num2
Checks if num1 is less than num2
JUIT Waknaghat
112
29 if ( num1 > num2 ) {
30 printf( "%d is greater than %d\n", num1, num2 );
31 } /* end if */
32
33 if ( num1 <= num2 ) {
34 printf( "%d is less than or equal to %d\n", num1, num2 );
35 } /* end if */
36
37 if ( num1 >= num2 ) {
38 printf( "%d is greater than or equal to %d\n", num1, num2 );
39 } /* end if */
40
41 return 0; /* indicate that program ended successfully */
42
43 } /* end function main */
43 } /* end function main */
(continued on next slide… )
Checks if num1 is greater than num2
Checks if num1 is less than or equal to num2
Checks if num1 is greater than equal to num2
JUIT Waknaghat
113
OutputEnter two integers, and I will tell you the relationships they satisfy: 3 73 is not equal to 73 is less than 73 is less than or equal to 7
Enter two integers, and I will tell you the relationships they satisfy: 22 is not equal to 1222 is greater than 1222 is greater than or equal to 12
Enter two integers, and I will tell you the relationships they satisfy: 7 is equal to 77 is less than or equal to 77 is greater than or equal to 7
JUIT Waknaghat
114
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 let’s say that x is an integer. the statement "x = 5;" will set the value of the variable named x to 5.
JUIT Waknaghat
115
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
116
Cont’d
• 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
117
Common Programming Error
• Using operator == for assignment or using operator = for equality is a logic error.
JUIT Waknaghat
118
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
119
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
120
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)• 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’Example:
3 < 7 < 53 < 7 && 7 < 5
(3 < 7) < 5 1 < 5 1
1 && 0 0
JUIT Waknaghat
Example:
Expression Result5||3 15||0 15&&3 15&&0 0i&&j (if i=0, j=0) 0i&&j+1 (if i=5, j=0) 1!5 0!0 1!i (if i=5) 0
121
Logical (Boolean) Operators
AND &&
input1 Input2 output
0 0 0
0 1 0
1 0 0
1 1 1
OR ||
input1 Input2 output
0 0 0
0 1 1
1 0 1
1 1 1
JUIT Waknaghat
122
Notsymbol !
input output
0 1
1 0
JUIT Waknaghat
123
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
124
Answer
Expression interpretation value
i<j True 1
(i+j)>=k True 1
(j+k)>(i+5) False 0
k !=3 False 0
J==2 True 1
JUIT Waknaghat
125
Conditional (ternary) Operator• Syntax
expr1 ? expr2 : expr3– If expr1 0, then execute expr2 and ignore expr3– If expr1 = 0, then execute expr3 and ignore expr2Example: x = i+j ? i+1 : j+1Example:x = 5 ? 4 : 2; /* x = 4 */
Example:j = 4;i = 2x = i+j ? i+1 : j-1 /* x = 3 */
Example:l = a > b ? a : b; /* the larger of a and b */
Example: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
126
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 integersizeof(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
127
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