C - Language by Prashanth
description
Transcript of C - Language by Prashanth
C-language
C-LANGUAGE
C-language
Introduction:
C-Language was invented by Dennis Ritchie. In the year 1972 at AT&T bell laboratories, Murrae Hills, New Jersy, USA. It was invented from its predecessor language BCPL which stands for Basic Combined Programming Language. It was invented while a team of people headed by Dennis Ritchie are working to invent UNIX operating system. C is a general purpose structured programming language. Some times it is called as middle level language also, because it supports a rich set of bitwise operators.
Applications of C language:
C-language is widely used in the construction of the following:
Operating System Computer Aided Designed (CAD)
Compilers
Interpreters
Games
Packages
Application Softwares (Banking, Postal etc.,)
C character set: The set of all characters that can be used in C-Programs is called C character set. The C character set will consists of the following:1) Letters a-z , A-Z
2) Digit 0-9
3) Special symbols # < > : ( ) { } [ ] ; + -_ * & ? ~ ! = etc., C- Tokens:
The C tokens are parts of C-program. These tokens will be used in construction of a C-program. The C tokens are as follows:
a) Keywords
b) Identifiers
c) Constants
d) Strings
e) Operators
Constants Constants
Numeric Character String
Real/Floating Integer
Octal Decimal Hexa Decimal
Constants are three types. They are:
i. Numeric constants
ii. Character constants
iii. String constants
1) Numeric constants: As the name suggests numeric constant will constant of numerals only. These are also called Number Constant. These are two types namely Integer constant, Real or Floating point constant.
2) Integer constant: Integer constants are classified as Octal Integer constancy, Decimal Integer constancy and Hexa Decimal Integer constancy. These are as follows:
Constant typeBase of Num SystemDigits IncludeRepresentation Example
Octal80-7Begins with 123
Decimal100-9No representation123
Hexa Decimal16A-F or a-fBegins with Oxx1a2A
Floating point constant: These are also called Real constant will consists of an integer part and decimal part separated by a period (.). Floating point constant can be expressed in these notations namely.i. Standard notation
ii. Scientific notations
iii. Mixed notations
1) Standard notation: In this notation individual part and decimal part will be separated by a period.
For eg: 4.6, 0.5.
.4 is a valid floating point constant whereas 4. is not a valid floating point.
2) Scientific notation: In this notation the letter e stands for exponent the number
Appears after the letter E is exponent to the base 10.
For eg: 46E-1. In these notations the number before the letter E is an integer.3) Mixed notation : The combination of Standard and Scientific notation is called
Mixed notation.
For eg: 4.6E-1
Character constant: A single character that is enclosed in single quotes is called character constant.
For eg: s, a, 1, A
String constant: A sequence of characters that are enclosed in double quotes is called a string constant.
For eg: switch, *123#
Structure of a C-program
The structure of C-program is as follows:Preprocessor statements ExamplesGlobal statements #include
Function Declarations void main ()void main () {
{ printf(Vivekananda); Variable Declarations; }
Function Declarations;
Executable statements;
}
Function Definitions
1) Every C-program must begin with preprocessor statements these are so called because these statements will be processed before actual processing. These statements will begin with the symbol #, which is called preprocessor directive.
Eg: #include, #define, #if etc.,
2) If any global variables are required they should be declared immediately after preprocessor statements.
3) Function declarations may present after global variable declarations before main() or after local variable declarations inside main().
4) main() is the function where the execution of the program begins.
5) Local variables must be declared immediately after opening curly brace.
6) If any function declarations are present their definitions can be written after main().
Example: Write a program to print your name?
ANS: #include Void main()
{
Printf(My name is Prashanth);
}
Output: My name is Prashanth
Escape Sequence
In C-language the escape sequence will begin with (\) backslash. The escape sequence and their meaning as follows:Escape SequenceMeaning
\aAlert
\bBack space
\fForm feed
\nNew line
\tHorizontal tab
\vVertical tab
\Single quote
\Double quote
\?Question marks
Format specifiers/Control stringsFormat specifiersMeaning
%cCharacter
%dDecimal integer
%fFloating point
%iInteger
%ldLong decimal
%oOctal integer
%sString
%xHexa decimal integer
All the above are called format specifiers, because they will give the format of constants or variables. These are also called control strings. Because they will control the output.
Variable:
A variable is a program element that can change its value during the execution of a program. A variable is an identifier and hence all the rules applicable for naming an identifier are applicable to name a variable.
Variable declaration:
A variable that is to be used in a program must be declared properly. The syntax for declaring a variable is
SYNTAX: datatype variable;
Eg: int p;
The datatype may be either a built-in datatype such as int, float or char or a derived datatype or a user defined datatype.
More than one variable of same datatype can be declared in single statement as follows:
SYNTAX: datatype variable1, variable2, variable3variable n;
Eg: int p, q, r, s;
printf() statement:
The printf() statement is used to print constants, variables and expressions to the standard output device (monitor). The definition for this function is available in the header file stdio.h. The syntax of printf() statement is
SYNTAX: printf(format specifiers/control strings, constants/variables/expressions);
Eg: printf(%d%f%d, 3+2,5.5,10);
scanf() statement:
The scanf() statement is used to input a value to a variable. The syntax for scanf() statement is
SYNTAX: scanf(format specifier,&variable); Eg: scanf(%d,&maths); The definition for the scanf() statement is available in the header file stdio.h. The symbol & should be pronounced as Ampersand or Address of. A relevant format specifier should be provided for a variable.
Input can be obtained for more variables with a single scanf() statement;
For eg: scanf(%d%d%d,&a,&b,&c);DATA TYPE
In C-language the data types can be classified as follows
DATA TYPE
FUNDAMENTAL DT/ DERIVED DT USER DEFINED DTBASIC DT/BUILT-IN DT ARRAYS STRUCTURES
POINTERS UNIONSvoid int float char ENUME -RATED DT Basic data types:
The basic data types that are available in C are void, int, float, char. These are also called fundamental data types.void:
void is a basic data type that is not useful for creating any variables. This is also used as a return type in functions to indicate no value is being returned.
int:
The variables of int datatype will occupy two bytes of memory. The data range for an integer variable is -32768 to 32767. The int datatype has various modifiers. The datatype, bytes, occupied and range are as follows:
Data typeSize (in bytes)Range
int2-32768 to 32767
unsigned int20 to 65535
signed int2-32768 to 32767
short int2-32768 to 32767
signed short int2-32768 to 32767
unsigned short int20 to 65535
long int4-2147483648 to 2147483647
signed long int4-2147483648 to 2147483647
unsigned long int40 to 4294967295
float:
The variables of float datatype will occupy 4 bytes of memory. This data type has the modifiers double and long double. The data type, bytes occupied and range are as followsData typeSize (in bytes)Range
float43.4e-38 to 3.4e38
double81.7e-308 to 1.7e308
long double103.4e-4932 to 1.7e4932
char: The variables of char data type will occupies 1 byte of memory. The char datatype is a form of integer data type because every character will have an integer ASCII code. The char data type and its modifiers size and ranges are as follows.Data typeSize (in bytes)Range
char1-128 to 127
unsigned char10 to 255
signed char1-128 to 127
OPERATORS AND EXPRESSIONS C-language supports a rich set of operators these are used to perform various operations on data. The available operators in C are
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Compound assignment operators
Bitwise operators
Increment and Decrement operators
Conditional operators
sizeof operators
If an operator takes only one operand then it is called a unary operator. A binary operator will takes two operands and a ternary operator will takes three operands.
1) Arithmetic operators:
There are five Arithmetic operators in C
OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modulo division
1) All the arithmetic operators are binary operators. However the operator (-) will works as unary operator also.
2) The / operator will performs the integer division if the operands are integers. However to get a floating point result the denominator must be of type float. Eg: 15/2=7 but 15/2.0=7.5
3) The operator % will gives the remainder after performing integer division. This operator is not
applicable for floating point data.
Eg: 18%3=0 but 3%18=3
Example: Write a program to demonstrate arithmetic operators.
ANS: #include void main() { int a, b, add, sub, mul, div, rem; printf(enter a, b); scanf(%d%d, &a,&b); add=a+b; sub=a-b; mul=a*b; div=a/b; rem=a%b; printf(%d+%d=%d\n,a,b,add);
printf(%d-%d=%d\n,a,b,sub);
printf(%d*%d=%d\n,a,b,mul);
printf(%d/%d=%d\n,a,b,div);
printf(%dmod%d=%d\n,a,b,rem); }
Relational operators:
There are six relational operators in C. All the operators are binary operators. They will give the relation between two operands. They will return a value 1 if the relation is true. Otherwise returns 0.
OperatorMeaning
=Greater than or equal to
==Equal to
!=Not equal to
Example: Write a C program to demonstrate relational operators.ANS: #include
void main()
{
int a=10, b=15, c=-6, x, y, z;
x=(a>b);
y=(b==c);
z=(a!=15);
printf(x=%d\ny=%d\nz=%d\n, x, y, z);
}Logical operators:
OperatorMeaning
&&Logical AND
||Logical OR
!Logical NOT
There are three logical operators the logical AND (&&), logical OR (||) are binary operators. The logical NOT (!) is a unary operator. The result will be either 1 or 0 which stands for true or false respectively.
Truth Tables ABA&&BA||B!A
11110
10010
01011
00001
Example: Write a C-program to demonstrate logical operators.ANS: #include void main()
{
int p=25, q=10, r=-6, s=30, a, b, c,d;
a=[(p>=q)&&(r==s)];
b=[(q!=s)!!(p==r)];
c=![p==s];
printf(a=%d\nb=%d\nc=%d\n, a, b, c);
d=![(p=a)];
printf(d=%d\n,d);
}
Assignment operators:
The assignment operator available in C is =. The syntax for using assignment operator is
SYNTAX: L value= R value;
The R value may be either a constant or variable or expression. Whereas the L value must be a variable
i.e., variable = variable/constant/expression.
When a value of a variable was assigned to another variable the variable of right hand side does not losts its value.
Eg: temp=a; radius=18; disc=(b*b)-4*a*c;
Compound assignment operator:
OperatorMeaning
+=Add and assign
-=Subtract and assign
*=Multiply and assign
/=Divide and assign
%=Modulo division and assign
All the compound assignment operators are formed by combining the Assignment operator with Arithmetic operators. All are binary operators.
Example: Write a C-program to demonstrate compound assignment operators.
ANS: #include void main() { int x=10, y=20; printf(x=%d\ty=%d\n, x, y); x+=5; y-=2; printf(x=%d\ty=%d\n,x, y); y/=x; printf(x=%d\ty=%d\n, x, y);
}
Bitwise operators:
There are six bitwise operators in C. They are:
OperatorMeaning
&Bitwise AND
|Bitwise OR
^Bitwise X-OR (Exclusive OR)
~Bitwise compliment
Bitwise shift right
Bitwise compliment is a unary operator and the remaining are binary operators.
Example: Write a C-program to demonstrate bitwise operators.
ANS: #include void main() { int x=25, y=15; printf(%d&%d=%d\n, x, y,x&y); printf(%d|%d=%d\n, x, y, x|y); printf(%d^%d=%d\n, x, y, x^y); printf(~%d=%d\n, x, ~x); printf(%d2); }Increment and Decrement operators:OperatorMeaning
++Increment operator
--Decrement operator
The Increment operator ++ increments the value of its operand by1. The Decrement operator decrements the value of its operand by 1. Both are unary operators.Operand ++; a++; post increment
++ Operand; ++a; pre increment
Operand --; a--; post decrement
-- Operand; --a; pre decrement.Example: Write a C-program to demonstrate Increment and Decrement operators.
ANS: #include
void main()
{
int a=15, b=20;
printf(a=%d\tb=%d\n, a, b);
a++;
--b;
printf(a=%d\t b=%d\n, a, b);
++a;
b--;
printf(a=%d\tb=%d\n, a, b);
}
Conditional operators:
The syntax for conditional operator is as follows:
SYNTAX: condition? expression1: expression2;
In conditional operator, if the condition is true, then expression 1 part will be executed. Otherwise expression 2 part will be executed. The conditional operator is a ternary operator.
Example: Write a C-program to demonstrate Conditional operator.
ANS: #include void main() { int a=10, b=15;
if(a=b)? printf(it is true): printf(it is false);
}
sizeof operator:
This operator will returns the size of a data type or a variable in bytes.
SYNTAX: sizeof(datatype/variable);
Eg: sizeof(int);
Example: Write a C-program to demonstrate sizeof operator.
ANS: #include void main() { int x, a, b; float p; a=sizeof(x); b=sizeof(p) c=sizeof(char); printf(a=%d\nb=%d\nc=%d\n,a, b, c); }Type casting:
The process of changing the datatype of a variable or constant during run time is called type casting.
SYNTAX: (datatype)variable/constant;
Eg: (float)6;
Example: Write a C-program to demonstrate Type casting.
ANS: #include void main() { int m, p, c, total, no_of_sub; float avg; no_of_sub=3; printf(enter marks in three subjects:); printf(%d%d%d , &m, &p, &c); total=m+p+c; avg= tot/(float)no_of_sub; printf(total=%d\n average=%f\n, total, avg);
}
Initialization:
Assigning a value to a variable at due time of declaring a variable itself is called initialization.
SYNTAX: datatype variable = initial value;
Eg: float pi=3.142;
Comments in C:
The statement that are enclosed between delimiters /**/ will be ignored by compiler. These statements are known as comments.
Identifiers:
Identifiers are programmer designed tokens. Identifiers are used to give names for variables. There are some rules:
Variable name should not begin with digits. It contains a-z & A-Z and underscore(_) or letters.
Uppercase and Lowercase letters are different.
Limited length to 32.
Keywords:
Keywords are essential parts of a program designing. We should not use keywords as identifiers. Because every keyword have its own meaning, its meaning cannot change. All keywords must be written in lowercase.
autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
constfloatshortunsigned
continueforsignedvoid
defaultgotosizeofvolatile
doifstaticwhile
Control structures In general all the statements in a program will be executed sequentially this type of execution is called sequential execution.
Using control structures it is possible to skip a few statements or repeatedly execute. The statements in control structure are classified as follows.
Control structures
Conditional
loop interactive Jump if if-else switch while do-while for goto break continueCONDITIONAL STATEMENTS
If statement:
1) Syntax: if(condition)
{
Statement;
}
Here if is keyword.
When the control enters if statement the condition will be evaluated .
If the condition is true the statement part will be executed and control transfers to sequential execution.
If the condition is false then by stopping statements part control will transfers to sequential execution.
Compound statements are to be enclosed in curly braces.
If statement can be nested.
Example: Write a C-program to demonstrate if statement.
Eg: #include
void main()
{
int n;
printf(enter n:);
scanf(%d, &n);
if(n>0)
printf(positive);
printf(program completed);
}
If_else statement:
SYNTAX: if(condition) statement 1;;
else
statement 2;
If and else are keywords.
When the control enters if statement the condition will be evaluated.
If condition is true then statement1 part will be executed by skipping statement 2 part control transfers to sequential execution.
If the condition is false then by skipping the statement part one , statement two part will be executed and control transfers to sequential execution.Compound statements are to be enclosed with in curly braces.Either if part or else part are both can be nested.
Example: Write a C-program to demonstrate if-else statement.
Eg: #include
void main()
{
int n;
printf(enter n:);
scanf(%d, &n);
if(n>0)
printf(positive);
else
printf(%d is negative, n);
printf(Program completed);
}
Switch statement:
SYNTAX: switch(expression)
{
Case label: statement 1;
Break;
Case label: statement 2;
Break;
.
.
.
Case label: statement n;
Break;
Default: statement; }
switch, case, break and default are keywords.
When control enters switch statement the expression will be evaluated. It must be positive integer constant or character constant.
The value of expression will be matched with case labels and if a exact match found then the corresponding statements will be executed.
If no match found then the default section will be executed if present.
switch statement is also called Multi branching statement or Selection statement.
Example: Write a C-program to demonstrate switch statement.
ANS: #include void main()
{
int n;
printf(enter n:);
scanf(%d, &n);
switch(n)
{
case 1: printf(one);
break;
case 2: printf(two);
break;
case 3: printf(three);
break;
case 4: printf(four);
break;
case 5: printf(five);
break;
}
}
LOOP STATEMENTS
While statement:
SYNTAX: while(statement) {
Statements;
}
While is a keyword.
When the control enters while statement the condition will be evaluated.
If the condition is true then the statements part will be executed and again the condition will be checked.
Still if the condition is true agarin the statements part will be executed.
If the condition becomes false then control will be transfers to outside of while statement.
Compound statements are to be enclosed in curly braces.
Example: Write a C-program to demonstrate while statement.
ANS: #include
Void main()
{
Int i=1;
While(i