Ent189 Week2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

Salient Features of C

C is a Structured programming language.

Programmer can concentrate only on the problem at hand


and not about the machine.

C language claim to be machine independent.

C language is flexible, simple and easy to use.

C language is based on modular function concepts.


C is a middle level language.
Preceders of C
C language is derived from ALGOL (ALGOrithmic Language).
C language has both program efficiency and machine efficiency.
C language precedes ‘B’ Language which was developed by Ken
Thomson.
C language was developed by Dennis Ritchie with the main features
derived from ALGOL, B and BCPL languages.

Who developed C?
C language was developed by Dennis Ritchie and Ken Thomson at
At&T Bell Laboratories.
A Simple program in C

#include<stdio.h> Pre compiler directives

void main(void) Main functions


{
printf(“Hi Good Morning”);
return;
}

Source Program
Keyboard

Word Processor

Source Program Compiler Object Program

Linker Executable Code

Loader
Input

Memory

Output
CPU
The original program written in a high level language is called the
source program.

A compiler is a program that scans the source program and check


whether the source program has followed the high-level language’s
syntax rule.
If the program is error free, it is converted into machine language
instructions called object program. If the program contains any
syntax error the compilers informs the same to the user.

The compiled program must be linked with operation codes provided


by the high-level language developer using a liker program. When the
program is linked, the object program receives the run time
information such as memory addresses where variables and codes
will be stored. The linker program provides a complete machine
language program called executable code.
The executable code can be now loaded into the computer memory
and a direction must be given to the CPU to begin the execution. As
the program is executed, it takes the one or more input from the
user and sends the result to the user.
PRE PROCESSOR DIRECTIVES

These are special instructions to the compiler.

They instruct the compiler how to prepare the program for


compilation.

The most important pre processor directive is #include statement.

The #include command is used to include the header files at the


time of compilation.

GLOBAL DECLARATIONS
This section defines the variables, functions that are visible or
accessible to the whole program.
MAIN FUNCTION

Every C program should have a function named main.


Execution of a program begins only at main (It is the starting point).
The main function has two divisions namely: Local definition section
and statement section
The definition section should be at the beginning of the main function.
The variables declared inside the main function are local to the main
function and they are not visible to other functions.
The statement section contains the instructions to the computer to
perform various data manipulation operations.
The key word main must be followed by parentheses.
The set of statements belonging to the main function are enclosed
within a pair of braces.
CHARACTER SET OF C

Alphabets A,B,…,Z,
a,b,…,z

Digits 0,1,2,3,4,5,6,7,8,9

Special Symbols
Special Symbols

~ apostrophe | Vertical bar


! Exclamation / Slash
@ at the rate of \ Back slash
# Hash : Colon
% Percentage ; Semi colon
^ Caps Mark . Period
& ampersand , Comma
* Star < Less than
( C open bracket > Greater Than
) C Closing bracket
{ Left curl bracket
} Right curl bracket Note: Symbols other than
[ left square bracket
] Right Square Bracket these are not allowed in C.
_ Under score
- Minus
+ Plus
= Equal to
‘ Single Quote
“ Double Quote
IDENTIFIERS
Identifiers are used to name data, variables and other objects in the
program.
Good identifier names should be short and descriptive.
The identifier name must start with an alphabetic character or
underscore character.
Must consist only alphabetic characters, digits or underscore.
First 31 characters of an identifier are significant.
The identifier must not be a C keyword.
C distinguishes between upper and lower case characters.

The system uses identifiers that have an underscore as the first


character. For this reason it is advisable not to use the underscore as
the first character.
Examples for Identifiers: The following are not
valid identifiers
total
TOTAL total$
sum 1apple
SUM apple=2
member +apple
cost distance in km
mark long
student_id short
i
j
K
sum_123
s1234
_total
Reserved words (32)

auto double if static


break else int struct
case enum long switch
char extern near typedef
const float register union
Continue far return unsigned
default for short void
do goto signed while
CONSTANTS

Data values that cannot be changed during program execution.


DATA TYPES

 The programs manipulate data. Data are stored in the


computer’s internal memory called “cell”.

 A cell is a section of memory that can store one data item


of a particular type at time.

STANDARD DATA TYPES OF C


void
int
char
float
Void Data Type
This data type has no value.
Used for assignment operation.
Can be used as a generic data type (in the case of
pointers).
int DATA TYPE
• A number without a decimal point
• C supports three different sizes of int data type :
short int, int, long int
• The type also defines the size of the field in which the data is
stores.
• The size of any data type can be found using the “sizeof”
operator.
• For any machine the following relation is always true.
• sizeof(short int) <= sizeof(int) <= sizeof(long)
• Each integer type can be further defined as signed integer or
unsigned integer.
• The signed integer can have positive or negative number while
the unsigned integer can have only positive number.
Rules for Constructing Integer constant

1. An integer constant must have at least one digit.


2. It must not have a decimal point.
3. It may be positive or negative.
4. If no sign precedes an integer constant is assumed to be positive.
5. No commas or blanks are allowed within an integer constant.

EXAMPLE:
12 -12 2341 -12321 -98709L

76543LU
Type Bytes Minimum value Maximum value

signed short int 2 -32768 32767


unsigned short int 2 0 65535
signed int (16 bit) 2 -32768 32767

unsigned int (16 bit) 2 0 65535

signed int (32 bit) 4 -2147483648 2147483647

unsigned int (32 bit) 4 0 4294967295


signed long int 4 -2147483648 2147483647

unsigned long int 4 0 4294967295

Note: To provide flexibility across different hardware platforms, C has a library


function limits.h that contains the size information of integers.
FLOATING POINT

A number with a decimal point.

C supports three floating point data type


float (Byte size 4) (f)
double (Byte size 8)
long double (Byte size 10) (L)

The default representation is double.

Example:
0.0 7.231 3.1416 Double
-2.6f 3.232f 7.23123f float
3.121314123L 1.234234L long double
Largest Possible floating point number is 3.40282e+38
Largest Possible double floating point is 1.79769e+308
Largest Possible long double floating point is 1.189732e+4932

Smallest Possible floating point number is 1.17549e-38


Smallest Possible double floating point is 2.22507e-308
Smallest Possible long double floating point is 3.3621e-4932
CHARACTER CONSTANT

Symbols are given numerical values.


Symbols represented in ASCII form
Numerical values range is 0 to 128.
Enclose between two single quotes
Special characters will have a back slash
(known as escape character).

‘A’ = 65; ‘Z’ = 90;


‘a’ = 97; ‘z’ = 122;
‘0’ = 48; ‘1’ = 49;
ESCAPE CHARACTERS

null character ‘\0’


alert ‘\a’
back space ‘\b’
horizontal tab ‘\t’
new line ‘\n’
vertical line ‘\v’
single quote ‘\’’
double quote ‘\”’
back slash ‘\\’
STRING CONSTANTS

A string constant is a sequence of zero or more characters


enclosed in double quotes.

EXAMPLE:
“”
“A”
“UniMAP”
“GOOD DAY”

Note: ‘A’ and “A” are different


LOGICAL DATA TYPE

Represents only two values namely True and False.

In ‘C’ zero represents false and any non zero value
represents true.
VARIABLES
Variable are named memory locations, which stores values that
are going to change during the execution of a program.

Every variable must be declared before assigning a value.

One Byte size


EXAMPLE
x C
char c;
int num;
float cost; 88888 num

8 Byte size
Four byte size
88.777 cost
NOTE A variable can not be of type void.
Variable initialization:
A variable can be assigned a value while declaring them
EXAMPLE

int i = 50; 50 i
char c = ‘a’;
float x = 20.1;
65 c

20.1 x
Type declaration:

EXAMPLE
short int i,j,k;
int m,n;
long int p,q;
unsigned short int u1,u2;
unsigned int m1,m2;
unsigned long int v1,v2,v3;
char letter1, letter2;
float sum,cost,rate;
double phi,charge;
long double ratio,mass,speed;
Structure of a C Program

Pre Compiler Preprocessor Directives


directives

Visible Global Declarations


Globally
void main(void)
Function Beginning {

Local Declarations
Statements

Function end }
A SIMPLE PROGRAM

#include<stdio.h>
/*preprocessor*/
/* main function declaration */
void main (void)
{
/* beginning of main */
printf(“Welcome to UniMAP\n”);
}
/* end of main */
main function
Every C program has a primary function that must be assigned
the name ‘main’.

The name ‘main’ can not be altered by you.

The C compiler needs to know where execution is to begin.


‘main’ is the first function to be executed.
Comment statement

Comments are notes describing what a particular portion of your


program does and how it does it does.

Comments make the program more readable and it is an important


part of documentation.

Text that are written between the starting symbol pair /* and the
ending symbol pair */ forms a comment and it will be ignored by the
compiler.

There should not be any blank space between / and *. The /* and */
form a couple, but they need not be on the same line.
A comment statement can start at any column and may continue to
another line also.

A comment line can be written in the very first line of a program or


on the very last line of a program.

Normally, most of the C compilers treat comment like a single


white space. Therefore, a comment is placed wherever a white
space is allowed to be placed.
Comment Statement Examples:

/* This is a comment */
/ *This is not a comment /
void /*comment*/ main(void)
printf /* comment */ (“UMS”);
printf(/*can not place comment like this */);
#include</*not a valid comment*/stdlib.h>
FORMATED INPUT/OUTPUT FUNCTIONS

A C program accepts data or output the result only through a file.

The keyboard is considered as the standard input file. The


monitor is considered as the standard output file.

When we enter a data on the keyboard, the C program receives


them.

Everything entered into the C program through the keyboard


must be in the form of a sequence of characters.
The standard input file is buffered.
ie. The data are stored into a temporary memory location till the
return key is pressed.

The C program formatting instructions then interpret the sequence


of characters into appropriate form.
scanf()
scanf() function is used to format the input sequence of characters.

KEYBOARD

scanf()

BUFFER

BUFFER
printf()

MONITOR MEMORY
printf()
The printf() function is used to convert the binary and text data
stored in the memory into user readable formatted data.

printf() function requires the following parameters:

Instructions for formatting the data (also known as format string)


The actual data to be printed (also known as data list).

function denoted by ( )

printf ( “format string” , data list ) ;

function name

contains format specifiers

expressions or variable names

statement terminator - semi colon


General syntax of printf ()

printf(format string, data list);

The format string is enclosed in a set of double quotation marks.

The format string contains the text data to be printed and


instructions for formatting the data.

The instructions for formatting the data are specified by field


specifiers.

Each field specification begins with a percent sign (%).


FIELD SPECIFIER

1. a percent sign token ,


2. a conversion code ,
3. optional modifier namely
(i) flag
(ii) minimum width
(iii) precision
(iv) size.
The conversion code specifies the data type. There are 30
different conversion codes.

The general form of a field specifier is

%<flag><minimum width><precision><size>conversion_code
CONVERSION CODE

Char – c
float – f
float scientific – e
integer – d
string – s
unsigned – u
octal – o
hexadecimal – x or X

The size is used to modify the type specified by the conversion


code.
SIZE REPRESENTATION

h – used with integer to represent short integer.


l – used with integer to represent long integer.
L – used with float to represent long double
The width modifier is used to specify the minimum number of
positions in the output.
If the data require more spaces the printf() will override the width
modifier.
The width modifier is used to align the output in columns.
If we don’t use the width modifier, each output will take just enough
room for the data.
Size Code Type Example

None c Char %c

h d short int %hd

None d int %d

l d long int %ld

None f float %f

None f double %f

L f Long double %Lf


Value %d %4d

12 12 BB12

123 123 B123

1234 1234 1234

12345 12345 12345


Precision modifier

1.The precision modifier is used to specify the number of decimal


places.
2.The precision modifier has the following format:
.m
where m represents the number of decimal digits.
3.If the precision modifier is not specified
then printf() prints six decimal positions.

When both width and precision are specified, the width must be
large enough to contain the integral value of the number, the decimal
point and the number of digits in the decimal position.
EXAMPLE

Field Specifier Meaning

%2hd Short integer minimum 2 print positions

%4d Integer 4 print positions

%8ld Long Integer 8 positions

%7.2f Float 7 print positions, nnnn.nn

%10.3L Long double 10 positions,


nnnnnn.nnn
Flag
Flag is used for two print modifications.
If the flag is a minus sign, then the data are formatted as left
justified.
If the flag is zero and there is width specification, the number will
be printed with leading zeros.
Field specifier Meaning
%-8d Integer 8 print positions,
left justify

%08d Integer 8 print positions


with leading zeros
Example 1:
printf(“%d%f%c”,123,4.56,’a’);
1234.560000a

Example 2:
printf(“%d %f %c”,123,4.56,’a’);
123 4.560000 a

Example 3:
printf(“%5d%7.2f”,123,4.56);
bb123bbb4.56
Example 4:
printf(“Transformers”);
Transformers

Example 5:
printf(“My age is %d”,21);
My age is 21

Example 6:
printf(“The cost of pen is %4.2f”,3.20);
The cost of pen is 3.20

Example 7:
printf(“Good Morning Class”);
Good Morning Class
Example 8:
printf(“Good\n\Morning\nClass”);
Good
Morning
Class
Example 9:
Printf(“Good\t\Morning\nClass”);
Good Morning
Class

Example 10:
Printf(“%06d\t%2hd”,22,22);
000022 22
scanf() function

scanf() is used to read the data supplied by the user and to transfer
them to the variable names.
The general syntax of scanf function is:
scanf(format string, address list);
scanf() requires that the variables in the address list be represented
by their addresses. To specify an address, you prefix the variable
name with the address operator, the ampersand (&).
Example:
To read the following data: 214 156 14z
scanf(“%d%d%d%c”,&a,&b,&c,&d);

The ‘scanf’ function allows the user to enter the data through the
standard input (keyboard), formats the data entered and assign
them to variables.
Buffer
Address Data
Keyboard 1 2 3 . 4 H
1500 12 a

1501
b
1502
scanf(“%d %f %c”, &a, &b &c )
1503 3.4

1504

1505 H c

1506
The general form a ‘scanf’ function is

scanf( “format string” , argument address list);

The format string determines how the ‘scanf’ function reads


information into the variables pointed by the argument address list.

The format string contains format specifiers that must match in order
with the arguments type. The number of format specifers must be
equal to the number of addresses in the address list. The ‘scanf’
functions returns the number of fields assigned values. If an error
occurs before any assignments are made, EOF (end of file) is
returned.
A field specifier must begin with a percentage sign. A field speciifer
must have a conversion code. With a few exceptions, the conversion
code used in a ‘printf’ function is used in the ‘scanf’ function also.
The general form of a format specifier is shown below

The conversion codes are used to interpret the data value keyed in by
the users and store them in the variable names. For example, a ‘%c’
field specifier specifies that the input data has to be interpreted as a
character.
Data type Conversion code
Char c
short int
int d
long int
unsigned int
unsigned short int u
unsigned long int
short-octal
int-octal o
long-octal
short-hexadecimal
int-hexadecimal x, X
long-hexadecimal
float
double f
long double
float-scientific
double-scientific e, E, g, G
long double-scientific
String s
Pointer p
When a user enters data, the data values are buffered in the input
stream.
The ‘scanf’ function reads the sequence of characters stored in the
buffer and interprets them using the format specifier.

Except for a character field specifier ‘%c’, the scanf function skips
all the leading white spaces, tabs or new-lines from the input
stream.
If the conversion code is of character type, then the scanf function
reads one character. This may be any character including white
space. While reading a character data and to skip the leading white
space a blank space is always included before the character field
specification (example “ %c”).

If the conversion code is of type numerical ( ‘%d’ , ‘%f’, ‘%e’), and


the format specifier has no width specifier, the ‘scanf’ function
reads the numeric data until it finds a trailing white space.
If the conversion code is of type numerical ( ‘%d’ , ‘%f’, ‘%e’), and
the format specifier has a width specifier, the ‘scanf’ function reads
the numeric data until the maximum number of numerical digits as
specified in the maximum width –specifier has been reached or if it
finds a white space character.

If the ‘scanf’ finds a white space before the maximum number of


numeric digits are processed, it stops.

The user can stop a ‘scanf’ function by signaling that there is no


more input to process by keying end of file (EOF). The user can also
signal the EOF by using ‘ctrl + z’ in microcomputers or using ‘ctrl
+ d’ in Unix and Apple machines.
If a ‘scanf’ encounters any invalid character, when it is trying to
convert the input to the stored data type, it stops. For example, if the
scanf encounters an alphabetical character when it is trying to read a
numerical value, it stops.

When reading a numerical data, the ‘scanf’ can encounter a plus


sign or a minus sign, numerical digits and one decimal point. If the
‘scanf’ function encounters any other character, it will cause an error.
The second argument in the ‘scanf’ function is an address list.

We have already seen that each and every memory location has an
address and using a type declaration statement we have also attached a
name to it. The name is referred as a variable name. Address operator
‘&’ is used to get the address associated to a variable name. For
example if ‘count’ is a variable name and prefixing a ‘&’ symbol to
the variable name, &count is the address.
The following section contains several examples on ‘scanf’
functions.
1. To read integer values
int a,b,c;
scanf(“%d%d%d”,&a,&b&c);

When the user enters the following input on a single


1234b56b7

then ‘a’ will be assigned with the value 1234, the variable ‘b’ will
be assigned with 56 and c will be assigned with the value 7.

The same result will occur if the user enters the three data on three
different lines as
1234
56
7
2. A leading white space is required to read a character. Consider
the following example.
int a;
char c;
scanf(“%d%c”,&a,&c);

a. If the user enters the following data as: 1234bx

Then the variable ‘a’ will be assigned with 1234 and a white space
character is assigned to c.

b. If the user enters as: 1234x

The variable ‘a’ is assigned with 1234 and the variable c will be
assigned with ‘x’.
The ‘scanf’ function shown above is modified as
scanf(“%d %c”,&a,&c);
c. If the user enters the data as
1234bx

The variable ‘a’ is assigned with 1234 and the variable c will be
assigned with ‘x’.
3. To read an integer, float and a character type data

int a;
float f;
char c;
scanf(“%d %f %c”,&a,&f,&c);
printf(“%d %f %c:,a,f,c);

If the user enters the following data

12 34.435 A

The output of the program fragment is

12b34.435000bA
4. To read data using a format specifier that has a maximum width
specifier

int a;
float f1,f2;
scanf(“%3d%5f%5f”,&a,&f1,&f2);
printf(“%d %f %f\n”,a,f1,f2);

If the user enters the following data

12312.3412.345

the ‘printf’ functions prints the output as

12b12.340000b12.345000
5. If the number of field specifiers is more than the number of
addresses in the address list, the ‘scanf’ forces the user to input as
many data values as the number of field specifiers. After reading
the data, the system will indicate the null pointer assignment.

int a,b;
scanf(“%d%d%d”,&a,&b);

The ‘scanf’ will force the user to input three values and as it is not
possible to assign all the three values, it will give an error
message as a “Null pointer assignment”.
Write a program that prompts the user to enter four integer
numbers and print them horizontally and vertically.

#include<stdio.h>

int main(void)
{
int a, b, c, d;
printf(“Please enter four numbers “);
scanf(“%d %d %d %d”,&a,&b,&c,&d);
printf(“\nYou have entered \n”);
printf(“%d %d %d %d\n”,a,b,c,d);
printf(“\nThe numbers are printed vertically\n”);
printf(“%d\n%d\n%d\n%d\n”,a,b,c,d);
return 0;
}
A sample run of the above program
is shown below.

Please enter four numbers 12 345


6789 123

You have entered


12b345b6789b123

The numbers are printed vertically


12
345
6789
123
Write a program in C that prompts the user to enter the length, breadth and height of a
room. The program should accept the data keyed in by the user and displays them
with appropriate messages.

/* Program to Read and Display room dimensions */

int main(void)
{
float length, breadth, height;
printf(“Enter the length of the room “);
scanf(“%f”, &length);
printf(“Enter the breadth of the room “);
scanf(“%f”,& breadth);
printf(“Enter the height of the room “);
scanf(“%f”, &height);
printf(“\nRoom Dimensions \n”);
printf(“Length = %.2f\n”, length);
printf(“Breadth = %.2f\n”, breadth);
printf(“Height = %.2f\n”, height);
return 0;
}
A sample run of the above program is shown below.

Enter the length of the room 10.23


Enter the breadth of the room 6.0
Enter the height of the room 5.12

Room Dimensions
Length = 10.23
Breadth = 6.00
Height = 5.12
Thank You

You might also like