C - Language by Prashanth
C - Language by Prashanth
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 CPrograms 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
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
Constants
Numeric
Character
String
Real/Floating
Integer
Octal
Decimal
Hexa Decimal
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
.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
Examples
Global statements
#include<stdio.h>
Function Declarations
void main ()
{
ananda);
Variable Declarations;
Function Declarations;
Executable statements;
}
Function Definitions
void main ()
{
printf(Vivek
}
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
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<stdio.h>
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 Sequence
Meaning
\a
\b
\f
\n
\t
\v
\
\
\?
Alert
Back space
Form feed
New line
Horizontal tab
Vertical tab
Single quote
Double quote
Question marks
Format specifiers/Control strings
Format specifiers
Meaning
%c
%d
%f
%i
%ld
%o
%s
%x
Character
Decimal integer
Floating point
Integer
Long decimal
Octal integer
String
Hexa decimal integer
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
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);
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
DATA TYPE
In C-language the data types can be
classified as follows
DATA TYPE
FUNDAMENTAL DT/
DEFINED DT
BASIC DT/BUILT-IN DT
STRUCTURES
DERIVED DT
USER
ARRAYS
POINTERS
UNIONS
void
ENUME
int
float
char
-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 type
int
unsigned int
signed int
short int
signed short int
Size (in
bytes)
2
2
2
2
2
Range
-32768 to 32767
0 to 65535
-32768 to 32767
-32768 to 32767
-32768 to 32767
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
unsigned short int
long int
signed long int
unsigned long int
2
4
4
4
0 to 65535
-2147483648 to 2147483647
-2147483648 to 2147483647
0 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 follows
Data type
float
double
long double
Size (in
bytes)
4
8
10
Range
3.4e-38 to 3.4e38
1.7e-308 to 1.7e308
3.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 type
char
unsigned char
signed char
Size (in
bytes)
1
1
1
Range
-128 to 127
0 to 255
-128 to 127
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
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
Operator
Meaning
+
*
/
%
Addition
Subtraction
Multiplication
Division
Modulo division
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
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.
Operator
Meaning
<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
==
Equal to
!=
Not equal to
Example: Write a C program to demonstrate relational operators.
ANS: #include<stdio.h>
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:
Operator
Meaning
&&
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
A&&
!
A B
A||B
B
A
1 1
1
1
0
1 0
0
1
0
0 1
0
1
1
0 0
0
0
1
Example: Write a C-program to demonstrate logical operators.
ANS: #include<stdio.h>
void main()
{
int p=25, q=10, r=-6, s=30, a, b, c,d;
a=[(p>=q)&&(r==s)];
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
b=[(q!=s)!!(p==r)];
c=![p==s];
printf(a=%d\nb=%d\nc=%d\n, a, b, c);
d=![(p<=r)||(r>=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:
Operator
Meaning
+=
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<stdio.h>
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:
Operator
Meaning
&
Bitwise AND
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
|
Bitwise OR
^
Bitwise X-OR (Exclusive OR)
~
Bitwise compliment
<<
Bitwise shift left
>>
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<stdio.h>
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(%d<<%d=%d\n, x, 2, x<<2);
printf(%d>>%d=%d\n, x, 2, x>>2);
}
Increment and Decrement operators:
Operator
Meaning
++
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 ++;
++ Operand;
Operand --;
-- Operand;
a++;
++a;
a--;
--a;
post increment
pre increment
post decrement
pre decrement.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
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<stdio.h>
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<stdio.h>
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<stdio.h>
void main()
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
{
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.
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
Control structures
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
Conditional
loop interactive
Jump
break
if
if-else
continue
switch while
do-while
for
goto
CONDITIONAL 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.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
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<stdio.h>
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;
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
}
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<stdio.h>
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.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
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<stdio.h>
Void main()
{
Int i=1;
While(i<=5)
{
Printf(%d\n,i);
I++;
}
}
Do-while statement:
SYNTAX: do
{
Statements;
}while(condition);
Do and while are keywords.
When the control enters do-while statements the statements will be
executed first and then the condition will be evaluated.
If the condition is true then again the statements part will be executed
and again the condition will be checked.
This will be repeated as long as the condition is true.
If the condition becomes false then control will be transferred to
outside of do-while statement.
Compound statements are to be enclosed in curly braces.
The statements in do-while loop will be executed atleast one time as
the condition will be evaluated at the end of the loop. Hence it is called
Exit control loop.
Example: Write a C-program to demonstrate do-while statement.
ANS:
#include<stdio.h>
void main()
{
int n, i;
printf(enter n:);
scanf(%d, &n);
i=1;
do
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
{
printf(%d\n, i);
i=i++;
}while(i<=n);
}
For statement:
SYNTAX: for(initializations;conditions;updation)
Statements;
For is a keyword.
When the control enters for statement the initializations can be done
first and then the condition will be check.
If the condition is true then the statements part will be executed and
control transfers to updation part.
After updations again the condition will be checked still if it is true
again the statements will be executed.
If the condition become false then the control will be transferred to
outside of the statement.
If there are more initializations or updations they should be separated
by commas.
If any part of initialization, condition, updation is emitted it should be
termed properly.
Eg: for(;i<=10;)
{
Statements;
}
Example: Write a C-program to demonstrate for statement.
ANS: #include<stdio.h>
void main()
{
int n, fact, i;
printf(enter n:);
scanf(%d,&n);
for(i=1;fact=1;i<=n;i++)
fact=fact*i;
printf(factorial=%d\n,fact);
}
JUMP STATEMENTS
goto statement:
SYNTAX: goto label;
goto is a keyword.
Label must be a valid identifier.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
When the goto statement is executed the control will be transferred to
other part of the program where the label presents.
If the control transfers to a forward point. It is called forward goto.
If the control transfers to a previous point then it is called backward
goto.
Example: Write a C-program to demonstrate goto statement.
ANS: #include<stdio.h>
void main()
{
int n;
positive;
printf(enter a positive number:);
scanf(%d,&n);
if(n<=0)
goto positive;
printf(given number =%d,n);
}
break statement:
SYNTAX: break;
break is a keyword.
When the break statement was executed, the statements that are
present after break will be skipped and control will be transferred to
outside of the block.
Example: Write a C-program to demonstrate break statement.
ANS: #include<stdio.h>
void main()
{
int i;
i=1;
while(i<=10)
{
if(i==5)
break;
printf((%d\n,i);
i++;
}
}
continue statement:
SYNTAX: continue;
continue is a keyword.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
When the control statement was executed the statements that are
present after continue will be skipped and control will be transferred
to next iteration.
Example: Write a C-program to demonstrate continue statement.
ANS: #include<stdio.h>
void main()
{
int =0;
while(i<=10)
{
i++;
if(i%2==0)
continue;
printf(%d\n,i);
}
}
ARRAYS
Definition:
An array is a collection of variables, in which all the
variables will belongs to a same data type.
i.e., an array is a collection of Homogeneous elements.
Declaring an Array:
SYNTAX: data type arrayname[size];
Eg: int marks[6];
The data type may be either built-in data type such as int, float, char
or a user defined data type.
Array name is the name of the array and is an identifier. Hence the
rules for naming an identifier are to be followed to name an array.
The size of the array must be a positive integer constant. It is to be
provided in square brackets([]).
Array declaration must end with a semicolon.
The declaration of an array and ordinary variables of same data type
can be combined into a single statement.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
Eg: int marks[6], m, n;
Accessing Array elements:
All the elements of the array will share the
same array name. However the individual elements of the array can be
accessed using its subscript.
The subscript of the array elements will ranges
from 0 to size-1. The mth element in an array will have the subscript
m-1.
Eg: int marks[6];
In the above example marks is an array consists
of 6 elements whose names are marks[0], marks[1], marks[2],
marks[3],.,marks[5];
Input/Output of Array:
Individual array elements can be used for
assigning values, input and output purposes.
Eg: int m[6];
m[0]=10;
m[2]=25;
scanf(%d%d%d, &m[1], &m[3], &m[4]);
printf(%d%d, m[1],m[3]);
All the elements of the array can be accessed
for input or output easily using a statement
Eg: int m[6];
for(i=0;i<=5;i++)
scanf(%d,&m[i]);
for(i=0;i<=5;i++)
printf(%d, m[i]);
m[1]
m[2]
m[3]
m[5]
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
2001
2005
2002
2003
2004
2006
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
Array is the name of the array and is an identifier. Hence all the rules
applicable for naming an identifier are applicable here.
size 1 and size2 must be positive integer constants.
Accessing elements of 2D array:
An element is a 2D array can be
accessed using the two subscripts. The first subscript gives the array
index and second subscript gives the element index in that array.
Eg: int marks[4][6];
In the above example marks is a 2D array
which consists of 4 one dimensional arrays where each 2D array is
having 6 elements. The elements of the above array are
Marks[0][0], Marks[0][1],Marks[0][2],.,Marks[0][5];
Marks[1][0], Marks[1][1],Marks[1][2],.,Marks[1][5];
Marks[2][0], Marks[2][1],Marks[2][2],.,Marks[2][5];
Marks[3][0], Marks[3][1],Marks[3][2],.,Marks[3][5];
Int marks[4][6];
0
1
2
3
4
5
[0][0]
[0][1]
[0][2]
[0][3]
[0][4]
[0][5]
[1][0]
[1][1]
[]1[2]
[1][3]
[1][4]
[1][5]
[2][0]
[2][1]
[2][2]
[2][3]
[2][4]
[2][5]
[3][0]
[3][1]
[3][2]
[3][3]
[3][4]
[3][5]
Input/Output of a 2D array:
Individual array elements can be
accessed for either assignment or input or output.
Eg: int marks[4][6];
Marks[0][0]=40;
However all the elements of 2D array can
be easily accessed for input/output using a nested loop statement.
Eg: int marks[4][6];
for(i=0;i<4;i++)
for(j=0;j<6;j++)
scanf(%d, &marks[i][j]);
Memory allocation for 2D array:
In a 1D array all the elements will be
stored at sequential memory locations. In a 2D array all the 1D arrays
will be stored in sequential memory locations.
int marks[4][6];
0
1
2
3
4
5
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
2001
2013
2025
2037
2003
2015
2027
2039
2005
2017
2029
2041
2007
2019
2031
2043
2009
2021
2033
2045
2011
2023
2035
2047
Initializing a 2D array:
A 2D array can be initialized by providing
comma separated one dimensional arrays in curly braces.
Eg: int m[3][4] = { {1, 2, 3, 4}, {1, 3, 5, 7}, {2, 4, 6, 8}};
The 1D need not be provided while
initializing a 2D array.
Eg: int m[][4] = {{1, 2, 3, 4}, {1, 3, 5,7}, {1, 3, 2, 7}, {2, 4, 6, 8}};
C-LANGUAGE
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
All the elements in a one dimensional character
array will be stored at sequential memory locations.
The total bytes of memory occupied by a 1D
character array is equal to the size of array.
Initialization of a 1D character array:
A character array can be initialized by providing comma separated
character constants in curly braces.
Eg: char str[6] = {v, s, x};
Providing the size of the array is optional during initialization.
Eg: char str[] = {a, b, c};
A string constant can be initialized to a character array as follows:
Eg: char str[6] = Vivekananda;
NOTE: All the strings in C are null character terminated.
i.e., at the end of the string the compiler ads the character \ at the
end of the string. To enable this the size of the array must be atleast
greater than one to the length of the string.
String handling functions
To perform various operations
on strings several built-in are available in the header file <string.h> .
These functions are called as string handling functions.
strlen(): This function will returns the length of the given string. The
length of the string is total number of characters excluding null
character.
SYNTAX: strlen(string constant or string variable):
EG:
L = strlen(VIVEKA);
strcpy(): This function copies the content of one string into another
string.
SYNTAX: strcpy(dest str, src str);
Eg: char str130]= hello, str2[30];
strcpy(str2, str1);
str1= hello
str2 = hello.
strncpy(): This function copies the first n characters of source string
to the destination string.
SYNTAX: strcpy(dest str, src str, n)
Eg: char str130]= hello, str2[30];
strcpy(str2, str1, 4);
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
str1= hello
str2 = hell.
strcat(): This function concatenates the content of one string to
another.
SYNTAX: strcat(str1, str2);
Eg: char str1[30] = Vivek, str2[30]= ananda;
strcat(str1, str2);
str1=Vivekananda, str2=ananda.
strncat(): This function concatenates the first n characters of 2nd
string to the 1st string.
SYNTAX: strncat(str1, str2, n);
Eg: char str1[30] = Vivek, str2[30]= ananda;
strcat(str1, str2, 5);
str1=Vivekanand, str2=ananda.
strLwr()This function converts a given string into Lowercase.
SYNTAX: strLwr(string);
EG: char str[30] = VIVEKA;
strLwr(str);
str= viveka.
strupr()This function converts given string into upper case.
SYNTAX: strupr(string);
EG: char str[30] = viveka;
strupr(str);
str= VIVEKA.
strrev() This function reverses a string.
SYNTAX: strrev(string);
EG: char str[20]= hello.
strrev(str);
str= olleh.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
2D character arrays (or) Array of strings:
Definition:
A 2D character array is an array whose dimension is two
that can hold an array of strings.
Declaring a 2D character array:
SYNTAX: char arrayname[size1][size2];
Eg: char name[15][30];
char is a datatype.
Array name is the name of the array and is an identifier.
Size 1 and size 2 are the integer constants.
In the above example name is an array that can store 15 strings, in
which each string can store 30 characters.
Accessing elements of 2D character array:
Individual array elements can be accessed by using
two subscripts along with the array name.
EG: name[o][0]=a;
To access the individual character elements repeatedly
a nested for statement can be used.
EG: char name[5][10];
for (i=0;i<5;i++)
for (j=0;j<10;j++)
getchar(name[i][j]);
Instead of handling characters, individual strings canbe handled as
follows:
EG: char name[5][10];
name [0] = apple
Memory allocation:
All the elements of a 2D character array will
be stored at sequential memory locations. The total bytes of memory
required by 2D character array is equal to the product of size1 and
size2.
Initialization of a 2D character array:
A 2D character array can be initialized by providing comma separated
one dimensional character arrays or strings in curly braces.
EG: char name[5][10] = {apple, bat, cat};
Providing the first dimension is optional while initializing a 2D
character array.
EG: char name[][10] = {apple, bat};
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
FUNCTIONS
Definition:
A function is a self contained program element that is
designed to achieve a specific task.
Functions are of two types. Namely:
1. Standard functions or built-in functions or pre-defined functions
2. User defined functions.
Built-in functions: These are the functions whose code was already
developed by expert programmers and can be directly used just by
including appropriate header files, without developing any code.
EG: printf(), scanf(), pow(), sqrt(), exit() etc.,
User defined functions: User defined functions are the functions,
whose definition was written by user.
EG: fact(), volume(), area() etc.,
Function Handling: There are three phases in function handling.
They are
1) Function Declaration
2) Function Call
3) Function Definition.
Function declaration or Function prototype:
SYNTAX: returntype functionname (datatype arg1, datatype arg2,
.,datatype argn);
EG: float sinterest(float p, int t, float r);
The returntype is the type of data that the function
returns. The returntype may be a built-in datatype such as int, float,
char, void or a user defined datatype. If the function does not return
any value then the returntype void is to be used.
Function name is the name of the function and is an
identifier. Hence all the rules applicable for naming an identifier are
applicable here.
Inside the parenthesis, the datatypes and
variables/arguments are present that indicates the number of
arguments and there datatypes to be used.
Each variable in function declaration must have its own
datatype.
For eg: void volume(float l, float m, float n); / *correct */
void volume(float l, m, n);
/*wrong*/
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
Function call():
SYNTAX: function call(argument 1, argument 2,., argument n);
Eg:
volume(6, 7.2, 4);
Function name must be same as declared in function declaration.
The no. of arguments and their data types must match with function
declaration.
The arguments may be either constants or variables.
Eg: volume(l, b, h);
If there are no arguments in function call() nothing should be specified
parenthesis, not even void.
If the functions returns any value it can be stored in a variable or can
be printed directly.
A function call() statement may be present either in main() or in the
definition of any other function.
Function definition:
SYNTAX: returntype functionname (datatype1 arg1, datatype2 arg2,
.,datatype n arg n)
{
Body of function;
}
The return type, function name, data types must be same as declared
in function declaration.
The arguments in function definition header must be only variable.
The body of the function consists of executable statements.
Eg: void volume(float l, float b, float h)
{
float v;
v=l*b*h;
printf(volume=%f, v);
}
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
NOTE: When a function call() statement was executed the control will
be transferred to the function definition and after executing function
definition the control will be transferred back to the point where the
function was called.
#include<stdio.h>
void main()
{
int n;
printf("Enter n:");
scanf("%d", &n);
printf("n=%d\n", n);
twice(n0;
printf("After invoking function");
printf("n=%d\n", n);
}
void twice(int n)
{
n=2*n;
printf("Double value= %d\n",n);
}
Arguments/Parameters:
The variables or constants that are
present in function call() and function definition header are called
Arguments or parameters.
Actual arguments:
The arguments that are present in function
call() statement are called Actual arguments or parameters.
Formal arguments:
The arguments that are present in function
definition header are called formal arguments or parameters.
Pass-by-value/ Call-by-value method:
In Pass-by-value method any changes made
to formal arguments does not affects the actual arguments. Because
the content actual arguments will be copied into formal arguments and
they behave independent.
Recursion: The method of invoking a function itself is called
Recursion. In recursion the function call() statement will be present in
the definition of the same function.
EG: int fact(int n)
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
{
int f;
if(n==0||n==1)
else
f=f*fact(n-1);
return f;
}
In the above example the function
fact() was invokes in the definition of the same function fact().
In recursion the function will be
recursively invoked and hence any values to be stored temporarily will
be pushed into a linear data structure called stack, which works on
the principle LIFO (Last In First Out).
Assume that factorial is to be find out
for the number 4. To find out fact(4), fact(3) is to be find out . Hence
now the value 4 pushed into stack. To find out fact(3), 3 is to be
pushed into stack and fact(2) is to be evaluated. This recursive process
is to be repeated until fact(1) returns the value 1. After recursive
process was stopped the values of the stack will be popped and final
value will be evaluated.
Advantages of functions:
1. Functions will reduce repetitive task and hence length of the
source code will be reduced.
2. Using functions a big task can be divided into small and
individual tasks. This is called modular programming.
3. When functions are used in a program, errors will be localized
and hence debugging will become easy.
4. Using functions it is possible to develop individual programs and
can be combined into a main program.
5. By defining functions in header files they can be made
accessible in any program.
Characteristics of functions:
1. A function to be used must contain function declaration,
function call() and function definition. However if the function
definition is present before function call() then function
declaration is optional.
2. A function can be called in the definition of any other function,
but declarations of all functions should be either before main()
or after main().
3. If a function return type is provided other than void, it must be
return a value.
4. A function can return only one value.
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
5. When a function call() was invoked the control will transfers to
the function definition and after executing the function the
control will transfers to the point where the function was called.
http://www.waytoeasyeducation.blogspot.com
Cpu register
Garbage
value
register
Static
Extern
http://www.waytoeasyeducation.blogspot.com
Hard disk
Hard disk
Hard disk
Auto
Garbage
value
Keyword
Scope
Life
Inside
Within the
function,
function
where it was where it was
declared
declared
Inside
function,
Throughout
where it was the program
declared
Throughout Throughout
the program the program
Inside function,
immediately after
opening curly brace
Inside function,
immediately after
opening curly brace
Inside
Within the
Inside function,
function,
function
immediately after
where it was where it was
opening curly brace
declared
declared
Place in declaration
C-LANGUAGE
STORAGE CLASSES
4.
Extern/Global
3. Static
2. Register
Storage
classes
1. Automatic
C-LANGUAGE
POINTERS
Pointer variable:
A pointer variable is a variable that can store
the address of an ordinary variable. It is derived datatype.
Declaring pointer variable:
1. SYNTAX: datatype *variablename;
2. Data type may be either a built-in datatype such as int, float,
char or a user defined datatype.
3. Pointer variable declaration will begins with the symbol *.
4. Variable name is an identifier and hence rules are applicable.
5. Pointer variable declaration will ends with a semicolon.
6. An ordinary variable and its pointer variable can be declared in a
single statement.
Example : int x;
int *ptr x;
Can be written as: int x, *ptr x;
The address of (&) operator:
The address of operator will gives the
address of a variable.
SYNTAX:
&variable;
The syntax for storing the address of an ordinary
variable into a pointer variable is
SYNTAX: datatype variable, *pointer variable;
pointer variable=& variable;
Eg:
int x, *ptr x;
Ptr x = & x;
Example: Write a C-program to display the address of a variable.
ANS: #include<stdio.h>
void main()
{
int x, *ptra;
x=10;
ptra= &x;
printf("Address of x =%d\n", ptra);
}
The indirection operator (*):
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
The indirection operator will gives the
value of a variable that its pointer is pointing.
SYNTAX: * pointer variable;
Eg: *ptra;
int a=10;
Eg: printf( Value of a= %d\n, *prta);
Pass-by-address:
In Pass-by-address method, instead of passing
values of variables, the address of variables will be passed. Hence the
formal arguments must be pointer variables.
i.e., the formal argument pointer variables will be pointing to actual
argument variables. Hence any changes made to formal arguments
will affects the actual arguments.
Example: Write a C-program to demonstrate call by address or call
by references.
ANS: #include<stdio.h>
void main()
{
void show(int *);
int num[]={12, 13,14, 15, 16, 17, 18};
clrscr();
show(num);
}
void show(int *u)
{
int m=0;
printf("\n num[7]={");
while(m!=7)
{
printf("%2d","*(u++));
m++;
}
printf("\b}");
}
Pointer Arithmetic:
Arithmetic operators addition, subtraction,
multiplication can be performed on pointer variables. However pointer
division is not possible.
It is possible to perform operation with two
pointer variables or one pointer and one constant. When a constant
was added to a pointer variable instead of adding the value, the value
multiplied by size of datatype will be added to the pointer.
Eg: int a, *ptra;
http://www.waytoeasyeducation.blogspot.com
C-LANGUAGE
ptra = &a;
let &a is 2001, hence ptra=2001
now ptra= ptra+2;
ptra = 2005;
Pointer and Arrays:
Inorder to store the address of elements of an
array. An array of pointer can be used as follows
Eg: int a[5]={1, 2, 3, 4, 5};
int *ptra[5];
int i;
for (i=0;i<5;i++)
ptra[i] = &a[i];
Pointers to characters:
To store the address of character variable,
its pointer variable also should be of type char. However pointer to
characters are useful to handle strings as they can point to character
arrays.
i.e., a character pointer can be used to handle a string.
An array of character pointers can be used to
handle array of strings.
EXAMPLE:
#include<stdio.h>
void main()
{
char *str;
printf(enter a string:);
scanf(%s, str);
printf( given string is:, str);
}
http://www.waytoeasyeducation.blogspot.com