Sei sulla pagina 1di 67

------------------------------Program to find greatest in 3 numbers-------------------#include<stdio.h> #include<conio.

h> void main() { int a,b,c; clrscr(); printf("enter value of a, b & c: "); scanf("%d%d%d",&a,&b,&c); if((a>b)&&(a>c)) printf("a is greatest"); if((b>c)&&(b>a)) printf("b is greatest"); if((c>a)&&(c>b)) printf("c is greatest"); getch(); } -----------------------------Program to find gross salary-----------------------------#include<stdio.h> #include<conio.h> void main() { int gs,bs,da,ta; clrscr(); printf("enter basic salary: "); scanf("%d",&bs); da=(10*bs)/100; ta=(12*bs)/100; gs=bs+da+ta; printf("gross salary=%d",gs); getch(); }

-----------------------------------------------------------------------------------Program to find area and circumference of circle.


#include<stdio.h> #include<conio.h> void main() { int r; float pi=3.14,area,ci; clrscr(); printf("enter radius of circle: ");

scanf("%d",&r); area=pi*r*r; printf("area of circle=%f",area); ci=2*pi*r; printf("circumference=%f",ci); getch(); } ----------------------Program to display first 10 natural no & their sum--------------------#include<stdio.h> #include<conio.h> void main() { int i,sum=0; clrscr(); for(i=1;i<=10;i++) { printf("%d no is= %d\n",i,I); sum=sum+i; } printf("sum =%d",sum); getch(); } ------------Program to display series and find sum of 1+3+5+..+n.-------------------void main() { int n,i,sum=0; clrscr(); printf("Enter any no: "); scanf("%d",&n); for(i=1;i<n;i=i+2) { printf("%d+",i); sum=sum+i; } printf("%d",n); printf("\nsum=%d",sum+n); getch(); } --------------------Program to find that entered year is leap year or not-------------------#include<stdio.h> #include<conio.h> void main()

{ int n; clrscr(); printf("enter any year: "); scanf("%d",&n); if(n%4==0) printf("year is a leap year"); else printf("year is not a leap year"); getch(); }

-----------------------simple if statement------------------------------------#include<stdio.h> void main() { int strollno,marks1,marks2,marks3,marks4,marks5,total; float avg; printf("Enter student rollno==>"); scanf("%d",&strollno); printf("Enter marks1==>"); scanf("%d",&marks1); printf("Enter marks2==>"); scanf("%d",&marks2); printf("Enter marks3==>"); scanf("%d",&marks3); printf("Enter marks4==>"); scanf("%d",&marks4); printf("Enter marks5==>"); scanf("%d",&marks5); total=marks1+marks2+marks3+marks4+marks5; avg=total/5; if(avg>=75) printf("You have distinction");

else if(avg>=60 && avg<70) printf("You have first class"); else if(avg>=50 && avg<60) printf("You have second class"); else if(avg>=40 && avg<50) printf("You have pass class"); else printf("fail"); } ----------------------------simple interest---------------------------------#include<stdio.h> #include<conio.h> void main() { float si,ci=0,p,r,n; int i=0,t=0; clrscr(); printf("Enter the value of principal amount : "); scanf("%f",&p); printf("Enter the value of Rate : "); scanf("%f",&r); printf("Enter the value for number of years : "); scanf("%f",&n); si=(p*r*n)/100; printf("\n\nSimple interest for given value are : %f",si); while(i<n) { t=(p*r)/100; printf("\n\n\n\n%d",t); p=p+t; ci=ci+t; i++; } printf("\nCompound interest for given value are : %f",ci); getch(); } -------------------------prime number------------------------------------#include<stdio.h>

#include<process.h> void main() { int a,r,i; printf("enter no\n"); scanf("%d",&a); i=2; while(i<a) { r=a%i; if(r==0) { printf("not prime"); exit(0); //2 3 5 7 11 13 17 19 23 29 31 37 41 43 } i=i+1; } printf("prime"); } ------------------------perfact no----------------------------------------#include<stdio.h> void main() { int i,no,rem,c; i=1; c=0; printf("Enter the number"); scanf("%d",&no); while(i<no) { rem=no%i; if(rem==0) { c=c+i; } i++;

} if(c==no) { printf("prefect"); } else { printf("Not perfect"); //6,28,496 } } ---------------------------febonasi series----------------------------------#include<stdio.h> void main() { int a,b,c,n,i; printf("enter no \n"); scanf("%d",&n); a=1;b=1; printf("%d\n%d" ,a,b); i=1; while(i<=n) { c=a+b; a=b; b=c; printf("\n%d" ,c); i=i+1; } } --------------------------factorial number----------------------------------#include<stdio.h> void main() { long int no,i,fact; fact=1; printf("Ente the number");

scanf("%ld",&no); for(i=1;i<=no;i++) { fact=fact*i; } printf("The fact is %ld",fact); } --------------------------gcd programe---------------------------------------#include<stdio.h> void main() { int a,b,d,rem; printf("Enter the number==>"); scanf("%d",&a); printf("\nEnter the number==>"); scanf("%d",&b); while(1) { rem=a%b; if(rem==0) { printf("%d",b); break; } a=b; b=rem; } }

//Then b is greatest common divisior

--------------------------------------------------------------------------------/* a & b are the numbers whose LCM (Lowest common multiple) is to be found */
Multiples of 4 are: 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, ... (add 4 to each to get the next). Multiples of 6 are: 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, ... (add 6 to each to get the next). Common multiples of 4 and 6 are numbers that these two lists share in common: 12, 24, 36, 48, .... The least common multiple of 4 and 6 is therefore 12.

#include<stdio.h> void main() { int a,b,n; printf("Enter the number==>"); scanf("%d",&a); printf("Enter the number==>"); scanf("%d",&b); for(n=1;;n++) { if(n%a == 0 && n%b == 0) { printf("\n%d",n); } } } --------------------------------------------------------------------------------/* The program is check that entered number by user is armstrong or not */ #include<stdio.h> void main() {

int no1,no2,sum=0,rem; printf("Enter the no==>"); scanf("%d", &no1 ); no2=no1; while( no1 > 0 ) { rem = no1%10; sum = sum + (rem*rem*rem); no1 = no1/10; } // 0,1,153,370,371,407 if( no2 == sum ) printf("The number is armstrong"); else printf("The number is not armstrong"); } ----------------------------------------------------------------------------------/* this programe is check wheather entered character is vowel or not */ #include<stdio.h> main() { char ch; printf("Enter the character==>"); scanf("%c",&ch); switch(ch) { case 'a': case 'e': case 'i': case 'o': case 'u': printf("Enter character is vowel"); break; default: printf("Enter character is not vowel");

} } __________________________________________________________________ /* this programe display multiple arithmetic opration using switch */ #include<stdio.h> main() { int choice,no1,no2,total=0; printf("\n\t\t1 )Addition"); printf("\n\t\t2 )Substraction"); printf("\n\t\t3 )Multiplication"); printf("\n\t\t4 )Division"); printf("\n\n\t\tEnter your choice===>"); scanf("%d",&choice); printf("\nEnter No==>"); scanf("%d",&no1); printf("\nEnter second No==>"); scanf("%d",&no2); switch(choice) { case 1: total=no1+no2; break; case 2: total=no1-no2; break; case 3: total=no1*no2; break; case 4: total=no1/no2; break; default: printf("Invalid choice seleceted"); } printf("The total of the opration is %d",total);

} -------Program to use switch statement. Display Monday to Sunday---------#include<stdio.h> #include<conio.h> void main() { char ch; clrscr(); printf("enter m for Monday\nt for Tuesday\nw for Wednesday\nh for Thursday\nf for Friday\ns for Saturday\nu for Sunday); scanf("%c",&ch); switch(ch) { case 'm': case 'M': printf("monday"); break; case 't': case 'T': printf("tuesday"); break; case 'w': case 'W': printf("wednesday"); break; case 'h': case 'H': printf("thusday"); break; case 'f': case 'F': printf("friday"); break; case 's': case 'S': printf("saturday"); break; case 'u': case 'U': printf("sunday"); break; default : printf("wrong input");

break; } getch(); }

====================Binary search============================ #include<stdio.h> #include<conio.h> void main() { int arr[10],i,mid,low,upp; low=0; upp=9; int no; for(i=0;i<=9;i++) { printf("enter the %d element ==>",i+1); scanf("%d",&arr[i]); } printf("Enter the number ==>"); scanf("%d",&no); for ( mid = ( low + upp ) / 2 ; low <= upp ; mid = ( low + upp ) / 2 ) { if(arr[mid]<no) { low=mid+1; } else if(arr[mid]>no) { upp=mid-1; } else if(arr[mid]==no) {

printf("\nThe number is found at %d position",mid+1); break; } else printf("\nThe number is not exist"); } } ====================Babble sort============================= #include<stdio.h> #include<conio.h>

void main() { int arr[10],i,j,temp; for(i=0;i<=9;i++) { printf("\nEnter number %d ==>:",i+1); scanf("%d",&arr[i]); } clrscr(); printf("\nThe original array is ==>"); for(i=0;i<=9;i++) { printf("\n%d\t",arr[i]); } for(i=0;i<=9;i++) { for(j=0;j<=9-i;j++) { if(arr[j]>arr[j+1]) { temp=arr[j+1]; arr[j+1]=arr[j];

arr[j]=temp; } } } printf("After exchange of arrays."); for(i=0;i<=9;i++) { printf("\n%d\t",arr[i]); } getch(); } ====================Linear Search============================= /* Linear search in an unsorted array. */ #include <stdio.h> #include <conio.h> void main( ) { int arr[10]; int i, num ; clrscr( ) ; for(i=0;i<=9;i++) { printf("Enter number for element %d==>",i+1); scanf("%d",&arr[i]); } printf ( "Enter number to search: " ) ; scanf ( "%d", &num ) ; for ( i = 0 ; i <= 9 ; i++ ) { if ( arr[i] == num ) break ; } if ( i == 10 ) printf ( "Number is not present in the array." ) ;

else printf ( "The number is at position %d in the array.", i ) ; getch( ) ; } ====================print series============================ #include<stdio.h> #include<string.h> //Print the series /* Input ABC Output CBA CB C */ void main() { char str[30]; int i,j,l; printf("Enter string ==>"); gets(str); l=strlen(str); printf("%d",l); for(i=0;i<l;i++) { printf("\n"); for(j=l-1;j>=i;j--) { printf("%c",str[j]); } } } ====================selection sort============================= #include<stdio.h>

void main() { int p[10],i,m,j,temp; for(i=0;i<10;i++) { printf("Enter no"); scanf("%d",&p[i]); } printf("\noriginal array is\n"); for(i=0;i<10;i++) printf("%d==>",p[i]); for(i=0;i<10;i++) { m=i; for(j=i+1;j<10;j++) { if(p[j]<p[m]) { m=j; } } if(m!=i) { temp=p[i]; p[i]=p[m]; p[m]=temp; } } printf("\n"); for(i=0;i<10;i++) { printf("%d=>",p[i]); } } ---------------------Program to show input and output of a string-----------------

#include<stdio.h> #include<conio.h> void main() { char a[50]; clrscr(); printf("enter any string: "); gets(a); puts(a); getch(); } ======================Find length of string========================== #include<stdio.h> #include<string.h> void main() { char str[30]; int i,l=0; printf("Enter the string==> "); gets(str); for(i=0;str[i]!=NULL;i++) { l++; } printf("length of the string is %d",l); } ======================Reverse string= ============================= #include<stdio.h> #include<string.h> void main() { char str[30]; int i,l=0; printf("Enter the string==> "); gets(str); for(i=0;str[i]!=NULL;i++) { l++;

} l--; // For removing null charater at end of string for(;l>=0;l--) { printf("%c",str[l]); } }

====================compare two string======================= #include<stdio.h> #include<string.h> void main() { char st1[30]; char st2[30]; printf("Enter string "); gets(st1); printf("Enter string "); gets(st2); if(strcmp(st1,st2)==0) { printf("two string are compared"); } else { printf("two string are not compared"); } } ==========Program to find whether a string is palindrome or not======
#include<stdio.h> #include<conio.h> void main() { char s1[20],s2[20]; clrscr(); printf("enter a string: "); scanf("%s",s1);

strcpy(s2,s1); strrev(s2); if(strcmp(s1,s2)==0) printf("string is a palindrome"); else printf("not a palindrome string"); getch(); }

====================print series============================ #include<stdio.h> #include<string.h> //Print the series /* Input ABC Output CBA CB C */ void main() { char str[30]; int i,j,l; printf("Enter string ==>"); gets(str); l=strlen(str); printf("%d",l); for(i=0;i<l;i++) { printf("\n"); for(j=l-1;j>=i;j--) { printf("%c",str[j]); } } } find whether how many time char enter by user is repeat in string

#include<stdio.h> #include<string.h> #include<conio.h> void main() { char str[30],ch; int i,l=0,c=0; printf("Enter the string==> "); gets(str); printf("Ente any character==>"); ch=getche(); for(i=0;str[i]!=NULL;i++) { if(ch==str[i]) { c++; } } if(c>0) { printf("\nThe total number of the occurenc of the %c is ==> %d",ch,c); } else { printf("\nThe character you want to find is not exist"); } } Copy string to other string without using inbuilt function #include<stdio.h> void main() { char str1[20],str2[20]; int i; printf("Enter string"); gets(str1); printf("Enter string");

gets(str2); printf("The original string is==>"); puts(str1); printf("\n"); puts(str2); for(i=0;str1[i]!=NULL || str2[i]!=NULL ;i++) { str1[i]=str2[i]; } printf("The copy string is ==>"); puts(str1); printf("\n"); } Concatenate of two string store out put in first string #include<stdio.h> void main() { char str1[20],str2[30]; int i,j; printf("Enter string"); gets(str1); printf("Enter string"); gets(str2); printf("The original string is==>"); puts(str1); printf("\n"); puts(str2); i=0; while(str1[i]!=NULL) { i++;

} j=0; while(str2[j]!=NULL) { str1[i++]=str2[j++]; } str2[i]=NULL; printf("The string is ==>"); puts(str1); }

convert string in upper case #include<stdio.h> void main() { char str1[20]; int i; printf("Enter string"); gets(str1); printf("The original string is==>"); puts(str1); for(i=0;str1[i]!=NULL;i++) { str1[i]=str1[i]-32; } printf("The string is ==>"); puts(str1); } convert string in lower case #include<stdio.h>

void main() { char str1[20]; int i; printf("Enter string"); gets(str1); printf("The original string is==>"); puts(str1); for(i=0;str1[i]!=NULL;i++) { str1[i]=str1[i]+32; } printf("The string is ==>"); puts(str1); } ====================compare two string======================== #include<stdio.h> #include<string.h>

void main() { char st1[30]; char st2[30]; printf("Enter string "); gets(st1); printf("Enter string "); gets(st2);

if(strcmp(st1,st2)==0) { printf("two string are compared"); } else { printf("two string are not compared"); } }

Function
The basic philosophy of function is divide and conquer by which a complicated tasks are successively divided into simpler and more manageable tasks which can be easily handled. A program can be divided into smaller subprograms that can be developed and tested successfully. A function is a complete and independent program which is used (or invoked) by the main program or other subprograms. A subprogram receives values called arguments from a calling program, performs calculations and returns the results to the calling program. There are many advantages in using functions in a program they are: 1. It facilitates top down modular programming. In this programming style, the high level logic of the overall problem is solved first while the details of each lower level functions is addressed later. 2. the length of the source program can be reduced by using functions at appropriate places. This factor is critical with microcomputers where memory space is limited. 3. It is easy to locate and isolate a faulty function for further investigation. 4. A function may be used by many other programs this means that a c programmer can build on what others have already done, instead of starting over from scratch.

5. A program can be used to avoid rewriting the same sequence of code at two or more locations in a program. This is especially useful if the code involved is long or complicated. 6. Programming teams does a large percentage of programming. If the program is divided into subprograms, each subprogram can be written by one or two team members of the team rather than having the whole team to work on the complex program We already know that C support the use of library functions and use defined functions. The library functions are used to carry out a number of commonly used operations or calculations. The user-defined functions are written by the programmer to carry out various individual tasks. Functions are used in c for the following reasons: 1. Many programs require that a specific function is repeated many times instead of writing the function code as many timers as it is required we can write it as a single function and access the same function again and again as many times as it is required. 2. We can avoid writing redundant program code of some instructions again and again. 3. Programs with using functions are compact & easy to understand. 4. Testing and correcting errors is easy because errors are localized and corrected. 5. We can understand the flow of program, and its code easily since the readability is enhanced while using the functions. 6. A single function written in a program can also be used in other programs also. Function definition: [ data type] function name (argument list) argument declaration; { local variable declarations; statements; [return expression] }

Example : mul(a,b) int a,b; { int y; y=a+b; return y; } When the value of y which is the addition of the values of a and b. the last two statements ie, y=a+b; can be combined as return(y) return(a+b); Types of functions: A function may belong to any one of the following categories: 1. Functions with no arguments and no return values. 2. Functions with arguments and no return values. 3. Functions with arguments and return values. Functions with no arguments and no return values: Let us consider the following program /* Program to illustrate a function with no argument and no return values*/ #include main() { staetemtn1(); starline(); statement2(); starline(); } /*function to print a message*/ statement1() { printf(\n Sample subprogram output); } statement2() { printf(\n Sample subprogram output two); }

starline() { int a; for (a=1;a<60;a++) printf(%c,*); printf(\n); } In the above example there is no data transfer between the calling function and the called function. When a function has no arguments it does not receive any data from the calling function. Similarly when it does not return value the calling function does not receive any data from the called function. A function that does not return any value cannot be used in an expression it can be used only as independent statement. Functions with arguments but no return values: The nature of data communication between the calling function and the arguments to the called function and the called function does not return any values to the calling function this shown in example below: Consider the following: Function calls containing appropriate arguments. For example the function call value (500,0.12,5) Would send the values 500,0.12 and 5 to the function value (p, r, n) and assign values 500 to p, 0.12 to r and 5 to n. the values 500,0.12 and 5 are the actual arguments which become the values of the formal arguments inside the called function. Both the arguments actual and formal should match in number type and order. The values of actual arguments are assigned to formal arguments on a one to one basis starting with the first argument as shown below: main() { function1(a1,a2,a3an) } function1(f1,f2,f3.fn); { function body; }

here a1,a2,a3 are actual arguments and f1,f2,f3 are formal arguments. The no of formal arguments and actual arguments must be matching to each other suppose if actual arguments are more than the formal arguments, the extra actual arguments are discarded. If the number of actual arguments are less than the formal arguments then the unmatched formal arguments are initialized to some garbage values. In both cases no error message will be generated. The formal arguments may be valid variable names, the actual arguments may be variable names expressions or constants. The values used in actual arguments must be assigned values before the function call is made. When a function call is made only a copy of the values actual arguments is passed to the called function. What occurs inside the functions will have no effect on the variables used in the actual argument list. Let us consider the following program /*Program to find the largest of two numbers using function*/ #include main() { int a,b; printf(Enter the two numbers); scanf(%d%d,&a,&b); largest(a,b) } /*Function to find the largest of two numbers*/ largest(int a, int b) { if(a>b) printf(Largest element=%d,a); else printf(Largest element=%d,b); } in the above program we could make the calling function to read the data from the terminal and pass it on to the called function. But function foes not return any value. Functions with arguments and return values:

The function of the type Arguments with return values will send arguments from the calling function to the called function and expects the result to be returned back from the called function back to the calling function. To assure a high degree of portability between programs a function should generally be coded without involving any input output operations. For example different programs may require different output formats for displaying the results. Theses shortcomings can be overcome by handing over the result of a function to its calling function where the returned value can be used as required by the program. In the above type of function the following steps are carried out: 1. The function call transfers the controls along with copies of the values of the actual arguments of the particular function where the formal arguments are creates and assigned memory space and are given the values of the actual arguments. 2. The called function is executed line by line in normal fashion until the return statement is encountered. The return value is passed back to the function call is called function. 3. The calling statement is executed normally and return value is thus assigned to the calling function. Note that the value return by any function when no format is specified is an integer. Return value data type of function: A C function returns a value of type int as the default data type when no other type is specified explicitly. For example if function does all the calculations by using float values and if the return statement such as return (sum); returns only the integer part of the sum. This is since we have not specified any return type for the sum. There is the necessity in some cases it is important to receive float or character or double data type. To enable a calling function to receive a non-integer value from a called function we can do the two things: 1. The explicit type specifier corresponding to the data type required must be mentioned in the function header. The general form of the function definition is Type_specifier function_name(argument list) Argument declaration; { function statement; }

The type specifier tells the compiler, the type of data the function is to return. 2. The called function must be declared at the start of the body in the calling function, like any other variable. This is to tell the calling function the type of data the function is actually returning. The program given below illustrates the transfer of a floating-point value between functions done in a multiple function program. main() { float x,y,add(); double sub(0; x=12.345; y=9.82; printf(%f\n add(x,y)); printf(%lf\nsub(x,y); } float add(a,b) float a,b; { return(a+b); } double sub(p,q) double p,q; { return(p-q); } We can notice that the functions too are declared along with the variables. These declarations clarify to the compiler that the return type of the function add is float and sub is double. Void functions: The functions that do not return any values can be explicitly defined as void. This prevents any accidental use of these functions in expressions.

Example: main() { void starline(); void message(); ------}

void printline { statements; } void value { statements; }

-----------------------------Function print the line----------------------------------------#include<stdio.h> void line(); /* prototype of function*/

void main() { line(); /* Function calling */ printf("\n\n\tHello, Good Morinig\n\n"); line(); /* Function calling */ } void line() { int i; for(i=0;i<40;i++) { printf("-"); } } --------------------------Function count square-------------------------------------------#include<stdio.h> void square(int); void main() { int no; printf("Enter no==>"); scanf("%d",&no); /* Function prototype */

square(no); }

/* Function calling */

void square(int a) { int i;

/* passing argument */

i=a*a; printf("The square of the entered no is %d",i); } Find area of rectangle using function #include<stdio.h> float area(float,float); void main() { float l,w,a; printf("\nEnter the lenght of Rectangel"); scanf("%f",&l); printf("\nEnter the width of the Rectangle"); scanf("%f",&w); a=area(l,w); } float area(float l1,float w1) { float k; /* Function calling which store the answer into a */ /* Prototype */

printf("The are of the Rectangle is %f",a);

k=l1*w1; return k; }

Create function that returns factorial of entire number #include<stdio.h> int fact(int); void main() { int n,f; printf("Enter Number==>"); scanf("%d",&n); f=fact(n); printf("Factorial value of %d is %d",n,f); } int fact(int n1) { int i,f=1; for(i=1;i<=n1;i++) { f=f*i; } return f; } Create function the check that enter no by user is perfect or not #include<stdio.h>

void perfect(int); void main() { int no; printf("Enter Number==>"); scanf("%d",&no); perfect(no); } void perfect(int no) { int i=1,rem,sum=0; while(i<no) { if(no%i==0) { sum=sum+i; } i++; } if(sum==no) { printf("The number is perfact"); } else { printf("The number is not perfect"); } } Call by Value function #include<stdio.h> void replace(int,int); void main() {

int a,b; printf("Enter a==>"); scanf("%d",&a); printf("Enter b==>"); scanf("%d",&b); printf("\n\nFrom main"); printf("\n a = %d b = %d",a,b); replace(a,b); printf("\n\n Back into main"); printf("\n a = %d b = %d",a,b); } void replace(int a,int b) { int temp; temp=a; a=b; b=temp; printf("\n\nFrom Function"); printf("\na = %d b = %d",a,b); }

Find Minimum and maximum into the array using function #include<stdio.h> #include<conio.h> #define size 30 int maximum(int[],int); int minimum(int[],int); void main()

{ int arr[size],i,n,max,min; clrscr(); printf("Enter the size of the array :"); scanf("%d",&n); printf("\nEnter the elements\n"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } max=maximum(arr,n); min=minimum(arr,n); printf("\n\nMaximum value is %d",max); printf("\nMinimum value is %d ",min); getch(); } int maximum(int x[],int n) { int m,i; m=x[0]; for(i=1;i<n;i++) { if(m<x[i]) { m=x[i]; } } return(m); } int minimum(int x[],int n) { int m,i; m=x[0]; for(i=1;i<n;i++) { if(m>x[i]) { m=x[i]; } } return(m); }

Find compound interest using Function #include<conio.h> #include<stdio.h> float comp_int_calc(float int_amt,float rate,int years) { float year,value; float inrate=rate/100; float compound_int=0; year=1; value=inrate*int_amt; printf("\nYear interest\n"); while(year<=years) { compound_int+=value; printf("%2f %8.2f\n",year,value); value=value+inrate*value; year+=1; } printf("\ncompound int %8.2f\n",compound_int); return compound_int; } void main() { int year; float principal,amount,value,period,r_value,rate; int choice; float compound_int; clrscr(); printf("Enter the amount :"); scanf("%d",&principal); printf("Enter the rate of interest :"); scanf("%d",&rate); printf("Enter the number of years"); scanf("%d",&period); compound_int=comp_int_calc(principal,rate,period);

r_value=compound_int+principal; printf("\n\nTotal compound interest is : %8.2f",compound_int); printf("\n\nReturned value is : %8.2f",r_value); getch(); }

Recursive Function
Recursion is a programming technique that allows the programmer to express operations in terms of themselves. In C++, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process". This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes be completed without the recursive call. One simple example is the idea of building a wall that is ten feet high; if I want to build a ten foot high wall, then I will first build a 9 foot high wall, and then add an extra foot of bricks. Conceptually, this is like saying the "build wall" function takes a height and if that height is greater than one, first calls itself to build a lower wall, and then adds one a foot of bricks.

-------------------------------Recursive implementation----------------------------------#include<stdio.h> int fact(int); void main() { int x; x=fact(5); printf("%d is factorial value of 3",x); } int fact(int n) { int fact1;

if(n==1) { return 1; } else { fact1=n*fact(n-1); return fact1; } } /* reversing string using recursion */ #include<stdio.h> main() { clrscr(); printf("Please enter a string :"); rev(); putchar('\n'); } rev() { char c; c=getchar(); if(c!='\n') rev(); putchar(c); }

Structure
Arrays are used to store large set of data and manipulate them but the disadvantage is that all the elements stored in an array are to be of the same data type. If we need to use a collection of different data type items it is not possible using an array. When we require using a collection of different data items of different data types we can use a structure. Structure is a method of packing data of different types. A structure is a convenient method of handling a group of related data items of different data types. Example: struct lib_books {

char title[20]; char author[15]; int pages; float price; }; the keyword struct declares a structure to holds the details of four fields namely title, author pages and price. These are members of the structures. Each member may belong to different or same data type. The tag name can be used to define objects that have the tag names structure. The structure we just declared is not a variable by itself but a template for the structure. We can declare structure variables using the tag name any where in the program. For example the statement, struct lib_books book1,book2,book3; declares book1,book2,book3 as variables of type struct lib_books each declaration has four elements of the structure lib_books. The complete structure declaration might look like this struct lib_books { char title[20]; char author[15]; int pages; float price; }; struct lib_books, book1, book2, book3; structures do not occupy any memory until it is associated with the structure variable such as book1. the template is terminated with a semicolon. While the entire declaration is considered as a statement, each member is declared independently for its name and type in a separate statement inside the template. The tag name such as lib_books can be used to declare structure variables of its data type later in the program. We can also combine both template declaration and variables declaration in one statement, the declaration struct lib_books { char title[20]; char author[15]; int pages; float price; } book1,book2,book3;

is valid. The use of tag name is optional for example struct { } book1, book2, book3 declares book1,book2,book3 as structure variables representing 3 books but does not include a tag name for use in the declaration. A structure is usually defines before main along with macro definitions. In such cases the structure assumes global status and all the functions can access the structure. Giving values to members: As mentioned earlier the members themselves are not variables they should be linked to structure variables in order to make them meaningful members. The link between a member and a variable is established using the member operator . Which is known as dot operator or period operator. For example: Book1.price Is the variable representing the price of book1 and can be treated like any other ordinary variable. We can use scanf statement to assign values like scanf(%s,book1.file); scanf(%d,& book1.pages); Or we can assign variables to the members of book1 strcpy(book1.title,basic); strcpy(book1.author,Balagurusamy); book1.pages=250; book1.price=28.50; ------------- Example program for using a structure-------#include< stdio.h > void main() { int id_no; char name[20]; char address[20]; char combination[3]; int age; }newstudent;

printf(Enter the student information); printf(Now Enter the student id_no); scanf(%d,&newstudent.id_no); printf(Enter the name of the student); scanf(%s,&new student.name); printf(Enter the address of the student); scanf(%s,&new student.address); printf(Enter the cmbination of the student); scanf(%d,&new student.combination); printf(Enter the age of the student); scanf(%d,&new student.age); printf(Student information\n); printf(student id_number=%d\n,newstudent.id_no); printf(student name=%s\n,newstudent.name); printf(student Address=%s\n,newstudent.address); printf(students combination=%s\n,newstudent.combination); printf(Age of student=%d\n,newstudent.age); }

/* initializing stricture with different types accept values and print them */ #include<stdio.h> main() { struct record { char name[20]; char city[15]; char phone[8]; char mstatus; int age; }; struct record rec1; static struct record rec2={"Sachin","Bombay","3445433",'Y',23}; printf ("Enter record1 details\n"); printf("Name :");scanf("%s",rec1.name); printf("City :");scanf("%s",rec1.city); printf("Phone :");scanf("%s",rec1.phone); fflush(stdin); getchar();

printf("Married :");scanf("%c",&rec1.mstatus); printf("Age :");scanf("%d",&rec1.age); clrscr(); printf("Record 1 details is as below :\n"); printf("Name :%s\n",rec1.name); printf("City :%s\n",rec1.city); printf("Phone :%s\n",rec1.phone); printf("Married :%c\n",rec1.mstatus); printf("Age :%d\n",rec1.age); printf("Record 2 details is as below :\n"); printf("Name :%s\n",rec2.name); printf("City :%s\n",rec2.city); printf("Phone :%s\n",rec2.phone); printf("Married :%c\n",rec2.mstatus); printf("Age :%d\n",rec2.age); fflush(stdin); getch(); }

Arrays of structure:
It is possible to define a array of structures for example if we are maintaining information of all the students in the college and if 100 students are studying in the college. We need to use an array than single variables. We can define an array of structures as shown in the following example: structure information { int id_no; char name[20]; char address[20]; char combination[3]; int age; } student[100]; An array of structures can be assigned initial values just as any other array can. Remember that each element is a structure that must be assigned corresponding initial values as illustrated below. #include< stdio.h > { struct info { int id_no;

char name[20]; char address[20]; char combination[3]; int age; } struct info std[100]; int I,n; printf(Enter the number of students); scanf(%d,&n); printf( Enter Id_no,name address combination age\m); for(I=0;I < n;I++) scanf(%d%s%s%s %d,&std[I].id_no,std[I].name,std[I].address,std[I].combina tion,&std[I].age); printf(\n Student information); for (I=0;I< n;I++) printf(%d%s%s%s%d\n, ,std[I].id_no,std[I].name,std[I].address,std[I].combinatio n,std[I].age); }

Union:
Unions like structure contain members whose individual data types may differ from one another. However the members that compose a union all share the same storage area within the computers memory where as each member within a structure is assigned its own unique storage area. Thus unions are used to observe memory. They are useful for application involving multiple members. Where values need not be assigned to all the members at any one time. Like structures union can be declared using the keyword union as follows: union item { int m; float p; char c; } code; this declares a variable code of type union item. The union contains three members each with a different data type. However we can use only one of them at a time. This is because if only one location is allocated for union variable irrespective of size. The compiler allocates a piece of storage that is large enough to access a union member we can use the same syntax that we use to access structure members. That is

code.m code.p code.c are all valid member variables. During accessing we should make sure that we are accessing the member whose value is currently stored. For example a statement such as code.m=456; code.p=456.78; printf(%d,code.m); Would prodece erroneous result.

Pointer #include<stdio.h> main() { int *p,i; p=&i; *p=10; clrscr(); printf("%d\n",*p); printf("%d\n",(*p)++); printf("%d\n",*p); printf("%d\n",++(*p)); printf("%d\n",*p); printf("%d\n",*p); } =====& and * mean in to the pointer=============== #include<stdio.h> main() { int var1=1000;

int *var2,temp; var2=&var1; temp=*var2; printf("%d",temp); } ====================find output============================== #include<stdio.h> void main() { int a=10; int *b=&a; printf("%d",a); //value of a

printf("\n %d",b); //address of a hold by b will print printf("\n %d",*b); //value of the a that is refer by b pointer printf("\n %u",&a); //print address of the a printf("\n %u",&b); // print address of pointer b printf("\n\n %d",*(&a)); // it will print 10 printf("\n %d",**(&b)); // it will print also 10 } ====================pointer with arrary====================== #include<stdio.h> void main() { int a[10],i; int *p; p=&a[0];

for(i=0;i<10;i++) { printf("\nEnter the number==>"); scanf("%d",&a[i]); } for(i=0;i<10;i++) printf("\n%d",*p++); } ==================call by references========================= #include<stdio.h> void swap(int *,int *); void main() { int a,b; int *p1,*p2; p1=&a; p2=&b; a=10; b=20; printf(\nFrom main); printf(a=%d b=%d,a,b); swap(p1,p2); printf(\nFrom main); printf(a=%d b=%d,a,b); printf("a = %d",a); printf("\nb = %d",b); } void swap(int *p1,int *p2) { int temp; temp=*p1; *p1=*p2; *p2=temp; } ==========================================================

#include<stdio.h> /* sort array using pointer*/ void sort(int*); void main() { int a[10],i; for(i=0;i<10;i++) { printf("Enter no==>"); scanf("%d",&a[i]); } sort(a); for(i=0;i<10;i++) { printf("%d==>",a[i]); } } void sort(int *arr) { int i,j,temp; for(i=0;i<10;i++) { for(j=0;j<10;j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } } #include<stdio.h> void main()

{ char *st; printf("enter string==>"); gets(st); printf("%s",st); }

Pointer pass to the structure and complete the operation #include <stdio.h> #include <string.h> struct tag { /* the structure type */ char lname[20]; /* last name */ char fname[20]; /* first name */ int age; /* age */ float rate; /* e.g. 12.75 per hour */ }; struct tag my_struct; void show_name(struct tag *p); int main(void) { struct tag *st_ptr; /* a pointer to a structure */ st_ptr = &my_struct; /* point the pointer to my_struct */ strcpy(my_struct.lname,"Jensen"); strcpy(my_struct.fname,"Ted"); printf("\n%s ",my_struct.fname); /* define the structure */

printf("%s\n",my_struct.lname); my_struct.age = 63; show_name(st_ptr); /* pass the pointer */ } void show_name(struct tag *p) { printf("\n%s ", p->fname); /* p points to a structure */ printf("%s ", p->lname); printf("%d\n", p->age); }

Using pointer create dynamic array and perform binary search in array #include<stdio.h> #include<alloc.h> void binary(int *); void main() { int *p,i; p=new int[10]; for(i=0;i<10;i++) { printf("Enter no==>"); scanf("%d",&p[i]); } printf("\n The original array is==>"); for(i=0;i<10;i++) { printf("%d=>",p[i]); }

binary(p); } void binary(int *a) { int low,upp,mid,no; printf("Enter no to search==>"); scanf("%d",&no); low=0; upp=9; for(mid=low+upp/2;low<upp;mid=low+upp/2) { if(a[mid]>no) { upp=mid-1; } else if(a[mid]<no) { low=mid+1; } else if(a[mid]==no) { printf("The number you want to find is at %d position",mid); break; return; } } } Using pointer copy string one into other

#include<stdio.h> void strcp(char*,char*); void main() { char str1[20],str2[20];

printf("Enter string"); gets(str1); printf("Enter string"); gets(str2); printf("The original string is==>"); puts(str1); printf("\n"); puts(str2); strcp(str1,str2); printf("The copy string is ==>"); puts(str1); printf("\n"); puts(str2); } void strcp(char *str1,char *str2) { while(*str1!=NULL) { *str2++=*str1++; } *str2=NULL; } Using pointer accept string and find out particular character #include<stdio.h> #include<conio.h> int count(char*,char); void main() { //char str1[20]; char ch;

int k; char *str1=new char[20]; printf("Enter string"); gets(str1); printf("Enter char"); scanf("%c",&ch); k=count(str1,ch); printf("%d",k); } int count(char *str1,char ch) { int c=0; while(*str1!=NULL) { if(*str1==ch) { c++; } *str1++; } if(c!=0) { return (c); } else { printf("character search by user is not exist"); return NULL; } } String concatenate using pointer #include<stdio.h> void strcat1(char*,char*); void main()

{ char *str1,*str2; str1=new char; str2=new char; printf("Enter string"); gets(str1); printf("Enter string"); gets(str2); printf("The original string is==>"); puts(str1); printf("\n"); puts(str2); strcat1(str1,str2); printf("The string is ==>"); puts(str1); } void strcat1(char *str1,char *str2) { while(*str1!=NULL) { *str1++; } while(*str2!=NULL) { *str1++=*str2++; } *str1=NULL; } string upper using pointer #include<stdio.h>

void strup(char*); void main() { char *str1; str1=new char; printf("Enter string"); gets(str1); printf("The original string is==>"); puts(str1); strup(str1); printf("The string is ==>"); puts(str1); } void strup(char *str1) { while(*str1!=NULL) { *str1-=32; *str1++; } } String lower using pointer #include<stdio.h> void strlw(char*); void main() { char *str1; str1=new char[20]; printf("Enter string"); gets(str1); printf("The original string is==>"); puts(str1);

strlw(str1); printf("The string is ==>"); puts(str1); } void strlw(char *str1) { while(*str1!=NULL) { *str1+=32; *str1++; } *str1=NULL; }

Making File pointer #include<stdio.h> void main()

{ FILE *fp; fp=fopen("test1","w"); }

Read Character form exist file and print it on console using fgetc

int fgetc(FILE *fp)


#include<stdio.h> #include<stdlib.h> void main() { FILE *fp; char ch;

/* prototype of fgetc */

if((fp=fopen("z:\\Hiren.txt","r"))==NULL) { printf("File can not open\n\n"); exit(0); } do { ch=fgetc(fp); printf("%c",ch); }while(ch!=EOF); /* OR You can write while loop as given bellow while((ch=getc(fp))!=EOF) { printf("%c",ch);

} */ fclose(fp); }

Make one File and write the line into file according to user input

int fputc(char ch,FILE *fp)


#include<stdio.h> #include<stdlib.h> #include<conio.h> void main() { FILE *fp; char ch=' '; fp=fopen("z:\\Hiren.txt","w"); if(fp==NULL) { printf("File can not open\n\n"); exit(0); } clrscr();

/* prototype of fgetc */

printf("Enter character (@ terminates)\n"); ch=getche(); while(ch!='@') { fputc(ch,fp); ch=getche(); } fclose(fp);

Take one line form one file and copy to another file using fgets() and fputs() Function

#include<stdio.h> #include<conio.h> #include<process.h> #include<string.h> void main() { FILE *fp1,*fp2; char sfile[13],tfile[13],line[80]; clrscr(); printf("Enter source File Name==>"); gets(sfile); printf("Enter Target File Name==>"); gets(tfile); if((fp1=fopen(sfile,"r"))==NULL) { printf("%s File not found",sfile); exit(0); } if((fp2=fopen(tfile,"w"))==NULL) {

printf("File is not created"); exit(0); } while(!feof(fp1)) { fgets(line,80,fp1); printf("%s",line); if(strcmp(line,"NULL")!=0) { fputs(line,fp2); } else { break; } strcpy(line," "); } fcloseall(); printf("\nThe operation is sucessfully completed"); }

#include<stdio.h> #include<conio.h> void main() { int account,i=1,a; char name[30];

double bal; FILE *fp; if((fp=fopen("kkk.dat","w"))==NULL) { printf("File not present"); getch(); } else { printf("How many record you want to enter==>"); scanf("%d",&a); while(i<=a) { fscanf(stdin,"%d%s%lf",&account,name,&bal); fprintf(fp,"%d%d%lf",account,name,bal); i++; } } fclose(fp); } #include<stdio.h> #include<conio.h> void main() { int account; char name[30]; double bal; FILE *fp; if((fp=fopen("abc.dat","r"))==NULL) { printf("File not present");

getch(); } else { do { fscanf(fp,"%d%s%lf",&account,name,&bal); if(bal==0) fprintf(stdout,"\n%d%s%lf",account,name,bal); }while(!feof(fp)); } } #include<stdio.h> void main() { FILE *f1; int number,i; printf("Contents of the data file\n\n"); f1=fopen("c:\\data.dat","w"); for(i=1;i<30;i++) { scanf("%d",&number); if(number==-1) break; putw(number,f1); } fclose(f1); f1=fopen("c:\\data.dat","r"); while((number=getw(f1))!=EOF)/* Read from data file*/ { printf("%d\n",number); }

fclose(f1); } #include< stdio.h > main() { FILE *fp; int num,qty,I; float price,value; char item[10],filename[10]; printf(Input filename); scanf(%s,filename); fp=fopen(filename,w); printf(Input inventory data\n\n0; printf(Item namem number price quantity\n); for I=1;I< =3;I++) { fscanf(stdin,%s%d%f%d,item,&number,&price,&quality); fprintf(fp,%s%d%f%d,itemnumber,price,quality); } fclose (fp); fprintf(stdout,\n\n); fp=fopen(filename,r); printf(Item name number price quantity value); for(I=1;I< =3;I++) { fscanf(fp,%s%d%f%d,item,&number,&prince,&quality); value=price*quantity); fprintf(stdout,%s%d%f%d%d\n,item,number,price,quantity,value); } fclose(fp); } /*Rewrite the program which copies files, ie, accept the source and destination filenames from the command line. Include a check on the number of arguments passed.*/ #include <stdio.h> void main( int argc, char *argv[]) {

FILE *in_file, *out_file; int c; printf("%s",argv[1]); printf("\n%s",argv[2]); if( argc != 3 ) { printf("Incorrect, format is FCOPY source dest\n"); return; } in_file = fopen( argv[1], "r"); if( in_file == NULL ) printf("Cannot open %s for reading\n", argv[1]); else { out_file = fopen( argv[2], "w"); if ( out_file == NULL ) printf("Cannot open %s for writing\n", argv[2]); else { printf("File copy program, copying %s to %s\n", argv[1], argv[2]); while ( (c=getc( in_file) ) != EOF ) putc( c, out_file ); printf("File has been copied.\n"); fclose( out_file); } fclose( in_file); } } write program for fread and fwrite function using C #include<stdio.h> void main() { struct stud { char name[30]; int age;

int rn; }s[2],st; int i; FILE *fp; fp=fopen("abc","w"); if(fp==NULL) { printf("Error while creating file"); return; } else { for(i=0;i<2;i++) scanf("%s%d%d",s[i].name,&s[i].age,&s[i].rn); fwrite(s,sizeof(struct stud),2,fp); } fclose(fp); fp=fopen("abc","r"); if(fp==NULL) { printf("The file does not exist"); return; } else { i=0; while(i<2) { fread(&st,sizeof(struct stud),1,fp); printf("\n%s%d%d",st.name,st.age,st.rn); i++; } } fclose(fp); } FSEEK FUNCTION

#include <stdio.h> int main () { FILE * pFile; pFile = fopen ( "myfile.txt" , "w" ); fputs ( "This is an apple." , pFile ); fseek ( pFile , 9 , SEEK_SET ); fputs ( " sam" , pFile ); fclose ( pFile ); return 0; } #include<stdio.h> #include<conio.h> void main() { struct stud { char name[30]; int age; int rn; }st; int r; FILE *fp; int found=0; int l; fp=fopen("abc","r"); if(fp==NULL) { printf("Error while creating file"); return; } else { printf("Enter age==>"); scanf("%d",&r); while(!feof(fp)&& !found) { fread(&st,sizeof(struct stud),1,fp); if(st.age==r) { found=1; fseek(fp,sizeof(stud),SEEK_CUR); l=ftell(fp); printf("%d",l); getch(); printf("Enter new name"); scanf("%s",st.name); fwrite(st.name,sizeof(stud),1,fp);

} if(found==0) { printf("Record is not present"); return; } } fclose(fp);

} }

Potrebbero piacerti anche