Академический Документы
Профессиональный Документы
Культура Документы
2) Background process in C
3) Structure of C program
Userdefined functions {
4) C Tokens:
Keywords: static, int, void Identifiers: deposit,amount Constants:20,23.4 Strings: xyz Special Symbols: (),{} Operators:+,-,*
Constants:
1) Numeric constants : Integer constants(10,-20), Real constants(5.23) 2) Character constants: single character constant(a), string constants(abc)
Data types:
a) Integer SignedType: int, short int, long int UnsignedType: unsigned int, unsigned short int, unsigned long int
Data type Char Unsigned char Short or int Unsigned int long unsigned long float double long double
size(bytes) 1 1 2 2 4 4 4 8 10
format string %c %c %i or %d %u
-2147483648 to 2147483647 %ld 0 to 4294967295 3.4 e-38 to 3.4e+38 1.7e-308 to 1.7e+308 3.4e-4932 to 1.1e+4932 %lu %f or %g %lf %lf
Variables: name given to a memory location during storage of data ie variable is a data name used for storing a data value. Rules:Variable name should not use c keywords. Variable name should not start with digit. Scope and life time of a variable: Example
1) #include<stdio.h> void main(){ double num=5.2; int var=5; printf("%d\t",sizeof(!num)); printf("%d\t",sizeof(var=15/2)); printf("%d",var); }
4. #include<stdio.h> int main(){ int _=5; int __=10; int ___; ___=_+__; printf("%i",___); return 0; }
Void main() { Printf(%d,num); } 6.#inlcude<stdio.h> Static num =5; Int num=5; Void main() { Printf(%d,num); }
1Ans: 2,2,5 2Ans: Compilation Error 3Ans: Compilation 4Ans: 15 5Ans: 5 6Ans: compilation error. Variable initialized more than once
Operators :
3) Logical Operators : &&,|| and ! 4) Increment and decrement Operator : ++ and 5) Assignment Operator : = 6) Bitwise Operators : &,|,^,>>,<< and ~ 7) Comma operator : ,
8) Conditional operator: ? :
Questions on Operators:
return 0; }
Output: 5 20 100
4. #define square(X) X*X; void main() { int i; i=64/square(4); printf( %d,i); }
void main() int x; x=3+4-7*8/5%10; printf("x=%d",x); }
5. .
{
Control Structures:
1) Branching or Decision making statements:
1. What will be output when you will execute following c code? #include<stdio.h> void main(){ int a=100; if(a>10) printf("M.S. Dhoni"); else if(a>20) printf("M.E.K Hussey"); else if(a>30) printf("A.B. de villiers"); } 2. What will be output when you will execute following c code? #include<stdio.h> void main(){ int x=-1,y=-1; if(++x=++y) printf("R.T. Ponting"); else printf("C.H. Gayle"); }
3. What will be output when you will execute following c code? #include<stdio.h> void main(){ if(sizeof(void)) printf("M. Muralilidaran"); else printf("Harbhajan Singh"); } 4. What will be output when you will execute following c code? #include<stdio.h> void main(){ int m=5,n=10,q=20; if(q/n*m) printf("William Gates"); else printf(" Warren Buffet"); printf(" Carlos Slim Helu"); } 5. What will be output when you will execute following c
code?
#include<stdio.h> void main(){ int a=5,b=10; if(++a||++b) printf("%d %d",a,b); else printf("John Terry"); }
code?
#include<stdio.h> void main(){ int check=2; switch(check){ case 1: printf("D.W.Steyn"); case 2: printf(" M.G.Johnson"); case 3: printf(" Mohammad Asif"); default: printf(" M.Muralidaran"); } } 7. What will be output when you will execute following c code? #include<stdio.h> void main(){ int movie=1; switch(movie<<2+movie){ default:printf("3 Idiots"); case 4: printf(" Ghajini"); case 5: printf(" Krrish"); case 8: printf(" Race"); } } 8. What will be output of following c code? #include<stdio.h> int main(){ int i=2,j=2; while(i+1?--i:j++) printf("%d",i); return 0; }
9. What will be output of following c code? #include<stdio.h> int main(){ int i,j; i=j=2,3; while(--i&&j++) printf("%d %d",i,j); return 0; } 10. #include<stdio.h> int main(){ static int i; for(++i;++i;++i) { printf("%d ",i); if(i==4) break; } return 0; }
1Ans:
M.S. Dhoni
2Ans: Compilation error 3Ans: Compilation error 4Ans: William Gates Carlos Slim Helu 5Ans: 6,10
6Ans: M.G.Johnson Mohammad Asif M.Muralidaran 7Ans: Race 8Ans:1 9Ans:1,3 10Ans:2,4 (with warning during compilation ) ( static variableb init to 0)
Pointers: & (reference operator), * (dereference) Arrays: 1)Single dimensional array Ex: int a[10]; 2)Two or multidimensional array Ex: int a[2][2] , int a[2][2][2]
2) main()
{ Int a=10,b=20,*x,*y,*t; x=&a; y=&b; t=x; x=y; y=t; Printf(%d %d,a,b); Printf(\n %d %d,*x,*y); }
3)main() { Int a=10,b=20,*x,*y,t; x=&a; y=&b; t=*x; *x=*y; *y=t; Printf(%d %d,a,b); Printf(\n %d %d,*x,*y); }
4) #include<stdio.h>
int main(){ int *i,*j; int x=10,y=20; i=&x; j=&y; *i=*i+*j; y=x+*j; printf("x=%d y=%d",x,y); }
5. #include<stdio.h> int main(){ int *i,*j; int x=10,y=20; i=&x; j=&y; *i=*i+*j+--*j; y=x+*j+++x; printf("x=%d y=%d",x,y); }
6. #include<stdio.h> int main(){ char *cptr,c; void *vptr,v; c=10,v=0; cptr=&c; vptr=&v; printf("%c %v",c,v);
printf("%d",++(*p));
} 8. #include<stdio.h> int main(){ char s[]=man; for(int i=0;s[i];i++) { printf("\n %c %c %c %c",s[i],*(s+i),*(i+s),i[s]); } } 9. . #include<stdio.h> int main(){ char *p; p=Hello; printf(%c \n,*&*p); }
1Ans:15
2Ans: 10 20 20 10 3Ans: 20 10 20 10
y=50 y=117
6Ans: Compilation error 7Ans: compilation error, cannot increment constant pointer 8Ans: mmmm,aaaa,nnnn 9Ans: H
10Ans: 2
Q)prg to print even and odd nos from 1 to 10 .store the display results in two separate arrays. Void main() { Int sumo=0;sume=0,i=o,odd[5],even[5],a=-1,b=-1; For(i=1;i<=10;i++) { If(i%2==0) Even[++a]=i; Else Odd[++b]=i; Printf(\n even \t \t odd); For(i=0;i<5;i++) { Printf(\n %d %d,even[i],odd[i]); Sume=sume+even[i]; Sumo=sumo+odd[i]; } Printf(% %d,sume,sumo); } }
Q)Write a program to print string in reverse order without using string reverse function. Main() { Static char s[15]; Int I; puts(enter a string); gets(s); puts(reverse string); for(i=14;i>0;i--) { Printf(%c,s[i]); } }
Main() { Static char s[15]; Char f; Int I,l=0; puts(enter a string); gets(s); puts(enter a character to find :); f=getchar(); for(i=0;i<15;i++) { If(s[i]==f) C++; } Printf(the character %c in a string %s occurs %d times,f,s,c); }
1.Main() { Int x[]={2,4,6,8,10}; Void abc(int *); abc(x); } Void abc(int *p) { Int k; For(k=0;k<=4;k++) { Printf(%d,*(p+k)); } } 2.Main() { Int a=10,b=20; Void abc(int *x,int *y); Prinft(%d %d,a,b); Abc(&a,&b); Printf(\n %d %d,a,b); } Void abc(int *m,int *n) { Int x;
3.void main() { Int a=10,b=20; Int *x,*y; *x=*x*y; *y=*x-*y; *x=*x-*y; Printf(%d %d,a,b); Printf(%d %d,*x,*y); }
2 Ans:2,4,6,8,10 2 Ans:20 10 10 20
3Ans: 20 10 20 10
String Functions:
i) In c language the group of characters ,digits, symbols enclosed within quotation marks are called as string. ii) Every string is terminated with null or \0 character. iii) Strings are nothing but character arrays. Each character of a string occupies 1 byte of memory .
String Operations:
the string functions strlen, strcpy, strcat, and strcmp, found in <string.h>. strcat(s,t) : concatenate t to end of s strncat(s,t,n) : concatenate n characters of t to end of s strcmp(s,t) : return negative, zero, or positive for s < t, s == t, s > t strncmp(s,t,n) : same as strcmp but only in first n characters strcpy(s,t) : copy t to s strncpy(s,t,n) : copy at most n characters of t to s strlen(s) : return length of s strchr(s,c) : return pointer to first c in s, or NULL if not present strstr(s1,s2) : checks for string in other string, or NULL if not present strupr(s) converts lower case characters to a string of uppercase strlwr(s) converts upper case characters to a string of lowercase strrev(s) reverses all characters of a string.
Q)Prg: to compare two strings using gets and puts and strcmp method
Main() { Char sr1[10],sr2[10]; Int diff; Printf(enter string1:); gets(sr1); printf(enter string2); gets(sr2); diff=strcmp(sr1,sr2); if(diff==0) puts(two strings are identical); else puts(two strings are Different); }
Q) prg to delete all the occurrences of vowels in a given string. Void main() { Char line1[80],line2[80];
Int I,j=0; Printf(enter text below); gets(line1); for(i=0;i<80;i++) if(line1[i]==a || line1[i]==e || line1[i]==i || line1[i]==o || line1[i]==u ) continue; else { Line2[j]=line1[i]; J++; } }
Q) prg to reverse the given string using string function. Void main() {
Q)prg to check whether entered string is palindrome or not. Main() { Char *string1; Char *string2; Printf(enter a string \n); Scanf(%s,string1); //copy original string1 to string2 String2=strdup(string1); //reverse original string String1=strrev(string1); //compare string1,string2 If(strcmp(string1,string2) Printf(\n %s is not a palindrome,string2); Else Printf(\n %s s palindrome ,string2); }
Note: i) Difference between strdup and strcpy. ii) int const *p; const int *P;
Files: i) File is a collection of numbers , symbols and text placed on the disk. ii) File can be read and modified as per the user requirement.
File Functions: 1) fopen() : creates a new file for read/write operation 2) fclose(): closes a file associated with file pointer. 3) closeall() : close all open files. 4) fgetc(): reads the character from current pointer position and advances the pointer to next character. 5) getc(): acts like fgetc() 6) fprintc() : writes all types of data values to the file 7) fscanf(): reads all types of data values from a file. 8) putc(): writes character by character to a file 9) fputc() : acts like putc().
10) gets() : reads string from the file. 11) puts(): writes string to the file. 12) putw(): writes an integer to the file 13) getw(): reads an integer to the file 14) fread(): reads structure data written by fwrite() function. 15) fwrite() : writes block of structured data to the file. 16) fseek(): gets the pointer position anywhere in the file.
17) feof() : detechs the end of file. 18) ftell() : returns the current pointer position. 19) rewind() : sets the record pointer at the beginning of the file. 20) unlink() : removes the specified file from the disk. 21) rename(): changes the name of the file.
Different modes of files: a) Text modes b) Binary modes Text modes: 1) w(write): this mode opens a new file on the disk for writing. Syn: fp=fopen(data.txt,w); 2) r(read): this modes open a pre-existing file for reading. (check for null pointer value using if function) Syn: fp= fopen(data.txt,r); 3)a(append): This mode opens a pre-existing file for appending data. 4) w+(write+read): In this mode file can be written and read. 5)a+(append+read): In this mode file can be read and appended at the end.
6) r+(read+write): we can both read and write. If the file doesnt exists ,the compiler returns null to the pointer.
B) Binary Modes:
1) wb(write): this mode opens a binary file in write mode. Ex: fp=fopen(data.dat , wb ); Here data.dat file is opened in binary mode for writing. 2)rb (read ) mode. : this mode opens binary file in read
Ex:fp=fopen(data.dat,rb);
ex5
3)ab(append): this mode opens a binary file in append mode. Ex:fp=fopen(data.dat,ab); 4)r+b(read + write):this mode in read and write mode. Ex:fp=fopen(data.dat,r+b); 5)w+b (read+write):this mode creates a new file in read and write . Ex:fp=fopen(data.dat,w+b); 6)a+b(append+read):this mode opens a file in append mode. open pre-existing file
Ex:fp=fopen(data.dat,a+b);
Q)prg Reading A File #include "/sys/stdio.h" main( ) { FILE *funny; int c; funny = fopen("TENLINES.TXT","r"); if (funny == NULL) printf("File doesnt exist\n"); else { do { c = getc(funny); /* get one character from the file */ putchar(c); /* display it on the monitor */ } while (c != EOF); /* repeat until EOF (end of file) */ } fclose(funny); }
Q)Prg Reading A Word At A Time #include "/sys/stdio.h" main( ) { FILE *fp1; char oneword[100]; int c; fp1 = fopen("TENLINES.TXT","r");
do { c = fscanf(fp1,"%s",oneword); /* got one word from the file */ printf("%s\n",oneword); /* display it on the monitor */ } while (c != EOF); /* repeat until EOF */ fclose(fp1); }
}; Void main() { struct Student s; Printf(\n enter rno ,s.name ); Scanf(%d,&s.carno); Scanf(%d %d %d,&s->name); Printf(\n student details are ); Printf(\n %d \t ,s->no); printf(%d ,s->name); }
Struct student { int rno; string name; }; Void main() { struct Student s,*sptr; sptr=&s;
Printf(\n enter rno ,s->name ); Scanf(%d,&s->carno); Scanf(%d %d %d,&s.name); Printf(\n student details are ); Printf(\n %d \t ,s->no); printf(%d ,s->name); } Q) prg to illustrate nested structure Void main() { Struct time { int second; int minute; int hour; }; Struct t { int carno; struct time st; struct time rt; };
Struct t r1; Printf(\n carno startingtime reaching time ); Scanf(%d,&r1.carno); Scanf(%d %d %d,&r1.st.hour,&r1.st.minute,&r1.st.second); Scanf(%d %d %d,&r1.rt.hour,&r1.rt.minute,&r1.rt.second); Printf(\n carno startingtime reaching time ); Printf(\n %d \t ,r1.carno); printf(%d %d %d,&r1.st.hour,&r1.st.minute,&r1.st.second); printf(%d %d %d,&r1.rt.hour,&r1.rt.minute,&r1.rt.second); }
Array of Structures:
Q) prg to illustrate array of structures. Void main() { int k; Struct time { int second; int minute; int hour; }; Struct t
Struct t r1[3]; //declaring array of structures. Printf(\n carno startingtime reaching time );
For(k=0;k<3;k++) { Scanf(%d,&r1[k].carno); Scanf(%d %d %d,&r1[k].st.hour,&r1[k].st.minute,&r1[k].st.second); Scanf(%d %d %d,&r1[k].rt.hour,&r1[k].rt.minute,&r1[k].rt.second); } Printf(\n carno startingtime reaching time ); For(k=0;k<3;k++) { Printf(\n %d \t ,r1[k].carno); printf(%d %d %d,&r1[k].st.hour,&r1[k].st.minute,&r1[k].st.second); printf(%d %d %d,&r1[k].rt.hour,&r1[k].rt.minute,&r1[k].rt.second); } }
Malloc: allocate a block of memory. Used for primitive data types. Syn:ptr =(type*) malloc(size); Ex: x= (int*) malloc(100*sizeof(int));
2)
Calloc: allocates multiple blocks of memory. Used for user defined data types like structure.
Data Structures: i)Its a collection of organized data that are related to each other.Data structures can be classified into two types a) linear data structure ex: array,stack,queque, circular queue,list b) Non-Linear data structure ex:trees and graphs
stack:
i)
Its a linear data structure in which insertion and deletion will be at one end. I
ii) It follows LIFO(last in first out) order. iii) Consists of push( for insertion) and pop(for deletion). iv) Uses single pointer (top) for insertion and deletion. v) Example pile restaurant. of books or plates in
Queue:
i)
Its also linear data structure, in which insertion will be done at rare end and deletion, will be done at front end. Its follows FIFO (first in first out) order.
ii)
iii) Consists of insert , delete options iv) Uses two pointer rare and front. v) Example railway ticket reservation.
Stack:
50 30 20
top=2 1 0
Queue: Front
10 2 20 30 12
rare
Circular Queue: i) ii) iii) Queue as circular known as Circular queue. Instead of taking linear approach, circular queue takes a circular approach.
Linked Lists: i) ii) List using array ,has the problem in which the size of the array must be specified precisely at the beginning. A linked lists is a collection of data segments each data segment is a structure , which consists of data or field and link or pointer to next data segment. Its a dynamic data structure. Therefore, the primary advantage of linked lists over arrays is that linked lists can grow or shrink in size during the execution of a program. It does not waste memory space, it uses the memory that is needed for the list at any point of time. Because its not necessary to specify the no.of nodes in the list.
iii)
iv)
10
12
a) Linear list
10 12 3 0
b) Circular List
10 12 3
10
12
d)
10
12
10
12
Item to be inserted
Insertion:
10 12 3 0
Deletion:
10 12 3 0
Note: similary insertion , deletion for double linked list. Similary Stack , queue using linked list can be implemented.
Consists of finite set of elements, called nodes and finite set of directed lines , called branches , which connect the nodes.
iii) The number of branches associated with the nodes is the degree of the node.
iv) Incoming branch is known as indegree and out going branch or edge is known as out degree. Binary Trees: i) A binary tree is a tree in which no node can have more than two subtrees. ii) Binary tree can be traversed in three different ways inorder, preorder, post order traversal.
iii)
In inorder traversal ,path is as leftnode, root, and right node. Whereas in preorder , path is as root , leftnode, and right node.
A B E
Binary Search Tree(BST): i) Its a binary tree, if all left subtree are less than root, and right subtree are greater or equal to root.
14
22
14
22
Inserting : 15
17 6 19
14 15
22
Graphs:
i)
Its a collection of nodes called vertices , and collection of lines called edges , connecting pair of vertices.
a)
B E F C
b)
E F
Types of Graphs:
a)
Weakly connected graph : directed graph is weakly connected if atleast two vertices are not connected.
A
B C
E D
b)
Strongly connected graph : directed graph is strongly connected if there is path from each vertex to every other vertex in digraph.
A
E F
c)
E F
Adjacency matrix: we use vector to store the vertices and a matrix to store the edges.
2)
Adjacency List: we use a vector list to store the vertices and a linked list to store the arcs or edges.
Depth first traversal: in this , all nodes descendents are processed before moving to an adjacent node.
A B D
Y x H E G
DFT: AXHPEYMJG 1:A 2:x 3: H G Breadth first traversal: in this, all adjacent vertices are processed before processing the descendants of a vertex.
A B C G H I D
4: P E G
5: E G
6: Y M G
7: M G
8: J G
9:
BFT: ABCDEFGHI
Y x H E G
1)
Selection sort: the selection sort divides the array into sorted and unsorted sublists. In each pass, algorithm chooses the smallest element from the unsorted sublist and swaps it with the element at the beginning of the unsorted sublist.
2)
Bubble sort: the bubble sort divides the array into sorted and unsorted sublists. In each pass, algorithm bubbles the smallest element from the unsorted sublist into the sorted lists.
Example: Original list : 23, 78,45,8,32,56 Pass 1: Pass 2: Pass 3: Pass 4: Pass 5: 8,23,78,45,32,56 8,23,78,45,32,56 8,23,32,78,45,56 8,23,32,45,78,56 8,78,32,45,56,78
3)
Insertion sort: the insertion sort divides the array into sorted and unsorted sublists. In each pass, algorithm inserts first element from the unsorted sublist into appropriate position in the sorted lists.
Example: Original list : 23, 78,45,8,32,56 Pass 1: Pass 2: Pass 3: Pass 4: Pass 4: 23,78,45,8,32,56 23,45,78,8,32,56 8,23,45,78,32,56 8,23,32,45,78,56 8,23,32,45,56,78
Quick sort:
i)
quick sort is more efficient than bubble sort in that it requires fewer exchanges to correctly position an element. Basic principle is to pick one element in the array and rearrange the remaining elements around it. The selected element is called pivot.
ii)
iii)
All elements lesser than pivot are moved to the left and all greater or equal to pivot are moved towards right of pivot.
2) Merge sort:
i) ii)
Its a divide and conquer algorithm. Main process will be to divide the list to be sorted into two smaller sublists and repeat the process untill elements in the sublists get sorted. To divide will use first + last element /2 , considering upper bound value.
iii)
Example: 44,36,57,19,25,89,28
44,36,57,19
25,89,28
44,36
57,19
25,89
28
44
36
57 19 25
89
28
36,44
19,57
25,89
28
19,36,44,57
25,28,89
Note: Efficiency of bubble sort is O(n2) Efficiency of selection sort is O(n2) Efficiency of insertion sort is O(n2) Efficiency of quick sort is O(nlogn) Efficiency of merge sort is O(nlogn)
Searching :
1) Linear or Sequential search: i) ii) Its used when list is not in ordered. We start searching from the beginning of the list until we get or until we sure that the element is not there in the list.
2) Binary Search: i) ii) iii) Its used when the list is sorted. Its faster than sequential search. Sorted list will be divided into two halves , and element to be searched will be compared will greater, than only right subtree will be searched or else left. This process will be followed until the element obtain or not found. Mid=(first+last)/2
iv)
i)
Fir:0,mid:5,last:11 22>21
ii)
iii)
Element found.