SlideShare a Scribd company logo
10 Most Important C Programming Interview Questions 
C Programming Interview Questions 
Powered by –
Index 
1. Write a C program to swap two variables without using a temporary variable 3 
2. What is the 8 queens problem. Write a C program to solve it 5 
3. Write a C program to print a square matrix helically 7 
4. Write a C program to reverse a string 8 8 
5. Write a C program to reverse the words in a sentence in place 11 
6. Write a C program generate permutations 14 
7. Write a C program for calculating the factorial of a number 16 
8. Write a C program to calculate pow(x,n) 17 
9. Write a C program which does wildcard pattern matching algorithm 18 
10. How do you calculate the maximum subarray of a list of numbers 19
Q. Write a C program to swap two variables without using a temporary variable? 
Soln: This question is asked almost always in every interview. The best way to swap two variables is to use a temporary variable. int a,b,t; t = a; a = b; b = t; 
There is no way better than this as you will find out soon. There are a few slick expressions that do swap variables without using temporary storage. But they come with their own set of problems. Method1 (The XOR trick) a ^= b ^= a ^= b; Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it won’t work in all the cases. This will also not work for floating-point values. Also, think of a scenario where you have written your code like this swap(int *a, int *b) { *a ^= *b ^= *a ^= *b; } Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other. swap(int *a, int *b) { if(*a!=*b) { *a ^= *b ^= *a ^= *b; }
} Method 2 This method is also quite popular a=a+b; b=a-b; a=a-b; But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results. One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap macro which looks something like this #define swap(type,a,b) type temp;temp=a;a=b;b=temp; Now, think what happens if you pass in something like this swap(int,temp,a) //You have a variable called "temp" (which is quite possible). This is how it gets replaced by the macro int temp; temp=temp; temp=b; b=temp; Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it? So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary variable. It’s not only fool proof, but also easier to understand and maintain.
Q. What is the 8 queens problem? Write a C program to solve it? 
Soln: The 8 queens problem is a classic problem using the chess board. This problem is to place 8 queens on the chess board so that they do not attack each other horizontally, vertically or diagonally. It turns out that there are 12 essentially distinct solutions to this problem. Suppose we have an array t[8] which keeps track of which column is occupied in which row of the chess board. That is, if t[0]==5, then it means that the queen has been placed in the fifth column of the first row. We need to couple the backtracking algorithm with a procedure that checks whether the tuple is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of the already placed 'j' (j < i): Two queens are in the same column if t[i]=t[j] Two queens are in the same major diagonal if (t[i]-t[j])=(i-j) two queens are in the same minor diagonal if (t[j]-t[i])=(i-j) Here is some working C code to solve this problem using backtracking #include<stdio.h> static int t[10]={-1}; void queens(int i); int empty(int i); void print_solution(); int main() { queens(1); print_solution(); return(0); } void queens(int i) { for(t[i]=1;t[i]<=8;t[i]++) { if(empty(i)) { if(i==8) { print_solution();
/* If this exit is commented, it will show ALL possible combinations */ exit(0); } else { // Recurse! queens(i+1); } }// if }// for } int empty(int i) { int j; j=1; while(t[i]!=t[j] && abs(t[i]-t[j])!=(i-j) &&j<8)j++; return((i==j)?1:0); } void print_solution() { int i; for(i=1;i<=8;i++)printf("nt[%d] = [%d]",i,t[i]); } And here is one of the possible solutions t[1] = [1] // This means the first square of the first row. t[2] = [5] // This means the fifth square of the second row. t[3] = [8] .. t[4] = [6] .. t[5] = [3] .. t[6] = [7] .. t[7] = [2] .. t[8] = [4] // This means the fourth square of the last row.
Q. Write a C program to print a square matrix helically? 
Soln: Here is a C program to print a matrix helically. Printing a matrix helically means printing it in this spiral fashion >-----------+ | +---->--+ | | | | | | | | <---+ | | | +-----------+ This is a simple program to print a matrix helically. #include<stdio.h> /* HELICAL MATRIX */ int main() { int arr[][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13, 14, 15, 16} }; int i, j, k,middle,size; printf("nn"); size = 4; for(i=size-1, j=0; i>0; i--, j++) { for(k=j; k<i; k++) printf("%d ", arr[j][k]); for(k=j; k<i; k++) printf("%d ", arr[k][i]); for(k=i; k>j; k--) printf("%d ", arr[i][k]); for(k=i; k>j; k--) printf("%d ", arr[k][j]); } middle = (size-1)/2; if (size % 2 == 1) printf("%d", arr[middle][middle]); printf("nn"); return 1; }
Q. Write a C program to reverse the words in a sentence in place? 
Soln: That is, given a sentence like this - I am a good boy - In place reverse would be boy good a am I Method1 First reverse the whole string and then individually reverse the words I am a good boy <-------------> yob doog a ma I <-> <--> <-> <-> <-> boy good a am I Here is some C code to do the same .... /* Algorithm.. 1. Reverse whole sentence first. 2. Reverse each word individually. All the reversing happens in-place. */ #include <stdio.h> void rev (char *l, char *r); 
int main(int argc, char *argv[]) { char buf[] = "the world will go on forever"; char *end, *x, *y; // Reverse the whole sentence first.. for(end=buf; *end; end++); rev(buf,end-1);
// Now swap each word within sentence... x = buf-1; y = buf; while(x++ < end) { if(*x == '0' || *x == ' ') { rev(y,x-1); y = x+1; } } // Now print the final string.... printf("%sn",buf); return(0); } // Function to reverse a string in place... void rev(char *l,char *r) { char t; while(l<r) { t = *l; *l++ = *r; *r-- = t; } } Method2 
Another way to do it is, allocate as much memory as the input for the final output. Start from the right of the string and copy the words one by one to the output. Input : I am a good boy <-- <------- <---------
<------------ <-------------- Output : boy : boy good : boy good a : boy good a am : boy good a am I The only problem to this solution is the extra space required for the output and one has to write this code really well as we are traversing the string in the reverse direction and there is no null at the start of the string to know we have reached the start of the string!. One can use the strtok() function to breakup the string into multiple words and rearrange them in the reverse order later. Method3 Create a linked list like +---+ +----------+ +----+ +----------+ +---+ +----------+ | I | -> | <spaces> | -> | am | -> | <spaces> | -> | a | -> | <spaces> | --+ +---+ +----------+ +----+ +----------+ +---+ +----------+ | | | +-------------------------------------------------------------------------+ | | +------+ +----------+ +-----+ +------+ +---> | good | -> | <spaces> | -> | boy | -> | NULL | +------+ +----------+ +-----+ +------+ Now it’s a simple question of reversing the linked list!. There are plenty of algorithms to reverse a linked list easily. This also keeps track of the number of spaces between the words. Note that the linked list algorithm, though inefficient, handles multiple spaces between the words really well. I really dont know what is the use of reversing a string or a sentence like this!, but its still asked. Can someone tell me a really practical application of this? Please!
Q. Write a C program generate permutations? 
Soln: Iterative C program #include <stdio.h> #define SIZE 3 int main(char *argv[],int argc) { char list[3]={'a','b','c'}; int i,j,k; for(i=0;i<SIZE;i++) for(j=0;j<SIZE;j++) for(k=0;k<SIZE;k++) if(i!=j && j!=k && i!=k) printf("%c%c%cn",list[i],list[j],list[k]); return(0); } Recursive C program #include <stdio.h> #define N 5 int main(char *argv[],int argc) { char list[5]={'a','b','c','d','e'}; permute(list,0,N); return(0); } void permute(char list[],int k, int m) { int i; char temp; if(k==m) { /* PRINT A FROM k to m! */
for(i=0;i<N;i++){printf("%c",list[i]);} printf("n"); } else { for(i=k;i<m;i++) { /* swap(a[i],a[m-1]); */ temp=list[i]; list[i]=list[m-1]; list[m-1]=temp; permute(list,k,m-1); /* swap(a[m-1],a[i]); */ temp=list[m-1]; list[m-1]=list[i]; list[i]=temp; } } }
Q. Write a C program for calculating the factorial of a number? 
Soln: Here is a recursive C program fact(int n) { int fact; if(n==1) return(1); else fact = n * fact(n-1); return(fact); } Please note that there is no error handling added to this function (to check if n is negative or 0. Or if n is too large for the system to handle). This is true for most of the answers in this website. Too much error handling and standard compliance results in a lot of clutter making it difficult to concentrate on the crux of the solution. You must of course add as much error handling and comply to the standards of your compiler when you actually write the code to implement these algorithms.
Q. Write a C program to calculate pow(x,n)? 
Soln: There are again different methods to do this in C Brute force C program int pow(int x, int y) { if(y == 1) return x ; return x * pow(x, y-1) ; } Divide and Conquer C program #include <stdio.h> int main(int argc, char*argv[]) { printf("n[%d]n",pow(5,4)); } int pow(int x, int n) { if(n==0)return(1); else if(n%2==0) { return(pow(x,n/2)*pow(x,(n/2))); } else { return(x*pow(x,n/2)*pow(x,(n/2))); } } Also, the code above can be optimized still by calculating pow(z, (n/2)) only one time (instead of twice) and using its value in the two return() expressions above.
Q. Write a C program which does wildcard pattern matching algorithm? 
Soln: Here is an example C program... #include<stdio.h> #define TRUE 1 #define FALSE 0 int wildcard(char *string, char *pattern); int main() { char *string = "hereheroherr"; char *pattern = "*hero*"; if(wildcard(string, pattern)==TRUE) { printf("nMatch Found!n"); } else { printf("nMatch not found!n"); } return(0); } int wildcard(char *string, char *pattern) { while(*string) { switch(*pattern) { case '*': do {++pattern;}while(*pattern == '*'); if(!*pattern) return(TRUE); while(*string){if(wildcard(pattern,string++)==TRUE)return(TRUE);} return(FALSE); default : if(*string!=*pattern)return(FALSE); break; } ++pattern; ++string; } while (*pattern == '*') ++pattern; return !*pattern; }
Q. How do you calculate the maximum subarray of a list of numbers? 
Soln: This is a very popular question You are given a large array X of integers (both positive and negative) and you need to find the maximum sum found in any contiguous subarray of X. Example X = [11, -12, 15, -3, 8, -9, 1, 8, 10, -2] 
Answer is 30. There are various methods to solve this problem, some are listed below Brute force maxSum = 0 for L = 1 to N { for R = L to N { sum = 0 for i = L to R { sum = sum + X[i] } maxSum = max(maxSum, sum) } } O(N^3) Quadratic Note that sum of [L..R] can be calculated from sum of [L..R-1] very easily. maxSum = 0 for L = 1 to N { sum = 0 for R = L to N
{ sum = sum + X[R] maxSum = max(maxSum, sum) } } Using divide-and-conquer O(N log(N)) maxSum(L, R) { if L > R then return 0 if L = R then return max(0, X[L]) M = (L + R)/2 sum = 0; maxToLeft = 0 for i = M downto L do { sum = sum + X[i] maxToLeft = max(maxToLeft, sum) } sum = 0; maxToRight = 0 for i = M to R do { sum = sum + X[i] maxToRight = max(maxToRight, sum) } maxCrossing = maxLeft + maxRight maxInA = maxSum(L,M) maxInB = maxSum(M+1,R) return max(maxCrossing, maxInA, maxInB) } Here is working C code for all the above cases #include<stdio.h>
#define N 10 int maxSubSum(int left, int right); int list[N] = {11, -12, 15, -3, 8, -9, 1, 8, 10, -2}; int main() { int i,j,k; int maxSum, sum; /*--------------------------------------- * CUBIC - O(n*n*n) *---------------------------------------*/ maxSum = 0; for(i=0; i<N; i++) { for(j=i; j<N; j++) { sum = 0; for(k=i ; k<j; k++) { sum = sum + list[k]; } maxSum = (maxSum>sum)?maxSum:sum; } } printf("nmaxSum = [%d]n", maxSum); /*------------------------------------- * Quadratic - O(n*n) * ------------------------------------ */ maxSum = 0; for(i=0; i<N; i++) { sum=0; for(j=i; j<N ;j++) { sum = sum + list[j]; maxSum = (maxSum>sum)?maxSum:sum; 
}
} printf("nmaxSum = [%d]n", maxSum); /*---------------------------------------- * Divide and Conquer - O(nlog(n)) * -------------------------------------- */ printf("nmaxSum : [%d]n", maxSubSum(0,9)); return(0); } int maxSubSum(int left, int right) { int mid, sum, maxToLeft, maxToRight, maxCrossing, maxInA, maxInB; int i; if(left>right){return 0;} if(left==right){return((0>list[left])?0:list[left]);} mid = (left + right)/2; sum=0; maxToLeft=0; for(i=mid; i>=left; i--) { sum = sum + list[i]; maxToLeft = (maxToLeft>sum)?maxToLeft:sum; } sum=0; maxToRight=0; for(i=mid+1; i<=right; i++) { sum = sum + list[i]; maxToRight = (maxToRight>sum)?maxToRight:sum; } maxCrossing = maxToLeft + maxToRight; maxInA = maxSubSum(left,mid); maxInB = maxSubSum(mid+1,right); return(((maxCrossing>maxInA)?maxCrossing:maxInA)>maxInB?((maxCrossing>maxInA)?maxCrossi 
ng:maxInA):maxInB); }
Note that, if the array has all negative numbers, then this code will return 0. This is wrong because it should return the maximum sum, which is the least negative integer in the array. This happens because we are setting maxSum to 0 initially. A small change in this code can be used to handle such cases.
Study on the go; get high quality complete preparation courses now on your mobile!
Ad

More Related Content

What's hot (20)

Computer Science Assignment Help
Computer Science Assignment HelpComputer Science Assignment Help
Computer Science Assignment Help
Programming Homework Help
 
Software Construction Assignment Help
Software Construction Assignment HelpSoftware Construction Assignment Help
Software Construction Assignment Help
Programming Homework Help
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
Dushmanta Nath
 
C Assignment Help
C Assignment HelpC Assignment Help
C Assignment Help
Programming Homework Help
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 
C Programming Assignment
C Programming AssignmentC Programming Assignment
C Programming Assignment
Vijayananda Mohire
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++[ITP - Lecture 17] Strings in C/C++
[ITP - Lecture 17] Strings in C/C++
Muhammad Hammad Waseem
 
Strings
StringsStrings
Strings
Saranya saran
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
CIMAP
 
C interview questions
C interview questionsC interview questions
C interview questions
Soba Arjun
 
Programming Homework Help
Programming Homework Help Programming Homework Help
Programming Homework Help
Programming Homework Help
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Philip Schwarz
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
Lập trình C
Lập trình CLập trình C
Lập trình C
Viet NguyenHoang
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
Dushmanta Nath
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
Muhammad Hammad Waseem
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
Dushmanta Nath
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 
[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++[ITP - Lecture 16] Structures in C/C++
[ITP - Lecture 16] Structures in C/C++
Muhammad Hammad Waseem
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 
Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02Claguage 110226222227-phpapp02
Claguage 110226222227-phpapp02
CIMAP
 
C interview questions
C interview questionsC interview questions
C interview questions
Soba Arjun
 
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Game of Life - Polyglot FP - Haskell - Scala - Unison - Part 3
Philip Schwarz
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
MomenMostafa
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
Dushmanta Nath
 

Viewers also liked (13)

important C questions and_answers praveensomesh
important C questions and_answers praveensomeshimportant C questions and_answers praveensomesh
important C questions and_answers praveensomesh
praveensomesh
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
ReKruiTIn.com
 
C++ questions and answers
C++ questions and answersC++ questions and answers
C++ questions and answers
Deepak Singh
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
 
Cat Quant Cheat Sheet
Cat Quant Cheat SheetCat Quant Cheat Sheet
Cat Quant Cheat Sheet
versabit technologies
 
Simple c program
Simple c programSimple c program
Simple c program
Ravi Singh
 
C interview Question and Answer
C interview Question and AnswerC interview Question and Answer
C interview Question and Answer
Jagan Mohan Bishoyi
 
Geometry formula sheet
Geometry formula sheetGeometry formula sheet
Geometry formula sheet
sidraqasim99
 
Algebra formulas
Algebra formulas Algebra formulas
Algebra formulas
Matthew McKenzie
 
Geometry formula-sheet
Geometry formula-sheetGeometry formula-sheet
Geometry formula-sheet
adheera dra
 
Probability Formula sheet
Probability Formula sheetProbability Formula sheet
Probability Formula sheet
Haris Hassan
 
Notes and-formulae-mathematics
Notes and-formulae-mathematicsNotes and-formulae-mathematics
Notes and-formulae-mathematics
Ragulan Dev
 
Shortcuts in Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...
Shortcuts in  Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...Shortcuts in  Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...
Shortcuts in Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...
paijayant
 
important C questions and_answers praveensomesh
important C questions and_answers praveensomeshimportant C questions and_answers praveensomesh
important C questions and_answers praveensomesh
praveensomesh
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
ReKruiTIn.com
 
C++ questions and answers
C++ questions and answersC++ questions and answers
C++ questions and answers
Deepak Singh
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar007
 
Simple c program
Simple c programSimple c program
Simple c program
Ravi Singh
 
Geometry formula sheet
Geometry formula sheetGeometry formula sheet
Geometry formula sheet
sidraqasim99
 
Geometry formula-sheet
Geometry formula-sheetGeometry formula-sheet
Geometry formula-sheet
adheera dra
 
Probability Formula sheet
Probability Formula sheetProbability Formula sheet
Probability Formula sheet
Haris Hassan
 
Notes and-formulae-mathematics
Notes and-formulae-mathematicsNotes and-formulae-mathematics
Notes and-formulae-mathematics
Ragulan Dev
 
Shortcuts in Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...
Shortcuts in  Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...Shortcuts in  Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...
Shortcuts in Mathematics for CAT, CET, GRE, GMAT or any similar competitive ...
paijayant
 
Ad

Similar to C Programming Interview Questions (20)

C code examples
C code examplesC code examples
C code examples
Industrial Electric, Electronic Ind. And Trade Co. Ltd.
 
C important questions
C important questionsC important questions
C important questions
JYOTI RANJAN PAL
 
Get Fast C++ Homework Help
Get Fast C++ Homework HelpGet Fast C++ Homework Help
Get Fast C++ Homework Help
C++ Homework Help
 
MATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdfMATLAB Questions and Answers.pdf
MATLAB Questions and Answers.pdf
ahmed8651
 
C++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdfC++ in 10 Hours.pdf.pdf
C++ in 10 Hours.pdf.pdf
SumitSingh813090
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Dr Mrs A A Miraje C Programming PPT.pptx
Dr Mrs A A Miraje C Programming PPT.pptxDr Mrs A A Miraje C Programming PPT.pptx
Dr Mrs A A Miraje C Programming PPT.pptx
ProfAAMiraje
 
C++ Programming Homework Help
C++ Programming Homework HelpC++ Programming Homework Help
C++ Programming Homework Help
C++ Homework Help
 
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdfN Queen Problem using Branch And Bound - GeeksforGeeks.pdf
N Queen Problem using Branch And Bound - GeeksforGeeks.pdf
akashreddy966699
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
Gradeup
 
C tutorial
C tutorialC tutorial
C tutorial
Anurag Sukhija
 
Code optimization
Code optimization Code optimization
Code optimization
baabtra.com - No. 1 supplier of quality freshers
 
Code optimization
Code optimization Code optimization
Code optimization
baabtra.com - No. 1 supplier of quality freshers
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
Programming Homework Help
 
C and C++ programming basics for Beginners.pptx
C and C++ programming basics for Beginners.pptxC and C++ programming basics for Beginners.pptx
C and C++ programming basics for Beginners.pptx
renuvprajapati
 
901131 examples
901131 examples901131 examples
901131 examples
Jeninä Juco III
 
C++ Homework Help
C++ Homework HelpC++ Homework Help
C++ Homework Help
C++ Homework Help
 
C operators
C operatorsC operators
C operators
srmohan06
 
Ansi c
Ansi cAnsi c
Ansi c
dayaramjatt001
 
CHAPTER 5
CHAPTER 5CHAPTER 5
CHAPTER 5
mohd_mizan
 
Ad

Recently uploaded (20)

Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Sinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_NameSinhala_Male_Names.pdf Sinhala_Male_Name
Sinhala_Male_Names.pdf Sinhala_Male_Name
keshanf79
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 

C Programming Interview Questions

  • 1. 10 Most Important C Programming Interview Questions C Programming Interview Questions Powered by –
  • 2. Index 1. Write a C program to swap two variables without using a temporary variable 3 2. What is the 8 queens problem. Write a C program to solve it 5 3. Write a C program to print a square matrix helically 7 4. Write a C program to reverse a string 8 8 5. Write a C program to reverse the words in a sentence in place 11 6. Write a C program generate permutations 14 7. Write a C program for calculating the factorial of a number 16 8. Write a C program to calculate pow(x,n) 17 9. Write a C program which does wildcard pattern matching algorithm 18 10. How do you calculate the maximum subarray of a list of numbers 19
  • 3. Q. Write a C program to swap two variables without using a temporary variable? Soln: This question is asked almost always in every interview. The best way to swap two variables is to use a temporary variable. int a,b,t; t = a; a = b; b = t; There is no way better than this as you will find out soon. There are a few slick expressions that do swap variables without using temporary storage. But they come with their own set of problems. Method1 (The XOR trick) a ^= b ^= a ^= b; Although the code above works fine for most of the cases, it tries to modify variable 'a' two times between sequence points, so the behavior is undefined. What this means is it won’t work in all the cases. This will also not work for floating-point values. Also, think of a scenario where you have written your code like this swap(int *a, int *b) { *a ^= *b ^= *a ^= *b; } Now, if suppose, by mistake, your code passes the pointer to the same variable to this function. Guess what happens? Since Xor'ing an element with itself sets the variable to zero, this routine will end up setting the variable to zero (ideally it should have swapped the variable with itself). This scenario is quite possible in sorting algorithms which sometimes try to swap a variable with itself (maybe due to some small, but not so fatal coding error). One solution to this problem is to check if the numbers to be swapped are already equal to each other. swap(int *a, int *b) { if(*a!=*b) { *a ^= *b ^= *a ^= *b; }
  • 4. } Method 2 This method is also quite popular a=a+b; b=a-b; a=a-b; But, note that here also, if a and b are big and their addition is bigger than the size of an int, even this might end up giving you wrong results. One can also swap two variables using a macro. However, it would be required to pass the type of the variable to the macro. Also, there is an interesting problem using macros. Suppose you have a swap macro which looks something like this #define swap(type,a,b) type temp;temp=a;a=b;b=temp; Now, think what happens if you pass in something like this swap(int,temp,a) //You have a variable called "temp" (which is quite possible). This is how it gets replaced by the macro int temp; temp=temp; temp=b; b=temp; Which means it sets the value of "b" to both the variables!. It never swapped them! Scary, isn't it? So the moral of the story is, dont try to be smart when writing code to swap variables. Use a temporary variable. It’s not only fool proof, but also easier to understand and maintain.
  • 5. Q. What is the 8 queens problem? Write a C program to solve it? Soln: The 8 queens problem is a classic problem using the chess board. This problem is to place 8 queens on the chess board so that they do not attack each other horizontally, vertically or diagonally. It turns out that there are 12 essentially distinct solutions to this problem. Suppose we have an array t[8] which keeps track of which column is occupied in which row of the chess board. That is, if t[0]==5, then it means that the queen has been placed in the fifth column of the first row. We need to couple the backtracking algorithm with a procedure that checks whether the tuple is completable or not, i.e. to check that the next placed queen 'i' is not menaced by any of the already placed 'j' (j < i): Two queens are in the same column if t[i]=t[j] Two queens are in the same major diagonal if (t[i]-t[j])=(i-j) two queens are in the same minor diagonal if (t[j]-t[i])=(i-j) Here is some working C code to solve this problem using backtracking #include<stdio.h> static int t[10]={-1}; void queens(int i); int empty(int i); void print_solution(); int main() { queens(1); print_solution(); return(0); } void queens(int i) { for(t[i]=1;t[i]<=8;t[i]++) { if(empty(i)) { if(i==8) { print_solution();
  • 6. /* If this exit is commented, it will show ALL possible combinations */ exit(0); } else { // Recurse! queens(i+1); } }// if }// for } int empty(int i) { int j; j=1; while(t[i]!=t[j] && abs(t[i]-t[j])!=(i-j) &&j<8)j++; return((i==j)?1:0); } void print_solution() { int i; for(i=1;i<=8;i++)printf("nt[%d] = [%d]",i,t[i]); } And here is one of the possible solutions t[1] = [1] // This means the first square of the first row. t[2] = [5] // This means the fifth square of the second row. t[3] = [8] .. t[4] = [6] .. t[5] = [3] .. t[6] = [7] .. t[7] = [2] .. t[8] = [4] // This means the fourth square of the last row.
  • 7. Q. Write a C program to print a square matrix helically? Soln: Here is a C program to print a matrix helically. Printing a matrix helically means printing it in this spiral fashion >-----------+ | +---->--+ | | | | | | | | <---+ | | | +-----------+ This is a simple program to print a matrix helically. #include<stdio.h> /* HELICAL MATRIX */ int main() { int arr[][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13, 14, 15, 16} }; int i, j, k,middle,size; printf("nn"); size = 4; for(i=size-1, j=0; i>0; i--, j++) { for(k=j; k<i; k++) printf("%d ", arr[j][k]); for(k=j; k<i; k++) printf("%d ", arr[k][i]); for(k=i; k>j; k--) printf("%d ", arr[i][k]); for(k=i; k>j; k--) printf("%d ", arr[k][j]); } middle = (size-1)/2; if (size % 2 == 1) printf("%d", arr[middle][middle]); printf("nn"); return 1; }
  • 8. Q. Write a C program to reverse the words in a sentence in place? Soln: That is, given a sentence like this - I am a good boy - In place reverse would be boy good a am I Method1 First reverse the whole string and then individually reverse the words I am a good boy <-------------> yob doog a ma I <-> <--> <-> <-> <-> boy good a am I Here is some C code to do the same .... /* Algorithm.. 1. Reverse whole sentence first. 2. Reverse each word individually. All the reversing happens in-place. */ #include <stdio.h> void rev (char *l, char *r); int main(int argc, char *argv[]) { char buf[] = "the world will go on forever"; char *end, *x, *y; // Reverse the whole sentence first.. for(end=buf; *end; end++); rev(buf,end-1);
  • 9. // Now swap each word within sentence... x = buf-1; y = buf; while(x++ < end) { if(*x == '0' || *x == ' ') { rev(y,x-1); y = x+1; } } // Now print the final string.... printf("%sn",buf); return(0); } // Function to reverse a string in place... void rev(char *l,char *r) { char t; while(l<r) { t = *l; *l++ = *r; *r-- = t; } } Method2 Another way to do it is, allocate as much memory as the input for the final output. Start from the right of the string and copy the words one by one to the output. Input : I am a good boy <-- <------- <---------
  • 10. <------------ <-------------- Output : boy : boy good : boy good a : boy good a am : boy good a am I The only problem to this solution is the extra space required for the output and one has to write this code really well as we are traversing the string in the reverse direction and there is no null at the start of the string to know we have reached the start of the string!. One can use the strtok() function to breakup the string into multiple words and rearrange them in the reverse order later. Method3 Create a linked list like +---+ +----------+ +----+ +----------+ +---+ +----------+ | I | -> | <spaces> | -> | am | -> | <spaces> | -> | a | -> | <spaces> | --+ +---+ +----------+ +----+ +----------+ +---+ +----------+ | | | +-------------------------------------------------------------------------+ | | +------+ +----------+ +-----+ +------+ +---> | good | -> | <spaces> | -> | boy | -> | NULL | +------+ +----------+ +-----+ +------+ Now it’s a simple question of reversing the linked list!. There are plenty of algorithms to reverse a linked list easily. This also keeps track of the number of spaces between the words. Note that the linked list algorithm, though inefficient, handles multiple spaces between the words really well. I really dont know what is the use of reversing a string or a sentence like this!, but its still asked. Can someone tell me a really practical application of this? Please!
  • 11. Q. Write a C program generate permutations? Soln: Iterative C program #include <stdio.h> #define SIZE 3 int main(char *argv[],int argc) { char list[3]={'a','b','c'}; int i,j,k; for(i=0;i<SIZE;i++) for(j=0;j<SIZE;j++) for(k=0;k<SIZE;k++) if(i!=j && j!=k && i!=k) printf("%c%c%cn",list[i],list[j],list[k]); return(0); } Recursive C program #include <stdio.h> #define N 5 int main(char *argv[],int argc) { char list[5]={'a','b','c','d','e'}; permute(list,0,N); return(0); } void permute(char list[],int k, int m) { int i; char temp; if(k==m) { /* PRINT A FROM k to m! */
  • 12. for(i=0;i<N;i++){printf("%c",list[i]);} printf("n"); } else { for(i=k;i<m;i++) { /* swap(a[i],a[m-1]); */ temp=list[i]; list[i]=list[m-1]; list[m-1]=temp; permute(list,k,m-1); /* swap(a[m-1],a[i]); */ temp=list[m-1]; list[m-1]=list[i]; list[i]=temp; } } }
  • 13. Q. Write a C program for calculating the factorial of a number? Soln: Here is a recursive C program fact(int n) { int fact; if(n==1) return(1); else fact = n * fact(n-1); return(fact); } Please note that there is no error handling added to this function (to check if n is negative or 0. Or if n is too large for the system to handle). This is true for most of the answers in this website. Too much error handling and standard compliance results in a lot of clutter making it difficult to concentrate on the crux of the solution. You must of course add as much error handling and comply to the standards of your compiler when you actually write the code to implement these algorithms.
  • 14. Q. Write a C program to calculate pow(x,n)? Soln: There are again different methods to do this in C Brute force C program int pow(int x, int y) { if(y == 1) return x ; return x * pow(x, y-1) ; } Divide and Conquer C program #include <stdio.h> int main(int argc, char*argv[]) { printf("n[%d]n",pow(5,4)); } int pow(int x, int n) { if(n==0)return(1); else if(n%2==0) { return(pow(x,n/2)*pow(x,(n/2))); } else { return(x*pow(x,n/2)*pow(x,(n/2))); } } Also, the code above can be optimized still by calculating pow(z, (n/2)) only one time (instead of twice) and using its value in the two return() expressions above.
  • 15. Q. Write a C program which does wildcard pattern matching algorithm? Soln: Here is an example C program... #include<stdio.h> #define TRUE 1 #define FALSE 0 int wildcard(char *string, char *pattern); int main() { char *string = "hereheroherr"; char *pattern = "*hero*"; if(wildcard(string, pattern)==TRUE) { printf("nMatch Found!n"); } else { printf("nMatch not found!n"); } return(0); } int wildcard(char *string, char *pattern) { while(*string) { switch(*pattern) { case '*': do {++pattern;}while(*pattern == '*'); if(!*pattern) return(TRUE); while(*string){if(wildcard(pattern,string++)==TRUE)return(TRUE);} return(FALSE); default : if(*string!=*pattern)return(FALSE); break; } ++pattern; ++string; } while (*pattern == '*') ++pattern; return !*pattern; }
  • 16. Q. How do you calculate the maximum subarray of a list of numbers? Soln: This is a very popular question You are given a large array X of integers (both positive and negative) and you need to find the maximum sum found in any contiguous subarray of X. Example X = [11, -12, 15, -3, 8, -9, 1, 8, 10, -2] Answer is 30. There are various methods to solve this problem, some are listed below Brute force maxSum = 0 for L = 1 to N { for R = L to N { sum = 0 for i = L to R { sum = sum + X[i] } maxSum = max(maxSum, sum) } } O(N^3) Quadratic Note that sum of [L..R] can be calculated from sum of [L..R-1] very easily. maxSum = 0 for L = 1 to N { sum = 0 for R = L to N
  • 17. { sum = sum + X[R] maxSum = max(maxSum, sum) } } Using divide-and-conquer O(N log(N)) maxSum(L, R) { if L > R then return 0 if L = R then return max(0, X[L]) M = (L + R)/2 sum = 0; maxToLeft = 0 for i = M downto L do { sum = sum + X[i] maxToLeft = max(maxToLeft, sum) } sum = 0; maxToRight = 0 for i = M to R do { sum = sum + X[i] maxToRight = max(maxToRight, sum) } maxCrossing = maxLeft + maxRight maxInA = maxSum(L,M) maxInB = maxSum(M+1,R) return max(maxCrossing, maxInA, maxInB) } Here is working C code for all the above cases #include<stdio.h>
  • 18. #define N 10 int maxSubSum(int left, int right); int list[N] = {11, -12, 15, -3, 8, -9, 1, 8, 10, -2}; int main() { int i,j,k; int maxSum, sum; /*--------------------------------------- * CUBIC - O(n*n*n) *---------------------------------------*/ maxSum = 0; for(i=0; i<N; i++) { for(j=i; j<N; j++) { sum = 0; for(k=i ; k<j; k++) { sum = sum + list[k]; } maxSum = (maxSum>sum)?maxSum:sum; } } printf("nmaxSum = [%d]n", maxSum); /*------------------------------------- * Quadratic - O(n*n) * ------------------------------------ */ maxSum = 0; for(i=0; i<N; i++) { sum=0; for(j=i; j<N ;j++) { sum = sum + list[j]; maxSum = (maxSum>sum)?maxSum:sum; }
  • 19. } printf("nmaxSum = [%d]n", maxSum); /*---------------------------------------- * Divide and Conquer - O(nlog(n)) * -------------------------------------- */ printf("nmaxSum : [%d]n", maxSubSum(0,9)); return(0); } int maxSubSum(int left, int right) { int mid, sum, maxToLeft, maxToRight, maxCrossing, maxInA, maxInB; int i; if(left>right){return 0;} if(left==right){return((0>list[left])?0:list[left]);} mid = (left + right)/2; sum=0; maxToLeft=0; for(i=mid; i>=left; i--) { sum = sum + list[i]; maxToLeft = (maxToLeft>sum)?maxToLeft:sum; } sum=0; maxToRight=0; for(i=mid+1; i<=right; i++) { sum = sum + list[i]; maxToRight = (maxToRight>sum)?maxToRight:sum; } maxCrossing = maxToLeft + maxToRight; maxInA = maxSubSum(left,mid); maxInB = maxSubSum(mid+1,right); return(((maxCrossing>maxInA)?maxCrossing:maxInA)>maxInB?((maxCrossing>maxInA)?maxCrossi ng:maxInA):maxInB); }
  • 20. Note that, if the array has all negative numbers, then this code will return 0. This is wrong because it should return the maximum sum, which is the least negative integer in the array. This happens because we are setting maxSum to 0 initially. A small change in this code can be used to handle such cases.
  • 21. Study on the go; get high quality complete preparation courses now on your mobile!