Unit-1 CPNM-1

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 36

1.

UNIT-1

INTRODUCTION TO C PROGRAMMING

History of C
 C language is a structure oriented programming language, was developed at Bell
Laboratories in 1972 by Dennis Ritchie
 C language features were derived from earlier language called “B” (Basic Combined
Programming Language – BCPL)

 C language was invented for implementing UNIX operating system

 In 1978, Dennis Ritchie and Brian Kernighan published the first edition  “The C
Programming Language” and commonly known as K&R C

 In 1983, the American National Standards Institute (ANSI) established a committee to


provide a modern, comprehensive definition of C. The resulting definition, the ANSI
standard, or “ANSI C”, was completed late 1988.

FEATURES or CHARACTERISTICS OF ‘C’ LANGUAGE

General-Purpose Programming Language: ‘C’ was originally developed for system


programming, but it is also used for writing commercial and scientific application.
Structured Programming Language: ‘C’ provides the fundamental flow-control (if, switch,
while, for loop etc.) constructs required for well-structured programs.
System Programming: ‘C’ Language is used to develop compilers, operating systems and other
utility programs for system software.
Portability: ‘C’ programs written for one computer can be executed on another with little or no
modifications
Modularity: Through modularization, we can break down program code into small functional
units called functions and then combine them to make a complete application.
Maintainability: It is reliable, simple, and easy to use.

1
Code-reusability: Programmer can easily create functions and use them again in different
applications.
Extensive library functions: ‘C’ language has a large set of library functions. Any
complex program can be easily written using these built-in functions
Efficiency and speed: the execution time of the ‘C’ program is very less.
Limited keywords: It has only 32 keywords and hence several standard functions are available
with ‘c’ are used for developing error free programs.

1.BASIC STRUCTURE OF A ‘C’ PROGRAM


The program written in C language follows this basic structure. The sequence of sections should
be as they are in the basic structure. A C program should have one or more sections but the
sequence of sections is to be followed.
1. Documentation section
2. Linking section
3. Definition section
4. Global declaration section
5. Main function section
{
Declaration section
Executable section
}
6. Sub program (User-defined Functions) section
Function 1
Function 2
-------------
-------------
Function N

2
1. Documentation Section: comes first and is used to document/write the program's objective,
developer and logic details. The documentation is done in C language with /* and */. Whatever is
written between these two are called comments. A comment is a nonexecutable statement in a
program.
2. Linking/Including Section: This section tells the compiler to link the certain occurrences of
keywords or functions in your program to the header files specified in this section.
e.g. #include <stdio.h>
3. Definition section: It is used to declare some constants and assign them some value
e.g. #define MAX 25
Here #define is a compiler directive which tells the compiler whenever MAX is found in the
program replace it with 25.
4. Global Declaration Section: There are some variables that are used in more than one
function. Such variables are called ‘Global Variables’ and are declared in the global declaration
section i.e. Outside of all the functions including main() function.
e.g. int i; (before main())
5. Main Function Section: tells the compiler where to start the execution from main()
6. Subprogram Section: Contains all the user defined functions that are called in the main
function.

‘C’ CHARACTER SET


Character set is a set of valid characters that a language can recognize.
A character represents any letter, digit or any other sign.
Letters ----- A, B, C……Z or a, b, c …………z.
Digits ----- 0,1…………9
Special Symbols ------ ~! @ # $ % ^ &.........
White Spaces ------- Blank space, horizontal tab, carriage return, new line, form feed.

‘C’ TOKENS
The smallest individual unit in a program is known as a token.
C has six tokens
i. Keywords
3
ii. Identifiers
iii. Constants
iv. Strings
v. Operators
vi. Special symbols
i. Keywords: System defined words are called keywords. All keywords have fixed meaning and
these meanings can’t be changed. All key words must be written in lower case. E.g.:- auto, long,
char, short etc. There are 32 key words in ‘C’ language.

ii. Identifiers: Identifiers refer to the names of variable, functions and arrays. These are user-
defined names. An identifier in C can be made up of letters, digits and underscore. Identifiers
may start with either alphabets or underscore. The underscore is used to make the identifiers easy
to read and mark functions or library members.
iii. Constants: - A Constant is a fixed value. That does not change during the execution of a
program. C support several types of constants.
a. Numerical Constants
i. Integer Constant
1. Decimal Integer Constant
2. Octal Integer Constant
3. Hexadecimal Integer Constant
ii. Real/ Float Constant
b. Character Constants
i. Single Character Constant
ii. String Constant
i. Integer Constant: An integer constant is a whole number without any fractional part. C has
three types of integer constants.
4
Decimal Constant: Decimal integer constant consists of digits from 0 through 9 preceded by an
optional sign .e.g.: 34, 900, 3457, -978
Octal Constant: An Octal integer constant consists of digits from 0 through 7. In C the first digit
of an octal number must be a zero (0) so as to differentiate it from a decimal number.
e.g.: 06, 034, -07564 etc.
Hexadecimal Constant: A hexadecimal integer constant consists of combination of digits 0
through 9 and alphabets from ‘a’ through ‘f’ or ‘A’ through ‘F’. In C, a hexadecimal constant
must begin with 0x or 0X (zero x) so as to differentiate it from a decimal number. e.g.:- 0x50,
0XAC2 etc.
Rules for constructing an integer constant:
An integer constant must have at least one digit.
It must not have a decimal point.
It could be either positive or negative
If no sign precedes and it is assumed to be positive
No commas or blank spaces are allowed with in an integer constant
The allowable range for integer constant is -32768 to +32767
ii. Floating Constants (Real): Real or floating point numbers can contain both an integer part
and a fractional part in the number. Floating point numbers may be represented in two forms,
either in the fractional form or in the exponent form.
A float point number in fractional form consists of signed or unsigned digits including decimal
point between digits. E.g.:- 18.5, .18 etc.
Very large and very small numbers are represented using the exponent form. The exponent
notations use the ‘E’ or ‘e’ symbol in the representation of the number. The number before the
‘E’ is called as mantissa and the number after forms the exponent.
e.g.:-5.3E-5,-6.79E3, 78e05 etc.
Single Character Constant: A character constant is usually a single character or any symbol
enclosed by apostrophes or single quotes. e.g. ch =’a’
String Constant: A sequence of character enclosed between double quotes is called string
constant. e.g.: “Hello Good Morning”
iv) Punctuations: 23 characters are used as punctuations in C. e.g.: + - / ; : > ! etc.

5
CREATING AND RUNNING PROGRAMS
Computer hardware understands a program only if it is coded in its machine language. It is
the job of the programmer to write and test the program .There are four steps in this process:
1.Writing and Editing the program
2.Compiliing the program
3.Linking the program with the required library modules
4.Executing the program.

1. Writing and Editing Programs


The software used to write programs is known as a text editor. A text editor helps us
enter, change, and store character data. Depending on the editor on our system, we could use it to
write letters, create reports, or write programs. The main difference between text processing and
program writing is that programs are written using lines of code, while most text processing is
done with character and lines.
Text editor is a generalized word processor, but it is more often a special editor included
with the compiler. Some of the features of the editor are search commands to locate and replace
statements, copy and paste commands to copy or move statements from one part of a program to
another, and formatting commands that allow us to set tabs to align statements. After completing

6
a program, we save our file to disk. This file will be input to the compiler; it is known as a
source file.

2. Compiling Programs:
The code in a source file stored on the disk must be translated into machine language; this
is the job of the compiler. The c compiler is two separate programs. The preprocessor and the
translator.
The preprocessor reads the source code and prepares it for the translator. While preparing
the code, it scans for special instructions known as preprocessor commands. These commands
tell the preprocessor to look for special code libraries, make substitutions in the code, and in
other ways prepare the code for translation into machine language. The result of preprocessing is
called the translation unit.
After the preprocessor has prepared the code for compilation, the translator does the
actual work of converting the program into machine language. The translator reads the
translation unit and writes the resulting object module to a file that can then be combined with
other precompiled units to form the final program. An object module is the code in machine
language. The output of the compiler is machine language code, but it is not ready to run; that is,
it is not executable because it does not have the required C and other functions included.
3. Linking Programs:
A C program is made up of many functions. We write some of these functions, and they are a
part of our source program. There are other functions, such as input/output processes and,
mathematical library functions, which exist elsewhere and must be attached to our program. The
linker assembles all of these functions, ours and systems into our final executable program.
4. Executing Programs:
Once program has been linked, it is ready for execution. To execute a program we use an
operating system command, such as run, to load the program into primary memory and execute
it. Getting the program into memory is the function of an operating system program known as
the loader. It locates the executable program and reads it into memory. When everything is
loaded, the program takes control and it begins execution.
In a typical program execution, the reads data for processing, either from the user or from a file.
After the program processes the data, it prepares the output. At output can be to the user’s
7
monitor or to a file. When the program has finished its job, it tells the operating system, which
then removes the program from memory.

DATA TYPES
To represent different types of data in C program we need different data types. A data type is
essential to indicate the types of data a variable can have and the type of operations that can be
performed on that data. C supports four different classes of data types namely
1. Primary or Simple or Basic or Fundamental or Primitive data types
2. Derived data types
3. User defined data types
4. Empty data set
1. Simple Data Types: There are four simple data types in C. They are
a. int
b. char
c. float
d. double
These data types can hold maximum one value at a time.

Integer Type:

The key word ‘int’ is used to declare integer type variables.


We can use sign qualifiers (signed or unsigned) and size qualifiers(short or long) in the
declaration of integer type variables
The qualifiers ‘short’ and ‘signed’ are the default qualifiers and hence they are optional in
the declaration
Float Type:
The keywords ‘float’ and ‘double’ are used to declare float type variables.
We can also use qualifiers to declare float type variables
Character type:
The keyword ‘char’ is used to declare character data type variables.
It contains any alphabet, digit, or special character

8
Each character has a code associated with it. This code is called ASCII (American Standard
Code for Information Interchange) value.
For example, The ASCII code for the letter ‘A’ is 65,the ASCII code for the letter ‘a’ is
97,the ASCII code for the digit ‘2’ is 50 and so on.
The following table shows the Storage size and Range of basic data types:

2. Derived Data Types: Derived data types are constructed from the simple data types and or
other derived data types. These data types are used to hold more than one value of similar type.
Derived data types include arrays, functions, pointers, references, constants, structures, unions
and enumerations. Structures, unions data types are used to hold more than one value of
dissimilar type.
3. User defined data types: These are created with typedef and enum keywords.
Syntax: typedef type identifier;
enum identifier {var1,var2,---------varn};
Example: typedef int INTEGER;
INTEGER a, b, c;
typedef int units;
units batch1,batch2;

9
Void Data Type: The data type void is used to specify an empty set of values and do not occupy
any memory. Void type is generally used with functions that do not return any value to the
calling portion of the program.
Syntax: void function-name()
Example: void main()

VARIABLES
A variable is an identifier which changes its value during the execution of a program. It is a
symbolic name given to the memory location where data is stored .Each variable may take on
any value or a specified type. e.g.: name, sum, stu_name, acc_no etc.
Rules for naming a variable:
A variable must contain combination of alphabets (A-Z, a-z), digits (0-9) and _
(Underscore).
The first letter should be either an alphabet or an underscore. Digit is not allowed.
A variable can have maximum number of characters up to 8 and some compilers allow up to
31 characters.
Commas are not allowed
Blank spaces are not allowed
Special symbols other than underscore are not allowed
Keywords must not be used as identifiers
A variable name must not be repeated in the declaration
Examples: Valid Variables: a salary sum stud_name c123 etc.
Invalid Variables: a+b (Special character is there)
2abc (First letter should not be alphabet)
Declaration of variables: A variable must be declared before it is used in the program, the
declaration of variables tells the compiler to reserve memory space with specified variable names
depending on the specified data type.
The general format of variables declaration is as follows:
Datatype var1[, var2, ------, var-n];
Examples: int a, b, sum;
float avg, f;
10
char ch;
Initialization of variables: Assigning a value to a variable while declaration is called
initialization of variables. If a variable is not initialized it contains garbage value.
Syntax:
Datatype var1=value[,var2=value,----------,var-n=value];
Examples:
1. int a=40, b=50, c=90;
In this example variables a, b, c are declared as integer data type and they are initialized
with values 40, 50 and 90 respectively
2. int a, b=50, c;
In this example variables a, b, and c are declared as integer data type. But the variable
‘b’ is initialized with value=50.The variables ‘a’ and ‘c’ are not initialized.

The array is another kind of variable that is used extensively in C. An array is an identifier that
refers to a collection of data items that all have the same name. The data items must all be of
the same type (e.g., all integers, all characters, etc.). The individual data items are represented
by their corresponding array-elements (i.e., the first data item is represented by the first array
element, etc.). The individual array elements are distinguished from one another by the value
that is assigned to a subscript.
There are several different ways to categorize arrays (e.g., integer arrays, character
arrays, onedimensional arrays, multi-dimensional arrays).
EX: Char letter[10]=”california”;

11
EXPRESSIONS
An expression is a combination of operators and operands which reduces to a single value. An
operator indicates an operation to be performed on data. An operand is a data item on which
operation to perform.
Example: sum= a+b; a, b are operands and + is operator.
A simple expression contains only one operator. A complex expression contains more than one
operator.
An Expression can be divided into six categories based on the no.of operators, no.of operands
and position of operators.
1. PRIMARY Expression
2. POST FIX
3. PREFIX

12
4. UNARY
5. BINARY
6. TERNARY
PRIMARY Expression: It can be a name, constant, a parenthesized expression.
Ex: c=a + (5*b);
POST FIX Expression: In postfix expression the operator will be after the operands. The
postfix expression consists of one operand and one operator.
Ex: Post increment operator ‘a++’
Post decrement operator ‘a—‘
Ex: z=a++ z=a; a=a+1;
PREFIX Expression: In prefix expression the operator will be before the operands. The prefix
expression consists of one operand and one operator.
Ex: pre increment operator ‘++a’
Pre decrement operator ‘--a’
Ex: z=++a, a=a+1; z=a;
UNARY EXPRESSION: The unary expression contains one operator and one operand.
Ex: a++,--b;
BINARY EXPRESSION: the binary expression contains two operands and one operator.
Ex: a+b, c*d;
TERNARY EXPRESSION: the ternary expression contains three operands and one operator
Ex: Exp1? exp2:exp3;
If exp1 is true, exp2 is executed otherwise exp3 is executed.
Ex: int a=75, b=30, c,d;
c=(a<b)? (a+b) : (a-b);
printf(“%d”,c);
d=(a<b)?(a+b) : (a-b);
printf(“%d”,d);
O/P : 105 45

STATEMENTS

13
A statement causes the computer to carry out some action. There are three different classes of
statements in C. They are expression statements, compound statements and control
statements. An expression statement consists of an expression followed by a semicolon.
The execution of an expression statement causes the expression to be evaluated.
EXAMPLE

The first two expression statements are assignment-type statements. Each causes the value of the
expression on the right of the equal sign to be assigned to the variable on the left. The third
expression statement is an incrementing-type statement, which causes the value of ito increase
by 1.
A compound statement consists of several individual statements enclosed within a pair of
braces { }.

The individual statements may themselves be expression statements, compound statements


or control statements.
Control statements are used to create special program features, such as logical tests, loops and
branches.

SYMBOLIC CONSTANTS

14
A symbolic constant is a name that substitutes for a sequence of characters. The
characters may represent a numeric constant, a character constant or a string constant. Thus, a
symbolic constant allows a name to appear in place of a numeric constant, a character constant
or a string. When a program is compiled, each occurrence of a symbolic constant is replaced by
its corresponding character sequence.
Symbolic constants are usually defined at the beginning of a program. The symbolic
constants may then appear later in the program in place of the numeric constants, character
constants, etc. that the symbolic constants represent.
A symbolic constant is defined by writing
#define name text
where name represents a symbolic name, typically written in uppercase letters, and text
represents the sequence of characters that is associated with the symbolic name. Note that
text does not end with a semicolon, since a symbolic constant definition is not a true C
statement.
EX: A C program contains the following symbolic constant definitions

Notice that the symbolic names are written in uppercase, to distinguish them from ordinary C
identifiers. Also, note that the definitions do not end with semicolons. Now suppose that the
program contains the statement
area = PI * radius * radius;
During the compilation process, each occurrence of a symbolic constant will be replaced by its
corresponding text. Thus, the above statement will become
area = 3.141593 * radius * radius;
15
Symbolic constants are not required when writing C programs. Their use is recommended,
however, since they contribute to the development of clear, orderly programs.
The #define feature, which is used to define symbolic constants, is one of several features
included in the C preprocessor (i.e., a program that provides the first step in the translation of a
C program into machine language).

OPERATORS
An operator is a symbol used to perform particular operation on operands. ’C’
language supports the following types of operators.
1. Arithmetic operators
2. Unary operators( Increment or Decrement operators)
3. Relational operators
4. Logical operators
5. Assignment operators
6. Conditional operator
7. Bit wise operators
8. Special operators

1. ARITHMETIC OPERATORS: Arithmetic operators are used to perform arithmetic


calculations. The following are the various arithmetic operators.

2. UNARY OPERATORS
C includes a class of operators that act upon a single operand to produce a new value. Such
operators are known as unary operators. Unary operators usually precede their single
operands, though some unary operators are written after their operands.
16
Perhaps the most common unary operation is unary minus, where a numerical constant,
variable or expression is preceded by a minus sign.

Here are several examples which illustrate the use of the unary minus operation.
-743 -0X7FFF -0.2 -5E-8
-root1 -(x + Y) -3 * (x + y)
In each case the minus sign is followed by a numerical operand which may be an integer
constant, a floating-point constant, a numeric variable or an arithmetic expression.
There are two other commonly used unary operators: The increment operator, ++, and the
decrement operator, --. The increment operator causes its operand to be increased by 1, whereas
the decrement operator causes its operand to be decreased by 1. The operand used with each
of these operators must be a single variable.

INCREMENT OPERATOR (++): The increment operator is a unary operator. It is used to


increase the value of an operand by 1.
Pre-increment: If the ‘++’ operator precedes the operand then it is called “Pre-increment”. In
this method, the pre-increment operator increments the value of variable first and then the new
value is used in the expression.
Example: c=++a; means a=a+1;
c=a;
Program: main()
{
int a=10, z;
z=++a; Output
printf(“z=%d”,z”); z=11
printf(“a=%d”,a); a=11
}

Post-increment: If the ‘++’ operator succeeds the operand then it is called “Postincrement”. In
this method, the old value of the variable is used in the expression and then it is incremented.
Example: c=a++; means c=a;
17
a=a+1;
Program: main()
{
int a=10, z;
z=a++; Output
printf(“z=%d”,z”); z=10
printf(“a=%d”,a); a=11
}
DECREMENT OPERATOR (--): The decrement operator is a unary operator. It is used to
decrease the value of an operand by 1.The operand must be a variable
Pre-decrement: If the ‘--’ operator precedes the operand then it is called “Pre-decrement”. In
this method, the pre-decrement operator decrements the value of variable first and then the new
value is used in the expression.
Example: c=--a; means a=a-1;
c=a;
Program: main()
{
int a=10, z;
z=--a; Output
printf(“z=%d”,z”); z=9
printf(“a=%d”,a); a=9
}
Post-decrement: If the ‘--’ operator succeeds the operand then it is called “Postdecrement”. In
this method, the old value of the variable is used in the expression and then it is decremented.
Example: c=a--; means c=a;
a=a-1;
Program: main()
{
int a=10, z;
z=a--; Output
printf(“z=%d”,z”); z=10
18
printf(“a=%d”,a); a=9
}

3. RELATIONAL OPERATORS: The relational operators are used to compare two values and
to give either true (1) or false (0) result. These are used to form simple conditions. The following
are the relational operators.

Program: main() OUTPUT


{
int a=10,b=20;
Printf(“%d”,a<b); 1
Printf(“%d”,a<=b); 1
Printf(“%d”,a>b); 0
Printf(“%d”,a>=b); 0
Printf(“%d”,a==b); 0
Printf(“%d”,a!=b); 1
}

4. LOGICAL OPERATORS: These are used to combine two or more conditions and give
either true or false. They are used to perform compound conditions.

Logical AND (&&) Operator: This operator gives true if all the conditions are true otherwise it
gives false.
Logical OR (||) Operator: This operator gives true if any one of the conditions is true otherwise
it gives false.

19
Logical NOT (!) Operator: This operator negates the result of a condition. It means if the
condition is true then it gives false. If the condition is false then it returns true.
5. ASSIGNMENT OPERATORS: The assignment operators are used to assign (store) a value
to a variable.an assignment operator always consists a variable on left hand side and a valid
expression/constant /variable on right hand side.
Variable = Expression/Constant/Variable
Example: a=10; a= c+d; a=c;
There are two types of assignment operators.
1. Simple assignment operator
2. Compound assignment operator

Program: main()
{
int a=10; Output
printf(“%d”,a); 10
printf(“%d”,a=+10); 20
}
6. CONDITIONAL OPERATORS: This operator performs condition based execution. It is
also known as Ternary Operator. This operator simplifies “if……else” control statement. The
general form of conditional operator is as follows
Syntax: (condition)? Statement 1: statement 2;
The conditional operator first evaluates the given condition. If the condition is true then
‘statement1’is evaluated. If the condition is false then ‘statement2’is evaluated.
Example: main()
{
int a, b, large;
printf(“Enter 2 number”);
scanf(“%d%d”,&a,&b);

20
large=(a>b)?a:b;
printf(“%d”,large);
}
7. BITWISE OPERATORS: ‘C’ Language has the capability of manipulating the bits (0 or 1)
directly stored in the memory. These operators perform bitwise operations on a bit by bit level.
These operators must be used only with integer or character type of values not with float. The
operators are as follows
Bitwise AND (&) operator: If all the bits are ‘1’ then this operator returns ‘1’ otherwise it
returns ‘0
Bitwise OR (|) operator: If any or all the bits are ‘1’ then this operator returns ‘1’ otherwise it
returns ‘0’
Bitwise XOR (^) operator: If one bit is ‘1’ and other is ‘0’ then this operator returns ‘1’
otherwise it returns ‘0’
1’s complement (~) operator: This operator is a unary operator that reverses the state of each
bit. That means it changes “0” as “1” and “1” as “0”.
Left Shift (<<) Operator: This operator is used to move bit pattern to the left and filled with
zero in right side.
Right Shift (>>) Operator: This operator is used to move bit patterns to the right and filled with
zero in left side.
8. Special Operators: The following are the special operators used in ‘C’ language.
 sizeof operator
 typecast operator
 Address operator
 Indirection operator
 Comma operator
sizeof operator: This operator returns the size of an operand . It is useful to find the size of
arrays and structures. The general format is as follows:
syntax: sizeof(operand) here the operand may be a variable or data type.
Examples:
Exression value of ‘a’
a=sizeof(int) 2
21
a=sizeof(float) 2
typecast operator: when a value is converted from one data type to another data type then it is
called type casting. The expression or variable must be preceded by the desired data type name
enclosed within parenthesis.
Syntax: (datatype)expression;
Example: int a=25; float y;
y=(float)a/4 ;
Address operator (&): The address operator gives the address of the variable. This operator
returns unsigned integer value.
Syntax: &variable Example: a=&b;
Program: main()
{ int a=10;
float b=25.5;
printf(“The value of a is %d”,a);
printf(“The address of a is %u”,&a);
printf(“The address of b is %u”,&a);
}
Indirection operator (*): The indirection operator gives the value at the specified address.
Syntax: *(address) Example: a=*b;
Comma operator (,): This operator is used to separate multiple statements. Normally it is
appear in the following statements
Variable declaration
Input and output statements
Control statements

Library functions

The C language is accompanied by a number of standard library functions which


carry out various useful tasks. In particular, all input and output operations (e.g.,
writing to the terminal) and all math operations (e.g., evaluation of sines and cosines)
are implemented by library functions.
22
In order to use a library function, it is necessary to call the appropriate header file at
the beginning of the program. The header file informs the program of the name, type,
and number and type of arguments, of all of the functions contained in the library in
question. A header file is called via the preprocessor statement

#include <filename>
where filename represents the name of the header file.

A library function is accessed by simply writing the function name, followed by a list
of arguments, which represent the information being passed to the function. The
arguments must be enclosed in parentheses, and separated by commas: they can be
constants, variables, or more complex expressions. Note that the parentheses must be
present even when there are no arguments. Some of library files are

1. stdio.h: I/O functions:


1. getchar() returns the next character typed on the keyboard.

2. putchar() outputs a single character to the screen.

3. printf() as previously described

4. scanf() as previously described

2. string.h: String functions

1. strcat() concatenates a copy of str2 to str1

2. strcmp() compares two strings

3. strcpy() copys contents of str2 to str1

1. ctype.h: Character functions

1. isdigit() returns non-0 if arg is digit 0 to 9

23
2. isalpha() returns non-0 if arg is a letter of the alphabet

3. isalnum() returns non-0 if arg is a letter or digit

4. islower() returns non-0 if arg is lowercase letter

5. isupper() returns non-0 if arg is uppercase letter

1. math.h: Mathematics functions

1. acos() returns arc cosine of arg

2. asin() returns arc sine of arg

3. atan() returns arc tangent of arg

4. cos() returns cosine of arg

5. exp() returns natural logarithim e

6. fabs() returns absolute value of num

7. sqrt() returns square root of num

1. time.h: Time and Date functions

1. time() returns current calender time of system

2. difftime() returns difference in secs between two times

3. clock() returns number of system clock cycles since program execution

1. stdlib.h:Miscellaneous functions

1. malloc() provides dynamic memory allocation, covered in future sections

2. rand() as already described previously

3. srand() used to set the starting point for rand()

INPUT AND OUTPUTSTATEMENTS


24
The C language is accompanied by a collection of library functions which includes a  number of
input/output functions. The basic input/output functions  are getchar, putchar, puts,gets,scanf
and printf.

An input/output function can be accessed from anywhere within a program simply by writing the
function name, followed by a list of arguments enclosed in parentheses. The arguments represent
data items that are sent to the function. Some input/output functions do not require arguments,
though the empty parentheses must still appear.

Single Character Input: the getchar Function

The getchar function is a part of the standard C input/output library. This Function reads a single
character from the standard input device. There is no parameter within the parentheses. Its syntax
is:
    char_var = getchar();    
where char_var is a character type variable to which an accepted character is assigned.

Example:
main()
{
char a;
a= getchar();
printf(“%c”,a);
}

Character String input: the gets Function

This Function reads in everything you enter from the keyboard until the ENTER key or
RETURN is pressed. Here everything means a string which is a sequence of all printable ASCII
characters. The syantax is:
    gets(string);    

where string is a sequence of characters and is of type char.

Example:
main()
{
char name[25];
printf(" Enter your Name\n");
gets(name);
25
printf(“%s”,name);
}
Single Character Output: the putchar Function

Single characters can be displayed using the C library function putchar. The putchar function like
getchar is a part of the standard C input/output library.

This Function prints a single character on the screen. The character to be displayed is of type char. Its
syntax is:
   putchar(ch_var);    
where ch_var is a character variable which is enclosed within the parenthesis.

EX: #include<stdio.h>

main()

char c;

printf("n Please enter a character:");

c=getchar();

printf("n The character entered is: ");

putchar(c);

Character String Output: the puts Function

This Function prints a string of characters on the screen. The syntax is:
   puts(string);   
where string is a sequence of characters.

Example:
Program:
#include<stdio.h>
main()
{
char msg[20];
printf(" Enter the msg\n");
26
gets(msg);
puts(msg);
}

Entering Input Data: the scanf Function

Input data can be entered from a standard input device by means of the C library function scanf.
This function can be used to enter any combination of numeric values, single characters and
strings.

In general terms, the scanf function is written as:

scanf(“control string”, arg1, arg2,.........,argN)


where control string refers to a string containing certain required formatting information,
and arg1,arg2,….,argN are arguments that represent the individual data items

The control string consists of the individual group of characters called format specifiers,
with one character group for each input data item. Each character group must begin with a per
cent sign (%) and be followed by a conversion character which indicates the type of the data
item.

The most commonly used conversion characters are listed below:

Conversion Character     Data type of input data

c                         character

d                         decimal integer

f                         floating point value

s                         string
The arguments to a scanf function are written as variables or arrays whose types match
the corresponding character groups in the control string. Each variable name must be preceded
by an ampersand (&). However, character array names do not begin with an ampersand.

Example 1:

#include<stdio.h>

27
int main()

char a[20];

int   i;

float b;

printf(" n Enter the value of a, i and b");

scanf("%s %d %f", a, &i, &b);

In the above program, within the scanf function, the control string is "%s %d %f". It
denotes three-character groups or format specifiers. The first format specifier %s denotes that the
first argument a represents a string (character array), the second format specifier %d denotes that
the second argument  i is an integer and the third format specifier %f denotes that the third
argument b is a floating point number.

Also note that the only argument not preceded by an ampersand (&) is a since a denotes a
character array.

The s-type conversion character applies to a string that is terminated by a whitespace


character. Therefore a string that includes whitespace characters cannot be entered in this
manner. To do so, there are two ways:

1. The s-type conversion character is replaced by a sequence of characters enclosed in


square brackets, designated as [. . .]. Whitespace characters are also included in the string
so that a string that contains whitespaces may be read.

Example:

#include<stdio.h>

main()

char line[80];

scanf(" %[  ABCDEFGHIJKLMNOPQRSTUVWXYZ]", line);


28
printf("%s", line);

2. To enter a string that includes whitespaces as well as uppercase and lowercase characters we
can use the circumflex, ie (^), followed by a newline character within the brackets.
Example:

scanf("%[^\n]", line);

EX:
main()
{
char name[50];
clrscr();
printf("enter names");
scanf("%[^\n]",name);
printf("%s",name);
getch();
}

Reading Numbers: Specifying Field Width

The consecutive non-whitespace characters that define a data item collectively define a field. To
limit the number of such characters for a data item, an unsigned integer indicating the field
width precedes the conversion character. The input data may contain fewer characters than the
specified field width. Extra characters will be ignored.

Example: If a and b are two integer variables and the following statement is being used to read
their values:

scanf( "%3d %3d", &a, &b);

and if the input data is: 1 4

then a will be assigned 1 and b 4.

If the input data is 123 456 then a=123 and b=456.

If the input is 1234567, then a=123 and b=456. 7 is ignored.

29
If the input is 123 4 56 (space inserted by a typing mistake), then a=123 and b=4. This is because
the space acts as a data item separator.

Writing Output Data: the printf Function

The printf function is used to output any combination of numerical values, single characters
and strings. The general form of the printf function is:

                      printf(“control string”, arg1, arg2, … , argN)

The control string consists of one or more of the following items:

 Characters that are simply printed as they are; ie, messages or prompts
 Conversion Specifications — the field width and the format specifier

 Escape Sequences — used to print certain non-printing characters like newline, tab and
bell alert

The arguments  arg1, arg2, … , argN are the variables whose values are formatted and
printed according to the specifications of the control string. The arguments must match in
number, order and type with the format specifications.

Example:

#include<stdio.h>
int main()
{

int marks=412;

float percent=85.4;

printf("n Marks= %d,n Percentage=%f ",marks, percent);

}
Output:
Marks= 412
Percentage= 85.4
A minimum field width can be specified  by preceding the conversion character with an
unsigned integer. If the number of characters in the corresponding data item is less than the
specified field width, the data item will be preceded by enough leading blanks to fill the
specified field. If the number of characters exceeds the field width, additional space will be
allocated to the data item, so that the entire data item can be displayed.

30
EX:

#include<stdio.h>
main()
{
int i = 1234;
float x= 348.45;
char a[];
printf( " %3d %5d %8d" , i, i, i);
printf("%7f  %7.1f  %7.3f ", x,x,x);
printf ("%10s %13s %10.5s",a,a,a);

Specifying Flags in printf:

In addition to the field width, the precision and the conversion character, each character group
within the control string can include a flag which affects the appearance of the output.

Some of the most commonly used flags are:

 -  Data item is left justified within the field (blank spaces required to fill the minimum
field width will be added after the data item. By default, numbers are printed right
justified.
 +  A sign (either + or -) will precede each signed numerical data item. Without this flag
only negative data items are preceded by a sign.

 0  Causes leading zeros to appear instead of leading blanks. Applies only to those data
items that are right justified within a field whose minimum field width is larger than the
data item.

 '  '  A blank space will precede each positive number. This flag is overridden by the + flag
if both are present.

 #  with o and x type conversion) Causes octal and hexadecimal data items to be preceded
by 0 and 0x respectively.

 #  (with e, f, and g type conversion) Causes a decimal point to be present in all floating
point numbers even if it is a whole number. Also prevents the truncation of trailing zeros
in g-type conversion.

The following example illustrates the use of flags with floating point and integer quantities.

main( ) /* use of flags with integer and floating-point numbers */

31
int i = 123;.
float x = 12.0, y = -3.3;
printf(':%6d %7.0f %lO.le:\n\n", i, x, y);
printf(' :%-6d %-7.0f %-lO.le: \n\n" 1, x, y) ;
printf(":%+6d %+7.0f %+lO.le:\n\n', 1, x, y);
printf(":%-+6d %-+7.0f %-+lO.le:\n\n", 1, x, y);
printf(":%7.0f %#7.0f %7g %#7g:", x, x, y, y);
}

Many modern computer programs are designed to create an interactive dialog between
the computer and the person using the program (the "user"). These dialogs usually involve
some form of question-answer
interaction, where the computer asks the questions and the user provides the answers, or
vice versa. The computer and the user thus appear to be carrying on some limited form of
conversation.
In C, such dialogs can be created by alternate use of the scanf and printf functions. The
actual programming is straightforward, though sometimes confusing to beginners, since the
printf function is used
both when entering data (to create the computer's questions) and when displaying results. On
the other hand, scanf is used only for actual data entry.
EX:
main()
{
float n,s,sr;
printf("enter the number:");
scanf("%f",&n);
s=pow(n,2);
sr=sqrt(n);
printf("\n the square is:%f \n the sqare root is:%f",s,sr);
getch();
}
Arithmetic Precedence and Associativity
Operator Precedence in C
Operator precedence determines which operator is evaluated first when an expression has more
than one operators. For example 100-2*30 would yield 40, because it is evaluated as 100 –

32
(2*30) and not (100-2)*30. The reason is that multiplication * has higher precedence than
subtraction(-).

Associativity in C
Associativity is used when there are two or more operators of same precedence is present in an
expression. For example multiplication and division arithmetic operators have same precedence,
lets say we have an expression 5*2/10, this expression would be evaluated as (5*2)/10 because
the associativity is left to right for these operators. Similarly 20/2*5 would be calculated as
(20*2)/5.

Operator precedence and Associativity Table in C Programming

Description Operator Associativity

Function expression () Left to Right

Array Expression [] Left to Right

Structure operators -> Left to Right

Unary minus – Right to Left

Increment & Decrement —  ++ Right to Left

One’s compliment ~ Right to Left

Pointer Operators &* Right to Left

Type cast (data type) Right to Left

size of operator sizeof Right to Left

33
Left and Right Shift >>  <<

Arithmetic Operators

Multiplication operator, Divide by, Modulus *,  /,  % Left to Right

Add, Substract +,  – Left to Right

Relational Operators

Less Than < Left to Right

Greater than > Left to Right

Less than equal to <= Left to Right

Greater than equal to >= Left to Right

Equal to == Left to Right

Not equal != Left to Right

Logical Operators

AND && Left to Right

OR || Left to Right

34
NOT ! Right to Left

Bitwise Operators

AND & Left to Right

Exclusive OR ^ Left to Right

Inclusive OR | Left to Right

Assignment Operators

= Right to Left

*= Right to Left

/= Right to Left

%= Right to Left

+= Right to Left

-= Right to Left

&= Right to Left

35
^= Right to Left

|= Right to Left

<<= Right to Left

>>= Right to Left

Other Operators

Comma , Right to Left

Conditional Operator ?: Right to Left

36

You might also like