Array
Array:-array is a set of
similar data type element we can store more than one elements and array
simultaneously and array is also called subscript variable array are similar to
matrices using common variable and single variable.
Or
In other words an array is a group or a table
of values referred to by the same variable name array element is also a variable
in the array declaration one must define the type of the array.
The type of array:-
1. one dimensional array
2. multi dimensional array
int a
[5]
data type of array name maximum
element permitted size
in
general one dimensional array may be expressed as:-
Data type array name[]
Eg:
int mark
[0]
array initialization:-
general format:-
data type array name[expression]
={element1,ele2,ele3};
int
value [7]={10,11,5,13,16,18,19};
or index
value [0]=10
int value [7]
value [1]=11
| |
| |
value [6]=19
Note:- array
index starts for 0 to n-1 where n is the maximum size of the array. If the
array element are not assigned explicitly, initial value will be automatically
set to zero.
Eg1
int no[5]={1,2,3}
no[0]=1
no[1]=2
no[2]=3
no[3]=0
no[4]=0
eg2- NOTE : Please Ignore Human being typing mistakes
int
a[7]={1,2,3,4,5,6,7}
int
i;
printf(“\n contents of the array”);
for
(i=0;i<=6;i++)
{
printf (“%d\n”,a[i]);
}
Note:-
a[0],a[1],a[2],a[3],a[4]
these are indices/subscript
eg3
int
a[10],i;
\\ int declaration
printf(“enter ten values”);
for(i=0;i<=a;i++)
{
scanf(“%d”,&a[i]); \\ by keyboard
}
for(i=0;i<=a;i++)
{
printf(“my array value \n”);
printf(“%d”,a[i]);
}
Explanation:- ex. no(suppose)
a[0]=101;
a[1]=102;
a[2]=202;
a[3]=1001;
Program:-
void main()
{
x[0]=5; 0
x[1]=15;
x[2]=x[0]+x[1];
}
Program:
for(i=0;i<=4;i++)
{
x[i]= i++;
}.
for{i=0;i<=4;i++)
{
printf(“%d \n”,x[i]);
}
Multi dimensional array:-
M.D.
array are define in the same manner as one dimensional arrays except that a
separate pair of square brackets are required for each subscript thus a 2-d
array will require two pairs of squares brackets 3-d array will require the
pairs of square brackets and so on.
Format:- Data
type array name[exp1] [exp2] [exp3]
Initialization:-
2-d array provides us matrix form in form of rows and columns we use the
separate square bracket for define M.d. array
Eg
int
a[2] [2]
rows columns
frist bracket for row & second bracket for columns
inilization:-
int a[3][2]={{70,80}{30,40}{63,92}};
int b[2][3]={{10,20,30}{16,18,30}};
int a[4][3]={{70,10,80}{16,80,90}{63,18,70}{17,10,40}};
output:-
Character array:-
Character-datatype array name[exp]
Eg.
char
page[40];
char
color[3]=”red”;
color[0]=”r”;
color[1]=”e”;
color[2]=”d”;
1. character array always terminates (end) with (‘\o’)
(null) (null character)
Null char
Eg.
char
line[]=“this is a my program”;
2. this null character will be added automatically by the
compiler provided there is enough space to accommodate the char
int i
char
name [ ]=”Ram lal Prasad babu”;
printf(“content of array”);
for(i=0;name[i]!=”\o”;i++)
{
printf(“%d
/n”,name[i]);
}
One dimensional array:-
A list
of items can be given one variable name using one subscript & such a
variable is called a single subscript variable or a one dimensional array
The subscript
can begin with no 0.That is x[0] is allowed.
Eg
If we
want to represent a set of five no.say (35,40,20,57,19)( by an array variable
no then we may declare the variable no as follows:
int number[5];
and the value
of an array element can show as follows:
x[0]=35 x[1]=40
x[2]=20 x[3]=57 x[4]=19
Declaration of 1-d array:-
Eg
float hight[50];
declares the hight to be an array containing 50 real
elements similarly int group[10];
declares the groups as an array contain 10 integer values
when we
declaring char array we must always allow one extra element space for the null
terminator
declaration must end with semi-colon(;)
.Two dimensional array:-
Declaring
two –d array is similar to declaring one-d array there will be an extra set of
[] to indicate the second index thus a 2-d array can be defined as
Eg.
int
array [4][4];
initializing of 2-d array:-
like
one-d array 2-d array may be initialized by following
row columns
this can be also written as: static int table[2][3] =[{0,0,0},{1,1,1}];
Standard library string functions or arithmetic
operations:-
#include
<string.h>
Function
use
1.
strlen()
find the lenth of the string
2.
strlwr() convert the string to the lower case
3. strupr()
convert the string to the upper case
4. strcat()
append
5. strcpy()
copies a string one in to anther
6. strcmp()
compiler a string one in to anther
7. strrev()
reverse a string one in to anther
8. strchar() find frist occurance
Find the
Errors & output and also try to complete the program.
program:-
1. char arr[ ] =”xyz”;
int len;
int lwr,upr,rev;
len = strlen (arr);
printf(“%d”,len);
lwrstr (arr);
uprstr (arr);
revstr (arr);
2. char source [ ]=”language”;
char target [20]:
str cpy (target, source);
printf(“%s”,source);
printf(“%s”, target);
3. char source[ ]=”hello”;
char target[30]=”good morning”;
strcat(target, source);
printf(“%s”,target);
result:-hello good morning
4. char string1[ ]=”hello”;
char string2[ ]=”h”;
int i,j,k;
i=strcmp(string1”hello”);
j=strcmp(string1,string2);
k=strcmp(string1,”hello xyz”);
printf(“%d\n%d\n%d\n”,i,j,k);
Program :- matrix{entering 2*2 matrix data}
int [2] [2],i,j;
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf(“enter a number of matrix”);
scanf(“%d”,
&x[i] [j]);
}
}
Explanation:-
x[0] [0]=2
x[0] [1]=2
x[1] [0]=2
x[1] [1]=2
/*displaying
2*2 matrix data*/
int s=0;
int[2] [2]
,i,j;
for(i=0;i<=1;i++)
{
for(j=0;j<=1;j++)
{
printf(“sum of matrix elements”);
s=s+x[i] [j];
printf(“%d”,s);
}
}
Program:-
main()
{
int num [ ]={24,34,12,44,56,17};
int i;
for(i=0;i<=5;i++)
{
printf(“\n address=% ”,num [i]);
printf(“element=%d”,num [i]);
}
}
Output:-
Address =
100 element =24
” = 102 ” =34
” = 104 ” =12
” = 106 ” =44
” = 108 ” =56
” = 110 ” =17
Summary:-
Note:-1. all
element of the array must be same data type in this sensor it is homogenous
data structure
Note:-2. the
allocation information about an array is
fixed at compiler time
Note:-3 during execution the memory space is
allocated for array. For all the element of array continuous space is
allocated. The array name is the start address of this memory.
Note:-4.
Normally declaration
#define max 100
int main()
{
int
a[max];
------------
-----------
}
Eg.
int
arr[2][3]={12,10,16,18,20,22};
int
arr[ ] [ ]={12,10,16,18,20,22};
int
arr[2] [ ]={12,10,16,18,20,22};
int
arr [ ][ ]={12,10,16,18,20,22}; // check is it valid or not
3-D array:-
int arr[3][4][2]={{{2,4},{7,8},{3,9},{5,6}},
{{7,6},{3,4},{5,3},{2,3}},{{7,6},{3,4},{8,9},{5,3}}};
A three D array can be as a arrays of the outer array has three
element of which is a 2 D array of 4 * 2
D array.
Que:-How to store 3D array in memory?
Que:-How to store 2D array in memory?
Program-:
Addition
of two matrix
int
x[3][3] ,y[3][3] ,z[3][3];
int
i,j,k;
for
(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf (“Ist matrix”);
printf (“enter the no”);
scanf (“%d”,&x[i][j]);
}
}
for (i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
printf (“IInd matrix”);
printf (“enter the no”);
scanf (“%d”,& y[i][j]);
}
}
for
(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
z[i][j]=x[i][j]+y[i][j]
printf(“%d”, z[i][j]);
}getch();
}
Program-: Find the Errors & output and
also try to complete the program.
Find out the maximum &
smallest number with the help of array
for (i=0;i<=9;i++)
{
printf (“enter the ten no”);
scanf (“%d”,&x[i]);
}
for(j=0;j<=i;j++)
{
if
(x[j]=x[i])
{
printf (“same
number”)
i--;
break;
}
max=x[0];
for(i=0;i<=9;i++)
{
if
(max<x[i]
{
max=x[i];
}
}
printf(“%d”,max);
}
getch();
}
Q.Write a program to occurrence of an element in the
array or find out the location of desired Element in the given array ?
/*W A P to find squar of any no*/
/* W A P to find the power of 2n
*/ Hint for(i=1;i<=10;i++) power(2,i)
/*W A P to find the ascending and descending the
element if the array*/
Sorting
int a[5],t,i,j,temp;
printf(“enter the size of array”);
scanf(“%d”,&t);
printf(“enter the value”);
for(i=0;i<t;i++)
{
scanf(“%d”,&a[i]);
}
for(i=0;i<t;i++)
{
for(j=i+1;j<t;j++)
{
if(a[i]>a[j])
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
for(i=0;i<t;i++)
{
printf(“descending order%d”,a[i]);
}
String :-
String are array of char type if we want to store sequence of char like
a word or a sentence we can use string type variable in our program last of
string array null char store (“\0”)but in case of integer array no null char
store at the last location
char x[10]=”DEEPAK”;
gets( ) or puts( ):-
gets( ) is use
for entering the string from the keyboard.it is similar to scanf( ) but major
difference between space problem. in case of gets( ) we can pass one variable into
gets( )
char
s[10]
gets(s)
scanf(“%d”,&s);
gets(s);
puts( ):-
Puts can display only one string at same time.it is similar to printf(
)but In case of puts(s) we can print only a value of variable we can not print
a msg by using puts(s).which is possible in printf( ) only using printf( ) we
can print msg as well as value of
both.but in case of puts(s)we can print one string at a time
Eg Puts(s);
Puts(“hello”);
Program
main()
{
char name[25];
printf(“enter
your name”);
scanf(“%s”,name);
printf(“%s”,name);
}
Test this program using different type of
string
char name[25];
printf(“enter your full name”);
gets(name);
puts(“hello”);
puts(name);
2-d char array:-
Eg main()
{
char
list [7] [10] =
{
“shilpi”
“upasana”
“rena”
“neeti”
“Deepak”
“amita”
“Anand”
}
}
}
Program-:
#include<stdio.h>
#include<conio.h>
main()
{
char name[]=”krishna”
int
i=0;
while(i<=6)
{
printf(“%c”,name[i]);
i++ ;
}
}
Output:-
K r i
s h n
a
Program
#include<stdio.h>
#include<conio.h>
main()
{
char name[]=”krishna”
int
i=0;
while(name[i]!=’\0’)
{
printf(“%c”,name[i]);
i++ ;
}
}
output:-
0
–K Memory location
1- r
2- i
3-s
4-h
5-n
6-a
Program
#include<stdio.h>
#include<conio.h>
main()
{
char name[]=”krishna”
printf (“%s”, name);
}
/* Find out the length of string*/
#include<stdio.h>
#include<conio.h>
main()
{
char name[]=”Hello”
int
i=0;
while(x[i]!=’\0’)
{
i++;
}
printf(“%d”,i);
}
/*Power Program*/
Find the
Errors & output and also try to complete the program.
Sorting:-
There are three types of sorting:-
1. Selection sort
2.Bubble sort
3.Insertion sort
Selection Sort:-
#include<stdio.h>
#include<conio.h>
main()
{
int
x[5]={5,10,15,2.19}
int i,j,t;
for(i=0;i<5;i++)
{
for(j=1+i;j<5;j++)
{
if(x[i]>x[j])
{
t=x[i];
x[i]=x[j];
x[j]=t;
}
}
}
for(i=0;i<5;i++)
{
printf
(“%d”,x[i]);
}
}
Output:-
int x[t]={2,5,10,15,19}
Bubble
Sort:-
#include<stdio.h>
#include<conio.h>
main ()
{
int i,j,t;
for(i=0;i<5:i++)
{
for(j=0;j<4-i;j++)
{
if(x[i]>x[j+1])
{
t=x[j];
x[i]=x[j+1];
x[j+1]=t;
}
}
}
for(i=0;i<5;i++)
{
printf(“%d”,x[i]);
}
}
Insertion sort:-
#include<stdio.h>
#include<conio.h>
void main()
{
int
x[5]={5,10,12,19,15};
int I,j,t;
{
printf(“%d”,x[i]);
}
for(i=0;i<5;i++)
{
for(j=i;j<5;j++)
{
if
x[i]<x[j-1]
{
t=x[j=1];
x[j-1]=x[j];
x[j]=t;
}
}
}
/*concalenation and appending*/
Add two string in third array
Eg
void main()
{
char x[10],y[10],z[20];
int i=0j=0k=0;
printf(“enter the frist string”);
gets(x);
printf(“enter the second string”);
gets(y);
while(x[i]!=null)
{
z[k]=x[i];
k++;
i++;
}
z[k]=“ ”;
k++;
while(y[j]!=null)
{
z[k]=y[j];
k++;
j++;
}z[k]=null or ‘
’;
printf(“%s”,z);
for(k=0;k[z]!=null;k++)
{
p
rintf(“%c”,z[k]);
}
}
/*W A P to input string and check palindrome or not*/ Ex -KANAK
char x[20],y[20];
int i=0,j=0;
printf(“enter the string”);
gets(x);
while(x[i]!=null)
{
i++
}
for(j=i-1;j>=0;j--)
{
y[j]=x[i];
j++;
}
y[j]=null;
for(i=0;x[i]!=null;i++)
{
if(x[i]!=y[j])
{
printf(“not
same character”);
break;
}
if(x[i]= =y[i])
{
printf(“same
character”);
}
}
getch();
}
Program:-
char x[10];
char y[10];
char z[20];
int i=0,j=0,k=0;
strcat(x,y,z);
/*palindrome------- String*/
#include<string.h>
char x[20],y[20];int n;
printf(“enter the string”);
gets(x);
strcpy(x,y);
strrev(y);
n= strcmp(x,y);
if(n==0)
{printf
(“palandrum”);
}else
printf (“not
paladrum”);
/*copy one string to another*/
main()
{
char str 1
[80],str2[80];
int i;
prinf(“enter frist string”);
scanf (“%s”,str1);
for(i=0;str1[i]!=’\0’;i++)
{
str2[i]=str1[i];
str2[i]=’\0’;
printf
(“%s\n”,str2);
printf (“no of
character=%d\n”,i);
}
}
/*counting character words and lines in a text*/
#include<string.h>
main()
{
char
line[81],ctr;
int i,c;
end =0;
character =0;
words=0;
lines =0;
printf(“key infu text”);
print(“give one space after each words\n”);
printf(“when completed press ‘return’\n \n”);
while(end= =0)
{
c=0;
while(ctr=getchar()!=’\n’)
line[c++]ctr;
line[c]=’\0’;
if (line[0]==’\0’)
break;
else
{
words++;
}
}
for(i=0;line[i]!=’\0’;i++)
if(line[i]== ‘ ’||line[i]==’\t’ );
words++;
}
/*counting lines and char*/
lines=lines+1;
character =character + str len (line);
{
printf(“%”,line);
printf(“%”,character);
printf(“%”,words);
}
Declaring and initializing string variable:-
The genral form
of declaration o fstring variable Char string_name[size];
The size determine the no of char in the string name
some eg are:-
Char city [10];
Char name[30];
When the compiler assign the char string to a array it
automatically supplides a null char(‘\0’)at the end of string char city[10]= “london”;
String char city[20]=“new york”;
string char city[20]=“{’n’,’e’,’w’,’y’,’o’,’r’,’k’}”;
c also permits us to initialize z char array without
declaring the no of char elements for eg:-
static char string [ ]={‘g’,’o’,’o’,’d’,’\o’};
reading string from terminal:-
char add [20];
scanf(“%s”,add);
gets(add);
writing string to screen:-
For printing a string statement we use %s format to
print string to screen
we have use printf function with %s format to
printf string to the screen
printf(“%s”,name);
getch( ):-
This function manily for reads a character from the key-board getch( )
is also used in tast of any program, here it is used for halt the screen.
-------------------------------------------------------------------------------------------------
Functions-:
Definition of function:-
Function is a sub program which can be called anywhere in our program
when it is needsd
Or
A
function is self contain block of statements that perform a some specific kind
of task
If we want to perform same task with different values
that time we can use function if we talk about the main function ( ) its
calling its self function may or may not be return any value. Function may
cover program east to understand and provide reusability but spend some more
time to groups the concept of calling a function.
Type of
function:-function has two types:
1. built in function or library function
2. user defined function.
- builtin
function:-
builtin
function are those function which are already built in library files
for eg:-
#include<math.h>
There are so
many function in this file like power ( ),sin( ),sqrt( )
- user
define function:-
user
define function are those functions which made by programmer. That means
programmer can creat own function.
for eg:-
ABC( )
int add()
int AB()
the form of c function:-
function
name (argument list)
argument declaration;
{
local variable
declaration;
excutable statement1;
excutable statement2;
excutable statement3;
--------------------------
--------------------------
return(expression);
}
Eg:-
void abc();
int i;for (i=1i<=10;i++)
{
printf(“\n
%d”,i);
}
}
void main()
{
printf(“hello”);
abc();
printf(welcome”);
abc();
printf(“very good morning to all of u”);
abc( );
}
/*program/
int xyz ( )
{
return(10);
}
void main( )
{
int a;
a=xyz();
printf(“%d”,a);
}
Output:- 10
/*program*/
int abc(int x)
{
return(x*5);
}
void main()
{
int a;
a=abc(10);
printf(“%d”,a);
}
Output:-50
/* program for addition*/
int add (int x, int y)
{
return (x+y);
}
void main()
{
int a;
a=add(50, 60);
printf(“%d”,a);
b=add(10, 20);
printf(“%d”,b);
}
output:-110
&30
/*square
program*/
main()
{
float a,b,c;
printf(“\n enter any number”);
scanf(%”f”,&a);
b=squar(a);
printf(“\n square of %f is %f”,a,b);
}
square(float x);
{
float y;
y=x*x;
return(y);
}
output:-
enter any no. 2
square of 2 is 4.000000
Note:-Need for user defined function:-
The program may become too large and complex and as a
result the task of debugging , testing and maintaining become difficult if a
program is divided into functional parts each parts may be indenpendelty coded
and letter combine into a single unit. These sub program are called functions
much easier to understand debug and test
Advantage:-
- top down
modular programming
- length of
source program reduced
- easy to
maintain
- function
may be use by many other programs
describe all these points
Note:-
The
main difference between library function & user define function is that
library function are not required to be written by us where as a user define
function has to be developed by the user define function can later become a
part of the c program library
modular programming:-
A large
program is divided into small modules the c provides the modularization
facilities of function which supports the modular programming modularization is
a design time activity to take full advantage of modulation , modules should be
independent of another
advantage of modular programming:-
- simplicity
is development:-
- faster
development:
- reusability:-
- abstraction:- it means hiding of details it provides
simplicity
- reduse code
size:-
- simplicity
in testing and modification:
disadvantages of modular programming:
- use of
function increase the execution time:-
/* prototype */
int add (int x,int y);
int main()
{
int a,b,c;
a=10;
b=20;
c=add(a,b);
return 0;
}
int add (int x, int y);
{
int x ;
z=x+y;
return z;
printf(“%d”,z);
}
Note:- prototype
mean behavior of function i. e. the return type the name the no & type
of inpute parameter there is no need of identifiers in the prototype so the
following is also sufficient
int add (int ,int);
this prototype is also called declaration or header
the body of a function that contains actual code for the function is called
definition the definition of can also be given before main() in this case there
is no need of prototype
the function main() is
calling function add( ) is called “called “
in the calling function there is a function called argument list in the head of called
function the list in side the parentheses is called parameter list the type and
no of argument list must exactly match with those of parameter.
The value of argument is assign to corresponding
parameter.
c=add(a,b);
/*calling*/
int add (int x,int y)
/*header of definition*/
x=a assign
value
y=b
The identifier a,b and c are called local identifiers
of function main the identifiers x,y and z are called local identifiers or add
function. A local identifiers can be used with in the function in which it is
declared a,b and c are execible with
main() only similary x,y and z are execible with in add ( ) only
The function can contain more than one return statement
physically but logically only one will be executed out of them.
The return value can be discorded if not required if
the function does not return any thisg its return type is void a void( )may or
may have not return statement it shows the end of function we can return only
single value from the function.
Multipli return values can be done with the help of
structure.
Note:- The
operating system maintain a user stack to keep track of functions called when a
function is called a new entey of the of
stack when the function end the entry is poped (to remove)
Stack (last in fast out)
/*
find a factorial no using functions*/
long factorial (int);
int main( )
{
int n;
longfact;
printf(“enter a no”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“\n the factorial is %d”, fact);
return 0;
}
long factorial (int num)
{
long fact =1;
for (int i=2;i<=num;i++)
fact*=i;
return fact;
}
/*program for making accept two no as parameter and
return h.c.f*/
(Highest
common factor)
int hcf(int x,int y);
int main()
{
int a,b,result;
printf(“\n enter two number”);
scanf(“%d%d”,&a,&b);
result=hcf(a,b);
printf(“\nthe hcf is %d ”,result);
return 0;
}
int hcf (int x, int y)
{
int result ,smaller;
smaller =(x<y)?x:y;
for (result = smaller; result>=1;result--)
{
if (x%result = =0)&& (y%result == 0)
return result;
}
/* program to print the given no is even or odd with
using function */
#include<stdio.h>
#include<conio.h>
void main( )
{
clrscr ( );
int s(int);
int a;
printf(“enter any number for finding even or odd with
the help of function concept \n”);
scanf(“%d”,& a);
s(a);
getch( );
}
s(int a);
{
if (a%2==0)
printf(“enterd no is even”);
else
printf(“entered no is odd”);
}
Note :-
A function is called it self such a process is
called recursion.
Library function eg:- printf( )and scanf( )
User define function:-add( ) and swap( )
Writing function avoids rewriting the same code over
and over using functions it becomes easier to write programs and keep track of
what they are doing
Eg:-
func();
{
char ch;
printf(“\n enter any alphabet”);
scanf(%c”,&ch);
if (ch>=65 && ch<=90)
return(ch);
else
return(ch+32);
}
/*scope rule of function (local and global variable)
*/
main( )
{
int a=80;value (a);
printf(“\n%d”,a);
}
value (int b);
{
int b=60;
printf(“\n%d”,b);
}
Output :-
60
30
main( )
{
int i=20;
display (i);
}
display (int y);
{
int k=35;
printf(“\n %d”,j);
printf(“\n%d”,k);
Output:-
20
35
Advance feature of functions:-
- function
declaration and prototypes
- calling
function by value
- calling
function by reference (address)
- recursion
pass(call) by value:-
in the formal
parameter is changed it will not effect the actual parameter but in the case
off pass by refrence if the formal parameter
is changed the actual parameter will also changed
we can pass the value of array to a function we can
pass the value of array to a function we can pass the address of a variable as
an argument to a function ih the normal way.
We called a function and passed something to it we
have always pass the value of variable to called function . such function calls
are called by value.
Eg:-
void
abc(int * x)
{
*x=*x+10;
printf(“%d”,*x);
}
void main( )
{
int a=50;
abc (&a);
printf(“%d”,a);
}
Output :-
60
/* pass by value*/
void swap (int a,int b)
{int t;
t=a;
a=b;
b=t;
printf(“%d%d”,a,b);
}
void main()
{ int x=10,y=20;
swap (x, y);
printf(“%d%d”,x,y);
}
Output:-
20,10
10,20
/* pass by reference*/
void swap (int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
printf(“%d%d”,*a,*b);
}
void main( )
{
int x=10;y=20;
swap(&x , &y);
printf(“%d%d”,x,y);
}
}
Output::-
20,10
10,20
Note:-
The
process of calling a function using pointers to pass the assess of
Variable is knows as call by reference The function
which is called by reference changed the value of the variable used in the call
Why we use function?
There are two reasons to use function:-
- writing
functions avoids rewriting the same code over and over
- using
functions it becomes easier to write program and keep track of they are
doing
Note:-
argument list
quadratic(a,b,c);
power(x,n);
square (y);
copy (name1,name2);
return value and their type:-
return 0;
or
return(expression);
return(x*y);
return(1);
return(0);
calling a function:-
p=mul(10,5)
Handling non-integer function:-
c-functions returns a value of type int as the default
case when no other type is specified explicitly
eg:-
main()
{
float a,b,mul( );
double dir ( );
a=12.345;
b=9.82;
printf(“%f\n”,mul (a,b));
printf(“%f\n”,dir(a,b));
}
float mul (x, y);
float x,y;
{
return(x*y);
}
double dir(p, q);
double p, q;
{
return(p/q);
}
/*function with array */
Like the value of simple variable it is also possible
to pass the value of an arrayto a function
void fa( )
{
int a[5], i;
printf(“enter the no”);
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}}
void fadisplay(
)
{
int i;
for( i=0;i<5;i++)
{
printf(“%d”,a[i];
}
}
void main( )
{
fa( );
fadisplay( );
}
Recursion:-
main( )
{
printf(“this is
an eg of recursion\n”);
main( );
It is possible for the functions to call them selves.
A function is call recursive if a statement with in the body of function calls
the same function some times called circular definition recursion is the
process of defining something interms of it self.
Or
A function which called itself is called recursive
function.
Program:-
int x=1;
void main( )
{
static int x=1;
printf(“hello”);
x++;
If (x<=10)
{
main( );
}
}
/*factorial program */
int fact(int x);
{
if (a==1)
{
return(1);
}
else{
return(a*fact (a-1));
}
}
void main( )
{
int n,x;;
printf(“enter a no ”);
scanf(“%d”,&n);
x=fact(n);
printf(“fact=%d”,x);
}
Explanation:-
fact(3);
{
return(3*fact(2));
fact(2){
return(2*fact(1));
}
fact(1);
{
return(1)
}
/*power program */
int power (int a,int b)
{
if (b= =1)
{
return(1);
}
else
{
return(a*power(a,(b-1)));
}
}
void main( )
{
int x,y,p;
printf(“enter two no”);
scanf(“%d%d”,&x,&y);
p=power(x, y);
printf(“%d”,p);
}
Note:-1.
Recursion may seem strong and complicated at the first stage. But it is
often must way to code then algorithm and once with the recursion the easiest way doing
so.
Pointer
pointer:-
pointer is variable that store address of another variable of the same
data type by declaring a counter the name the name of the counter variable
present by *(stric)
eg:-1
int
*p,q;
p=&q;
printf(“%d”,p);
printf(%d”,&q);
printf(“%d”,*p);
eg:-2
main( )
{
int a=30,y=20;
int *p,*q;
q=&a;
p=&y;
printf(“%d%d”, *p,*q);
}
Find the
Errors & output and also try to complete the program.
program:-eg:-3
int
a=50;
int *p;
p=x;
printf(“%d”,p);
p++;
printf(%d”,p);
Array & pointer:-
Eg:-
int
x[5]={1,2,3,4,5};
int*p;
p=x;
printf(%d”,*p);
p++;
printf(“%d”,*p);
Eg:-
int
x[5]={1,2,3,4,5};
int *p;
int i;
p=&x[0];
Or
p=x;
for(i=0;i<=4;i++)
{
printf(“%d”,(&p+i));
printf(“%d”,*(p+i));
}
Eg:-
int
x[5]={3,5,9,8,12};
int *p, *q;
int i;
p=x;
q=&x[2];
q++;
p=q;
printf(“%d”,*p);
for(i=3;i>=0;i--)
{
printf(“%d”,i[x]);
}
Pointer and function:-
Eg:-
void
abc(int*x)
{
printf(“%d”,*x);
void main( )
int a=50;
abc(*a);
}
Output:-
50
Eg:-
void
abc(int*x)
{
*x=*x+10;
printf(“%d”,*x);
}
void main( )
{
int a=50;
abc(&a);
printf(“%d”,a);
}
Note:-
in
pass by value if the formal parameter is change it will not effect the
actual parameter but in case of pass by refrence if the formal parameter is
change the actual parameter will also be change.
Note:-
As
like we can pass the value of the array to a function we can pass the add of a
variable as an argument to a function in the normal way.
Note:-
The
process of calling a function using pointer to pass the add of variable is
known as call by reference. The function which is called by
change the value of the variable used
Array and pointer :-
Eg:-
char
x[10]=”hello:”
p=x; or p=&x[0];
while (*p)
{
printf(“%c”,*p);
p++;
}
Eg:-
W A P lenth of string using pointer
main( )
{
charx[30],*p;
int n=0;
printf(“enter a string “);
gets(x);
p=x;
while(*p)
{
n++;
p++;
}
printf(“length=%d”,n);
}
Eg:-W A P compare two strings
main( )
{
char x[30],y[30];
printf(“enter the two string”);
gets(x);
p=x;
q=y;
while (*p)
{
if (*p!=*q)
{
printf(“string are not equal”);
break;
}
p++;
q++;
}
if (*p= = null)
{
printf(“string are equal”);
}
}
Pointer and structure :-
Eg:-
struct
abc;
{
int x;
int y;
};
abc m={10,20};
abc *p;
p=&m;
printf(“%d %d”,(*p).x, (*p).y );
Eg:-
main( )
{
struct date
{
int d, m, y;
};
date x[3]={{10, 9, 2006},{21, 11, 1988},{16, 5,
1988}};
date *p;
p=x;
int n;
for(n=1; n<=3; n++)
{
p++;
}
}
Eg :-
struct
xyz
{
int a,b;
}
void modify(xyz *m)
{
}
xyz n={50, 60};
modify (&n);
printf (“%d%d%d”, n.a, n.b); }
The reason for using pointer are:-
1. First pointer provides the means by which function can
modify calling argument.
2. pointer supports dynamic memory location.
3. pointer can improve the efficiency of certain
routines.
4. * operator is
also known as indirection operator
5. & operator
is known as address of operator.
6. for printing address is an unsigned integer(%u)
note:-
&
and * are known as unary operator.
Some rules for pointer :-
1. pointer declaration must have prefix to f*
2. while assigning variable to the pointer variable the
address operator (&) must be used along with variable.
3. mix data type is not allowed.
Pointer arithmetic:-
As a pointer
holds the memory add of a variable some airthmatic operations can be perform
with pointersare:-
1. add
2. sub
3. increment ++
4. decrement –
eg :-
int
value, *ptr;
value =120;
ptr=&value;
ptr++;
printf(“address =%u”,ptr);
note:-
(*ptr)++=++(*ptr)
Call by value:-
Whenever a portion of a program invokes a function with formal argument
control will be transfer from the main( )to calling function and the value
of actual argument is copied to the with in the function the actual
value
the calling portion of the program may be altered or changed when the
control is transfer back from the function to the calling portion of the
program .the actual value are not transferred back this type of passing formal
argument to a function is technically known as call by value.
Call by reference:-
1. actual argument are copied on to the formal argument
2. it referred by the different variable names
3. the formal and actual argument referencing the some
memory areas
Operators: An operator is a symbol that tells the
computer to perform mathematical or logical manipulations. Operators are used
in programs to manipulate data and variables. They usually form a part of the
mathematical of logical expressions.
Operators can
be classified into a number of categories. They include:
(1)
Arithmetic operators.
(2)
Relational operators.
(3)
Logical operators.
(4)
Assignment operators.
(5)
Increment and
decrement operators.
(6)
Conditional operator.
(7)
Bitwise operator.
(8)
Special operators.
(1)
Arithmetic
operator : C provides all the basic
arithmetic operators such as + , – , *
, / , % .
OPERATORS
MEANING
+
Addition or unary plus
– Subtraction or
unary minus
* Multiplication
/ Division
% Modulo division
Example of arithmetic operators are a – b ,a + b ,a*b
,a / b ,a % b.
Here a and b are two variables and are known as
operators.
Integer arithmetic ;- When both the operands in a
single arithmetic expression such as a + b are integers. The expression is
called an integer expression and the operand is called integer arithmetic.
Integer arithmetic always fields an integer value.
Example , if a & b are integers , then for
a = 14 & b = 4.
We have following results:
a + b = 18
a – b = 10
a * b = 56
a / b =
3 ( decimal part truncated )
a %b = 2 (
reminder of division )
(2) Real arithmetic : An arithmetic operation
involving only real operands is called real arithmetic. A real operand may be
assume values either in decimal or exponential notation.
Relational
Operator
OPREATORS MEANING
<
is less than
< = is
less than equal to
>
is greater than
> = is
greater than equal to
= = is equal to
! =
is not equal to
Logical operator : In addition to the relational operators ‘ C’ has following three
logical operators.
&& meaning
logical AND
| | meaning logical OR
! meaning logical NOT
The logical operator && and || are used when
we want to test more than one condition and more decisions. An example is,
a > b &&
x = = 10
the logical expression is true only if a > 6 is true and x = = 10 is also true. If either
( or both ) of them are false ,the expression is false.
e.g. if x, y, & z are floats then we will have:
x = 6.0 / 7.0 =
0.857143
y = 1.0 / 3.0 =
0.33333
z = -2.0/3.0 =
-0.666667
the operator %
(modulo division ) can not be used with real operands.
(2)
MIXED MODE
ARITHMETIC : When one of the operand is
real and other is integer , the expression is called a mixed mode arithmetic
expression.
If either operand is of the real type then only the real operation is
performed and the result is always a real number.
They 15 / 10.0 = 1.5
where as 15 / 10.0 = 1.0
(3)
RELATIONAL
OPERATOR : If we want to compare two quantities we use
relational operator.
Example : we may compare the
age of two persons , or the price of two items and so on these comparisons can
be done with the help of relational operator.
Containing
of relational operator is termed as a relation expression.
Example of relational operator is < , > , <=
,>= ,= = , !=
(4) Assignment operator: assignment operator are used to assign the
result of an expression to a variable. We have seen the usual assignment
operator ‘=’.
‘C’ has a set
of ‘ shorthand’ assignment operators of the form.
v op = exp ;
where V is variable , exp is an expression and op
is a known as the shorthand assignment operator.
SHORTHAND OPERATORS:
Statement with simple assignment operator
|
Statement with shorthand operator
|
a = a + 1
|
a + = 1
|
a = a – 1
|
a – = 1
|
a = a * ( n + 1)
|
a * = n + 1
|
a = a / ( n + 1)
|
a / = n + 1
|
a = a % b
|
a % = b
|
(5) INCREMENT AND DECREMENT OPERATOR:
‘C’
has two very useful operators not generally found in other language. These are
the increment and decrement operator.
++ and – –
The operator ++ adds 1 to the operand while – – substrates 1.
Types of
increment and decrement operator :
(a)
pre-increment ++m
(b)
post- increment
m++ (m+=1)
(c)
pre-decrement m–
– (m-=1)
(d)
post- decrement –
– m
+ + m is
equivalent to m = m+1
–
– m is equivalent
to m = m –1
We use increment and decrement statements in for and
while loops.
(6) CONDITIONAL OPERATORS: A ternary operator pair ‘?
: ‘ is available in C to construct conditional expressions of the form.
exp1 ? exp2 :
exp3
where exp1 , exp2 and exp3 are expressions.
The operator ?: works as follows :-
If exp1 is
true the answer will be exp2 else exp3
Example: a =
10;
b = 15;
x = ( a > b) ? a : b ;
printf”%d”,x);
if ( a>b)
x = a;
else x = b;
(7) SPECIAL OPERATOR :
‘C’ supports some special operator of interest such as comma operator,
size of operator, pointer operator.
The comma operator :-
The comma
operator can be used to link the related expressions together . For example ,
the statement
value = ( x = 10,
y = 5 , x + y);
first assign
the value 10 to x then assigns 5 to y and finally assigns 15 i.e., (10+5) to
value.
NOTE : Please Ignore
Human being typing mistakes
The size of
operator:
The size of operator is a compile time operator and when used with an
operand, it returns the numbers of bytes
the operand occupies. The operand may be a variable , a constant or a data type
qualifier.
Example ; m = size of (sum)
n =
size of (long int.)
the size of operator is normally used to determine the length of arrays
and structures when their sizes are not known to the programmer.
EXPRESSIONS
Algebraic expression
|
‘ C ’ expression
|
a * b – c
(m + n) (x + y)
ab/c
3x2 + 2x +1
x/y + c
|
a * b – c
( m + n ) * ( x + y)
a * b/c
3*x*x + 2*x +1
x/y + c
|
EXPRESSION : There are
two types of expressions .
(1)
Arithmetic
expression.
(2)
Relational / Logical /Conditional expression.
An arithmetic expression is written numeric values an relational
expression is either true or false. Arithmetic expressions uses arithmetic
operators relational operators uses relational and logical operator.
Example of
arithmetic expression :
a + b ,
a – b
a + ( a/b * d )
Example of relational expression :
a <
b
a > b
( a || b) * ( a
!= b ) && ( c = = d)
!( a > b )
Note: There is almost no difference between relational
expression and arithmetic expression both can be used in place of each other.
Zero ––––
false
Non zero –––– true
If relational expression is true than returns numeric
value 1 otherwise 0.
Example of
logical operators:
AND ––––––
&&
OR ––––––
| |
NOT ––––––
!
A
|
B
|
AB
|
A+B
|
0
|
0
|
0
|
0
|
0
|
1
|
0
|
1
|
1
|
0
|
0
|
1
|
1
|
1
|
1
|
1
|
(9)
PRECEDENCE
OPERATOR:
An arithmetic expression without parentheses will be
evaluated from left to right using the rules of precedence of operators.
There are two distinct priority level of arithmetic
operators.
High
priority * , / , %
Low
priority + , –
Firstly high priority operators are applied as they
are encountered then low priority operators are applied.
Example
: x = a- b/3 + c* 2-1
where a=9, b=12 ,and c=3
x =
9- 12/3 + 3*2-1
first pass
step1 x = 9 – 4 + 3* 2 –1
step2 x = 9 – 4 + 6 –1
second pass
step3 x = 5 + 6 –1
step4 x = 5 +5
step5 x = 1
Example. A && B , A || B , (!A) , (!A=B)
Hierarchy
of operation:- (BODMOS)
Bracket,
open, Divide, Multiply, Add, Subtraction.
Priority Operators
1st * / %
2nd + -
3rd =
Example. 2*5 – 4/2 + 3*2
10 –
4/2 + 6
10
– 2 + 6
16
– 2
14 Ans.
Control structure :-
1. Decision control structure
2. loop control structure.
3. case control structure.
1. decision control structure:-
(a) if statement
(b) if – else statement
(c) nested if statement.
(a) Syntax of if statement:-
If (condition
is true)
Execute
this statement ;
Example. if
(A = B)
{
Printf
(“ marks are equal”);
}
If the
condition is true than the statement is executed. If the condition is not true
than the statement is not executed.
Multiple statement :-
if(
condition )
{
Statement
1 ;
Statement 2 ;
}
(6) if – else
condition
Example.
Syntax.
if( condition
)
{
Statement 1 ;
Statement 2 ;
}
else
(condition )
{
Statement 3 ;
Statement 4 ;
}
Example. if ( A >= B )
{
printf(“ Drink tea “);
}
else
{
printf(“ Drink coffee ”);
}
(C) Nested if statement :-
Syntax:
if(
condition )
{
if(
condition )
{
Statement ;
}
else
{
Statement ;
}
}
Conditional operators : Ternary operators
Syntax: exp1?
exp2 : exp3
if exp1 is true
then the result will be exp2 else exp3. We can do similar with if-else
statement.
Example.
int x, y;
scanf(“%d”,&x);
y=(x>5?3:4);
This statement will store 3 in y if x>5 otherwise
it will store 4 in y.
Example.
char a;
int
y;
printf(“Enter any character”);
scanf(“%c”, &a);
y=(a>65 && a<=90?1:0);
Note: It is not necessary that the conditional
operator should be used only in arithmetic statements.
Modulus operator :-
c = a % b
a
|
b
|
C = a % b
|
10
|
2
|
0
|
11
|
2
|
1
|
11
|
7
|
4
|
13
|
7
|
6
|
24
|
8
|
0
|
7
|
21
|
7
|
132
|
10
|
2
|
Exercise: 153
% 10
7842 % 2
98 % 10
4 % 10
Else if ladder :-
Syntax:
if(condition1)
Statement1;
else if (condition2)
Statement2;
else if (condition3)
Statement3;
else
default statement ;
Assignment operator :-
An assignment
operator used to assign the value of any expression to a single variable.
It can be a single variable. A variable constant an
expression
function call.
int x = 5;
x = ( a++) + ( b–1) *c
int x = y;
x = add( ) ;
Note :- The
variables declared inside main function are called local automatic variable.
The variables outside any function are called global variables. The local
automatic variable are not initialized so these stores garbage or meaningless
value till assign to some useful value , the global variables are automatically
initialized by the system .
Global and Local Variable -:
Example.
#include < stdio.h >
int
g ; //
global variable
void
main()
{
int a
; // local variable
printf(“ \n %d %d”,a ,g);
g + =
a ;
printf(“ \n %d %d” ,a ,g);
}
NESTED
IF STATEMENT
When a series of decisions are involved. We
may have to use more than one if-else statement in nested form.
if( test
condition-1 )
{
if( test
ondition-2)
{ Statement 1;
}
else
{ Statement 2;
}
} else
{Statement 3;
}
If
the condition-1 is false then the statement 3 is executed, otherwise it
continues to perform the second test.
If
the condition 2 is true statement 1 is executed otherwise statement 2 is
executed. And then the control is transferred to the statement x.
The else – if ladder :
There is another way of putting if
together when multipath decisions are involved. A multipath decision is a chain
if in which the statement associated with each else is an if.
Syntax :
if( condition-1 )
statement-1;
else-if ( condition-2)
statement-2;
else-if ( condition-3)
statement-3;
else-if ( condition-n)
statement-n;
else
default-statement;
statement-x;
This
construct is known as the else if ladder.
LOOPS
LOOPS: loops are use in programming for repeating a
set of statement again and again till a logical condition is true. There are
three types of loops:
(1)
While loop
(2)
For loop
(3)
Do while loop
Important for loop :-
(1)
initialization
part
(2)
condition
(3)
update counter.
(1)
for loop:
syntax:
for(initialization ; condition ; updating)
initialization
condition increment
Note : when one or more statements are to be executed
repeat loops are used.
·
Looping is also called repetition or
iteration.
·
Looping can also
be incremented with the help of go to statement but the go to statement is
avoided in structure programming because it destroys the concept of “ locality
of reference” . locality of references increase the efficiency of the memory
axis.
·
Example : for ( i =5;
i>=0 ; i--)
i = 5 5 >= 0
i = 4 4 >= 0
i = 3 3 >= 0
i = 2 2 >= 0
i = 1 1 >= 0
i = 0 0 >= 0
Program:
# include < stdio.h >
# include < conio.h >
void main ()
{
int i;
for ( i = 0 ; i < = 5 ; i + +)
{
printf (“ \n
%d ”,i);
}
getch( );
}
While loop :
void main ( )
{ int i;
i = 1;
while( i < = 10)
{
printf(“\n %d”, i);
printf(“Hello”);
i = i +1;
}
getch( );
}
Do-while loop:
void main ( )
{
int i ;
i = 1;
do {
printf(“ Hello ”);
printf(“ %d”,i);
i =
i + 1;
}while
( i <= 10);
getch( );
}
Note:
do-while loop is slightly differ from
while loop and for loop. In this loop , the statements are printed and
condition checking after them. And while has to be terminated at the last with
semi colon. This loop is generally used in the menu design.
Error in loops: The errors in loops are caused due to
incorrect condition. Error may be three types:
(1)
infinite looping
(2)
for breaking a
infinite loop we use “ Ctrl + break ” .
(3)
Syntax error.
Nested
for loop : loop with in loop is called nested loop. First loop is outer loop
and second loop is inside loop.
Syntax: for( condition )
for ( condition )
{
Statement;
}
}
Program:
# include < stdio.h >
# include < conio.h >
void main ( )
{
int x, y;
for ( x = 1 ; x < =
5 ; x + +)
{
for ( y = 1 ; y
< = x ; y + +)
{
printf(“
Hello”);
}
printf(“\n”);
}
getch( );
}
Switch statement :
We
have seen that when one of the many alternatives is to be selected , we can use
an if statement to control the selection. However the complexity of a such a
program increases when the number of alternative increases. The program becomes
difficult to read and follow. To overcome this difficulty, ‘C’ has a built in
multiway decision statement knows as switch.
The
switch statement tests the value of a given variable or expression against a
list of case.
Syntax:
Switch ( expression)
{
case value –
1:
block 1
break;
case value –
2:
block 2
break;
……….………
……………….
default:
default block
break;
}
Loop
with break : -
(1)
while ( )
{ ______________
______________
if (condition )
break ;
______________
______________
}
(2)
for ( )
{
______________
______________
if ( error )
break;
______________
______________
}
(3) while (
)
{
______________
if (error )
goto stop ;
______________
if ( condition )
goto abc ;
______________
______________
abc:
______________
______________
stop:
}
Example: Menu:
1.
Add.
2.
Sub.
3.
Div.
4.
Mul.
Choose any one option.
Example program:
# include < stdio.h >
# include < conio.h >
void main ( )
{
int i = 2;
switch (i)
{
case 1: printf(“ My case one”);
break ;
case 2: printf(“ My case two”);
break ;
default:
printf(“ I am in default”);
break ;
}
Example 2:
void main ( )
{
int i ;
printf(“ Enter any
number for choice.”);
scanf(“ %d”,
&i);
switch( i )
{
case 1:
printf(“\n Cold drink”);
break;
case 2:
printf(“\n Coffee”);
break;
default:
printf(“\n Not available”);
break;
}
getch();
}
Note: We can also use character type option.
e.g., char ch;
switch (ch )
{ case ‘ A’ : Do this;
break;
}
break statement
:
we use break state in two cases.
(1)
Switch case.
(2)
Looping.
When the keyword break is use it controls the loop.
Example.
void main ( )
{
int i = 1,j = 1;
while (i++ < = 200)
{
if ( j = = 150 )
break ;
else
printf( “ %d %d \n”, i, j) ;
}
}
}
Example :
void main( )
{
int i = 1;
while ( i <=
200)
{
if( i == 100)
break ;
else
printf(“
%d”,i);
i ++;
}
getch();
}
THE CONTINUE STATEMENT :
This statement is used in looping an switch statement when condition is
true than loop start again.
Example :
int value , i ;
i = 0;
while (i<=10)
{
printf(“ Enter
a number :”);
scanf(“ %d”
,&value);
if(value <=
0)
{
printf(“ zero
or negative value found ”);
continue ;
}
i ++;
}
go-to statement : go-to statement is use for line changing. It is not useful
for a good programming skill. There are some limits in go-to statement. Firstly
check the condition if condition is true then control transfer to the particular
line or label. It is time consuming process. It is difficult to de-bug a
program.
The big
problem with go-to is that when we use them we can never be sure how we got a
certain point in our code. That means flow of control is not clear so we
neglect the go-to statement.
Example:
main( )
{
int goals;
printf(“ Enter numbers:”);
scanf(“ %d”, &goals);
if( goals<=5)
goto score;
else
{
printf(“Good
Score”);
exit();
}
score:
printf(“To error is by human”);
}
Note: In this program we have to use #include
<process.h> because the function exit() belongs inside that header file.
CHARACTER
The
character that can be used to form words, numbers and expressions depend upon
the computer on which the problem is run.
The
char. In ‘C’ are grouped into the following categories :
(1)
Letters.
(2)
Digits.
(3)
Special char.
(4)
White spaces.
CHARACTER SET
Letters
Digits
Uppercase A……Z
All decimal digits 0…9
Lowercase a…….z
SPECIAL CHARACTERS
,
|
Comma
|
.
|
Period
|
;
|
Semicolon
|
:
|
Colon
|
?
|
Question mark
|
“
|
Quotation mark
|
/
|
Slash
|
\
|
Backslash
|
_
|
Underscore
|
%
|
Percentage
|
|
|
Vertical bar
|
#
|
Number sign
|
$
|
Dollar sign
|
&
|
Ampersand sign
|
-
|
Minus sign
|
<
|
Less than
|
>
|
Greater than
|
+
|
Plus sign
|
[
|
Left bracket
|
]
|
Right bracket
|
{
|
Left brace
|
}
|
Right brace
|
(
|
Open bracket
|
)
|
Close bracket
|
!
|
|
White spaces
|
|
Blank spaces
|
|
Horizontal tab
|
|
New line
|
|
Form feed
|
Print
format codes:-
% i --
Signed decimal number
% u -- Unsigned
decimal number
% x -- Hex decimal number
Reading a character
:
By using getchar( ) function we
can take value from keyboard one by one character. It is similar to scanf( )
function. But difference is that reading a single character only.
Example: (1) char ch;
ch =
getchar( );
(2) char ch ;
ch = ‘ ‘ ;
while
( ch != ‘\n’)
{
ch
= getchar( );
}
Character
test function:
(1)
isalpha( )
(2)
isdigit( )
(3)
islower( )
(4)
isupper( )
(5)
isspace( )
all of above are belong into the ctype.h
header file.
Example:
#include < stdio.h >
#include < conio.h >
void main( )
{
int i, j;
clrscr( );
for ( i = 1; i <= 5 ;
i++ )
{
for ( j = 1; j
<= i ; j++)
{
printf( “ %d ”, i
);
}
printf( “ \n ” );
}
getch( );
}
Writing
a character :
By
putchar( ) function we can put the value on screen.
putchar (
variable name) ;
it is similar to printf ( ) function , but we
never use formatting like %d , %f ,and we can not print multiple value . no
commands are allow.
Example: char ch;
ch = getchar ( );
putchar( ch );
Formatted
input :
By using scanf( ) function
we take the value from keyboard.
Syntax
: scanf( “control string”, &arg1, &arg2 ,&arg3….);
Blank,
tabs, \n ( new line ) are ignore. For reading a integer number is
%wd.
where ,
w = width
The % sign indicates that a conversion
specification follows :
w = “ is an integer number. “
Example
: Scanf(“ %d %d %d”, &a
,&b, &c);
Formatted output: By printf( ) function, we can printf( ) the value or
message on the screen.
Syntax
: printf( “control string ”, arg1 ,arg2…);
Three
types of items control string contains :
(1)
Print character
or value.
(2)
Output format.
(3)
Escape sequence
character such as \n ,\t,..
Example:
printf(“ a =%f \n b = %f” ,a ,b);
printf(“ sum =%d “ ,
1234);
printf(“ \n \n
”);
Example:
printf(“ %6d” ,9876);
printf(“ %2d “ , 9876);
Example:
printf(“ %7.2f ”, number);
Type
casting :- or cast operator :
The general format of
cast type expression:
Example:
float a ;
int x = 6 , y = 4;
a = float (x/y);
printf(“ %f”, a);
The cast operator is technique to
force fully convert one data type to the other this process is known as type
casting.
Example: float a =1.23;
printf(“ Value of an
type casting = %d” int(a));
printf(“
value of a = %f” , a) ;
Result
: 1st :- 1
2nd
:- 1.230000
C Language Summary
An array is defined by writing the
data type followed by the name followed by the size in brackets; for example,
int
x[20];
double
car[ROWS][COLS];
In the first case, the variables x[0],
x[1], ... ,x[19] are created. In the second case, a
2-D array (matrix) is created. In C, array names without the brackets are
pointers.
When the statement
break;
is encountered, the innermost while,
do while, for, or switch construct is terminated.
The cast operator is written as
(type)
where type is a data type. When the cast operator is executed, the
operand is converted to type. As examples, if we write:
int
i = 2;
float
x;
x
= (float) i;
the value of i is converted to float
and copied into x. If we write:
struct
node {
char* data;
struct node* link;
};
struct
node* ptr;
ptr
= malloc(sizeof (struct node));
storage for one structure whose
members are data and link is allocated by the library function malloc. The
address of this storage is assigned to ptr.
A C comment is delimited by /* and */.
Integer constants may be written in
decimal:
130 45 88203
An integer constant that begins with
0 (zero) is an octal number:
0130 045
A sequence of digits preceded by 0X
or 0x is a hexadecimal number:
0x90A 0Xf2
Either lowercase a through f or
uppercase A through F is acceptable.
An integer constant may be terminated
by u or U, to indicate that it is unsigned, or by l or L to indicate that it is
long. If a decimal constant is not terminated with either u, U, l, or L, it is
the first of the types int, long, or unsigned long in which its value can be
represented. If an octal or hexadecimal constant is not terminated with either
u, U, l, or L, it is the first of the types int, unsigned int, long, or
unsigned long in which its value can be represented. If a decimal, octal, or
hexadecimal constant is terminated with either u or U, it is the first of the
types unsigned int or unsigned long in which its value can be represented. If a
decimal, octal, or hexadecimal constant is terminated with either l or L, it is
the first of the types long or unsigned long in which its value can be
represented. If a decimal, octal, or hexadecimal constant is terminated with
either l or L and u or U, it is of type unsigned long.
A floating-point constant consists
of a string of digits (integral part) followed by a decimal point followed by a
string of digits (fractional part) followed by an integer exponent. The integer
exponent is e or E optionally followed by + or followed by a string of digits.
Either the integral part or the fractional part, but not both, may be omitted.
Either the decimal point or the integer exponent, but not both, may be omitted.
Examples of floating-point constants are:
2.0 4.3e4 9.21E9 13.E+4 4e3 .390
A floating-point constant may be
terminated by f or F to indicate that it is a float or by l or L to indicate
that it is a long double. If a floating-point constant is not terminated with
either f, F, l, or L, it is of type double.
A char constant is delimited by
single quotation marks, for example, 'Y'.
A string constant is delimited by
double quotation marks, for example,
"This
is a string constant."
C recognizes the following escape
sequences in character and string constants:
Constant
|
Meaning
|
\a
|
Ring bell (alert)
|
\b
|
Backspace
|
\f
|
Formfeed
|
\n
|
Newline
|
\r
|
Carriage return
|
\t
|
Horizontal tab
|
\v
|
Vertical tab
|
\\
|
Backslash
|
\'
|
Single quote
|
\"
|
Double quote
|
\?
|
Question mark
|
\ddd
|
Octal constant
|
\xhh
|
Hexadecimal constant
|
Continue
When the statement
continue;
is encountered in a while or do while
loop, control passes to the condition that determines whether to execute the body
of the loop again. When the statement
continue;
for
(expr1; expr2; expr3) body
Then expr2 is evaluated to
determine whether to execute body again.
The integer data types are char, short int (which may be abbreviated short), int,
and long int (which
may be abbreviated long).
The sizes of these data types satisfy
sizeof(char)
<= sizeof(short) <= sizeof(int) <= sizeof(long)
The signed integer types are signed
char, signed
short int, signed
int, and signed
long int. In addition, the unsigned integer
types unsigned char, unsigned short int, unsigned int (which may be abbreviated unsigned), and unsigned long int are available.
The floating-point data types are float, double,
and long double. The
sizes of these data types satisfy
sizeof(float)
<= sizeof(double) <= sizeof(long double)
Some other types, defined in
standard headers, are given in the following table:
Type
|
Defined
in
|
Represents
|
ptrdiff_t
|
stddef.h
|
The difference of two pointers
|
size_t
|
stddef.h
stdio.h stdlib.h string.h time.h |
The value of sizeof
|
va_list
|
stdarg.h
|
Information needed by macros in stdarg.h
|
FILE
|
stdio.h
|
Information needed to manipulate
files
|
fpos_t
|
stdio.h
|
A position within a file
|
clock_t
|
time.h
|
Time
|
time_t
|
time.h
|
Time
|
Define
The #define statement is often used
to create symbolic (also called manifest) constants. For example, the statement
#define
WIDTH 80 /* Characters per line */
Notice there is no equals sign in
the definition and it is not followed by a semicolon.
Do While
The statement
do
body while (condition) ;
results in the execution of body as long as condition is true (nonzero). The condition is tested after body is executed. In addition, body must be enclosed in braces unless it consists of a single
statement, in which case it is simply terminated with a semicolon.
Enum
An enumerated type is a data type
with user-specified values. For example, the declaration
enum
director (Hitchcock, Huston, Meyer);
describes the enumerated type enum
director. A variable of type enum director should take one of the values
Hitchcock, Huston, or Mayer. To define a variable name of type enum director,
write
enum
director name;
After the preceding definition, the
assignment
name
= Huston;
is valid.
For
The statement
for
(expr1; expr2; expr3) body
first executes expr1. Then, as long as expr2 is true (i.e., nonzero), body is executed followed by expr3. Note that expr2 is tested before body and expr3 are executed. In addition, body must be enclosed in braces unless it consists of a single
statement, in which case it is simply terminated with a semicolon.
Functions
The definition of a function consists
of a header and a body. The header consists of the data type returned followed
by the function's name followed by the data types and names of any parameters
(also called arguments) in parentheses. If the function returns no value, the
keyword void occurs in place of the returned data type. If there are no
parameters, the keyword void occurs in parentheses. No semicolon follows the
right parenthesis. The body of the function, that is, the code that implements
the function, follows the header and is enclosed in braces.
A declaration of a function
resembles a function header. The declaration consists of the data type returned
followed by the function's name, followed, in parentheses, by the data types
and optional names of the expected arguments terminated by a semicolon. If the
function returns no value, the keyword void occurs in place of the returned
data type. If there are no expected arguments, the keyword void occurs in the
parentheses.
Here is an example of a function
definition:
int
fun(char letter) /* header */
{
/*
body */
}
Here is a declaration of the
preceding function:
int
fun( char letter);
In C, function parameters are
normally passed by value. That is, the value of each parameter is copied to a
local variable when the function is called. This local variable is distroyed
when the function returns. Any changes made to the local copy of a parameter
are lost upon return as a result of this mechanism.
Pointers can be used to pass
variables to functions such that their values can be changed in the functions
and their modified values returned. For example, the function
void
swap(float* x, float* y)
{
float z;
z = *x;
*x = *y;
*y = z;
return;
}
could be called as follows
swap(&a,
&b);
to interchange the values of float
variables a and b. Notice the use of the address-of operator
(&) in calling statement and the indirection operator (*) in the function
body.
If
The expression
if
(condition) body
Results in the execution of body
if condition is true (nonzero). Otherwise, control skips to the
statement immediately following body. In addition, body must be
enclosed in braces unless it consists of a single statement, in which case it
is simply terminated with a semicolon.
The expression
if
(condition) body1 else body2
Results in the execution of body1
if condition is true (nonzero). Otherwise, body2 is executed. In
either case, the next statement executed is the statement immediately following
body2. In addition, body1 must be enclosed in braces unless it
consists of a single statement, in which case it is simply terminated with a
semicolon. Similarly, body2 must be enclosed in braces unless it
consists of a single statement, in which case it is simply terminated with a
semicolon.
Initializing in Definitions
Any variable may be initialized in
its definition be writing, for example,
int
x = 5;
An array can be initialized, for
example, by writing
int
age[ 5 ] = { 4, 32, 5, 27, 29 };
A structure can be initialized, for
example, by writing
struct
data {
int day;
char* month;
int year;
}
due_date = { 8, "Jan", 1990 };
The C keywords are listed below.
These words should not be used as identifiers (variable names).
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
auto
break
case
char
const
continue
default
do
double
else
enum
extern
float
for
goto
if
int
long
register
short
signed
sizeof
static
struct
switch
typedef
union
unsigned
void
volatile
while
Pointers
A pointer must be defined so as to
point to a particular data type. For example, in the case of
int*
ptr;
ptr can hold the address of an int.
The syntax
*ptr
assesses the contents of the cell
whose address is ptr. The star (*) is called the indirection operator. The
address-of operator (&) is used to obtain the address of a variable. For
example
int
a
int*
b
b
= &a
results in variable a and
pointer b refering to the same memory location.
Operators and Precedence
The C operators are list from
highest (evaluated first) to lowest (evaluated last) precedence in the
following table. Operators between horizontal lines have the same precedence.
Description
|
Operator(s)
|
Associates
from the
|
Function expression
Array expression Struct indirection Struct member |
( )
[ ] -> . |
left
|
Increment/decrement
One's complement Negation Address of Dereference Type cast Unary minus Unary plus Size in bytes |
++ --
~ ! & * (type) - + sizeof |
right
|
Multiplication
Division Remainder |
*
/ % |
left
|
Addition
Subtraction |
+
- |
left
|
Shift left
Shift right |
<<
>> |
left
|
Less than
Less than or equal Greater than Greater than or equal |
<
<= > >= |
left
|
Equal
Not equal |
==
!= |
left
|
Bitwise and
|
&
|
left
|
Bitwise exclusive or
|
^
|
left
|
Bitwise inclusive or
|
|
|
left
|
Logical and
|
&&
|
left
|
Logical or
|
||
|
left
|
Conditional
|
? :
|
right
|
Assignment
|
= %= +=
-= *= /=
>>= <<= &= ^= |= |
right
|
Comma
|
,
|
left
|
Return
When the statement
return;
is encountered, the function returns
to its invoker without returning a value.
When the statement
return
expression;
is encountered, the function returns
to its invoker the value of expression.
The statement return
expression; has the same meaning as return(expression);.
Sizeof
The value of the sizeof operator is
the size, in bytes, of its operand. One byte is defined to be sizeof (char). If
a is an array, sizeof (a) is the total size, in bytes, of a. If a is a
structure, sizeof (a) is the total size, in bytes, of all of the members of a.
Because sizeof is an operator and not a function, its value is known at compile
time. For this reason, it is legal to write
struct
date {
int day;
char* month;
int year;
};
#define
DATE_SIZE sizeof (struct date)
Standard Headers
The following table lists the header
files mandated by the ANSI C Standard and gives a brief description of the
purpose of each.
Header File
|
Purpose
|
assert.h
|
Putting diagnostics into programs
|
ctype.h
|
Testing and modifying characters
|
errno.h
|
Reporting error conditions
|
float.h
|
Describing floating-point types
|
limits.h
|
Describing integer types
|
locale.h
|
Formatting numeric values
|
math.h
|
Mathematical functions
|
setjmp.h
|
Bypassing default function call
and return conventions
|
signal.h
|
Handling signals
|
stdarg.h
|
Writing functions with an
arbitrary number of arguments
|
stddef.h
|
Common definitions
|
stdio.h
|
Handling input and output
|
stdlib.h
|
General utilities
|
string.h
|
Handling arrays of characters
|
time.h
|
Handling time
|
Storage Classes
The C storage classes are
auto extern
static register
Structures
A structure declaration consists of
struct followed by an optional structure tag followed by the declaration of its
members in braces. The terminating brace must be followed by a semicolon. For
example;
struct
data {
int day;
char* month;
int year;
};
Given a structure declaration one
can define a structure of the given type by writing struct followed by the
structure tag followed by the name of the variable to be defined. For example,
given the preceding structure declaration, we can define a structure d
by writing
struct
date d;
It is possible to declare and define
structures simultaneously.
A member of a structure can be
accessed by using the dot operator. For example, given the preceding
declaration and definition, we may access month in d by writing
d.month
The syntax (*s).x is equivalent to s->x.
C permits structure assignments
using the assignment operator = and permits passing structures to functions and returning
structures from functions.
Switch
The switch statement has the form
switch
(expression) {
case
c1:
statements1
case
c2:
statements2
...
default:
default statements
}
When the construct is executed, expression
is evaluated. Control passes to the line at which expression is equal to ci.
(Each of c1, c2, ... must be distinct.) If expression is not
equal to any of the ci's, control passes to default statements.
Execution continues until a break statement is encountered, at which point
control passes to the first statement after default statements. If no break statement
is present, execution continues through all the statements, beginning with the
first case in which ci equals expression. Normally, each of statements1,
statements2, ..., default statements concludes with a break; statement.
Each of c1, c2, ...
must be an integer constant and the default block is optional.
Typedef
The use of typedef creates a synonym
for some other data type. For example, if we write
typedef
struct x {
int day;
char* month;
int year;
}
DATE;
the types struct x and DATE are
synonyms. Given the preceding typedef, writing
DATE
d;
is the same as writing
struct
x {
int day;
char* month;
int year;
}
d;
Type Qualifiers
Type qualifiers are specified by the
keywords const
and volatile and are
used to inform the compiler about the behavior of variables and parameters. The
type qualifier const
("constant") indicates to the compiler that a variable or parameter
is not to have its value reset. Any attempt to reset the value of a const variable or parameter results in an error. The type
qualifier volatile indicates to the compiler that a variable or parameter may
have its value set by something (e.g., an operating system call) outside the C
program. In effect, the volatile type qualifier warns an optimizing compiler against making
assumptions about how the value of the variable or parameter will be set.
The type qualifiers may occur
together in variable definitions and parameter declarations. However, the type
qualifiers always come after the storage class and before the data type. Here
are two examples:
const
int num = 10; /* variable definition */
void
fun(const float real) /* parameter
declaration */
Union
The union construct is syntactically
identical to the structure construct (see Structures). A union may, at different times, hold one, and only one,
of the types defined. For example, if we define
union
num {
int x;
float y;
}
u;
u may hold an int or a float, but
not both. Storage is allocated for the largest of the data types specified. A
member of union u is accessed syntactically exactly as a member of a structure.
Void
The keyword void shows that a
function returns no value or expects no arguments. For example
void
f(int x, int y)
is the header of a function with two
parameters, both of type int, that returns no value. As another example,
float
g(void)
is the header of a function with no
parameters that returns a value of type float. Also, certain library functions
such as malloc return a pointer to void.
While
When we execute
while
(condition) body
as long as condition is true
(nonzero), we execute body. The condition is tested before body
is executed. In addition, body is enclosed in braces unless it consists
of a single statement, in which case it is simply terminated with a semicolon.
No comments:
Post a Comment