SlideShare una empresa de Scribd logo
1 de 168
‘C’ Programming
Implement strcpy() function.
Method1: char *mystrcpy(char *dst, const char *src) {  char *ptr; ptr = dst;  while(*dst++=*src++);   return(ptr); }
The strcpy function copies src, including the terminating null character, to thelocation specified by dst.  No overflow checking is performed when strings are copied or appended.  The behavior of strcpy is undefined if the source and destination strings overlap.  It returns the destination string.  No return value is reserved to indicate an error.
The prototype of strcpy as per the C standards is  char *strcpy(char *dst, const char *src); const for the source, signifies that the function must not change the source string
Method2: char *my_strcpy(char dest[], const char source[]) {  int i = 0;  while (source[i] != '')   { dest[i] = source[i];   i++;  } dest[i] = '';  return(dest); }
Write C programs to implement the toupper() and the isupper() functions
toUpper() isUpper() int toUpper(int ch) {  if(ch>='a' && ch<='z')   return('A' + ch - 'a'); else  return(ch); } int isUpper(int ch) {  if(ch>='A' && ch <='Z')   return(1); //Yes, its upper!  else   return(0); // No, its lower! }
Write a C program to swap two variables without using a temporary variable
Method1: (The XOR) a ^= b ^= a ^= b; Method2: (The XOR) a=a+b; b=a-b; a=a-b;
When should a typecast be used?
There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly.  The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. structfoo *p = (structfoo *) malloc(sizeof(structfoo));
What do lvalue and rvalue mean?
An lvalue is an expression that could appear on the left-hand sign of an assignment (An object that has a location).  An rvalue is any expression that has a value (and that can appear on the right-hand sign of an assignment).
What is the difference between & and && operators and | and || operators?
& and | are bitwise AND and OR operators respectively. They are usually used to manipulate the contents of a variable on the bit level.  && and || are logical AND and OR operators respectively. They are usually used in conditionals.
What is sizeof()?  Function Operator
Function Operator sizeof() is a compile time operator.  To calculate the size of an object, we need the type information.
How to declare a pointer to a function?
int myfunc(); // The function. int (*fp)();  // Pointer to that function. fp = myfunc;  // Assigning the address of the function to the pointer. (*fp)();      // Calling the function. fp();         // Another way to call the function.
What are the common causes of pointer bugs?
Uninitialized pointers:  One of the easiest ways to create a pointer bug is to try to reference the value of a pointer even though the pointer is uninitialized and does not yet point to a valid address.  For example:  int *p; *p = 12;
The pointer p is uninitialized and points to a random location in memory when you declare it.  It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system.  When you say *p=12;, the program will simply try to write a 12 to whatever random location p points to. Make sure you initialize all pointers to a valid address before dereferencing them.
Invalid Pointer References:  An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block.  One way to create this error is to say p=q; when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference.  The only way to avoid this bug is to draw pictures of each step of the program and make sure that all pointers point somewhere.
Zero Pointer Reference:  A zero pointer reference occurs whenever a pointer pointing to zero is used in a statement that attempts to reference a block.  For example, if p is a pointer to an integer, the following code is invalid:  There is no block pointed to by p. Therefore, trying to read or write anything from or to that block is an invalid zero pointer reference.  p = 0; *p = 12;
How to declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
Declare it this way char *(*(*a[N])())();
Will C allow passing more or less arguments than required to a function?
It will not allow if the prototype is around.   It will ideally throw an error like Too many arguments  or Too few arguments But if the prototype is not around, the behavior is undefined.
Try this out #include <stdio.h> int foo(int a); int foo2(int a, int b); int main(int a) {  int (*fp)(int a);  a = foo();  a = foo2(1);  exit(0); } int foo(int a) {  return(a); } int foo2(int a, int b) {  return(a+b); }
What does printf() return?
Upon a successful return, the printf() function returns the number of characters printed (not including the trailing '' used to end output to strings).  If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '') which would have been written to the final string if enough space had been available.  Thus, a return value of size or more means that the output was truncated. If an output error is encountered, a negative value is returned.
Look at the code below.  What should X be replaced with inorder to get the output as "Hello World"?  void main() {    if(X) {  printf("Hello"); } else {  printf(" World");} }
#include <stdio.h> int main()  {  if(!printf("Hello")) {  printf("Hello"); } else {  printf(" World");  } }
Write a C program to count bits set in an integer.
#include <stdio.h> int CountSetBits(int n) {  int count = 0;  while(n) {   n &= (n-1);   ++count;  }  return count; } int main(void) {  int n;scanf("%d",&n);  printf("Number of set bits in %d is %d ", n, CountSetBits(n));  return 0; }
Write a C Program to calculate pow(x,n)
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("[%d]",pow(5,4)); }  printf("[%d]",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.
Write a code to return a string from a function
char *myfunc() {  char *temp = "string";  return temp; } int main() {  puts(myfunc ()); }
Write code to evaluate a polynomial.
typedefstruct node {  float cf;  float px;  float py; struct node *next; }mynode; float evaluate(mynode *head) {  float x,y,sum;  sum = 0; mynode *poly;  for(poly = head->next; poly !=    head; poly = poly->next) {  sum = sum + poly->cf * pow(x,  poly->px) * pow(y, poly->py); }   return(sum); }
Write a C program to convert from decimal to any base (binary, hex)
#include <stdio.h> #include <conio.h> void decimal_to_anybase(int,int); void main() { decimal_to_anybase(10, 2); decimal_to_anybase(255, 16);  getch(); } void decimal_to_anybase(int n, int base) {  int i, m, digits[1000], flag;  i=0;  printf("[%d] converted to base [%d] : ", n, base);
while(n) {  m=n%base;  digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m];  n=n/base;  i++; } //Eliminate any leading zeroes for(i--;i>=0;i--) {  if(!flag && digits[i]!='0')flag=1;  if(flag)printf("%c",digits[i]);  } }
How to fast multiply a number by 7?
(num<<3 - num) Same as, num*8 - num = num * (8-1) = num * 7
How can we sum the digits of a given number in single statement?
# include<stdio.h> void main() {  int num=123456;  int sum=0;  for(;num>0;sum+=num%10,num/=10); // This is   the "single line".  printf("sum = [%d]", sum); }
Given two strings A and B, how would you find out if the characters in B were a subset of the characters in A?
#include <stdio.h> #include <conio.h> int isSubset(char *a, char *b); int main(){  char str1[]="defabc";  char str2[]="abcfed";  if(isSubset(str1, str2)==0){   printf("Yes, characters in B=[%s] are a subset of characters in A=[%s]",str2,str1); }  else {   printf("No, characters in B=[%s] are not a subset of characters     in A=[%s]",str2,str1);  }  getch();  return(0); }
// Function to check if characters in "b" are a subset // of the characters in "a“ int isSubset(char *a, char *b) {  int letterPresent[256];  int i;  for(i=0; i<256; i++) letterPresent[i]=0;  for(i=0; a[i]!=''; i++) letterPresent[a[i]]++;  for(i=0; b[i]!=''; i++)   if(!letterPresent[b[i]])    return(1);  return(0); }
Write a program to print numbers from 1 to 100 without using loops!
void printUp(int startNumber, int endNumber) {  if (startNumber > endNumber)   return;  printf("[%d]", startNumber++); printUp(startNumber, endNumber); }
Write code to round numbers
(int)(num < 0 ? (num - 0.5) : (num + 0.5))
How to swap the two nibbles in a byte?
#include <stdio.h> unsigned char swap_nibbles(unsigned char c) {  unsigned char temp1, temp2;  temp1 = c & 0x0F;  temp2 = c & 0xF0;  temp1=temp1 << 4;  temp2=temp2 >> 4;  return(temp2|temp1); //adding the bits } int main(void) {  char ch=0x34;  printf("The exchanged value is %x",swap_nibbles(ch));  return 0;  }
Write a C program to reverse the words in a sentence in place. Like,  Input: I am a good girl Output: should be: lrigdoog a ma I
First reverse the whole string and then individually reverse the words #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 == '' || *x == ' ')   {    rev(y,x-1);    y = x+1;}   }
// Now print the final string....  printf("%s",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; } }
Write a C program to multiply two matrices.
// Matrix A (m*n) // Matrix B (n*k) // Matrix C (m*k) for(i=0; i<m; i++) {  for(j=0;j<k;j++) {   c[i][j]=0;  for(l=0;l<n;l++)   c[i][j] += a[i][l] * b[l][j];  } }
Is there something we can do in C but not in C++?  Declare variable names that are keywords in C++ but not C.
 #include <stdio.h> int main(void) {   int old, new=3;return 0; }
Write a C program for calculating the factorial of a number (use recursive function)
Here is a recursive C program int 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
If a character string is to be received through the keyboard which function would work faster?  gets scanf
gets
Consider the following piece of code and predict the output 100 4 2 99 void main() {  int i=100; clrscr();  printf("%d", sizeof(sizeof(i)));  getch();  }
2
Choose the correct output from the following code snippet. It prints "God is Great“ Run time error Compilation error No output void main() {  static int a,b;  if(a & b)  printf("God is Great"); }
No Output
Which of the following header file is required for strcpy () function? string.h strings.h stdio.h file.h
string.h
Choose the correct answer Main cannot be printed %p is an invalid control string Some address will be printed Compile time error main() {  Printf(“%p”,main); }
Some address will be printed
What error will the below function give on compilation? The function should be defined as int f(int a, int b) Redeclaration of a Missing parentheses in return f(int a, int b) {  int a;  a = 20;  return a; }
Redeclaration of a
Choose the correct output for the below code 123,201 121,200 120,201 120,199 main()  {  int x=45,y=78; clrscr();  x = y-- + x--;  y = ++y + ++x;  printf ("%d %d", x, y);  }
123,201
Consider the code snippet and choose the correct output 0 No Output Null 1 void main() {  static int i;  i = i+1;  printf("%d", i);  getch();  }
1
What is the output of the below code?  main(){  int a=10,*j;  void *k;   j=k=&a; j++;  k++; printf(" %u %u ",j,k); }
Compiler error: Cannot increment a void pointer Explanation: Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type.  No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers
What is the output of the below code? main() {  float i = 1.5;  switch(i)  {   case 1: printf(“1”);   case 2: printf(“2”);   default: printf(“0”); }}
Compiler Error: switch expression not integral Explanation:  Switch statements can be applied only to integral types.
What is the output of the below code? void main() { static int i;  while(i<=10)  (i>2)?i++:i--; printf(“%d”, i); }
32767 Explanation: Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--.  This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.
What is the output of the below code? main(){ char str1[] = ”some”;  char str2[] =”some”;  if (strcmp(str1,str2))    printf(“Strings are not equal”); }
No output
What is the output of the below code? main(){ char p[ ]="%d";  p[1] = 'c';  printf(p,65);}
A Explanation: Due to the assignment p[1] = ‘c’ the string becomes, “%c”.  Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.
What is the output of the below code? void main() { int i=5;  printf(“%d”,i=++i ==6); }
1 Explanation: The expression can be treated as i = (++i==6), because == is of higher precedence than = operator.  In the inner expression, ++i is equal to 6 yielding true (1).  Hence the result.
What is the output of the following code? main() {  int a[5] = {2,3};  printf(" "%d %d d"",a[2],a[3],a[4]); }
0 0 0
What will be the output of the below program? 4 3 No output 0 #include<stdio.h> #define MIN(x,y)(x<y)?x:y void main() {  int x = 3, y = 4,z;  z = MIN(x+y/2,y-1);  if(z>0)   printf("%d",z); }
3
Which of the following is correct about the statement given below? structure engine is nested within structure maruti structure maruti is nested within structure engine structure maruti is nested within structure bolts structure engine is nested within structure engine maruti.engine.bolts = 25;
structure engine is nested within structure maruti
Which of the following is the correct output for the program given below? 1 2 5 4 int fun(int); void main(){  int i = 3;  fun(i = fun(fun(i)));  printf("%d",i); } fun(int i){  i++;  return(i); }
5
Recursions works slower than loops True False
True
Choose the correct answer based on output from following piece of code 16, 25 9,49 Error in code 6,7 #define PRODUCT(x) (x*x) main() {  int i = 3,j,k;  j = PRODUCT (i++);  k = PRODUCT(++i);  printf(“%d %d”, j,k); }
9,49
Which of the following is the correct output for the given program? d Abcdefgh e Compile time error void main() { printf("%c","abcdefgh"[4]); }
e
Which of the following is the correct output for the program given below? 20 10 30 0 #include<stdio.h> void main() {  union var  {   int a, b;  };  union var v; v.a = 10; v.b = 20;  printf("%d",v.a); }
20
On opening a file for reading which of the following activities are performed? A pointer is set up which points to the first character in the file The disk is searched for existence of the file The file is brought into memory
a, b and c
The assignment operation X=Y means? l-value of Y is stored in l-value of X r-value of Y is stored in r- value of X r-value of Y is stored in l-value of X l-value of Y is stored in r-value of X
r-value of Y is stored in l-value of X
Which of the following statement is/are true? A char data type variable always occupies one byte independent of the system architecture. The sizeof operator is used to determine the amount of memory occupied by a variable. Only i Only ii Both i & ii Neither i nor ii
Only ii
Write down the equivalent pointer expression for referring element a[i][j][k][l] ?
a[i] == *(a+i) a[i][j] == *(*(a+i)+j) a[i][j][k] == *(*(*(a+i)+j)+k) a[i][j][k][l] == *(*(*(*(a+i)+j)+k)+l) Hence Final output is *(*(*(*(a+i)+j)+k)+l)
The preprocessor can trap the simple errors like missing declarations, nested comments or mismatch of braces. True False
False
What is the output of the below code? Syntax Error No Output Compiler Error hello #include main(){  struct xx {   int x=3;  char name[]=”hello”;  }; struct xx *s;
Compiler Error
What is the output of the below code? H Syntax error Compiler error E void main() {  char *p;  p=”Hello”;  printf(“%c”,*&*p); }
H
In the following code fp points to A Structure which contains a char pointer which points to the first character in the file The name of the file The First character in the file #include<stdio.h> main() { FILE *fp; fp=fopen("trail","r"); }
A Structure which contains a char pointer which points to the first character in the file
#include<stdio.h>main(){char line[80];scanf("%[^n]",line);printf("%s",line);} what will scanf do ? Compiler error terminates reading input into variable line after newline terminates reading input into variable line after entering ^n
Terminates reading input into variable line after newline
What is the output of the below code? void main(){ char s[ ]="Welcome"; int i; for(i=0;s[ i ];i++)   printf("%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}
WWWW eeee llll cccc oooo mmmm eeee
Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array.  Here s is the base address.  i is the index number/displacement from the base address.  So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].
What does the following program do? #include "math.h" main(){  int n,i,j,m;  printf("Enter any number "); scanf("%d", &n);  for(i=1;i<=n;i++)  {   m=(int)(sqrt(i));   for(j=1; j<=m;j++)     if(func(i,j)!=1)        break; if(j==m+1)    printf("%d", i);  } } int func(int u, int v){  int min,i,val;  min = (u<v?u:v);  for(i=1;i<min;i++)   if(u%i==0&&v%i==0)    val = i;  return(val);  }
It will print the list of all primary numbers less than or equal to a given number n
You have given 1000 integers to sort. But, your RAM accommodates maximum of 100 integers only. How do your sort them?
We have to use external sorting (by tapes, disks etc.) mechanism.  We can use merge sort for internal sorting iterations.
How to allocate and deallocate memory for char** ?
In the order, first construct the main objects, and then construct the internal objects Allocation char** pp = new char*[10];    for(int i=0;i<10;i++)        char*[i]=new char[100];
In the reverse order, first destruct the internal objects, then destruct the main object Deallocation    for(int i=0;i<10;i++)    delete [] char*[i];     delete[] pp;
What are the best data structures for insertion, deletion and search operations?
For Insertion and deletion - Linked list For search - Map (it is a height balanced Red-black tree. We can search in O(log n))
Describe two scenarios where an application will crash due to stack overflow.
The two most common causes  for a stack overflow is: (i) An infinite recursion  int f1(){  f2(); } int f2() {  f1();   } f1() calls f2(), which in turn calls f1() and so on. Eventually, the stack overflows.
(ii) An attempt to create a large array on the stack, for example: int main() {   int a[100000000]; // array is too large    int b =0; //b's address exceeds the stack's limits, error } If our program crashes due to a stack overflow, we need to check for infinite recursion or too large local objects
Can main function be overloaded? Explain.
No, only one type of calling is allowed in a program (with out arguments/with two arguments/ with three arguments)
How to count the number of set bits of an integer using that many number of iterations of for loop?
unsigned int v; // count the number of bits set in v unsigned int c; // c accumulates the total bits set in v for (c = 0; v; c++) {   v &= v - 1; // clear the least significant bit set }
What is the output of this program? #include <stdio.h> void main()  {        char s[20];       char *str = "SachinTendulker";       sscanf(str, "%s", s);        printf("%s", s);       sscanf(str+7, "%[duenTlk]", s);        printf("%s", s);       sscanf(str+15, "%[^Ganguly]", s);        printf("%s", s);  }
SachinTendulker Explanation: The above statement captures Sachin only into S, because of white space character. The above statement captures Tendulker into S freshly. Because the format specifier has wildcard character [duenTlk], which means the scanning of string would be done as long as the character is one among the list of characters(starting from str+7). when it encounters a new character which is not there in the list the reading stops. sscanf(str, "%s", s); sscanf(str+7, "%[duenTlk]", s);
The above statement captures  r into S freshly. Because the format specifier has wildcard character [^Ganguly], which means the scanning of string would be done as long as the character is not one among the list of characters(starting from str+15). when it encounters a new character which is there in the list(or when the null character occurs) the reading stops. sscanf(str+15, "%[^Ganguly]", s);
What is the output of the following program? main()    {  union abc     {    int a:1;    int b:1;    int c:1; int d:1;    int e:1;    int f:1;          int g:1;   int h:1;  };  abc X;  abc.a = abc.b = abc.c = abc.d = abc.e = abc.f =abc.g = abc.h = 1; printf("%d",X);   }
-1 Explanation: By default, X is signed and has sign bit 1. Therefore, it is stored in 2’s complement form.
Consider the following code: What is the scope difference between i and j? int i; static int j; main( )                {  }
Both i and j have global scope, but j cannot be accessed in the other modules(files)
How many times the following program would print India? main( ) {  printf("  India");  main(); }
Till stack does not overflow (Infinite loop)
What is heap?
The heap is where malloc(), calloc(), and realloc() get memory. Getting memory from the heap is much slower than getting it from the stack.  On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time  and deallocated in any order. Such memory is not deallocated automatically; you have to call free(). Recursive data structures are almost always implemented with memory from the heap.
What would be the output of the following program if the array begins at the location 65472? main( ) {   int a[3][4] = {                   1,2,3, 4,                   4,3,2,1,                   7,8,9,0                  };   printf( " %u %u ",a+1, &a+1); }
65488, 65520
Provide simple implementation of   int atoi(char* pStr)
int atoi(char* pStr) {  int iRetVal=0;  if (pStr){   while (*pStr && *pStr<= ‘9’ && *pStr>=’0’)   { iRetval = (iRetval*10) + (*pStr – ‘0’); pStr++;   }  }  return iRetval; }
What is the output of the below statement? printf(“%d”);
Garbage Value.  Because, when we write printf("%d",x); this means compiler will print the value of x.  But as here, there is nothing after %d so garbage value is given as an output.

Más contenido relacionado

La actualidad más candente

Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1smruti sarangi
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and QueuesBHARATH KUMAR
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structureeShikshak
 
Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductionsirshad17
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its FundamentalsHitesh Mohapatra
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structureTushar Aneyrao
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queuestech4us
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structuresNiraj Agarwal
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceTransweb Global Inc
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsHoang Nguyen
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : PointerS P Sajjan
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)Arvind Devaraj
 

La actualidad más candente (20)

Data structure
Data structureData structure
Data structure
 
Data structure using c module 1
Data structure using c module 1Data structure using c module 1
Data structure using c module 1
 
ADT STACK and Queues
ADT STACK and QueuesADT STACK and Queues
ADT STACK and Queues
 
Introduction of data structure
Introduction of data structureIntroduction of data structure
Introduction of data structure
 
Ch 1 intriductions
Ch 1 intriductionsCh 1 intriductions
Ch 1 intriductions
 
Data structures
Data structuresData structures
Data structures
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Linked list
Linked listLinked list
Linked list
 
Data Structure and its Fundamentals
Data Structure and its FundamentalsData Structure and its Fundamentals
Data Structure and its Fundamentals
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
Stacks & Queues
Stacks & QueuesStacks & Queues
Stacks & Queues
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Fundamentals of data structures
Fundamentals of data structuresFundamentals of data structures
Fundamentals of data structures
 
Data Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer ScienceData Structure & Algorithms | Computer Science
Data Structure & Algorithms | Computer Science
 
Chapter 11 ds
Chapter 11 dsChapter 11 ds
Chapter 11 ds
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Introduction to Data Structure : Pointer
Introduction to Data Structure : PointerIntroduction to Data Structure : Pointer
Introduction to Data Structure : Pointer
 
Data structures (introduction)
 Data structures (introduction) Data structures (introduction)
Data structures (introduction)
 
Data structure
 Data structure Data structure
Data structure
 

Destacado

Connecting the Dots-Webcon 2015
Connecting the Dots-Webcon 2015Connecting the Dots-Webcon 2015
Connecting the Dots-Webcon 2015Holli Beckman
 
Materials construcció
Materials construccióMaterials construcció
Materials construccióXisca Vindel
 
Jornada sobre periodisme i territori - Vilanova Digital #neixunnoudiari
Jornada sobre periodisme i territori - Vilanova Digital #neixunnoudiariJornada sobre periodisme i territori - Vilanova Digital #neixunnoudiari
Jornada sobre periodisme i territori - Vilanova Digital #neixunnoudiariNúria Escalona
 
Collaborative Solutions eHealth Event - Specialist Information Services
Collaborative Solutions eHealth Event - Specialist Information ServicesCollaborative Solutions eHealth Event - Specialist Information Services
Collaborative Solutions eHealth Event - Specialist Information ServicesCollaborative Solutions
 
Fisheries NSW (Fish Online) - Peter Brown
Fisheries NSW (Fish Online) - Peter Brown Fisheries NSW (Fish Online) - Peter Brown
Fisheries NSW (Fish Online) - Peter Brown Collaborative Solutions
 
Drupal: Mitigating Risk with Multiple Content Creators
Drupal: Mitigating Risk with Multiple Content CreatorsDrupal: Mitigating Risk with Multiple Content Creators
Drupal: Mitigating Risk with Multiple Content CreatorsiFactory
 
A letter from ny
A letter from nyA letter from ny
A letter from nyipbingles
 
03. Dept Overview: Industry Innovation & Investment
03. Dept Overview: Industry Innovation & Investment03. Dept Overview: Industry Innovation & Investment
03. Dept Overview: Industry Innovation & InvestmentCollaborative Solutions
 
Detecting Drug Effects in the Brain
Detecting Drug Effects in the BrainDetecting Drug Effects in the Brain
Detecting Drug Effects in the Brainhtstatistics
 
Pembuktian rumus-luas-lingkaran
Pembuktian rumus-luas-lingkaranPembuktian rumus-luas-lingkaran
Pembuktian rumus-luas-lingkaranAank Genit
 
Flynn web2.0presentation
Flynn web2.0presentationFlynn web2.0presentation
Flynn web2.0presentationlosyork1
 

Destacado (14)

Connecting the Dots-Webcon 2015
Connecting the Dots-Webcon 2015Connecting the Dots-Webcon 2015
Connecting the Dots-Webcon 2015
 
Materials construcció
Materials construccióMaterials construcció
Materials construcció
 
Jornada sobre periodisme i territori - Vilanova Digital #neixunnoudiari
Jornada sobre periodisme i territori - Vilanova Digital #neixunnoudiariJornada sobre periodisme i territori - Vilanova Digital #neixunnoudiari
Jornada sobre periodisme i territori - Vilanova Digital #neixunnoudiari
 
Technology in Tourism
Technology in TourismTechnology in Tourism
Technology in Tourism
 
Collaborative Solutions eHealth Event - Specialist Information Services
Collaborative Solutions eHealth Event - Specialist Information ServicesCollaborative Solutions eHealth Event - Specialist Information Services
Collaborative Solutions eHealth Event - Specialist Information Services
 
DIA DE LA MUJER 2014
DIA DE LA MUJER 2014DIA DE LA MUJER 2014
DIA DE LA MUJER 2014
 
Intuition: Leading Edge for You and Your Clients
Intuition: Leading Edge for You and Your ClientsIntuition: Leading Edge for You and Your Clients
Intuition: Leading Edge for You and Your Clients
 
Fisheries NSW (Fish Online) - Peter Brown
Fisheries NSW (Fish Online) - Peter Brown Fisheries NSW (Fish Online) - Peter Brown
Fisheries NSW (Fish Online) - Peter Brown
 
Drupal: Mitigating Risk with Multiple Content Creators
Drupal: Mitigating Risk with Multiple Content CreatorsDrupal: Mitigating Risk with Multiple Content Creators
Drupal: Mitigating Risk with Multiple Content Creators
 
A letter from ny
A letter from nyA letter from ny
A letter from ny
 
03. Dept Overview: Industry Innovation & Investment
03. Dept Overview: Industry Innovation & Investment03. Dept Overview: Industry Innovation & Investment
03. Dept Overview: Industry Innovation & Investment
 
Detecting Drug Effects in the Brain
Detecting Drug Effects in the BrainDetecting Drug Effects in the Brain
Detecting Drug Effects in the Brain
 
Pembuktian rumus-luas-lingkaran
Pembuktian rumus-luas-lingkaranPembuktian rumus-luas-lingkaran
Pembuktian rumus-luas-lingkaran
 
Flynn web2.0presentation
Flynn web2.0presentationFlynn web2.0presentation
Flynn web2.0presentation
 

Similar a C programming

Similar a C programming (20)

Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Unit 5 Foc
Unit 5 FocUnit 5 Foc
Unit 5 Foc
 
pointers 1
pointers 1pointers 1
pointers 1
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
string , pointer
string , pointerstring , pointer
string , pointer
 
C programm.pptx
C programm.pptxC programm.pptx
C programm.pptx
 
Input output functions
Input output functionsInput output functions
Input output functions
 
C Programming
C ProgrammingC Programming
C Programming
 
7 functions
7  functions7  functions
7 functions
 
Input And Output
 Input And Output Input And Output
Input And Output
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
2 data and c
2 data and c2 data and c
2 data and c
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
 
CSE240 Pointers
CSE240 PointersCSE240 Pointers
CSE240 Pointers
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Último (20)

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

C programming

  • 3. Method1: char *mystrcpy(char *dst, const char *src) { char *ptr; ptr = dst; while(*dst++=*src++); return(ptr); }
  • 4. The strcpy function copies src, including the terminating null character, to thelocation specified by dst. No overflow checking is performed when strings are copied or appended. The behavior of strcpy is undefined if the source and destination strings overlap. It returns the destination string. No return value is reserved to indicate an error.
  • 5. The prototype of strcpy as per the C standards is char *strcpy(char *dst, const char *src); const for the source, signifies that the function must not change the source string
  • 6. Method2: char *my_strcpy(char dest[], const char source[]) { int i = 0; while (source[i] != '') { dest[i] = source[i]; i++; } dest[i] = ''; return(dest); }
  • 7. Write C programs to implement the toupper() and the isupper() functions
  • 8. toUpper() isUpper() int toUpper(int ch) { if(ch>='a' && ch<='z') return('A' + ch - 'a'); else return(ch); } int isUpper(int ch) { if(ch>='A' && ch <='Z') return(1); //Yes, its upper! else return(0); // No, its lower! }
  • 9. Write a C program to swap two variables without using a temporary variable
  • 10. Method1: (The XOR) a ^= b ^= a ^= b; Method2: (The XOR) a=a+b; b=a-b; a=a-b;
  • 11. When should a typecast be used?
  • 12. There are two situations in which to use a type cast. The first use is to change the type of an operand to an arithmetic operation so that the operation will be performed properly. The second case is to cast pointer types to and from void * in order to interface with functions that expect or return void pointers. structfoo *p = (structfoo *) malloc(sizeof(structfoo));
  • 13. What do lvalue and rvalue mean?
  • 14. An lvalue is an expression that could appear on the left-hand sign of an assignment (An object that has a location). An rvalue is any expression that has a value (and that can appear on the right-hand sign of an assignment).
  • 15. What is the difference between & and && operators and | and || operators?
  • 16. & and | are bitwise AND and OR operators respectively. They are usually used to manipulate the contents of a variable on the bit level. && and || are logical AND and OR operators respectively. They are usually used in conditionals.
  • 17. What is sizeof()? Function Operator
  • 18. Function Operator sizeof() is a compile time operator. To calculate the size of an object, we need the type information.
  • 19. How to declare a pointer to a function?
  • 20. int myfunc(); // The function. int (*fp)(); // Pointer to that function. fp = myfunc; // Assigning the address of the function to the pointer. (*fp)(); // Calling the function. fp(); // Another way to call the function.
  • 21. What are the common causes of pointer bugs?
  • 22. Uninitialized pointers: One of the easiest ways to create a pointer bug is to try to reference the value of a pointer even though the pointer is uninitialized and does not yet point to a valid address. For example: int *p; *p = 12;
  • 23. The pointer p is uninitialized and points to a random location in memory when you declare it. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system. When you say *p=12;, the program will simply try to write a 12 to whatever random location p points to. Make sure you initialize all pointers to a valid address before dereferencing them.
  • 24. Invalid Pointer References: An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block. One way to create this error is to say p=q; when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference. The only way to avoid this bug is to draw pictures of each step of the program and make sure that all pointers point somewhere.
  • 25. Zero Pointer Reference: A zero pointer reference occurs whenever a pointer pointing to zero is used in a statement that attempts to reference a block. For example, if p is a pointer to an integer, the following code is invalid: There is no block pointed to by p. Therefore, trying to read or write anything from or to that block is an invalid zero pointer reference. p = 0; *p = 12;
  • 26. How to declare an array of N pointers to functions returning pointers to functions returning pointers to characters?
  • 27. Declare it this way char *(*(*a[N])())();
  • 28. Will C allow passing more or less arguments than required to a function?
  • 29. It will not allow if the prototype is around. It will ideally throw an error like Too many arguments or Too few arguments But if the prototype is not around, the behavior is undefined.
  • 30. Try this out #include <stdio.h> int foo(int a); int foo2(int a, int b); int main(int a) { int (*fp)(int a); a = foo(); a = foo2(1); exit(0); } int foo(int a) { return(a); } int foo2(int a, int b) { return(a+b); }
  • 32. Upon a successful return, the printf() function returns the number of characters printed (not including the trailing '' used to end output to strings). If the output was truncated due to this limit then the return value is the number of characters (not including the trailing '') which would have been written to the final string if enough space had been available. Thus, a return value of size or more means that the output was truncated. If an output error is encountered, a negative value is returned.
  • 33. Look at the code below. What should X be replaced with inorder to get the output as "Hello World"? void main() { if(X) { printf("Hello"); } else { printf(" World");} }
  • 34. #include <stdio.h> int main() { if(!printf("Hello")) { printf("Hello"); } else { printf(" World"); } }
  • 35. Write a C program to count bits set in an integer.
  • 36. #include <stdio.h> int CountSetBits(int n) { int count = 0; while(n) { n &= (n-1); ++count; } return count; } int main(void) { int n;scanf("%d",&n); printf("Number of set bits in %d is %d ", n, CountSetBits(n)); return 0; }
  • 37. Write a C Program to calculate pow(x,n)
  • 38. 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("[%d]",pow(5,4)); } printf("[%d]",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))); } }
  • 39. 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.
  • 40. Write a code to return a string from a function
  • 41. char *myfunc() { char *temp = "string"; return temp; } int main() { puts(myfunc ()); }
  • 42. Write code to evaluate a polynomial.
  • 43. typedefstruct node { float cf; float px; float py; struct node *next; }mynode; float evaluate(mynode *head) { float x,y,sum; sum = 0; mynode *poly; for(poly = head->next; poly != head; poly = poly->next) { sum = sum + poly->cf * pow(x, poly->px) * pow(y, poly->py); } return(sum); }
  • 44. Write a C program to convert from decimal to any base (binary, hex)
  • 45. #include <stdio.h> #include <conio.h> void decimal_to_anybase(int,int); void main() { decimal_to_anybase(10, 2); decimal_to_anybase(255, 16); getch(); } void decimal_to_anybase(int n, int base) { int i, m, digits[1000], flag; i=0; printf("[%d] converted to base [%d] : ", n, base);
  • 46. while(n) { m=n%base; digits[i]="0123456789abcdefghijklmnopqrstuvwxyz"[m]; n=n/base; i++; } //Eliminate any leading zeroes for(i--;i>=0;i--) { if(!flag && digits[i]!='0')flag=1; if(flag)printf("%c",digits[i]); } }
  • 47. How to fast multiply a number by 7?
  • 48. (num<<3 - num) Same as, num*8 - num = num * (8-1) = num * 7
  • 49. How can we sum the digits of a given number in single statement?
  • 50. # include<stdio.h> void main() { int num=123456; int sum=0; for(;num>0;sum+=num%10,num/=10); // This is the "single line". printf("sum = [%d]", sum); }
  • 51. Given two strings A and B, how would you find out if the characters in B were a subset of the characters in A?
  • 52. #include <stdio.h> #include <conio.h> int isSubset(char *a, char *b); int main(){ char str1[]="defabc"; char str2[]="abcfed"; if(isSubset(str1, str2)==0){ printf("Yes, characters in B=[%s] are a subset of characters in A=[%s]",str2,str1); } else { printf("No, characters in B=[%s] are not a subset of characters in A=[%s]",str2,str1); } getch(); return(0); }
  • 53. // Function to check if characters in "b" are a subset // of the characters in "a“ int isSubset(char *a, char *b) { int letterPresent[256]; int i; for(i=0; i<256; i++) letterPresent[i]=0; for(i=0; a[i]!=''; i++) letterPresent[a[i]]++; for(i=0; b[i]!=''; i++) if(!letterPresent[b[i]]) return(1); return(0); }
  • 54. Write a program to print numbers from 1 to 100 without using loops!
  • 55. void printUp(int startNumber, int endNumber) { if (startNumber > endNumber) return; printf("[%d]", startNumber++); printUp(startNumber, endNumber); }
  • 56. Write code to round numbers
  • 57. (int)(num < 0 ? (num - 0.5) : (num + 0.5))
  • 58. How to swap the two nibbles in a byte?
  • 59. #include <stdio.h> unsigned char swap_nibbles(unsigned char c) { unsigned char temp1, temp2; temp1 = c & 0x0F; temp2 = c & 0xF0; temp1=temp1 << 4; temp2=temp2 >> 4; return(temp2|temp1); //adding the bits } int main(void) { char ch=0x34; printf("The exchanged value is %x",swap_nibbles(ch)); return 0; }
  • 60. Write a C program to reverse the words in a sentence in place. Like, Input: I am a good girl Output: should be: lrigdoog a ma I
  • 61. First reverse the whole string and then individually reverse the words #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);
  • 62. // Now swap each word within sentence... x = buf-1; y = buf; while(x++ < end) { if(*x == '' || *x == ' ') { rev(y,x-1); y = x+1;} }
  • 63. // Now print the final string.... printf("%s",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; } }
  • 64. Write a C program to multiply two matrices.
  • 65. // Matrix A (m*n) // Matrix B (n*k) // Matrix C (m*k) for(i=0; i<m; i++) { for(j=0;j<k;j++) { c[i][j]=0; for(l=0;l<n;l++) c[i][j] += a[i][l] * b[l][j]; } }
  • 66. Is there something we can do in C but not in C++? Declare variable names that are keywords in C++ but not C.
  • 67. #include <stdio.h> int main(void) { int old, new=3;return 0; }
  • 68. Write a C program for calculating the factorial of a number (use recursive function)
  • 69. Here is a recursive C program int 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
  • 70.
  • 71. If a character string is to be received through the keyboard which function would work faster? gets scanf
  • 72. gets
  • 73. Consider the following piece of code and predict the output 100 4 2 99 void main() { int i=100; clrscr(); printf("%d", sizeof(sizeof(i))); getch(); }
  • 74. 2
  • 75. Choose the correct output from the following code snippet. It prints "God is Great“ Run time error Compilation error No output void main() { static int a,b; if(a & b) printf("God is Great"); }
  • 77. Which of the following header file is required for strcpy () function? string.h strings.h stdio.h file.h
  • 79. Choose the correct answer Main cannot be printed %p is an invalid control string Some address will be printed Compile time error main() { Printf(“%p”,main); }
  • 80. Some address will be printed
  • 81. What error will the below function give on compilation? The function should be defined as int f(int a, int b) Redeclaration of a Missing parentheses in return f(int a, int b) { int a; a = 20; return a; }
  • 83. Choose the correct output for the below code 123,201 121,200 120,201 120,199 main() { int x=45,y=78; clrscr(); x = y-- + x--; y = ++y + ++x; printf ("%d %d", x, y); }
  • 85. Consider the code snippet and choose the correct output 0 No Output Null 1 void main() { static int i; i = i+1; printf("%d", i); getch(); }
  • 86. 1
  • 87. What is the output of the below code? main(){ int a=10,*j; void *k; j=k=&a; j++; k++; printf(" %u %u ",j,k); }
  • 88. Compiler error: Cannot increment a void pointer Explanation: Void pointers are generic pointers and they can be used only when the type is not known and as an intermediate address storage type. No pointer arithmetic can be done on it and you cannot apply indirection operator (*) on void pointers
  • 89. What is the output of the below code? main() { float i = 1.5; switch(i) { case 1: printf(“1”); case 2: printf(“2”); default: printf(“0”); }}
  • 90. Compiler Error: switch expression not integral Explanation: Switch statements can be applied only to integral types.
  • 91. What is the output of the below code? void main() { static int i; while(i<=10) (i>2)?i++:i--; printf(“%d”, i); }
  • 92. 32767 Explanation: Since i is static it is initialized to 0. Inside the while loop the conditional operator evaluates to false, executing i--. This continues till the integer value rotates to positive value (32767). The while condition becomes false and hence, comes out of the while loop, printing the i value.
  • 93. What is the output of the below code? main(){ char str1[] = ”some”; char str2[] =”some”; if (strcmp(str1,str2)) printf(“Strings are not equal”); }
  • 95. What is the output of the below code? main(){ char p[ ]="%d"; p[1] = 'c'; printf(p,65);}
  • 96. A Explanation: Due to the assignment p[1] = ‘c’ the string becomes, “%c”. Since this string becomes the format string for printf and ASCII value of 65 is ‘A’, the same gets printed.
  • 97. What is the output of the below code? void main() { int i=5; printf(“%d”,i=++i ==6); }
  • 98. 1 Explanation: The expression can be treated as i = (++i==6), because == is of higher precedence than = operator. In the inner expression, ++i is equal to 6 yielding true (1). Hence the result.
  • 99. What is the output of the following code? main() { int a[5] = {2,3}; printf(" "%d %d d"",a[2],a[3],a[4]); }
  • 100. 0 0 0
  • 101. What will be the output of the below program? 4 3 No output 0 #include<stdio.h> #define MIN(x,y)(x<y)?x:y void main() { int x = 3, y = 4,z; z = MIN(x+y/2,y-1); if(z>0) printf("%d",z); }
  • 102. 3
  • 103. Which of the following is correct about the statement given below? structure engine is nested within structure maruti structure maruti is nested within structure engine structure maruti is nested within structure bolts structure engine is nested within structure engine maruti.engine.bolts = 25;
  • 104. structure engine is nested within structure maruti
  • 105. Which of the following is the correct output for the program given below? 1 2 5 4 int fun(int); void main(){ int i = 3; fun(i = fun(fun(i))); printf("%d",i); } fun(int i){ i++; return(i); }
  • 106. 5
  • 107. Recursions works slower than loops True False
  • 108. True
  • 109. Choose the correct answer based on output from following piece of code 16, 25 9,49 Error in code 6,7 #define PRODUCT(x) (x*x) main() { int i = 3,j,k; j = PRODUCT (i++); k = PRODUCT(++i); printf(“%d %d”, j,k); }
  • 110. 9,49
  • 111. Which of the following is the correct output for the given program? d Abcdefgh e Compile time error void main() { printf("%c","abcdefgh"[4]); }
  • 112. e
  • 113. Which of the following is the correct output for the program given below? 20 10 30 0 #include<stdio.h> void main() { union var { int a, b; }; union var v; v.a = 10; v.b = 20; printf("%d",v.a); }
  • 114. 20
  • 115. On opening a file for reading which of the following activities are performed? A pointer is set up which points to the first character in the file The disk is searched for existence of the file The file is brought into memory
  • 116. a, b and c
  • 117. The assignment operation X=Y means? l-value of Y is stored in l-value of X r-value of Y is stored in r- value of X r-value of Y is stored in l-value of X l-value of Y is stored in r-value of X
  • 118. r-value of Y is stored in l-value of X
  • 119. Which of the following statement is/are true? A char data type variable always occupies one byte independent of the system architecture. The sizeof operator is used to determine the amount of memory occupied by a variable. Only i Only ii Both i & ii Neither i nor ii
  • 121. Write down the equivalent pointer expression for referring element a[i][j][k][l] ?
  • 122. a[i] == *(a+i) a[i][j] == *(*(a+i)+j) a[i][j][k] == *(*(*(a+i)+j)+k) a[i][j][k][l] == *(*(*(*(a+i)+j)+k)+l) Hence Final output is *(*(*(*(a+i)+j)+k)+l)
  • 123. The preprocessor can trap the simple errors like missing declarations, nested comments or mismatch of braces. True False
  • 124. False
  • 125. What is the output of the below code? Syntax Error No Output Compiler Error hello #include main(){ struct xx { int x=3; char name[]=”hello”; }; struct xx *s;
  • 127. What is the output of the below code? H Syntax error Compiler error E void main() { char *p; p=”Hello”; printf(“%c”,*&*p); }
  • 128. H
  • 129. In the following code fp points to A Structure which contains a char pointer which points to the first character in the file The name of the file The First character in the file #include<stdio.h> main() { FILE *fp; fp=fopen("trail","r"); }
  • 130. A Structure which contains a char pointer which points to the first character in the file
  • 131. #include<stdio.h>main(){char line[80];scanf("%[^n]",line);printf("%s",line);} what will scanf do ? Compiler error terminates reading input into variable line after newline terminates reading input into variable line after entering ^n
  • 132. Terminates reading input into variable line after newline
  • 133. What is the output of the below code? void main(){ char s[ ]="Welcome"; int i; for(i=0;s[ i ];i++) printf("%c%c%c%c",s[ i ],*(s+i),*(i+s),i[s]);}
  • 134. WWWW eeee llll cccc oooo mmmm eeee
  • 135. Explanation: s[i], *(i+s), *(s+i), i[s] are all different ways of expressing the same idea. Generally array name is the base address for that array. Here s is the base address. i is the index number/displacement from the base address. So, indirecting it with * is same as s[i]. i[s] may be surprising. But in the case of C it is same as s[i].
  • 136. What does the following program do? #include "math.h" main(){ int n,i,j,m; printf("Enter any number "); scanf("%d", &n); for(i=1;i<=n;i++) { m=(int)(sqrt(i)); for(j=1; j<=m;j++) if(func(i,j)!=1) break; if(j==m+1) printf("%d", i); } } int func(int u, int v){ int min,i,val; min = (u<v?u:v); for(i=1;i<min;i++) if(u%i==0&&v%i==0) val = i; return(val); }
  • 137. It will print the list of all primary numbers less than or equal to a given number n
  • 138. You have given 1000 integers to sort. But, your RAM accommodates maximum of 100 integers only. How do your sort them?
  • 139. We have to use external sorting (by tapes, disks etc.) mechanism. We can use merge sort for internal sorting iterations.
  • 140. How to allocate and deallocate memory for char** ?
  • 141. In the order, first construct the main objects, and then construct the internal objects Allocation char** pp = new char*[10]; for(int i=0;i<10;i++) char*[i]=new char[100];
  • 142. In the reverse order, first destruct the internal objects, then destruct the main object Deallocation for(int i=0;i<10;i++) delete [] char*[i]; delete[] pp;
  • 143. What are the best data structures for insertion, deletion and search operations?
  • 144. For Insertion and deletion - Linked list For search - Map (it is a height balanced Red-black tree. We can search in O(log n))
  • 145. Describe two scenarios where an application will crash due to stack overflow.
  • 146. The two most common causes for a stack overflow is: (i) An infinite recursion int f1(){ f2(); } int f2() { f1(); } f1() calls f2(), which in turn calls f1() and so on. Eventually, the stack overflows.
  • 147. (ii) An attempt to create a large array on the stack, for example: int main() { int a[100000000]; // array is too large int b =0; //b's address exceeds the stack's limits, error } If our program crashes due to a stack overflow, we need to check for infinite recursion or too large local objects
  • 148. Can main function be overloaded? Explain.
  • 149. No, only one type of calling is allowed in a program (with out arguments/with two arguments/ with three arguments)
  • 150. How to count the number of set bits of an integer using that many number of iterations of for loop?
  • 151. unsigned int v; // count the number of bits set in v unsigned int c; // c accumulates the total bits set in v for (c = 0; v; c++) { v &= v - 1; // clear the least significant bit set }
  • 152. What is the output of this program? #include <stdio.h> void main() { char s[20]; char *str = "SachinTendulker"; sscanf(str, "%s", s); printf("%s", s); sscanf(str+7, "%[duenTlk]", s); printf("%s", s); sscanf(str+15, "%[^Ganguly]", s); printf("%s", s); }
  • 153. SachinTendulker Explanation: The above statement captures Sachin only into S, because of white space character. The above statement captures Tendulker into S freshly. Because the format specifier has wildcard character [duenTlk], which means the scanning of string would be done as long as the character is one among the list of characters(starting from str+7). when it encounters a new character which is not there in the list the reading stops. sscanf(str, "%s", s); sscanf(str+7, "%[duenTlk]", s);
  • 154. The above statement captures r into S freshly. Because the format specifier has wildcard character [^Ganguly], which means the scanning of string would be done as long as the character is not one among the list of characters(starting from str+15). when it encounters a new character which is there in the list(or when the null character occurs) the reading stops. sscanf(str+15, "%[^Ganguly]", s);
  • 155. What is the output of the following program? main() { union abc { int a:1; int b:1; int c:1; int d:1; int e:1; int f:1; int g:1; int h:1; }; abc X; abc.a = abc.b = abc.c = abc.d = abc.e = abc.f =abc.g = abc.h = 1; printf("%d",X); }
  • 156. -1 Explanation: By default, X is signed and has sign bit 1. Therefore, it is stored in 2’s complement form.
  • 157. Consider the following code: What is the scope difference between i and j? int i; static int j; main( ) { }
  • 158. Both i and j have global scope, but j cannot be accessed in the other modules(files)
  • 159. How many times the following program would print India? main( ) { printf(" India"); main(); }
  • 160. Till stack does not overflow (Infinite loop)
  • 162. The heap is where malloc(), calloc(), and realloc() get memory. Getting memory from the heap is much slower than getting it from the stack. On the other hand, the heap is much more flexible than the stack. Memory can be allocated at any time and deallocated in any order. Such memory is not deallocated automatically; you have to call free(). Recursive data structures are almost always implemented with memory from the heap.
  • 163. What would be the output of the following program if the array begins at the location 65472? main( ) { int a[3][4] = { 1,2,3, 4, 4,3,2,1, 7,8,9,0 }; printf( " %u %u ",a+1, &a+1); }
  • 165. Provide simple implementation of int atoi(char* pStr)
  • 166. int atoi(char* pStr) { int iRetVal=0; if (pStr){ while (*pStr && *pStr<= ‘9’ && *pStr>=’0’) { iRetval = (iRetval*10) + (*pStr – ‘0’); pStr++; } } return iRetval; }
  • 167. What is the output of the below statement? printf(“%d”);
  • 168. Garbage Value. Because, when we write printf("%d",x); this means compiler will print the value of x. But as here, there is nothing after %d so garbage value is given as an output.