Wednesday, July 11, 2012

C programming......


#include <stdio.h>
#include <stdlib.h>

struct NODE {
 int number;
 struct NODE *next;
};

int  search_value(struct NODE *llist, int num);
void append_node(struct NODE *llist, int num);
void display_list(struct NODE *llist);
void delete_node(struct NODE *llist, int num);

int main(void) {
 int num = 0;
 int input = 1;
 int retval = 0;
 struct NODE *llist;
  
 llist = (struct NODE *)malloc(sizeof(struct NODE));
 llist->number = 0;
 llist->next = NULL;
  
 while(input != 0) {
  printf("\n-- Menu Selection --\n");
  printf("0) Quit\n");
  printf("1) Insert\n");
  printf("2) Delete\n");
  printf("3) Search\n");
  printf("4) Display\n");
  scanf("%d", &input);

  switch(input) {
   case 0:
   default:
    printf("Goodbye ...\n");
    input = 0;
    break;
   case 1:
    printf("Your choice: `Insertion'\n");
    printf("Enter the value which should be inserted: ");
    scanf("%d", &num);
    append_node(llist, num);
    break;
   case 2:
    printf("Your choice: `Deletion'\n");
    printf("Enter the value which should be deleted: ");
    scanf("%d", &num);
    delete_node(llist, num);
    break;
   case 3:
    printf("Your choice: `Search'\n");
    printf("Enter the value you want to find: ");
    scanf("%d", &num);
    if((retval = search_value(llist, num)) == -1)
     printf("Value `%d' not found\n", num);
    else
     printf("Value `%d' located at position `%d'\n", num, retval);
    break;
   case 4:
    printf("You choice: `Display'\n");
    display_list(llist);
    break;
   } /* switch */
  } /* while */

 free(llist);
 return(0);
}

void display_list(struct NODE *llist) {
 while(llist->next != NULL) {
  printf("%d ", llist->number);
  llist = llist->next;
 }

 printf("%d", llist->number);
}

void append_node(struct NODE *llist, int num) {
 while(llist->next != NULL)
  llist = llist->next;

 llist->next = (struct NODE *)malloc(sizeof(struct NODE));
 llist->next->number = num;
 llist->next->next = NULL;
}

void delete_node(struct NODE *llist, int num) {
 struct NODE *temp;
 temp = (struct NODE *)malloc(sizeof(struct NODE));

 if(llist->number == num) {
  /* remove the node */
  temp = llist->next;
  free(llist);
  llist = temp;
 } else {
  while(llist->next->number != num)
   llist = llist->next;

  temp = llist->next->next;
  free(llist->next);
  llist->next = temp;
 }  
}

int search_value(struct NODE *llist, int num) {
 int retval = -1;
 int i = 1;

 while(llist->next != NULL) {
  if(llist->next->number == num)
   return i;
  else
   i++;

  llist = llist->next;
 }

 return retval;
}

Structure :

Structure is user defined data type which is used to store heterogeneous data under unique name. Keyword 'struct' is used to declare structure.
The variables which are declared inside the structure are called as 'members of structure'.
Syntax:

struct structure_nm
{
 <data-type> element 1;
 <data-type> element 2;
 - - - - - - - - - - -
 - - - - - - - - - - -
 <data-type> element n;
}struct_var;


Example :

struct emp_info
{
 char emp_id[10];
 char nm[100];
 float sal;
}emp;

Note : 1. Structure is always terminated with semicolon (;).
2. Structure name as emp_info can be later used to declare structure variables of its type in a program.

* Instances of Structure :

Instances of structure can be created in two ways as,
Instance 1:

struct emp_info
{
 char emp_id[10];
 char nm[100];
 float sal;
}emp;


Instance 2:

struct emp_info
{
 char emp_id[10];
 char nm[100];
 float sal;
};
struct emp_info emp;
In above example, emp_info is a simple structure which consists of stucture members as Employee ID(emp_id), Employee Name(nm), Employee Salary(sal).

* Aceessing Structure Members :

Structure members can be accessed using member operator '.' . It is also called as 'dot operator' or 'period operator'.
structure_var.member;

Program :


/*  Program to demonstrate structure.

Creation Date : 23 Nov 2010 02:41:01 AM

Author : www.technoexam.com [Technowell, Sangli] */

#include <stdio.h>
#include <conio.h>

struct comp_info
{
 char nm[100];
 char addr[100];
}info;

void main()
{
 clrscr();
 printf("\n Enter Company Name : ");
 gets(info.nm);
 printf("\n Enter Address : ");
 gets(info.addr);
 printf("\n\n Company Name : %s",info.nm);
 printf("\n\n Address : %s",info.addr);
 getch();
}


Structures in C defines the group of contiguous
(adjacent) fields, such as records or
control blocks. A structure is a collection of variables grouped 
together under
a single name. It provides an elegant and powerful way for keeping 
related
data together.
Structure Declaration:   

struct struct-name{
type field-name;
type field-name;
... };

Once the structure is defined, you can declare a structure variable by preceding the variable name by the structure type name. In the given example, a small structure i.e struct is created student and declared three instances of it as shown below.

struct student{
int id;
char *name;
float percentage;
}
 
In structures, we have assigned the values to the instances i.e, id, name, percentage in the following way:
student1.id=1;
student2.name = "Angelina";
student3.percentage = 90.5;

Here is the code:

STRUCTUR.C

#include <stdio.h>
#include <conio.h>

struct student {
  int id;
  char *name;
  float percentage;
student1, student2, student3;
int main() {
  struct student st;
  student1.id=1;
  student2.name = "Angelina";
  student3.percentage = 90.5;
  printf(" Id is: %d \n", student1.id);
  printf(" Name is: %s \n", student2.name);
  printf(" Percentage is: %f \n", student3.percentage);
  getch();
  return 0;
}
Output will be displayed as:
 

C interview questions – recursion, unions vs structures, storage allocation of variables.

by Madhulika Reddy on October 26, 2008

 
 
 
 
 
 
i
 
14 Votes
Quantcast
c interview questions Below are six of the most frequently asked C language questions in an entry level / experienced interview in software companies. Question.6 (recursion & factorial program) is frequently asked in fresher’s or entry level interview in C language. Recursion and factorial are interviewers’ favourite to start off in an interview. Question.7(binary to hex) is not purely a C language question. It tests whether the candidate is aware of hexa-decimal and binary representation. Binary and Hexa decimal representation is often used in Embedded System programming in C language. Question.8 is about the differences between structures and unions. Many confuse sturctures and unions. It is a good way to test whether the candidate knows the subtle differences between the both. Question.9 is about the memory advantage of Unions over structures. Question.10, 11 are the most essential basics for a C programmer viz. scope and storage allocation of variables. Any C programmer fairly acquainted with the language must be able to answer these two. See all C interview questions in this blog in one page.

  • What is recursion? Write a program using recursion (factorial)?
  • Recursion: A function is called ‘recursive’ if a statement within the body of a function calls the same function. It is also called ‘circular definition’. Recursion is thus a process of defining something in terms of itself. Program: To calculate the factorial value using recursion.
    #include <stdio.h>
    int fact(int n);
    
    int main() {
     int x, i;
     printf("Enter a value for x: \n");
     scanf("%d", &x);
     i = fact(x);
     printf("\nFactorial of %d is %d", x, i);
     return 0;
    }
    
    int fact(int n) {
     /* n=0 indicates a terminating condition */
     if (n <= 0) {
      return (1);
     } else {
      /* function calling itself */
      return (n * fact(n - 1));
      /*n*fact(n-1) is a recursive expression */
     }
    }
    Download Code
    Output:
    Enter a value for x: 4
    Factorial of 4 is 24
    Explanation:
    fact(n) = n * fact(n-1)
           If n=4
           fact(4) = 4 * fact(3)  there is a call to fact(3)
           fact(3) = 3 * fact(2)
           fact(2) = 2 * fact(1)
           fact(1) = 1 * fact(0)
           fact(0) = 1
    
           fact(1) = 1 * 1 = 1
           fact(2) = 2 * 1 = 2
           fact(3) = 3 * 2 = 6
           Thus fact(4) = 4 * 6 = 24
    Terminating condition(n <= 0 here;) is a must for a recursive program. Otherwise the program enters into an infinite loop.
    Back to top

    1. To which numbering system, can the binary number 1101100100111100 be easily converted to?
    2. 1101100100111100 can be easily converted to hexadecimal numbering system. Hexa-decimal integer constants consist of combination of digits from 0 to 9 and alphabets ‘A’ to ‘F’. The alphabets represent numbers 10 to 15 respectively. Hexa-decimal numbers are preceeded by ’0x’.
      1101,1001,0011,1100
            1101 = D
            1001 = 9
            0011 = 3
            1100 = C
      1101,1001,0011,1100 = 0xD93C
      Thus the given binary number 1101100100111100 in hexadecimal form is 0xD93C
      Back to top

    3. What are the differences between structures and unions?
    4. Structures and Unions are used to store members of different data types.
      STRUCTURE UNION
      a)Declaration:
      struct
        {
         data type member1;
         data type member2;
        };
      a)Declaration:
      union
        {
         data type member1;
         data type member2;
        };
      b)Every structure member is allocated memory when a structure variable is defined.
      Example:
      struct emp {
       char name[5];
       int age;
       float sal;
      };
      
      struct emp e1;
      Memory allocated for structure is 5+4+4=13 bytes(assuming sizeof int is 4, float is 4, char is 1). 5 byte for name, 4 bytes for age and 4 bytes for sal.
      b)The memory equivalent to the largest item is allocated commonly for all members.
      Example:
      union emp1 {
       char name[5];
       int age;
       float sal;
      };
      
      union emp1 e2;
      Memory allocated to a union is equal to size of the largest member. In this case, char name[5] is the largest-sized member. Hence memory allocated to this union is 5 bytes.
      c)All structure variables can be initialized at a time
      struct st {
       int a;
       float b;
      };
      struct st s = { .a=4, .b=10.5 };
      Structure is used when all members are to be independently used in a program.
      c)Only one union member can be initialized at a time
      union un {
       int a;
       float b;
      };
      
      union un un1 = { .a=10 };
      Union is used when members of it are not required to be accessed at the same time.
      Back to top

    5. What are the advantages of using unions?
    6. Union is a collection of data items of different data types.
      It can hold data of only one member at a time though it has members of different data types.
      If a union has two members of different data types, they are allocated the same memory. The memory allocated is equal to maximum size of the members. The data is interpreted in bytes depending on which member is being accessed.
      Example:
      union pen {
       char name;
       float point;
      };
      Here name and point are union members. Out of these two variables, ‘point’ is larger variable which is of float data type and it would need 4 bytes of memory. Therefore 4 bytes space is allocated for both the variables. Both the variables have the same memory location. They are accessed according to their type.
      Union is efficient when members of it are not required to be accessed at the same time.
      Back to top

    7. What is scope & storage allocation of global and extern variables? Explain with an example
    8. Extern variables: belong to the External storage class and are stored in the main memory. extern is used when we have to refer a function or variable that is implemented in other file in the same project. The scope of the extern variables is Global.
      Example:
      /***************
      Index: f1.c
      ****************/
      #include <stdio.h>
      extern int x;
      
      int main() {
       printf("value of x %d", x);
       return 0;
      }
      Download Code
      /***************
      Index: f2.c
      ****************/
      int x = 3;
      Here, the program written in file f1.c has the main function and reference to variable x. The file f2.c has the declaration of variable x. The compiler should know the datatype of x and this is done by extern definition.
      Global variables: are variables which are declared above the main( ) function. These variables are accessible throughout the program. They can be accessed by all the functions in the program. Their default value is zero.
      Example:
      #include <stdio.h>
      int x = 0;
      /* Variable x is a global variable.
      It can be accessed throughout the program */
      void increment(void) {
       x = x + 1;
       printf("\n value of x: %d", x);
      }
      
      int main(){
       printf("\n value of x: %d", x);
       increment();
       return 0;
      }
      Download Code
      Back to top

    9. What is scope & storage allocation of static, local and register variables? Explain with an example.
    10. Register variables: belong to the register storage class and are stored in the CPU registers. The scope of the register variables is local to the block in which the variables are defined. The variables which are used for more number of times in a program are declared as register variables for faster access.
      Example: loop counter variables.
      register int y=6;
      Static variables: Memory is allocated at the beginning of the program execution and it is reallocated only after the program terminates. The scope of the static variables is local to the block in which the variables are defined.
      Example:
      #include <stdio.h>
      void decrement(){
        static int a=5;
        a--;
        printf("Value of a:%d\n", a);
      }
      
      int main(){
       decrement();
       return 0;
      }
     

    ccepting command line arguments in C using argc and argv

    In C it is possible to accept command line arguments. Command-line arguments are given after the name of a program in command-line operating systems like DOS or Linux, and are passed in to the program from the operating system. To use command line arguments in your program, you must first understand the full declaration of the main function, which previously has accepted no arguments. In fact, main can actually accept two arguments: one argument is number of command line arguments, and the other argument is a full list of all of the command line arguments.



    The full declaration of main looks like this:
    int main ( int argc, char *argv[] )
    The integer, argc is the argument count. It is the number of arguments passed into the program from the command line, including the name of the program.

    The array of character pointers is the listing of all the arguments. argv[0] is the name of the program, or an empty string if the name is not available. After that, every element number less than argc is a command line argument. You can use each argv element just like a string, or use argv as a two dimensional array. argv[argc] is a null pointer.

    How could this be used? Almost any program that wants its parameters to be set when it is executed would use this. One common use is to write a function that takes the name of a file and outputs the entire text of it onto the screen.
    #include <stdio.h>
    
    int main ( int argc, char *argv[] )
    {
        if ( argc != 2 ) /* argc should be 2 for correct execution */
        {
            /* We print argv[0] assuming it is the program name */
            printf( "usage: %s filename", argv[0] );
        }
        else 
        {
            // We assume argv[1] is a filename to open
            FILE *file = fopen( argv[1], "r" );
    
            /* fopen returns 0, the NULL pointer, on failure */
            if ( file == 0 )
            {
                printf( "Could not open file\n" );
            }
            else 
            {
                int x;
                /* read one character at a time from file, stopping at EOF, which
                   indicates the end of the file.  Note that the idiom of "assign
                   to a variable, check the value" used below works because
                   the assignment statement evaluates to the value assigned. */
                while  ( ( x = fgetc( file ) ) != EOF )
                {
                    printf( "%c", x );
                }
                fclose( file );
            }
        }
    }
    This program is fairly short, but it incorporates the full version of main and even performs a useful function. It first checks to ensure the user added the second argument, theoretically a file name. The program then checks to see if the file is valid by trying to open it. This is a standard operation, and if it results in the file being opened, then the return value of fopen will be a valid FILE*; otherwise, it will be 0, the NULL pointer. After that, we just execute a loop to print out one character at a time from the file. The code is self-explanatory, but is littered with comments; you should have no trouble understanding its operation this far into the tutorial. :-)

    Structures in C and C++

    Declaring a Struct

    The syntax for a struct declaration differs between C and C++. Although the C version is still valid in C++, it is slightly clunkier.

    In C++:
    struct [struct_name]
    {
        type attribute;
        // ...
        [struct_name *struct_attribute;]
    } [instance1, [instance2, ...]];
    
    A struct declaration requires the keyword struct, optionally the name of the struct (see below), and a body consisting of one or more attributes. It is possible to optionally include a self-referential pointer, but not possible to include a struct of type struct_name (struct_name struct_attribute).

    If one or more structs is immediately desired, the entire declaration can be treated as a type, and the name of one or more instances may follow the declaration. In this case, it is possible to omit struct_name entirely, though this is not advisable.

    To declare a struct for use at any other point, the name of the struct, struct_name, can be used as though it were any other type.
    struct_name struct_instance [, instance2, ...];
    In C:
    [typedef] struct [struct_name]
    {
        type attribute;
        type attribute2;
        // ...
        [struct struct_name *struct_instance;]
    } [struct_name_t] [struct_instance];
    In this case, there are two options: the first is to omit both typedef and struct_name_t, in which case to declare a struct you will need to actually include the struct keyword:
    struct struct_name struct_instance;
    Or you can use a typedef to declare a struct_name_t type that you can use:
    struct_name_t struct_instance;
    In either case, if you wish to declare a pointer to a struct inside of the struct, you must use the first syntax, with the keyword struct:
    struct struct_name *struct_instance;

    No comments:

    Post a Comment