Professional Documents
Culture Documents
Unit I C
Unit I C
Unit I C
IMPORTANCE OF C
C is highly portable i.e., Software written for one computer can be run on another
computer. C language is well suited for structured programming. An important feature of
‘C’ is its ability to extend itself. A C program is basically a collection of functions. It
encourages us to write out own functions and add to the C library. Also C is modular, i.e.,
a unit of task can be performed by a single function and this unit of task can be reutilized
when needed. The large number of functions makes programming task simple.
Every C program starts with a function called main(). This is the place where
program execution begins. Hence, there should be main() function in every program. The
functions are building blocks of C program. Each function has a name and a list of
parameters ( or arguments).
1
Documentation section
Linkage section
Definition section optional
Global declaration section
main ()
{
Declaration part
Execution part / statement part
}
Sub program section
Or optional
User defined section
Documentation section:
This section group of comments that explains about program name, purpose of the
program, program logic, programmer name, date of written program etc.
Comments can be included anywhere into the program. Comments are enclosed
between /* and */.
Linkage Section:
It is the pre processing directive operation section under this we can include the
header files with the # include <header file name. h>
Or
# include “header file name. h”
Whenever we are using standard functions into the main program those are
referred into the header files. When we included header file. Otherwise it gives error
message header file inclusion error
# include < stdio. h> or # include < graphic. h>
2
Definition section:
It is also the pre-processing directive operation. Under this we can define the
symbolic constant with the # define identifier data.
Example: #define
These symbolic constant calls as macros. These macros are global.
3
The following is a simple C program that prints a message on the screen.
# include <stdio.h>
/* A simple program for printing a message */
main()
{
printf( “ hello , this is a C program.”);
}
# include <stdio.h>
tells the compiler to read the file stdio.h and include its contents in this file. stdio.h, one of
header files, contain the information about input output functions. The next line is a
comment line Comments in the C program are optional and may appear anywhere in a C
program. Comments are enclosed between /* and */.
main() is the start of the main program. The word main is followed by a pair of
ordinary parenthesis (), which indicates that main is also a function. The left brace {
represents the beginning of the function where as the right brace } represents the end of
the function. It means, the braces enclose the body of function. In this program, the body
consists of only one statement, the one beginning with printf. The printf() function is
causes its arguments to printed on the computer screen. The closing (right) brace of the
main function is the logical end of the program.
4
5. No restriction in using blank spaces or blank lines that separates different words
or different parts of program. Blank spaces improve the readability of the
statements. But blank spaces are not allowed within a variable, constant or
keyword.
6. Comments cannot be nested. For example,
/* A simple ‘C’ program, /* it prints a message */ */
is not valid.
7. A comment can be split into more than one line.
Execution of C program:
Steps to be followed in writing and running a C program.
(a) Creation of Source Program
(b) Compilation of the Program (Alt + F9).
(c) Program Execution (ctrl + F9).
(d) Output or Console Screen ( Alt +f5).
5
CONSTANTS, VARIABLES, AND DATA TYPES:
C Tokens
A C program must be syntactically valid sequences of characters of the language.
In every C program, the most basic element recognized by the compiler is single character
or group of characters called C tokens.
Steps in learning C language are…
1. Character Set – Alphabets, Digits and Special Symbols
2. Datatypes, Constants, Variables and Keywords
3. Instructions
4. Functions, Program
The C character set:
The C character set includes the upper case letters A to Z, the lower case a to z,
the decimal digits 0 to 9 and certain special characters/symbols. The character set is
given bellow.
Alphabets A, B, C, …….Z
a, b, c,. ……. Z
Digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special characters/Symbols~, . : ; ? ‘ “ ! ( ) [ ] { } / \ < > = + - $ # & * % ^
White Spaces blank space,horizontal,carriage return,new line
and form feed
Keywords and Identifiers:
Key words are predefined tokens in C. these are also called as reserved words.
Key words have special meaning to the C compiler. These key words can be only for
their intended action. They cannot be used for any other pupose.
The standard key words are:
auto break case char const continue
default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while
6
Data types and Sizes:
A data type a set of values and the operations that can be performed on them.
Every data type item (constant, variable etc.) in a C program has a data type associated
with it.
The memory requirements for each data type will determine the permissible range
of values for that type. These requirements may vary from one compiler to another.
Generally the following rule is true for any complier to specify the size of data types:
char ≤ sizeof(short int)≤ sizeof(int) ≤ sizeof(long int) ≤ sizeof(float) ≤ sizeof(double)
int %d
unsigned int %u
long int %ld
unsigned long int %lu
char %c
float %f
double %lf
long double %Lf
7
Datatype Description Size Range
in Bytes
Signed Character 1 -128 to +127
char/char
Unsigned char Unsigned character 1 0 to 255
8
Constants and variables:
A constant is a literal, which remain unchanged during the execution of a program.
A variable is a name that is used to store data value and is allowed to vary the value
during the program execution.
Constants:
A constant is a fixed value that cannot be altered during the execution of a program.
C Constants can be classified into two categories.
1. Primary constants.
2. Secondary constants.
Constants
Integer float
Single char string
Integer constants:
An integer constant is an integer-valued number consisting of a sequence of digits.
The following are the rules for constructing integer constants.
1) An integer constant must have at least one digit.
2) It should not contain either a decimal point or exponent.
3) If a constant is positive, it may not be preceded by a plus sign. If it is a negative,
it must be preceded by a minus sign.
4) Commas, blanks and non digit-characters are not allowed in integer constants.
5) The valid range is –32768 to +32767.
These range my larger for 32 bit computers.
9
Real constants:
Real constants are often called floating-point constants. These are two ways to
represent a real constant decimal form and exponential form.
Real constants expressed in decimal form must have at least one digit and one
decimal point. As in the case of integers, the real constants can be either positive or
negative. Commas, blanks, and non-digit characters are not allowed with in a real
constant.
In exponential form, a real constant is expressed as an integer number or a decimal
number multiplied by an integral power of 10. This simplifies the writing of very large and
very small numbers. In this representation, letter e is written instead of 10, the power is
written just to the right of e. generally, the part appearing before e is called mantissa,
whereas the part following e is called exponent.
Rules for constructing real constants are:
1) The mantissa part and the exponential part should be separated by a letter e.
2) The mantissa part may have a positive or negative sign. Default sign of mantissa
part is positive.
3) Commas, blanks and non-digit characters are not allowed with in a real constant.
4) The exponent part must be an integer.
5) The mantissa part must have at least one digit.
6) Range of real constants expressed in exponential form is –3.4e38 to +3.4e38
String constants:
A string constant is a sequence of characters enclosed in double quote. The
characters may be letters, numbers, blank space or special characters.
Example: “welcome”
“this is a sting”
“a+b=8”
““
“a”
Note that ““ is a null string or empty string. And the single string constant “a” is not
equivalent to the single character constant ‘a’.
10
Each sting constant must end with a special character ‘\0’. This character is called
null character and used to terminate the string. The compiler automatically places a null
‘\0’ character at the end of every string constant. This constant is not visible when the
string is displayed. The null character is very much useful in finding the end of a string.
Variables:
A variable can be considered as a name given to the location in memory. The term
variable is used to denote any value that is referred to a name instead of explicit value. A
variable is able to hold different values during execution of a program.
For example, in the equation 2x+3y=10; since x and y can change, they are
variables, whereas 2,3 and 10 cannot change, hence they are constants.
Rules for constructing variable names:
1) The name of a variable is composed of one to several characters; the first of which
must be a letter.
2) No special characters other than letters, digits, and underscore can be used in
variable name. some compilers permit underscore as the first character.
3) Commas, or blanks are not allowed with in a variable name.
4) Upper case and lower case letters are significant (different).
5) The variable name should not be a C key word. Also it should not have the same
name as a function.
Examples: income, name, rate, marks, sno, etc.
Operators in C :
There are 8 types of operators in C. They are
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators && Compound assignment operators
5. Increment and Decrement operators
6. Bit wise operators
7. Conditional operators
8. Special operators
11
1). Arithmetic Operators:-
These are used for the mathematical operations.
Operator Meaning
+ addition
- subtraction
* multiplication
/ division
% modulus
The division operator ( / ) gives the quotient of the division.
The modulus operator ( % ) gives the remainder of the division.
Note:- All operators must works only with two operands. so these are also called as the
"Binary operators". Example:
main()
{
int a =10,b=20,c; /* variable declaration part */
c=a+b;
printf(“%d”, c); /* it displays addition of c value */
c= a-b;
printf(“%d”, c);
c= a*b;
printf(“%d”, c);
c= a/b;
printf(“%d”, c);
c= a%b;
printf(“%d”, c);
getch();
}
Note:
- Compilation of the Program (Alt + F9).
- Program Execution (ctrl + F9).
- Output or Console Screen ( Alt +f5).
12
Output:
30
-10
200
0
10
2). Relational operators:-
These are the operators, which tell the relation between the values or operands.
In C language all relational and logical operators returns 1 or zero. If the expression is
true then it will gives 1 other wise 0.
Operator Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equals to
!= Not equals
Examples on relational operators:-
- a=3<4; 1
- a=3>2; 1
- a=2>=3; 0
- a= 5<=5; 1
- a= 5==5; 1
- a= 5!=8; 1
3). Logical operator:-
The logical operators are used to compare more than one condition
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Truth table for AND (&&) operator:
13
Expression1 Expression2 Result
T T T
T F F
F T F
F F F
examples:-
1. a = 1&&1; 1
2. a = 7&&5; 1
3. a = 5>4 && 4>10; 0
4. a = 5>4 || 4>10; 1
5. a = 1 || 0 1
6. a = !1 0
7. a = 1 && 4>3 1
8. a = ! (5>5); 1
4). Assignment operator (=):
The assignment operator can be used to store the data into the identifier (variable).
The nature of storage is that right side of the data stored into left side of identifier.
Ex: a=10;
14
Assignment operators (+=, - =, * =, / =, % =):
The compound assignment operator can be used to minimize the arithmetic
operations.
Example:
a+= 1; it is equal to a= a+1;
b+=a; it is equal to b= b + a;
c-=a; it is equal to c= c-a;
d*= a ; it is equal to d= d*a;
a/=b; it is equal to a=a/b;
b%=a; it is equal to b=b%a;
Increment (++)
Always it increment only one value to the existing identifier. They are two types.
++a pre-increment.
a++ post-increment
pre- increment:
When ever the pre-increment operators using into the arithmetic expressions then
it is increasing the one value to the adjusting identifier and participating into the
expressions. This can be written ++identifier.
Ex: ++a;
Post- increment:
When ever the post incrimination operators including into the arithmetic operators
then the identifier values directly participating into the arithmetic expressions. After that
the identifier value incrementing by one only.
Syntax:
identifier ++ ;
Ex: a++;
15
Decrement operator (- - ):
It is always decreased by one value and result stored into the same identifier. We
have two types of decrement operators.
Pre – decrement ex: --a;
Post – decrement ex: a--;
Pre – decrement:
When ever pre – decrement operators using into the arithmetic expressions then
it is decreasing the one value to the adjusting identifier and processing into the
expressions. This can be written as -- identifier.
Ex: --a;
Post decrement:
When ever the post decrement operators including into the arithmetic operations
then the identifier values directly participating into the arithmetic expressions. After that
the identifier values decrement by one only.
Syntax:
Identifier --;
16
expression. These operators work only with int and char datatypes and cannot be used
with float or double type.
Bitwise Exclusive OR (XOR) Operator:
An exclusive OR set the 0 bit 1, if both bits that are compared are different. The
truth-values for XOR are.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
for example 127 ^ 120 is
01111111 127 in binary
01111000 120 in binary
XOR result= 00000111
Bitwise complement operator:
The bitwise complement (or one’s complement) operator ~ (called tilde) changes
each 1 bit in its operand to 0 and changes 0 bit to 1, ~0= 1, ~1= 0.
For example:
Consider that , the int variable has the value 5.
The binary number is 0000000000000101
The bitwise complement ~ is 1111111111111010
Shift Operators >> and <<
The shift operators move all the bits in a variable to the right or left as specified.
The general form of the shift right statement is
Variable >> number of bit positions.
The general form of the shift left statement is
Variable << number of bit positions,
As bit are shifted out to one end, the zeros are entered from the other end. The bits which
are shifted out are lost. The shifting of bit is not a rotation of bits.
Consider the following operations where the initial value of x is 9
X=9 00001001 9
X << 1 00010010 18
17
X << 1 00100100 36
X << 2 10010000 144
X >> 1 01001000 72
X >> 1 00100100 36
X >> 2 00001001 9
It can be noted from the above operations that the left shift by one place is nothing
but multiplications of a number with 2, and the right shift by one place is nothing but
division of a number by 2 .
7). Conditional operator (?:)
C provides a peculiar operator ?: which is useful in reducing the code. It is ternary
operator requiring three operands.
The general format is
Exp1 ? Exp2 : Exp3 ;
Where exp1, exp2 and exp3 are expressions. The constituents of conditional operator
are separated in conditional expressions and the order should not be changed, that is
should be in between the first two expressions and : should be between the second and
third expressions.
In the above conditional expression, exp1 is evaluated first. If the value of exp1 is
non zero (true), then the value returned will be exp2. if the value of exp1 is zero (false).
Then the value returned will be exp3.
Example:
#include < stdio.h>
main()
{
int option;
printf(“Enter any number “);
scanf(“%d”, &option);
option ? printf(“Entered non-zero number”): printf(“entered zero”);
}
example 2: z= (x>10 ? 8: -3);
18
8). Special operators:
1. Comma operator:-
The comma operator allows two or more different expressions to appear when
only one expression is expected. The expressions are separated by the comma
operator.
The general form is
Exp1,exp2, exp3,…expn
2. Size of operator
The sizeof operator in c will determine the size of variables storage in bytes.
The sizeof operator is a unary operator and can be used to know the size of any
variable, constant, etc. the sizeof operator is very useful in writing machine-
independent program.
19
GETS() :
gets reads a whole line of input into a string until a newline or EOF is encountered. It is
critical to ensure that the string is large enough to hold any expected input lines.
PUTS():
puts writes a string to the output, and follows it with a newline character.
Example: Program which uses gets and puts to double space typed input.
#include <stdio.h>
main()
{ char line[256]; /* Define string sufficiently large to
store a line of input */
Note that putchar, printf and puts can be freely used together. So can getchar, scanf and
gets.
getchar() and putchar functions: the standard function that prints a single character on
the standard devices.
Ex:
main()
Char ch;
Getchar(ch);
Putchar(ch);
20
ESCAPE SEQUENCES:
Escape sequences are special notations through which we can display our data
Variety of ways:
Example:
#include <stdio.h>
#include <conio.h>
void main(void)
21
printf(" \\n \t line feed & carriage return\n ");
getch();
--------------------------------------------
------------------------------------------
\\ \
\’ ‘
\" \"
22
C LIBRARY FUNCTIONS:
STORAGE CLASSES:
Storage class specifiers in C language tells the compiler where to store a variable, how to store the
variable, what is the initial value of the variable and life time of the variable.
Syntax:
storage_specifier data_type variable _name;
1. auto
2. extern
3. static
4. register
23
Storage place: CPU memory
Initial/default value: Zero
static Scope: local
Life: Retains the value of the variable between different function
calls.
Storage place: Register memory
Initial/default value: Garbage value
Register
Scope: local
Life: Within the function only.
Note:
For faster access of a variable, it is better to go for register specifiers rather than auto
specifiers.
Because, register variables are stored in register memory whereas auto variables are stored
in main CPU memory.
Only few variables can be stored in register memory. So, we can use variables as register
that are used very often in a C program.
1 #include<stdio.h>
2 void increment(void);
3 int main()
4 {
5 increment();
6 increment();
7 increment();
8 increment();
9 return 0;
10 }
11
12 void increment(void)
13 {
14 auto int i = 0 ;
15 printf ( "%d ", i ) ;
16 i++;
17 }
Output:
0000
2. Example program for static variable in C:
Static variables retain the value of the variable between different function calls.
24
3 void increment(void);
4 int main()
5 {
6 increment();
7 increment();
8 increment();
9 increment();
10 return 0;
11 }
12 void increment(void)
13 {
14 static int i = 0 ;
15 printf ( "%d ", i ) ;
16 i++;
17 }
Output:
0123
3. Example program for extern variable in C:
The scope of this extern variable is throughout the main program. It is equivalent to global variable.
Definition for extern variable might be anywhere in the C program.
1 #include<stdio.h>
2
3 int x = 10 ;
4 int main( )
5 {
6 extern int y;
7 printf("The value of x is %d \n",x);
8 printf("The value of y is %d",y);
9 return 0;
10 }
11 int y=50;
Output:
The value of x is 10
The value of y is 50
4. Example program for register variable in C:
Register variables are also local variables, but stored in register memory. Whereas, auto
variables are stored in main CPU memory.
Register variables will be accessed very faster than the normal variables since they are
stored in register memory rather than main memory.
25
But, only limited variables can be used as register since register size is very low. (16 bits,
32 bits or 64 bits)
1 #include <stdio.h>
2 int main()
3 {
4 register int i;
5 int arr[5];// declaring array
6 arr[0] = 10;// Initializing array
7 arr[1] = 20;
8 arr[2] = 30;
9 arr[3] = 40;
10 arr[4] = 50;
11 for (i=0;i<5;i++)
12 {
13 // Accessing each variable
14 printf("value of arr[%d] is %d \n", i, arr[i]);
15 }
16 return 0;
17 }
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
COMPILER DIRECTORIES:
#define directive
#if
#include
#endif
26
Common Short cut Keys Description
27