0% found this document useful (0 votes)
263 views143 pages

CPU Part 2

nil

Uploaded by

Tejas Shastri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
263 views143 pages

CPU Part 2

nil

Uploaded by

Tejas Shastri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 143
Solution of quadratic equation using pointer #include #include void main() { float a,b,c, root1,root2; void solve (float, float, float, float*, float*); printf("Enter a,b andc :"); scanf ("£8£%£", ga, &b, &c) ; solve(a,b,c, &root1, &root2) ; print? ("Alpha=#f\tBeta=$f\n" , root, root2) ; + petncdud ) . : fEevoid ma; void solve(float aa, float bb, float cc, float *ri, float #r2) he t : float delta; ‘dnt delta=bb*bb-4*aatcc; _ Beh *rls(-bb+sart (delta) ) /(2#aa) ; weet *r2=(-bb-sqrt (delta }/(2*aa) pray for Pointer and 1-p array #include void main () { » p=65516,. 4 2 int arr[5]=(4, 2,843 p+0=65516 [Be ~~ — ; int tod p+1=65518 |B Pointer | p+2=65520 {7p #include +3=65522 ],4g Void mair p+4=65524 |: tint * (pel i *(pe2)e8 | ints * (p43) <3 ‘peary * (pra)ea ‘print for (3 for (i wn Reading and printing array elements using pointer #include void main() { int *p,i; printf ("Enter 5 elements below\n") ; for(i=0; i<5; ++i) {scanf ("$a",p+i) ;} NICE, V.V.Nagar - Ph. (02692)238534 print£("You Have Entered\n") ; for(iz0; i<5; ++i) Enter 5 elements below 145 0 -45 345 65 you Have Entered * 45 0-45 { printé ("d\n") *(pri))i pointer and character string #include #include void main () { char *s; int i; . > print é (*s=tu\n",s) 7 2 | . s="NICE Computer"; print£(“s=tu\n", 5); for(i=0; i main() C struct a (char ch[7]; {struct a {char *str; struct a *ptr; di static struct a arr[]= iB { {"Niranjan*,arr+2},{"Parveen",arr), ("Ashish",arr+1) ye struct a *p[3]; . int i; for (i=0; i<=2; ++i)pli]=arr[i].ptr; : print£("\nts",p[0]=>str) ; printf ("\nts", (*p)->str) ; printf("\n%s", (**p)); } ICE, V.V.Nagar - Ph, (02692)238534 Module 2.11 : File Management Writing a string (character by character) into a fils #include Hnclude void main() mt Enter a string : Hello How Are You (Contents of file CHAR. TXT would be . Hello How Are You) - FILE *fp; int i; char str[80]; printf£("Enter a string : scanf("%[*\n]", str) ; fp=fopen ("CHAR. TXT", "w") ; for (i=0; i #include _ #include void main() { FILE *fp; +» char ch; fp=fopen ( "CHAR. while ( (ch= Hgete( Ef raw i) ([owette oe “Bednto a £411 ‘J. From the £: ', Separate even and odd numbers and. store them into files -UXT and ODD. TXT respectively. Display contents fall the three files. es #include 10 « Enter 10 numbers 12345678910 Contents of File ALL. TXT. 12345678910 Contents of File EVEN. TXT 246810 , Contents of File ODD.5XxT. while ( (num=getw(#£1)) !=EOP) print£ ("d\¢i"? niin) ; fclose(f£1); printf£("\nContents of File EVEN. £2=fopen("EVEN. TXT", "r") ; while ( (num=getw (£2) ) != Eclose (£2) ; f print£(*"\nContents of Fi £3=fopen(*ODD.TXT", "x" while ( (rumegetw(t3)) Eclose(£3) ; Read n nunber from keyboa: all the contents of UNSOR Display Cor tinal #inclh oni void main ( dint n,i;data,arr [10]; FILE *£1, *£23 printf ("How scanf ("$d", ni) ; printf ("Enter %d numbers\n") ; £2=fopen ("UNSORT. TXT", "w") ; for(i=0; icn; ++4) numbers ? "); { scanf("%d",&arr (iJ); putw(arr(i},£1); } fclose (£1); £1=fopen ("UNSORT. TAI", "x") 7 i=0; NICE, V.V.Nagar - Ph. (02692)238534 sand store into SORT.TxT. les. How many.-: Enter 4 numbers 12-40 156° Sorted Numbers From File -40 12 156 fol ££ for while( (data=getw(£1)) !=EOF) {arr [i++]=data;} felose(£1) ; nei; . for (i=0; iarr[j]) ae {temp=arr [i] ;arr[i]=arr[j]:arr[j]=temp;}" ) me ‘ } . : £2=fopen ("SORT.TXT", "w") 7 : a for (i=0; icnum; ++i)putw(arr [i] £2); tne Eclose (£2) ; print£ ("Sorted Numbers From File\n"); 2. ges £2=fopen("SORT.TXE","x") ; ae Me gn" ta)ig void main () { . FILE *f£; - int total, i,rol} float epi; — | char name[29] printe£ ( Rollno : 11 Name s Shasbikant CPr's 7,800000 Rodino 172 Names Ashok CPL’; 6.900000 ollno : 33 Mana + Uanati CPT + 9.300000 print£ ("CPI %a scant ("8£", &cpi) vet fprintf (£,"%4d%20s%5.2£" ,vollno, name,.cpi) 7's : scloge(#); a f=fopen ("student .txt","r"); * for(i=0; ictotal; ++i) + {Escanf (£,"$4d820s%5.2£", &rol1no, name, &cpi) ; printf£(*Rollno : $d\tName : %s\tCPI : #f\n",rolIno,name,cpi) ; } ek fclose(f) ; os } — woe, oh 135 NICE, V.V.Nagar - Ph. (02692)238534 Random Access To File 4 Assume that CHAR.TXT file already exists and it contains a lin "Hello How Are You". #include void main() ( FILE *fp; int n; char ch; fp=fopen("CHAR.TXT", "r"); n=ftell (fp); printf£("%d\n",n); ch=getc(fp); printf("%c\n",ch); chegetc(fp); print£("tc\n",ch); BOQpo Temes fseek(£p, 7,0); prin neftell (fp); printé("$A\n",n) ; felo ch=gete (fp); printf ("%c\n",ch) ; a fseek(fp,-5,2)7 os n=ftell (fp); print£("%d\n",n eS UBB Two file ch=getc(fp); printf ("%c\n" ,¢h: ;, Generate rewind (fp) ; 4 UB two file: ‘n=ftell (fp); print£(*%d\ : 4 fi #include ch=getc(fp) ; print£ ("sq i * MB void mais { ToT 77 aT TTT int Command Line Argument bint File Name : CM.CPPS , Bs \Material\C\File>cml hello | # FILE #include void main(int argc, char*argv{]) {FILE *fp; _char ch; fp=fopen{argv[1],"r"); while ((ch=getc(fp)) !=EOF) . ) frinté("8e", ch) 3) ICE, V.V.Nagar - Ph. (02692)238534 B.command Line Argument . : ‘File Name : MYCOPY.CPP ‘ Usage : mycopy source destination ay Hnclude } void main(int argc, char*argv(]) : { FILS *£pl, *£p2; char ch; fpl=fopen(argv(1],"r") i~ £p2=£open (argv[2], "w") + while((ch=getc(fp1) ) !=EOF) : {pute (ch, fp2); . eo } SE printf ("My Message : 1 File Copied"); Ly fclose(fpl); : fclose(fp2); Datal and Data2 contad, re i z mee. Ee e ‘List of these “two files. #include void main() { int a[100],b[100 FILE *fpl, *£p2) *£} cere a re m=getw (£p2 isles yates) fclose (fp2)7) /* Merging 4 ; iem; ++i) cLil=alil; for(i=0; iel3]) {temp=c [i]; elil=cl3]+ : gisi-temp; . : NICE, V.V.Nagar - Ph. (02692)238534 137, /* Writing back into the third filet/ £p3=fopen ("DATA3", "w"); : for(i=0; i void main(int argc, char *argv[]) a { FILE *fp; char ch; int line=0,totalchar=0; fp=fopen(argv(1],"r"); while ((ch=getc(fp)) !=EOF) { Pe if(chs='\n')liner+; °°) else totalchar++; printf ("Total number of: print£ ("Total ni Passing standard is 40 marks in each subject. #include [output \ - #define total 500 Self struct student { char name [20]; int m1,m2; he void main() . { L FILE *in, *out; int i; student s (500); NICE, V.V.Nagar - Ph, (02692)208534 char result [20]; in=fopen("input", "x"); out=fopen("output", "w"); for(i=0; i=40 && s[i] .m2>=20)strepy (result, "PASS" ao else strepy(result, “FAIL") ; fprint£ (out, "%20s%3dt3d%3dt4a\n", . s[i].name,s[i].m1,s[i] .m2,s[i] .ml+s[i] .m2, result); } fclose(in); fclose(out) ; 7. A file DATA is having 500 integer numb , DATA file and creates two more fil contain all the numbers arrange respectively. Program should also display tl #include #define total 500 void main() {FILE *dt, *as, *ds;* int num[total], £4 dt=fopen ( DATA» } for (is0; ictotal; ++i)putw(num[i),as) + for (istotal-1; i>=0; --i)putw(num[i] ,ds) ; fclose (dt) ; fclose (as) ; fclose (ds); printf ("Descending Printing\n") ; ds=fopen("DES", "r") ; aa while ((temp=getw(ds))!=EOF)printé("td\n",temp); >" fclose (ds) ; ~ ‘ “) NICE, V.V.Nagar - Ph, (02692)238534 Module 2.12 Dynamic Memory Allocation & Preprocessor Dynamic Memory Allocation To understand DMA, let us first understand static memory alloca- tion. Array is an example of static memory allocation. Fox example, if we write int num[100], compiler will allocate total 200 (100 x 2)] bytes for the array. Now if our program uses all 100:elements (200; Bytes) the memory utilization is considered as 100% (No ‘memory wast~' age). But if we use less than 100 elements than other memory. “Loca=! tions will be wastage, Here the problem is, we do not know in advance, i.e. before running the program, that how much memory we will be. needing. So we have to give some maximum figure (here 100). But if we could allocate memory as and when required, i.e. at run time, not before running the program, we can Yeduce or eliminate the wastage memory problem. The process of allocating memory at run-time’ is known as dynamic memory allocation. There are four “memory manage-. ment functions” that can be used to allgcat ‘and’ frée a memory during program execution. ted size of bytes and returns a . pointer to the first byte to the allocated block. ‘The mali size weatttumns a pointer to type void. This means we can j Pek assign it to any type of pointer. Example: int *x; “x= (int*), malloc (100 * sizeof (int)); re Above statement, reserves a block of 200 bytes (100. x 2) and: address of of the first byte is assigned to x which is pointer to integer type quantity. ealloc: Allocating multiple blocks of memory. While malloc function reserves single block of menory of ; specified size, calloc allocates multiple blocks of storage, each of; NICE, V.V.Nagar - Ph. (02692)238534 same size, and then sets all bytes to zero. . ptr = (cast-type*) calloc(n,byte-size) free: Releasing the used space . With the dynamic run-time allocation, it is our résponsibility to release the space when it is not required. The release of storage space becomes important when the storage is limited..The syntax of free function is : free (ptr); where ptr is a pointer to a memory block which has already been created by malléc and calloc. . realloc: Altering the size of a block If we want to change the size of already allocated blot. this function is used. The format is ptr = realloc(ptr,new-size) Concepts of Linked List: . A list is a set of items organized s entially. an warray is an ‘example of list. In array we use index fOr. manipulating individual elements. one problem in: ave.to define the initial size of the array i roblem is we cannot increase or reduce the: sf é é in-time. A completely different -we nie ae E item is a list part of struct structure containing next i: called linked list because it 4: from one item to next. Structure 1 Structure 4 Next jee > Each structure? ode and consists of two fields, one containing:the item and other containing the address of the next ” item. Adinked 1. erefore a collection of structures ordexed not by ther e physical Pl cement in memory (like an’ array) but by logical links. that are’stored as part of data in the structuré. itself. Example of Linked*List . |. finclude struct node { ot int item; . ane node *link; Ve void main() - . Item NICE, V.V.Nagar - Ph. (02692)238534 ° ae) node *first, *temp, *prev; temp= (node*)malloc (sizeof (node) ) ; tenp->item=10; : . temp= (node*) malloc (sizeof (node) ) ; temp->item=20; prev->link=temp; Prev=temp; temp= (node*) malloc (sizeof (node) ) ; temp->item=30; prev->link=temp; temp->1ink=NULL; temp=first; while (temp! =NULL) { printf (“%d\n",temp->item) ; temp=temp->link; } } oureur 10 20 30 Types of Linked List (a) Linear List tem NICE, V.V.Nagar - Ph, (02692)238534 Application of Linked List: pete Linked list concepts are useful to model many different abstract data types such as queues, stacks and trees. Bs at other end. This obeys the discipline of “First In First Out” ~ FIFO. Example: Row for ticket at cinema. = Stack is a list where insertion and deletion is made al only. This obeys the discipline of “Last In First “out* “"LIFO, Sxample: A Pile of Books. Normally, insertion in stack is known as PUSH and deletion from stack is known as POP, Lt : ree is a two-dimensional linked list. Trees “dre ‘frequently encountered in everyday life. Example: The organization chart of a large company. . Fock ba Preprocessor : . The preprocessor, as its name implie: esses the source code before it passed Operates under the control of what is line or prepreocessor directives:,,The placed in a program before the si passes through the compiler, sii ‘any preprocessor directives {Tf per the directives) are take over to the compiler. 2 ve £15 program that’proe- hréugh the ‘compiler. It prOcessor command cessor directives are ‘ore the source code reprocesso for Preprocessor 2) Source Program after proces . sing Proprocessor directives define #include #endift Queue is a list where insertion is made at one-end and deletion’ ‘The preprocessor directives can be divided into three categories 1, Macro Substitution directives. ©” a. Simple Macro Subtitution b. Macros with argument c. Nesting of macros 2. File Inclusion directives. 3. Compiler control directives. 1, Macro Substitution directives. ore Macro substitution is a process where an identifier ina aprogram iis replaced by a predefined string composed of one or-more: tokens: a. Simple Macro Subtitution ‘ Examples are: #defineCOUNT 100 #define TRUE 1 #define PI 3.1415 #define CAPITAL “DELHI” In above macro definitions, their equivalent contants val If we have macro definition #deifne D 45-22 and #defin A would result irito 45 -22, But if we write the macy #deifine D (45-22) and < defined name ocgirs. include 7 oureor: x is gr ’b. Macros with argument , Refer following program to understand macros with arguments. ae #include #define CUBEL (x) (x#x*x)- #define CUBE2 (x) ( (x) * (x) * (x)) #define MAX(a,b) ( ((a)>(b)) ? (a) : (b) ) #define MIN(a,b) ( ((a)<(b)) ? (a) + (b) ) ‘void main() {int a=5,b=10; print£(*Sa\tea\t", CUBE1 (a) , CUBE2 (a) My i printé (“%a\t%d\t" , CUBE1 (a+b) ; CUBE2 (a+b) ) + printé (“%d\t%d" ,MAX (a,b) ,MIN(a,b))7 NICE, V.V.Nagar - Ph, (02692)238534 } - of oureuT soeeM testy os! 125 125 115 337510 5 avidoet it sual ¢. Nesting of macros is.ai Baipsxalh ort bos avn #include #define SQUARE (x)..( (x) * (x) ) 2 #define CUBE(x) : (SQUARE(x) * (Gx) ) Lay ado #define SIXTH(x) (CUBE (x) *CUBE (x)) #tdefine MAX(a,b) ( ((a)>(b)) ? (a) #define MIN(a,b) ( (a)s{>)) ? (a) pat vo void main() dt sil’! gow Jor (b) ) (bibs ovispexid 10 ib yorxe# sat s+ {int a=2, b=! 10,c=8; , s printf (*\n8d\ted\t%d" , SQUARE (a) , CUBE (a)»SIXTH(a})idzoso print (*\tmax=d\ tmin=%d” , MAX (MAX (a, b)',¢), MIN (MIN(a,,b) ene } OUTPUT hip 4 8 64 max=10 mi . 4. wile mclusion directives. | / Sneed not rewrite! \ thespreprio deniers i “The difference Petyeen £4 ©) of First, declaration; be se “the specified: file 3 er di: the in the standard sdirectoryii {e.g._.Cz\EC\ING only. in the stat | cont: _ main() (#define combine (x,y) x##y o int total=10,sales=20, totalsales=1000; printf (%d", combine (total, sales) ) ; NICE, V.V.Nagar - Ph. (02692)238534 | NICE, VV. Nagar - Ph. (02692)238534 Module 3.1 - Decision Making and Branching 4. Write a program to determine whether a number Is ‘odd’ or 'even' and print ti message NUMBER |S EVEN or NUMBER IS ODD (a) without using else ojstio) Y and (b) with using else option. 5 /* (a) Without Using else option */ #include main () { int nun; printf("Enter your number : "); scant ("$d", &num) ; Lf (num2==0)print£ ("NUMBER IS EVEN") ; if (num&21=0)print£ ("NUMBER IS ODD") ; } /*(b) With Using else option */ #include main() { int num; printé ("Enter your number : "). scanf("$d", enum) ; " - if (num2==0) printf ("NUMBER IS EVEN") ; * else printf ("NUMBER IS QDD' ‘ } is 2... Write a program to. if (auinc=200) goto again; printf ("SUM=%d", sum) ; } c * “3 . 3. Aset of two linear equation with two unknowns x1 and x2 is given as: ax1 + bx2 =m and cx1 + dx2 =n. The set has unique solution x1=(md-bn)ad-cb) and x2=(na-me)/(ad-cb) provided the denominator ad-cbiis not equal to zero. Write a program that will read the values of constants a, b, q d, mand n and computes the value of x1 and x2. An appropriate: message st Should be printed if ad-cb=0. #include € main () : « {int a,b,c,d,m,n,x1, x2; 4 “ ( NICE, V.V.Nagar - Ph, (02692)238534 brint£ ("Enter a,b,c,d,mn =>"); +o pSeant (* 8dadSdkdedea", ga, Sb, ac, xd, &m, én) ; Spe ee if ( (a*d-c*b) ==0) (print ("Denominator becomes zero") ;) ap ise (x1 = (m*d-b*n) /(a*a-c#py ; . Fo, ¥2 = (n*a-m*c) /(a*d-c*b) ; on i printf ("X1=%d\nx2=84",x1,x2) ; nee} ) : ) aa . 4 Given alist of marks ranging from 0 to 100, write a Program to compu print the number of students: CBR a . (2) who have obtained more than 80 marks, an : (b) who have obtained more than 60 marks, ae : (c) who have obtained more than 40 marks, Na ts (d) who have obtained 40 or less marks, * (e) in the range 81 to 100, (fin the range 61 to 80, (g) in the range 41 to 60, and +. (h)inthe Tange 0 to 40, ~ 4 The program should use. minimum fumbe: f ifs: #include nain() { int total_student ,more80=0, int bet81to100=0, bet61togo. int marks; 3 printf ("Enter totalsnuttber of students” scanf ("$d" , &total_ student. again: ee : iore60++;more40++;betBitol004+;) ° *y 1 S<= 80) {more60++;mored0++; bet 61to804. : 'S540&émarks<=60) {mored0++;betalto60e+7} 0) | else(less40++;bet0t040++; } : , pefetal_student--) oe if (total student>0)goto again; of Peinté ("\nstudents who have obtained more than 80 marks ; | printf ("\nStudents who have obtained more than 60 marks. vg Brinté("\nStudents who have obtained more than 40 marks, : 84", mored| ‘printf ("\nstudents who have obtained less than 40 marks ", Less4( printf ("\nstudents in range 81 te 100 marks : $d", bet81to100) : wprint£ ("\nstudents in range 61 to 80 marks : 8d", bet61t0g9) printf ("\nstudents in range 41 to 60 marks. ; 8d", bet 41t06( ) brint£("\nStudents in range 0 to 40 marks : $d", bet0to40);., $d" ;more6| s ; 5. Admission toa Professional course is ‘subject to the following conditions:. - (a) Marks in mathematics >= 60 . {b) Marks in physics >= 50 poe va (c) Marks in chemistry >= 49 ' ay (d) Total in all three Subject >= 200 or Total in mathematics and physics >= 18 +8 1B NICE, V.V.Nagar- Ph. (02692)238534 146 tion to list the eligible candidates. #include main(). ¢ int total_student,m,p,c; printé ("How many candidates ? "); scanf ("%d", &total_student) ; again: print£("Enter marks in physics,chemestry & maths +"); scanf ("sd%d%d", &p,&C, 1m) ; fat Lf (m>=6084p>=50&6.0>=4086 (m+p+e>=200 | |m+p>=150) ) ’ - printf ("\nCandidate is eligible"); ~ i . else print£("\nCandidate is not eligible" total_student--; if (total_student>0) goto again; } 4 6. Write a program to print two dimensional squi root of any number from 0to9.9. #include #include main() { float x=0.0,y=0.0; label2: printf ("\n"); y=0.07 labell: printf ("85.2£) yey+0.1; 3 } : 7 Shown below isia Floyd's triangle - 23 we 456 zeus <.78910 . (aw Write a progra te print this triangle. (b) Modify the program to produce the following form of Floyd's walle » * > findhnae’ qain( ) ~ Ly int num=1, totall=1,total2=1; * label2: NICE, V.V.Nagar - Ph, (02692)298534 totali=1; printé("\n"); labeli: if(totali<=total2) ( printf ("%3d",num++) ; if (num>91) goto end; totall++; goto label; } total2i+; goto label2; end: i (* (b) */ #include main() dn num=1,total1=1, total2=1; label2 : totali=1; : printf ("\n"); num=total2; labell: if(totali main () { dnt mp, hp; float md, hd; Purchase Item Discount 0-100 Mill Cloth 101-200 5% 201-300 7.5% } 8 Acloth Showroom has announced the following seasonal discount on. pur- Handlopm Items 7.5% yl 10.0% 10.0% 15.0% Write a program using switch and If ‘statement to compute the net amount to be paid NICE, V.V.Nagar - Ph, (02692)238534 . . printf ("Enter mill clothes purchase : scanf ("td", &mp) ; printf ("Enter handloom clothers purchase : "); scant ("%d", &hp) ; “Vi switch (mp/100) int {case 0: Ee caso 1: s00)mi=0; h @ else ma=5.0; main () break; : case 2: if (mp==200)md=5.0; else md=7.5; int case 3: default: ) switch (hp/100) {case 0: case 1: case 2: (a) nested if statement (b) else if statements and ¢ conditionalo erator Pp 7 (a) */ re #include nu main() } { ‘printf int x,y; — printé ("Enter x: "); scant ("d" , &) ; if 000) NICE, V.V\Nagar - Ph, (02692)238534 100) })z : function 152 (iE (x= else y=1i d else y=-1; . printé ("Y=8",y); : : * ) 7* (b) */ #include main() { ! int x.y7 printf("Enter x: ")7 scanf ("%d" , &x) 7 print£("Y=%d",y)7 } i (oe) #7 #include main() ¢ int x,y; printf ("Enter x + scanf ("%a", &) 7 . It “Decision making and looping 4. Given.a number write.a program using while loop to reverse the digits of ‘For example, ‘the number 42345 should be written as 54321. long num, rev_num=07 printf ("Enter Number : "); . scanf("81d",S:um); while (nun>0) {rev_num*=10; vev_num+snum’10; num/=10; } printf ("Reverse Number : 1d", rev_num); } NICE, V.V.Nagar - Ph. (02692)238534 2. The factorial of an integer m is the product of consecutive integers from 1 t That is, Factorial m = ml = m x (m-1) x (m-2) K 2 X 1. . q Write a program to compute and prints a table of factorials for any given m| #include 4 main() { int i,m; long fact=1; print£("Enter m: "); 1 scan£ ("%a" , &m) 7 for(is2; i main() int num, sum=0; printf ("Enter any number : "); scanf ("%d" ,&num) ; while (num>0) {sum+=numt10; : num/=10; aly } 5 Ea oe print£ ("Sum of the digits is $d\n%,sum); } 4 The number in the sequence’ 123581321....are called Fibonacei numb Write a program using a do-while loop to calculate and print the first m Fibonaj numbers,“ #include .” main()) fo { es ? int n=0,m=1,temp,total; ~~ printf ("How marly numbers : "); ; scanf ("%d", &total) ; : while (total>0) {printé("%d\t";m); temp=n; n=m; memttemp; fotal="7 } 5. Write a program to evaluate the investment equation V = P(1+r)" and print the tables which would give the value of V for various combinati the follcwing values of P,r and n. P: 1000, 2000, 3000,......-, 10,1000 r:0.10, 0.11, 0.12,...-.,020 Nit, 208, veers 910 NICE, V.V.Nagar - Ph. (02692)238534 MB include gaint) ait . Pong P, V=0, temp_P; : int n; {float x; for(P=1000; P<=10000; P+=1000) » (V=05 temp_P=P; ~ for (r=0.1; r<=0.2; r+=0.01) {V=0; P=temp_P; : printf ("Amount=1d\tRate=%f\n\nYear\t\tMoney Value\n",P,r); for (n=1; n<=10; ++n) . {V=P*(1+r}; * printé ("Sd\t\t%ld\n" nV) P2V; : ) — } 6 Write a program to print the following outputs using for loops. (b) © : I rere 1 22 teen 22 333 wee Pry may #7 finclude int) int i,j, space; for(i=5; i>0; --i) { _ NICE, V.V.Nagar - Ph. (02692)238534 for (space=1; space<=(S-i); ++space) {printf£(" "))} for (j=i; j>=0; --J) {printf ("*");} printf ("\n"); ) * (ce) */ include ain() nt i,j,space; or(i=1; i<=5; ++i) include ain() nt count=0,i,age; “ int ALS or (i=0; i<100; ++i) for(ix0 | fok printé ("Enter age f¢ son #%G: ",i1); , scanf("$d" gage) ; SNe } x 50.age>60) continue. * 2 We : : rintf ("Number of desired'person = %d", count); ¢ nm Write a program to print a table of values of the function y=exp(-x) for x Vani inci from 0.0 and 16.0.. “AR nain() include : { include pint. i,t ain() int Sur int sur loat x,y,57 gepcintt nt count=1; AB scant ( rint£("\n "); WR for (i= ox(j=0; j<10; ++j)printé(*------- "G { rinté("\n"); . pr or (x=0; x<=10; x+=0.1) i 86 st { if (x==0)printf(" x") else if (x<=0.9] | (count-1)%1 ICE, V.V.Nagar - Ph. (02692)238534 )print£("87.2£",x); else printf ("%7.2£*,exp(-x)); if(count==10) . & { printf£("\n "); . for(j=0; j<10; ++j) print £(*"------- "Ge y if(count%10==0)print£("\n") ; count++; } . printf£(" "); for(j=0; j<10; ++j)printg(*------- "e printé("\n"); } Module 3.3 - Arrays 1. Write a segment of a program that initializes the array A as follows. . 10000 See 01000 00100 00010 me 00001 . . * All diagonal elements are initialized to one an #include $ main() C int A[5][5],i,3; for(i=0; i<5; +44) ) else A(1] (j]=0; 2. Write a program for fitting a straight line through a set of points(xi,yi), i=1 .. .n. The straight line equation is y=mx+c. and the values of m and c aré given by m= (nExy, * (Zx)(Zy))MA(Ex4)-( Ex,)?) , c=t/n (Zy,-mzx) All summations are from 1 to n. #include : inl ) x varying int i,n,x[10],y{10],m,c; int sum_xy=0, Sum_xSum_y=0,Sum_x=0, Sum_y=0; int Sum_xSquare=0; printf ("How many points : "); scant ("$d",&n) ; for(i=l; ix=n; ++i) ' ( printf ("Enter (x%d,y%d) scanf ("sdtd", &x(i},&y[il); “Sum_x+=x [i] ;Sum_y+=y [i]; Laid; 156 NICE, V.V.Nagar - Ph. (02692)298534 157 oe nena paneer nen Sum_xyt=x[i]*y(i)7 Sum_xSquare+=x(i]**[i]; } : mms ( (n*Sum_xy) ~ (Sum x*Sumy) ) / ( (n*Sum_xSquare) ~ (Sum_x* Sum) ) i c= (Sum_y-m*Sum_x) /ni printf ("m=%d,c=%d",m,c) 7 } . 3. The daily maximum temperatures recorded in 10 cities during the month of - January (for all 31 days) have been tabulated, Write a program to read the table jonal array temperature, and to find the city and day elements into a two-dimensi corresponding to (a) the highest temperature and (b) the lowest ‘temperature.’ #include main() float temp[31] [10] pmax=-999.99,min=999 .99; int i,j,max_day ,max_city,min_day,min_city;; for(i=0; i<31; ++i) { 2 for (j=0; j<10; +45) 2 2 & brine? (*Day:8d City:td Temp 7 ",i+1,5 scanf ("td8d", &temp Ae “ if (temp [i] [j] >max) i£(temp(i] (j]=1&&vote<=5) count [vote=1] ++7 for(i else spoilt++; { print£ ("More Voters ? (y/n) ")i 5 choice=getche (); _#F y 2 for (is0; i<5; ++4) : NICE a ______. NICE, V.V.Nagar - Ph. (02692)238534 ith of he table and day rature. a} } city); city); d1to5 2aper. ndidate e1tod, ald also 158 { print£("\ncandidate %d gets %d votes", i+1, count [i]); } . * printf ("\nThere are $d spoint ballots",spoilt); } 6. yhe following set of numbers is popularly known as Pascal's triangle. it 121 1331 14641 Write a program to calculate the elements of the Pascal triangle for 10 rows printresults. #include pain ) int p[10](10],i,3; for (i=0;i<10; ++i) { print£("\n"); for (j=0;j<=i;++3) C 0} li==j) pli] (J]=1; else p[i] [j]=pli-1] [5-1] +pli-11 [5 Write a program to read the data and determine the following. (a) Total marks obtained by each student. (b) The highest marks in each subject and the Roll no. of the student who secured it. . (c) The student who obtained the highest total marks. #define ALL 4 #include main() int marks [ALL] (3]',i,j,student_total [ALL] ; int High Marks [3]={0,0,0),High Rolino([3] ,High_total=0,High_total_Rollr for(i=0; iHigh Marks [j]) ({High_Marks (j]=marks [i] [3];High_Rollno[j)=i+1;} if (student_total[i]>High_total) {High_total=student_total [i] ;High_total_Rollno=i+1;} orintf("\n\nTotal marks obtained by each students"); for (i=0; i ain() nt c[{total*2],a[total] nt 1,i=0,5-0,k; d if(j==5) {for(1=i; l define n 3 . main () { int a(n] {n} ,b{n] (n] ,cla] [nl ,4,5,/k; print£ ("Enter td x $d matrix A\n",n,n); for(i=0; i Module 3.4 - Handling of Character Strings 1. Write a‘program which.teads your name from the keyboard and outputs a list of ASCII codes which represents your name. mo finclude a rain() print£ ("Enter your name : "); : Ascanf ("%s" name) ; : for (i=0; name [i] !="\0';++i)printé ("te=%d\n" name [i] ,name[i]); | } 2 Write a program to do the following . : (a) To output the question "Who is the inventor of C2" oat _ «(b) To accept an answer . is ee (c) To print out "Good" and then stop, if answer is correct. (d) To output the message "try again’, if the answer Is wrong. (e) To display the correct answer when the answer is wrong even at third at- alti- - (02692)238534 Bee ~~ 161 #include * #include main() ‘BB scan { . 9B prin char name [30], true_name[30]="Dennis Ritchie"; BB scan int i : for(i=0; <3; ++4) { ~ print£(*\nWho is the inventor of ¢?"); seanf("%[*\n]",name) ; if(strcmpi (name, "Dennis Ritchie")==0) { print£("Good\n"); return 0; ) else print e( “Try Again\n"); fflush (stdin) ; } } string. Assume that mcharact #include #include main() { char str [80]; print # ("Enter:starting igcation i"); scant (*%d", &m) o3 erintt ( Characters : "); prints seanf ("Sd",én); 1£(((m+n)>strlen(str)) | |m>strlen(str) | Inostrlen (str) I Im<01 In<0) re printf("Error : Input parameter out of range 11"); _ ON return 0; inclu } in() cor(ism; i<=min; ++i)print£("%e",str[i]); tinclude tain() char str[80],word[20],extract [20]; ICE, V.V.Nagar - Ph. (02692)238534 int i, j,count=0; print£("Enter a string : "); scanf ("%[*\n}", str); printf ("Enter a word : scanf ("%s", word) ; for(i=0; i 7 : main() { char str [80], temp; int i,d;. printf ("Enter a string : scant ("%s", str); . Z for(i=0; i . main() : { L char str[80]="NICE produces fluent ¢ programmers"; . char newword[20}="C", oldword[20]="COMPUTER", extract (201; char dummy [80}="\0"; int i,j,count=0,k; for(i=0; i . } int’ x,y; Float main() fl c if void exchage (void) ; el printf ("Enter x andy: "); scanf ("$d%d", &x, 6y) + print£("\nBefore calling fun . exchage(); ° s : prince (* \nafter calling funct $d y=$d\n", x,y); } int fa oid exchage (void) / C int temp; : in temp=x; fo xEY? xe ystemp; | } } “ 4 Ww pl or ro #include |. include { float sum=0,x, £ (float, int); int fact (int); printf("Enter x : scant ("%£", &&); print# ("How many terms ? "); scanf(" ter, ani . Sumt=t (x, peinee (vane %£", sum) ; "he ee float f(float x,int m) { float temp=pow(x, 2*m-1) /fact ( if(m-=n) {return (temp) ;} else if (m821=0) return(temp - f return (temp + £{ ) int fact (int m) C int i,ans=1; for (i=2; icon? nda floating-point value to an indicated decimal ber 34.557 would yield the value 34.56 when itis rounded off! two decimal places. #include =0.5)new_num++; S return( (float) (nmew_num) / (float) (powér.(10. } . 5. Write a function prime that return: turn 0 otherwise. #include main() { int prime (int) ,num; printé ("Enter a numb scanf ("$d", &num) ; if (prime (num) =: {printf ("Number %d is. else int prime(int { int i; con for (i=2; i<(n/2); ++i) : pris (i (n8is=0) return 0; “4 scat } : : ‘ priz return 1; scar 3 . prir 6. Write a function that will scan a character string passed as an argument and. Scar convert all lower-case characters Into Upper-case equivalents, ; pra #include 8 scar #include prir #include . . ° nain() NICE, V.V.Nagar - Ph. (02692)238534 pchar str [80]; tYoid convert_upper (char s[80}); forint f ("Enter a string : "); " ae uae gcanf (*[*\n]",str); + Noah tog Wwert_upper (str) ; ~ tee forint £ ("\nts",str) ; roid convert_upper (char s[80}) or (10; icstrlen(s); +44) if (islower (s[i]))s[i]=toupper(s[i}) 7, Module 3.6 - Structures sn Unions. Define a structure that describes a hotel. It shou! , the name, address, grade, average room “Write a function to perform the following qi (a) To print out all hotels of a given grade in {b) To print out hotels with room charges | finclude struct hotel { char name [50]; char address [100] ; char grade; float avg_room_chargé int total_rooms; ; si float chargé} char g? for(i=0; it «for (j= id spor (1=0; i £15 Below specified charge are\n"); Seine : printf printé print, prints ? y @ print, cE (" \nN 1 2s ) one ntf ("\nName™ 8s", x.name) ; men’ nef ("\nAddress_ 2s", x.address) ; pats ae NE ntf("\nGrade +*. grade) ; include * lude ict cricket y Write at E, V.V.Nagar - Ph. (02692)238534 uy [struct cricket player[50], dummy; int 1,3; prints ("Player # d\n", i+1); an printf (“Name : "); seen - scanf ("%[*\n]",player [i] .p_name) ; i printf ("Team Name : "); . - scanf ("%[*\n]",player[i] .t_name) ; . printf ("Batting Average : "); grant ("8£", splayer[i] .b_avg); for (i=0; i<49; ++i) for (j=itl; 3<50; +43) if (strempi (player {i] ¢ : for(i=0; i<50; +41) : why. Module 3.7 - Pointers Bees Write a program using pointers to read in an array of integers and printits elements in reverse order. e “ fidefine N 5 : Wtinclude ain() printf ("Enter %d elements below\n",N); Gfor(i=0; i=0; ~-i)print£("$d\n",* (A+i)); Write a function to calculate roots of quadratic equation (ax? + bx'+. ¢=0). The function must use two pointer parameters, one to receive the coefficients a, b ICE, V.V.Nagar - Ph, (02692)238534 OS and ¢ and the other to send the roots to the calling function. The roots are given by following equation : X= (-b + Square root(b?- 4ac)) /2a #include #include /main() ’ { ” £loat *para, *root; . void find_root (float*, float*) ; . printf("Enter a,b,c : "); “ scanf ("£%f£%f" ,para,para+1,para+2) ; find_root (para, root) ; . print £ ("\nRoot1=%f\nRoot2=%£\n", *root,, *root+1) ; } void £ind_xoot (float *p, float *r) L float délta=(* (p+1)) *(#(p+1))~ (4* (p) * *rs(~ (*p+1) +sqrt (delta) ) /(2*(*p) ) 4, * (x41) =(- (*p4l) -sart (delta)) / (2*( #5) } 3. Write a function that receives ‘sorted array of inte and inserts the value it its Spfrect { placa. : #include #define N 5 main() { int *a,num, i; . int “insert (int*, int) ;; “ ) printf ("inter all $d elements below in ascending sorted order\n" ,N)j fyold ade for (i=0; i #define N 3 4 main’) Pint *a[3],*b[3],*c13] 4,57 Mae i Avoid add(int*[],int*(],int*{]); printf ("Enter tdxtd matrix A\n",N,N); for (i=0; i for(j=0; 3 nain() ( thar *day_name(int) ; ‘responding day. The day nai Jocal to the funtion. int arr[n 4E( (X=by . prin rint£ ("%s",day_name(4)); jelse * "pri } ‘Bint b_sez { int first a2: Ih ig (firsts aon Bete OP inidde= (£ _ Write: re gram to.read in an array of names and to sort them In alphabetical | Fit (n==* (é order. User sort function that receives pointers to the functions strcmp ans . fF {is_g swap. Sortiin-turn should call these functions via the Pointers. else if (n include 0)swap(s{i],s[3]) void-swap (char *s1, char *s2) “fven an array of sorted list of integer numbers, write a functlon.to search fora pzrticular item, using the method of binary search. And also show how this function may be used in a program. Use pointer‘and pointer arithmetic. ) include . #define N 5 | main () { int arr ([N]= {-3,2,6,100,645},x, iEisirst>tase) gota! niddle= (firet+last)/: 4£(n==* (armiddle) ) {is_got=iniddle;goto ay) “else if (n<* (at e)) : last=middl else o8 first-middle+t; goto a2; al: return is_got; Module 3.8 - File Management in ¢ 1. Write a program to copy the content of one file into other. #include pmind al FILE *fpi, *£p2; . oe vba char c; | fpi=fopen ("input .txt*,*r") ; ICE, V.V.Nagar - fp2=fopen(*output.txt","w"); * while ((c=getc (fp1)) !=BOF) (pute (c, fp2) ; } } 2. Two files DATA1 and DATA2 contain sorted list of Integers. Write a program jong produce a third file DATA which holds a single sorted, merged list of these tw lists. Use command line argument to specify file names. “AB ei arc #include se : . main(int argc, char *argv{]) ' ' { 1 PILE *£1,*£2,*£3; 1 int a[5],b(5],c[10] ,i=0,5=0,k,1; s if(arge!=4) (printf("Error : Incorrect no. of argument's\n") ;return 0 I f1=fopen(argv[1],"x"); ‘ ‘open (argv[2],"r" f £3=fopen(argv(3],"w"); E for (i=0; i<5; +44) (ali]=getw(£1) sbLi]=a s iz0; 1 for (k=0; k<10; ++k) . } { i | clos i£(ali] pa struct customer “ { char name[20] ; long t_no; a Ap 7 As: Of struct “BP char « main() { NICE, V.V.Nagar - Ph. (02692)238534 : 174 struct customer c[10]; » char ch,n[20]; F long no; } int i=0,5; PILE *£1; se fl=fopen ("custom.dat", “w") ; : printf("\nEnter data for customer # %d\n",i+1); printf ("Name ': "); scanf ("%s",c[i] name) ; print £("elephone No : "); scanf ("%1d", &c[i] .t_no) ; | fprintf£(f1,"%s %1d\n",c[i] .name,c[i].t_no); printf ("\nMore Customer ? (y/n) : "); ch=getche (); ite; }while(ch=='y'||ch=='¥") ; fclose (£1); fl=fopen("custom.dat","r"); for (j=0; j

You might also like