Professional Documents
Culture Documents
History of C
History of C
C
• Evolved by Ritchie from two previous programming
languages, BCPL and B
• Used to develop UNIX
• Used to write modern operating systems
• Hardware independent (portable)
• By late 1970's C had evolved to "Traditional C"
Standardization
• Many slight variations of C existed, and were
incompatible
• Committee formed to create a "unambiguous,
machine-independent" definition
• Standard created in 1989, updated in 1999
C programs consist of pieces/modules called functions
• A programmer can create his own functions
Advantage: the programmer knows exactly how it works
Disadvantage: time consuming
• Structured language
i k
header l library e
(stdio.h) (ANSI)
e r
debugger
r
source object
code code
Terms: Syntax vs Semantics
Syntax: the required form of the program punctuation,
keywords (int, if, return, …), word order, etc.
The C compiler always catches these “syntax errors” or
“compiler errors”
Semantics (logic): what the program means
what you want it to do
The C compiler cannot catch these kinds of errors!
Primary Memory
CPU takes each
6. Execute CPU instruction and
executes it,
possibly storing
..
.. new data values
..
as the program
The Preprocessor
FORTRAN
Used for scientific and engineering applications
COBOL
Used to manipulate large amounts of data
Pascal
Intended for academic use
Structure of a C Program
Documentation Section
Link Section
Definition Section
Global Declaration Section
main() Function Section
{
Declaration Part
Executable Part
}
Subprogram Section
Function1 (User-defined Functions)
Function2
. .
.
.
Function3
Memory Concepts
• Variables
– Variable names correspond to locations in the
computer's memory
– Every variable has a name, a type, a size and a
value
– Whenever a new value is placed into a variable
(through scanf, for example), it replaces (and
destroys) the previous value
– Reading variables from memory does not change
them
C Character Set
Uppercase A..Z
Lowercase a..z
Digits 0..9
Comma ,
Period .
Semicolon ;
Colon :
Question mark ?
Apostrophe ‘
Quotation mark “
Exclaimation mark !
Vertical bar |
Slash /
Backslash \
Tilde ~
Underscore _
Dollar sign $
Percent sign %
Ampersand &
Caret ^
Asterisk *
Minus sign -
Plus sign +
Opening angle bracket <
Closing angle bracket >
Left parenthesis (
Right parenthesis )
Left bracket [
Right bracket ]
Left brace {
Right brace` }
Number sign #
•White spaces
-blank space
-horizontal tab
-carriage return
-new line
-form feed
C tokens
Operators
keywords
Special
Identifiers
symbols
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
C Data Types
Data types in C
Data Types
Primitive Data Type Non-Primitive Data Type User-Defined Data Type Empty Data Type
int arrays
enu
m void
floa structur
t es typede
f
cha unions
r
Size and range of data types
Type Size(bits) Range
Lower Upper
char or signed 8 -128 127
char
unsigned char 8 0 255
int or signed int 16 -32768 32767
unsigned int 16 0 65535
NOTE: There is NO Boolean type in C -- you should use char, int or (better) unsigned char.
Unsigned can be used with all char and int types.
Type of constants
Constants
Numeric Non-Numeric
constants Constants
When you declare a constant it is a bit like a variable declaration except the
value cannot be changed. The const keyword is to declare a constant, as
shown below:
nt const a = 1;
const int a = 2;
typedef –
typedef is an abbreviation used for “Type Definition”. Its purpose is to
redefine the name of an existing data type. This can be later used to
declare variables. Its general form is:
typedef standard-datatype userdefined-datatype.
Ex: (i) typedef int age;
int x;
age p,q,r,s;
Here, all the variables are holding integer value but age helps us to
understand that these 4 variables will hold age. It helps users debugging
the program.
(ii) struct student
{
char name [30];
int roll_no;
float percent;
};
struct student s;
Using typedef:
struct student
{
char name [30];
int roll_no;
float percent;
};
typedef struct student STU;
STU s1, s2;
Enumerated data types
The enumerated data type gives us an opportunity to invent our
own data type and define what values the variables of this data
type can take. Its general form is:
enum datatype-name {val1,val2,…..,valn};
Ex:-
enum weekdays {
Sunday, Monday, Thursday, Wednesday, Thursday,
Friday, Saturday};
weekdays x, y;
(ii) enum marks
{
gradeA=1, gradeB=2, gradeC=3
};
enum marks s1, s2;
printf
Precise output formatting
Conversion specifications: flags, field widths, precisions, etc.
Can perform rounding, aligning columns, right/left justification,
inserting literal characters, exponential format, hexadecimal format,
and fixed width and precision
Format
printf( format-control-string, other-arguments );
Format control string: describes output format
Other-arguments: correspond to each conversion specification in
format-control-string
Each specification begins with a percent sign(%), ends with conversion
specifier
Printing Integers
Integer
Whole number (no decimal point): 25, 0, -9
Positive, negative, or zero
Only minus sign prints by default (later we shall change this)
Conversion Specifier Description
c
Prints char argument
Cannot be used to print the first character of a string
s
Requires a pointer to char as an argument
Prints characters until NULL ('\0') encountered
Cannot print a char argument
Remember
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>
4
1. Initialize
5 int main()
variables
6 {
7 char character = 'A';
8 char string[] = "This is a string"; 2. Print
9 const char *stringPtr = "This is also a string";
10
11 printf( "%c\n", character );
12 printf( "%s\n", "This is a string" );
13 printf( "%s\n", string );
14 printf( "%s\n", stringPtr );
15
16 return 0;
17 }
A
This is a string
This is a string Program Output
This is also a string
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
%%
1 /* Fig 9.7: fig09_07.c */
2 /* Using the p, n, and % conversion specifiers */
3 #include <stdio.h>
4
5 int main() 1. Initialize
6 { variables
7 int *ptr;
8 int x = 12345, y;
9 2. Print
10 ptr = &x;
11 printf( "The value of ptr is %p\n", ptr );
12 printf( "The address of x is %p\n\n", &x );
13
14 printf( "Total characters printed on this line is:%n",
15
&y ); printf( " %d\n\n", y );
16
17 y = printf( "This line has 28 characters\n" );
18 printf( "%d characters were printed\n\n", y );
19
20 printf( "Printing a %% in a format control string\n" );
21
22 return 0;
23 }
The value of ptr is 0065FDF0
The address of x is 0065FDF0 Program Output
Total characters printed on this line is: 41
Field width
Size of field in which data is printed
If width larger than data, default right justified
If field width too small, increases to fit data
Minus sign uses one character position in field
Precision
Meaning varies depending on data type
Integers (default 1)
Minimum number of digits to print
If data too small, prefixed with zeros
Floating point
Number of digits to appear after decimal (e and f)
For g – maximum number of significant digits
Strings
Maximum number of characters to be written from string
Format
Use a dot (.) then precision number after %
%.3f
Printing with Field Widths and Precisions
Flags
Supplement formatting capabilities
Place flag immediately to the right of percent sign
Several flags may be combined
Flag Desc ription
- (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
o.
Prefix 0x or 0X to the output value when used with the hexadecimal conver
sion
specifiers x or X.
hello 7 a 1.230000
Program Output
hello 7 a 1.230000
1 /* Fig 9.14: fig09_14.c */
2 /* Using the # flag with conversion specifiers
3 o, x, X and any floating-point specifier */
4 #include <stdio.h>
5 1. Initialize
6 int main() variables
7 {
8 int c = 1427;
2. Print
9 double p = 1427.0;
10
11 printf( "%#o\n", c );
12 printf( "%#x\n", c );
13 printf( "%#X\n", c );
14 printf( "\n%g\n", p );
15 printf( "%#g\n", p );
16
17 return 0;
18 }
02623
0x593 Program Output
0X593
1427
1427.00
Printing Literals and Escape Sequences
Printing Literals
Most characters can be printed
Certain "problem" characters, such as the quotation mark "
Must be represented by escape sequences
Represented by a backslash \ followed by an escape character
Printing Literals and Escape Sequences
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
Other-arguments
Pointers to variables where input will be stored
Can include field widths to read a specific number of characters from
the stream
Formatting Input with Scanf
C onversion specifier Description
Integers
d Read an optionally signed decimal integer. The corresponding
argument is a pointer to integer.
i Read an optionally signed decimal, octal, or hexadecimal inte ger.
The corresponding argument is a pointer to integer.
o Read an octal integer. The corresponding argument is a pointer to
unsigned integer.
u Read an unsigned decimal integer. The corresponding argument is
a pointer to unsigned integer.
x or X Read a hexadecimal integer. The corresponding argument is a
pointer to unsigned integer.
h or l Place before any of the integer conversion specifiers to indicate
that a short or long integer is to be input.
Floating-point numbers
e, E, f, g or G Read a floating-point value. The corresponding argument is a
pointer to a floating-point variable.
l or L Place before any of the floating-point conversion specifiers to
indicate that a double or long double value is to be input.
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
Usea 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
1 /* Fig 9.20: fig09_20.c */
2 /* Reading characters and strings */
3 #include <stdio.h>
4
5 int main() 1. Initialize
6 { variables
7 char x, y[ 9 ];
8
9 printf( "Enter a string: " ); 2. Input
10 scanf( "%c%s", &x, y );
11
3. Print
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 }
* Multiplication
/ Division
% Modulo Division
Relational Operators
Operator Meaning
== Is equal to
!= Is not equal to
Logical Operators
Operator Meaning
|| Logical OR
! Logical NOT
Increment & Decrement Operator
Operator Meaning
++ Increment
-- Decrement
Conditional Operator
? : -> IF-THEN-ELSE OPERATOR
Assignment Operator
Operator Meaning
~ One’s Complement
| Bitwise OR
^ Bitwise EX-OR
All data represented internally as sequences of bits
Each bit can be either 0 or 1
Sequence of 8 bits forms a byte
~ One’s complement All 0 bits are set to 1 and all 1 bits are set to 0.
Special Operator
Operator Meaning
* Pointer Operator
, Comma Operator
[] Subscript Operator
‘*’ operator is also called “value at address operator”. It gives the value
stored data particular address. This operator is also called “indirection
operator”.
C
Typecasting
Typecasting
=> Typecasting means forcing the compiler to explicitly convert the value
of an expression to a particular datatype.
Ex:
float a;
int x=6, y=4;
a = (float) x/y;
printf(“a=%d”,a);
o/p : 1.5000
Precedence & Associativity of
operators
Operator Precedence
From high priority to low priority the order for all C operators (we have not met all
of them yet) is:
Operator Description Associativity Rank
( ) Function call Left to right 1
[] Array element reference
+ Unary plus Right to left 2
- Unary minus
++ Increment
-- Decrement
! Logical negation
~ 1’s complement
* Pointer reference(indirection)
& Address
sizeof size of an object
(type) Type cast(conversion)
Operator Description Associativity Rank
LINK SECTION
DEFINITION SECTION
SUBPROGRAM SECTION
Function1
Function2
-
-
-
Function n
Developing Simple Program
A Simple C Program printing a line of text
1
2 A first program in C */
3 #include <stdio.h>
4
5 int main()
6 {
7 printf( "Welcome to C!\n" );
8
9 return 0;
10 }
Comments
Text surrounded by /* and */ is ignored by computer
Used to describe program
#include <stdio.h>
Preprocessor directive
Tells computer to load contents of a certain file
<stdio.h> allows standard input/output operations
A Simple C Program printing a line of text
• int main()
– C programs contain one or more functions,
exactly one of which must be main
– Parenthesis used to indicate a function
– int means that main "returns" an integer value
– Braces ({ and }) indicate a block
• The bodies of all functions must be contained in
braces
A Simple C Program printing a line of text
• return 0;
– A way to exit a function
– return 0, in this case, means that the program terminated
normally
• Right brace }
– Indicates end of main has been reached
• Linker
– When a function is called, linker locates it in the library
As before
Comments, #include <stdio.h> and main
int integer1, integer2, sum;
Declaration of variables
• = (assignment operator)
– Assigns a value to a variable
32 num1, num2 );
33