बिजनेस मार्केटिंग का लो कॉस्ट फंडा , अपने मोबाइल से ऑटो sms भेजकर मार्केटिंग करे विजिट करे http://autotextsms.com/ बिजनेस मार्केटिंग का लो कॉस्ट फंडा http://autotextsms.com/

Search This Blog

Translate

Showing posts with label Explain Array in c. Show all posts
Showing posts with label Explain Array in c. Show all posts

MCA C import Theory interview Question with answers



1.    Explain various Data Types in C Language?
A C language programmer has to tell the system the type of numbers or characters he is using in his program. These are data types. There are many data types in C language. Data types are used to store various types of data.
C has a concept of 'Data types' which are used to define a variable before its use. C supports various data types such as character, integer and floating-point types.
All the data types are made up of units of memory called bytes.
In order of size, starting with the smallest, the integer types are char, short, int, longetc. The smaller types take less memory, the larger types takes more space in memory,.
C has different data types for different types of data and they are classified as:
I) Primary Data Type   II) Secondary Data Types



Primary Data Types:
I) Primary Data Type _____________________________1. Integer Data Type:
Integers are whole numbers with a range of values,generally an integer occupies 2 bytes memory space and its value range limited to -32768 to +32768. To control the range of numbers and
storage space, C has three classes of integer storage namely short int, intand long int. All three data types
have signed and unsigned forms. Integer Data Types are denoted by int. 
Syntax For Integer Data Type
int;
For Example :
inta;
short intb;
long intnum;
Memory Occupied By Integer :short int (1 Byte),int (2 Bytes),long int (4 Bytes) ____________________________________
a)    Long integer: long integer is a data type that can represent a whole number whose range is greater than or equal to that of a standard integer. The  range of long integer is -2147483648 to 2147483647.
Declaration of long int:longintcolor;    OR longcolor; _______________________________
b)   Short Integer:The range of short int is -32768 to -32767.'shortint' should assign less than or the same amount of storage as an 'int' and the 'int' should be less or the same bytes than a 'long int'. shortint must be at least 16 bits long.
Declaration of short int :shortintyellow; _______________________________
c)    Unsigned Integer:unsignedint has a range of 0 - 65535. "int" can be negative, but "unsigned int" cannot be negative. %u Prints an unsigned integer. The size can range from 2 to 8, or (again) whatever the implementation provides.
Declaration of unsigned integer :unsignedintx;ORunsignedchargrey; ___________________________
d)   Signed Integer:%d Prints a signed integer. Range of signed int is -32768 to 32767.
Declaration of signed integer :signed inty; signed charwhite;
________________________________
2. Floating Point Types:
The float data type is used to store fractional numbers (real numbers).
Floating point numbers are denoted by the keywordfloat. The double is same as float but it takes double space (8 bytes) than float.
Syntax For Floating Point Types: float ;
For Example:
float num1;
double num2;
long double num3;
Memory Occupied by Float:float (4 bytes),double (8 bytes),long double (10bytes) ____________________________________
3. CharacterTypes:
Character type variable can hold a single character. As there are singed and
unsigned int (either short or long), in the same way there are signed and unsigned chars; both occupy
 1 byte each, but having different ranges. Unsigned characters have values between 0 and 255; signed characters have values from –128 to 127. Character is declared by char
Syntax For Character Types: char;

For Example :
char ch='m';
char name='P';
Types built out of primitive data types - linked list, queue, stack, etc. ____________________________________
What Is Signed and Unsigned Char in C
C allows the character type char to be signed or unsigned, depending on the platform and compiler.With an unsigned char, the variable c takes the value 255, but with a signed char it becomes -1. If the signed or unsigned version of char is explicitly required at certain points in a program, it can be specified using the declarations signed char or unsigned char.
Declaration of signed and unsigned char:
unsignedchargrey;signedcharwhite; ___________________________________


 II) Secondary Data Types

1. Arrays:
An array in C language is a collection ofsimilar data-type, means an array can hold value of a particular data type for which it has been declared. Arrays can be created from any of the C data-types int, float, and char. So an integer array can only hold integer values and cannot hold values other than integer.
Types of Arrays:
·         One DimensionalArray
·         Two Dimensional Array
·         Multi Dimensional Array
Declaration OfArrays :
Syntax : type var_name[size];
____________________________________
2.Structures:We used variable in our C program to store value but one variable can store only single piece information (an integer can hold only one integer value) and to store similar type of values we had to declare many variables.
We used array which can hold numbers of similar data type. But array too have some limitations, like in our real world application we deal with set of dissimilar data types and single array cannot store dissimilar data.


For example: Think about storing book information or product information, a product can have different information to store like
Product code (an integer), product name (a char array), product price (a float) etc.
 And to store 20 products information we can declare integer array for product code, 2D character array for storing product name and float array to store product price. This approach definitely achieves your goals, but try to consider these things too. What if you wanted to add more products than 20, what if you want to add more information on products like stock, discount, tax etc? It will become difficult to differentiate these variables with other variables declared for calculation etc.
To solve this problem C language has a unique data type called Structure. C structure is nothing but collection of different related data types. If we are using C structure then we are combining different related data types in one group so that we can use and manage those variables easily. Here related data type means, a structure holding information about book will contains variable and array related to book.


Syntax for Structures:
For Example:
structproducts
{
char name[20];
intstock;
float price;
}; _________________________________
Pointers :In C a pointer is a variable that points to or references a memory location in which data is stored. By usimg the pointer we change the content of the memory location.
Pointer Declaration :A pointer is a variable that contains the memory location of another variable. The asterisk tells the compiler that you are creating a pointer variable. Finally we have to give the name of the variable.

Syntax For Pointers : 

Syntax : type * variable name;
For Example :
int*ptr; float *string
________________________________
2.    Explain Storage Classes in C?
Define storage classes in c?
Every variable not only has a data type but also have a storage class. If don't specify any storage class of a variable in its declaration, the compiler will assume a storage class depending on the context in which the variable is used. Thus, variables have certain default storage classes. A variable name identifies some physical location within the computer where the string of bits representing the variable value is stored. There are basically two kinds of locations in a computer where such a value may be kept memory and CPU registers. It is the variable's storage class, which determines in which of these two locations the value is stored.
A variable storage class tells us
1) Where the variable would be stored.
2) What will be the initial value of the variable, if the initial value is not specifically assigned (i.e, the default initial value).
3) What is the scope of the variable, i.e., in which functions the value of the variable would be available.
4) What is the life of the variables; i.e., how long would the variable exist.

There are four storage classes in C.
a) Automatic storage class
b) Register storage class
c) Static storage class
d) External storage class


a) Automatic storage class:- These variables comes into existence whenever and wherever the variable is declared. These variables are also called as local variables, because these are available local to a function. The storage is in the memory and it has a default value, which is a garbage value. It is local to the block in which it has been declared and it life is till the control remains within the block in which the variable is defined. The key word used is 'auto'.

b) Register storage class:-The storage of this type of variables is in the CPU registers. It has a garbage value initially. The scope of the variable is it is local to the block in which the variable is defined. Its life is till the control remains in the block in which it is defined. A value stored in a CPU register cal always be accessed faster than the one which is stored in memory. Therefore, if a variable is used at many places in a program it is better to declare its storage class as register. A good example of frequently used variables is loop counters. The key word used is 'register'.

c) Static storage class:-The storage is in the memory and default initial value is zero. It is local to the block in which it has been defined. The value of the variable persists between different function calls. The value will not disappear once the function in which it has been declared becomes inactive. It is unavailable only when you come out the program. The key word used is 'static'.
main(){  value();  value ();  value();  getch(); }

value()
{
   static int a=5;
   a=a+2;
   printf("\n%d",a);
}

The output of the program is not 7,7,7 but it is, 7,9,11.
a)    Extern storage class:-The variable has a storage in the memory. Default initial value is zero. The scope of the variable is global. It is present as long as the program execution comes to an end. The keyword used is 'extern'.
class
Automatic
Register
Static

External
1.variable stored
memory

CPU registers.
memory
memory
2.Default value
garbage
garbage 
Zero
Zero
3.scope of the variable
It is local to the block in which it has been declared
is it is local to the block in which the variable is defined.
It is local to the block in which it has been defined
scope of the variable is global
4.life of the variables
life is till the control remains within the block in which the variable is defined
Its life is till the control remains in the block in which it is defined.
value of variable persists between different function calls
It is present as long as the program execution comes to an end
5.Keyword
'auto'.
'register'.
‘static’
‘extern’
3.    Explain Operators in C?
Different types of operators
Present in C are
1. Arithmetic operator
2. Relational Operators
3.Logical Operators
4.Assignment Operators
5.Increments and Decrement Operators
6.Conditional Operators
7.Bitwise Operators
8. Special Operators
Arithmetic Operators:

Arithmetic operators means do the all arithmetic operations like as addition, subtraction, multiplication , division, modules etc.
All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in C language. Unary operations operate on a singe operand, therefore the number 5 when operated by unary – will have the value –5.
Arithmetic Operators:
             Operator                                           Meaning

+        Addition or Unary Plus
 –       Subtraction or Unary Minus
 *       Multiplication
 /       Division
 %     Modulus Operator

Example:
#include//include header file stdio.h
void main()  // the start of the program
{
int numb1, num2, sum, sub, mul, div, mod;           //declaration of variables
scanf (“%d %d”, &num1, &num2);                      //inputs the operands

sum = num1+num2;    //addition and storing in sum.
printf(“\n Thu sum is = %d”, sum);            //display the output
sub = num1-num2;                                    //subtraction and storing in sub.
printf(“\n Thu difference is = %d”, sub);      //display the output
mul = num1*num2;                                    //multiplication storing in mul.
printf(“\n Thu product is = %d”, mul);              //display the output
div = num1/num2;     //division storing in div.
printf(“\n Thu division is = %d”, div);  
//display the output
mod = num1%num2;                                    //modulus and storing in mod.
printf(“\n Thu modulus is = %d”, mod);              //display the output
}
Integer Arithmetic

When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic.
  It always gives an integer as the result.
 Let x = 20 and y = 5 be 2 integer numbers.
Then the integer operation leads to the following results.
x+y=27
x–y=15
x*y=100
x%y=0
x/y=4
In integer division the fractional part is truncated
Floating point arithmetic

When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point
arithmetic.
The floating point results can be truncated according to the properties requirement.
The remainder operator is not applicable for floating point arithmeticoperands.
Let x=14.0 and y=4.0
then
x+y=18.0
x–y=10.0
x*y=56.0
x/y=3.50

Mixed mode arithmetic

When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is
called as mixed mode arithmetic.
If anyone operand is of real type then the result will always be real thus 15/10.0 = 1.5

2. Relational Operators

Often it is required to compare the relationship between operands and bring out a decision and program accordingly. This is when
The relational operator comes into picture.
C supports the following relational operators.

   Operator                          Meaning
<                                  is less than                   <=     isless than or equal to                is greater than
>=                 is greater than or equal to
  ==                               is equal to                                                 !=                          is not equal to

It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational operators.

A simple relational expression contains only one relational operator and takes the following form.

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given below is a list of
Examples of relational expressions and evaluated values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE


Relational expressions are used in decision making statements of C language such as if, while and for statements to decide
the course of action of a running program.

3. Logical Operators
C has the following logical operators, they compare or evaluate logical and relational expressions.
                                      Operator                            Meanings
                                          &&                                          Logical AND
                                            ||                                              Logical OR
                                            !                                             Logical NOT

Logical AND (&&) :
This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true.
Example:      a>b && x==10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||) :
The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true.
Example :      a

The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.
Logical NOT (!) :
The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression.
For example:
! (x >= y) the NOT expression evaluates to true only if the value of x is neither greater than or equal to y

4. Assignment Operators
The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression.
Example :   x = a + b
Here the value of a + b is evaluated and substituted to the variable x.

In addition, C has a set of shorthand assignment operators of the form.
Varoper = exp;

Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper = is known as shorthand assignment operator


Example :
x + = 1 is same as x = x + 1
The commonly used shorthand assignment operators are as follows

Shorthand assignment operators

Statement with simple Statement with
assignment operator  shorthand operator


     a = a + 1                          a += 1
     a = a – 1                            a -= 1
     a = a * (n+1)                a *= (n+1)
     a = a / (n+1)                 a /= (n+1)
     a = a % b                       a %= b
Example for using shorthand assignment operator

#define N 100                      //creates a variable N with constant value 100
#define A 2                         //creates a variable A with constant value 2
main()                               //start of the program
{
int a;                              //variable a declaration
a = A;                              //assigns value 2 to a
while (a < N)                       //while value of a is less than N
{                                   //evaluate or do the following
printf(“%d \n”,a);                    //print the current value of a
a *= a;                             //shorthand form of a = a * a
                                  //end of the loop
}                                   //end of the program
Output :
2
4
16
_______________________________
4.    Explain Various File Related Function
Or
Any Two Input Output Functions
For files
    Different File Related Functions as Follows   fputc( ) ,  fgetc() , getc() , putc() , fputs( ),fgets()
fputc():  this function writes a character to a specified file at the current file position and then increment the file position pointer .The putc() macro acts essentially identically to fputc(), but is a macro  that expands in-line.  It may evaluate stream more than once, so arguments given to putc() should not be expressions with potential side effects.
 
Syntax:     intfputc(int c, FILE *fp);
Return:    The fputc function returns an integer representing  the character written. If a write error occurs the error indicator is set and fputc returns EOF. .
/* program to  understand the use of fputc( ) function */
#include
void main()
{
FILE *p;
char ch;
if((p==fopen("myfile.txt","w"))==NULL)
{
printf("this file does not exist\n");
exit()
}
else
{
printf("enter the text")
while((ch==getchar())!=EOF)
fputc(ch,p);
}
fclose(p);
}
 
fgetc() Function :   fgetc() is a character oriented function.this function reads the single character  from a given file and increment the file pointer position. On success it return the character after converting it. it to an int without sign extension. on error it return EOF .
Syntax:  intfgetc(FILE *stream );
Return:  If successful, it  return the next requested object from the stream. Character values are returned as

anunsigned char converted to an int. If the stream is at end-of-file or a read error occurs, then it  returnEOF.
/* program to understand the use of fgetc( ) function */.
#include

void main()
{
int c; /* Character read from the file.           */
  FILE *ptr;/* Pointer to the file. FILE is a structure  defined in */

                                                
ptr = fopen("Ritu.txt","r");
/* Read one character at a time, checking
for the End of File. EOF is defined in   as -1 */
while ((c = fgetc(ptr)) != EOF)
  {
printf("%c",c);     /* O/P the character to the screen   */
  }

fclose(ptr); /* Close the file.                                   */
} 
getc( ) function and putc( ) function :   The getc( ) and putc( )  are exactly similar to that of fgetc( ) and fputc( ).The putc function writes the character contained in character variable c to the file associated with the pointer fp1.
Syntax:  intputc (intch, FILE *file)
 ex ..     putc(c,fp1);
Syntax:       intgetc (FILE *file) .
The getc() function takes the file pointer as its argument, reads in the next character from the file and returns that character as a integer or EOF when it reaches the end of the file. The integer returned can easily type cast into a character variable for your use.Thegetc function acts essentially identically to fgetc, but is a macro that expands in-line.

/ Program to Read/Write using getc( ) and putc( ) */
 #include
void main()
{
file *fp1;
char c;
fp1=fopen("myfile.txt","w")
while((c=getchar())!=EOF)
{
putc(c,fp1);
}
fclose(fp1);
fp1=fopen("myfile.txt","r")
while((c=getc(fp1))!=EOF)
{
printf("%c",c)
}
fclose(fp1);
}
fputs( ) function :
Declaration:          char * fputs(const char *str , FILE *stream);
The fputs( ) function writes the content of the string pointed to by str to the specified stream. The null terminator is not written. The fputs( ) function returns the last character written on success and EOF on failure.
/* program to understand the use of fputs( ) */
#include
void main()
{
FILE *fp1;
charstr[100];
fp1=fopen("rajesh.txt","w");
printf("enter the text\n")
if((gets(str)!=NULL))
fputs(str,fp1);
fclose(fp1);}
Declarations of fgets() Function:  char  *fgets(char *str, int n, FILE *fptr);
Here str is the base address where the string is to be stored, n is the number of characters to be stored and fptr is a file pointer of type FILE structure which specifies the name of the file to which the input has to be read .The fgets() function reads characters from the current file pointer position upto and including the first new line character ‘\n’, upto the end of the stream, or until the number of characters read is equal to (n-1), whichever comes first. Now look at the second argument of fgets() function more carefully. This second argument is used to prevent fgets() from reading a too long string and overflowing the array.
 
fgets( ) function:   This function is used to read character from a file  and these characters are store in the string pointed to by str . Characters are read until either a newline or an EOF is received or until the specified limit is reached. After the character has been read, a null is stored in the array immediately after the last character is read. A newline character will be retained and will be a part of the array pointed to by str.
/* program to understand the use of fgets( ) */
#include
#include
void main()
{
            FILE *FP1;
            char name[100];
            fp1=fopen("rohit.txt","r");
            printf("enter the data")
                        while(fgets(name,80,fp1)!=NULL)
                        puts(name);
            fclose(fp1);
}
OUTPUT:master ofcomputer application
____________________________________
5.    Dynamic Memory Allocation
Or
Explain malloc(),calloc(),reallc(),
And free() function in C
         In dynamic memory management memory will be allocate at runtime. This is also known as  heap memory. Some language at the run time have ability to calculate and assign the memory space at run time for an array but c can't have this feature. But in C there is some function which provide the facility to allocate and deallocate the memory. In ,Local Memory, when these function will call memory will allocate automatically and when function will exit memory will deallocated automatically . In dynamic memory allocation ,allocation of memory is explicitly requested for a  particular size of block .For deallocation of memory explicitly requested.
the function through which the dynamic memory allocation and deallocation will performed are :
  1. malloc()
  2. calloc()
  3. free()
  4. realloc()
malloc():malloc()function allocate a block of byte of memory in byte. In this when the memory block needed explicitly requested. The malloc() function is same as a function is request for RAM in the system  memory. If the request is grant then a void pointerreturn and the pointer point start of that block. If the request fail then a NULL pointer return.
Example:
malloc( number of element * size of each element);
int * ptr;
ptr = malloc(10*sizeof(int));

Where size represents the memory required in bytes .The memory which is provided is contiguous memory. But malloc function return void pointer so it needed type casting of that pointer.
Examlpe:
(type cast)malloc( number of element * size of each element);

int * ptr;
ptr =(int*) malloc(10*sizeof(int));

similarly for allocation of memory to a structure variable :
Examlpe:
(struct name)malloc( sizeof(struct name));
struct employee
{
            intemp_id;
            charemp_name[20];
            floatemp_contact_no;

};
struct employee *ptr
ptr=(struct employee*)malloc(sizeof(struct employee));

2.calloc():In malloc requested memory is provided a block of contiguous memory .calloc() function  is similar to the malloc rather then calloc() function
allocated the memory block for an array of elements. Memory for a group of objects used calloc() function. If calloc() function is executed succesfully then its allocated memory  is set as zero and a pointer  returned and if the function failed then a NULL pointer return.
Example:
void *calloc(size_tnumber,size_t size);
size_t used for unsigned on most compilers.The number is the number of objects which is allocate, and size is the size (in bytes) of each object.
int main ()
 {
intnumber,i;                
printf("Enter the number ");      
scanf("%d",&number);  
printf("Number which is here are",number);       
int *ptr = (int *) calloc (number,sizeof(int));       
for (i=0; i
{               
ptr[i] = i +i;
  }
for (i=0; i
{              
printf("Result is %d %d\n",i,ptr[i]);
 }
}

3. free ():
For deallocation of the memory which is allocated through the malloc() function and calloc() function used free() function.
Example:
free(ptr);
int main () {
      intnumber,i;
      printf("Enter the number ");
      scanf("%d",&number);
       printf("Number which is here are",number);
    for (i=0; i                                      ptr[i] = i +i;
                                     }                      for (i=0; i
                                       printf("Result is %d %d\n",i,ptr[i]);
                            }
 
    free(ptr);}
4.realloc()
realloc() function is used  for resize the size of memory block which is allocated by the malloc() and calloc () function.

Two situation where use realloc() function.               
·         When allocated block is insufficient need more memory then use realloc().
·         When allocated memory is much more then the required application then use realloc(). Example:

realloc(ptr, new size);
/* Through realloc() resize the memory . */

 #include
#include
#include
  {  char buffer[80], *msg;
    /* Input a string. */   

puts("Enter the text line");   
gets(buffer);
     /* The string copied in to initial allocated block */       
msg = realloc(NULL, strlen(buffur)+1);       
strcpy(msg, buffer);     
     /* Display the message which copied. */
puts(message);
       /* Get another string from the user. */    
puts("Enter another text line.");    ;
 gets(buffer);

     /* Resize the memory and also concatenate the string to it. */
   
msg = realloc(msg,(strlen(msg) + strlen(buffer)+1));    
        
strcat(msg, buffer);
     }


6.    Explain Various Loop Control structures in c
Or
Explain Do while, for, while
Loop present in c
Different loops
1.while loop
2. do while loop
3. for loop
a) all loops use same logical(true /false)
b) stop
1.While loop: while(something is true)
{
   (body of program)
}
If the loop condition is not true then at the beginning loop never executed
2.do while loop: do while loop is always executed once.do while loop statement allows you to execute code block in loop body at least one.
syntax:
 do {  // statements  } while (expression);
do {loop body}
  While loop(loop condition);

  Void main {
  do{
  printf(“hello world”);
  }
  while (4<1 br=""> for example using do while loop statement
#include
void main()
{  int x = 5;
int i = 0;
// using do while loop statement
do{ i++;
printf("%d\n",i);
}while(i < x);
 }
The program output
1
2
3
4
3. For loop:Thefor loop is used to implement any type of loopcondition. It is based on numeric variables.There are three parts which is separated by semi-colons in control block of the forloop.initialization_expression is executed before execution of the loop starts.
The execution of the loop continues until the loop_condition is false
Theincrement_expression, is usually used to increment the loop counter. This is executed at the end of each loop iteration.
for example of using for loop statement to print an integer five times


#include

    void main()
{
    // using for loop statement
    int max = 5;
    int i = 0;
     for(i = 0; i
 printf("%d\n",i);
    }
 }
And the output is
1
2
3
4
5

For Loop Example Using C
For example:
Void main()
{
intp,n,count;
float r, si;
for (count =3;count <=3;count=count ++ )
{
printf (“enter the value of p,n,r”);
scanf(“%d%d%f”,&p,&n,&r);
si =(p*n*r)/100;
printf(“simple interest =%f”,si);
}
getch();
}
nesting for loop: void main()
{
int r ,c,sum;
for(r =1;r<=3;r++)
{
for (c=1;c=2;c++)
{
sum =r+c;
printf(“r=%d,c=%d,sum=%d\n”,r,c,sum);
}
}
}

7.    Explain Continue and Break Statement in c
Continue Statement 
 continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions.
Void main ()
{
int r ,c;
for(r=1;r<=10;r++)
{
if (r==5)
Continue;
else
printf(“r=%d,\n”,r);
}
getch();
}

Break statement:
 break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately.
Void main()
{
int a;
for (a=1;a<=10;a++)
{
if (j==5)
Break;
else
printf(“%d\n”,a);
}
Printf(“hello”) // control pas here
getch();
}

8.Explain Bitwise Operators in C

Bitwise Operators ( &, |, ^, ~, <<, >> )


Bitwise operators modify variables or shifting the bit left or right patterns that represent the values they store.

 

operator asm equivalent description
& AND Bitwise AND
| OR Bitwise Inclusive OR
^ XOR Bitwise Exclusive OR
~ NOT Unary complement (bit inversion)
<< SHL Shift Left
>> SHR Shift Right

sizeof()

This operator will accept one parameter, which can be a variable itself and returns the size of it in bytes of that type or object.
a = sizeof (char);
This will assign the value 1 to a becausechar is a one-byte long type. The value returned by sizeof is a constant, so it is always determined before program execution.

9.ExpalinRECURSION
A function is called ‘recursive’ if a statement within the body of a function calls the same function. Sometimes called ‘circular definition’, recursion is thus the process of defining something in terms of itself.
example of recursion--
/*factorial of a number*/
main( )
{
int a, fact ;
printf ( "\nEnter any number " ) ;
scanf ( "%d", &a ) ;
fact = rec ( a ) ;
printf ( "Factorial value = %d", fact ) ;
}
rec ( int x )
{
int f ;
if ( x == 1 )
return ( 1 ) ;
else
f = x * rec ( x - 1 ) ;
return ( f ) ;
}

And here is the output for four runs of the program
Enter any number 1
Factorial value = 1
Enter any number 2
Factorial value = 2
Enter any number 3
Factorial value = 6
Enter any number 5
Factorial value = 120

explanation of the program-
 In the first run when the number enteredthrough scanf( ) is 1, let us see what action does rec( ) take. The value of a (i.e. 1) is copied into x. Since x turns out to be 1 the condition if ( x == 1 ) is satisfied and hence 1 (which indeed is the value of 1 factorial) is returned through the return statement. When the number entered through scanf( ) is 2, the ( x == 1 ) test
fails, so we reach the statement,
       f = x * rec ( x - 1 ) ;
And here is where we meet recursion. How do we handle the expression x * rec ( x - 1 )? We multiply x by rec ( x - 1 ). Since the current value of x is 2, it is same as saying that we must calculate the value (2 * rec ( 1 )). We know that the value returned by rec ( 1 ) is 1, so the expression reduces to (2 * 1), or simply 2. Thus the statement,
         x * rec ( x - 1 ) ;
evaluates to 2, which is stored in the variable f, and is returned to main( ), where it is duly printed as
       Factorial value = 2



10. Explain C PRE-PROCESSOR
It is a program that processes our source program before it is passed to the compiler.
 FEATURES OF PRE-PROCESSOR-
 The pre-processor offers several features called pre-processor directives. Each of these pre-processor directives begin with a # symbol. The directives can be placed anywhere in a program but are most often placed at the beginning of a program, before the first function definition.
We would learn the following pre-processor directives here:
(a) Macro expansion             
 (b) File inclusion  
(c) Conditional Compilation             
(d) Miscellaneous directives
MACRO EXPANSION
Have a look at the following program.
       
#define UPPER 25
            main( )
           {
           int i ;
           for ( i = 1 ; i <= UPPER ; i++ )
         printf ( "\n%d", i ) ;
          }


In this program instead of writing 25 in the for loop we are writing it in the form of UPPER, which has already been defined before main( ) through the statement,#define UPPER 25 This statement is called ‘macro definition’ or more commonly, just a ‘macro’. What purpose does it serve? During preprocessing, the preprocessor replaces every occurrence of UPPER in the program with 25.
When we compile the program, before the source code passes to the compiler it is examined by the C preprocessor for any macro definitions. When it sees the #define directive, it goes through the entire program in search of the macro templates; wherever it finds one, it replaces the macro template with the appropriate macro expansion.
In C programming it is customary to use capital letters for macro template. This makes it easy for programmers to pick out all the macro templates when reading through the program.
Note that a macro template and its macro expansion are separated by blanks or tabs. A space between # and define is optional. Remember that a macro definition is never to be terminated by a semicolon.

MACROS WITH ARGUMENT-
The macros that we have used so far are called simple macros. Macros can have arguments, just as functions can. Here is an example that illustrates this fact.

#define Area) ( 3.14 * x * x )
main( )
{
float r1 = 6.25, r2 = 2.5, a ;
a = AREA ( r1 ) ;
printf ( "\area of circle = %f", a ) ;
a = AREA ( r2 ) ;
printf ( "\area of circle = %f", a ) ;
}

Here’s the output of the program...
Area of circle = 122.656250
Area of circle = 19.625000

In this program wherever the pre-processor finds the phrase Area) it expands it into the statement( 3.14 * x * x ). However, that’s not all that it does. The x in the macro template Area) is an argument that matches the x in the macro expansion ( 3.14 * x * x ). The statement AREA(r1) in the program causes the variable r1 to be substituted for x. Thus the statement AREA(r1) is equivalent to: ( 3.14 * r1 * r1 )
After the above source code has passed through the pre-processor, what the compiler gets to work on will be this:
 

main( )
{
float r1 = 6.25, r2 = 2.5, a ;
a = 3.14 * r1 *r1 ;
printf ( "Area of circle = %f\n", a ) ;
a = 3.14 *r2 * r2 ;
printf ( "Area of circle = %f", a ) ;
}
Here is another example of macros with arguments:
#define ISDIGIT(y) ( y>= 48 && y <= 57 )
main( )
{
charch ;
printf ( "Enter any digit " ) ;
scanf ( "%c", &ch ) ;
if ( ISDIGIT ( ch ) )
printf ( "\nYou entered a digit" ) ;
else
printf ( "\nIllegal input" ) ;
}

11. Explain Array in c
Array by definition is a variable that hold multiple elements which has the same data type.Array is variables that hold multiple elements which has same data type.
An array is a multi element box, uses an indexing system
Declaring the array:  We can declare an array by specify its data type, name and the number of elements the array holds between square brackets immediately following the array name. Name;
Type of array
Number of element  "data type array name[size];"
There are some rules on array declaration. The data type can be any valid C data types including structure and union. The array name has to follow the rule of variable and the size of array has to be a positive constant integer.We can access array elements via indexes array_name[index]. Indexes of array starts from 0 not 1 so the highest elements of an array is array_name[size-1].
Initializing the array: It is like a variable, an array can be initialized. To initialize an array, you provide initializing values which are enclosed within curly braces in the declaration and placed following an equals sign after the array name.
int list[5]={2,3,4,5,6} OR  int list[5] = {2,1,3,7,8};
Character arrays:   char string1[]=”first”;, "Here ,we using char string and its array size is six."
char string[]={‘f’,’g’,’t’,’y’,’u’,’I’,’\0’};    //  \0 null character terminating the string.
Passing the array    To pass an array argument in a function specifies the name of array to pass without any bracket.
intmyarray[24];
myfunction(my array,24).
• array usually pass to the function
• array using call by refrence
• function knows where the array stored
Passing array element:
• using call by value
• pass subscripted name (ex: myarray[5]) to function.

Function prototype: void modify array (intb[],int array size);
Parameter name may be optional.
int b[] may be int[]
int array size may be int
Multidimensional Array: An array with more than one index value is called a multidimensional array. All the array above is called single-dimensional array. To declare a multidimensional array you can do follow syntax
data_typearray_name[][][];
The number of square brackets specifies the dimension of the array. For example to declare two dimensions integer array we can do as follows:
1. intmatrix[3][3];
Initializing Multidimensional Arrays
you can initialize an array as a single-dimension array. Here is an example of initialize an two dimensions integer array:

1. int matrix[3][3] =  { {11,12,13},
 {21,22,23},
{32,31,33},
 };
 Two dimensional arrays
Multidimensional array have two or more than indexs values which specify the element in the array. i.e., multi[i][j].
Where [i] specify row and [j] specify column
Declaration and calculation:
int a[10][10];
int b[2][2];   // int b [2][2]={{0,1},{2,3}}
Sum = a[10][10]+b[2][2]
Array and Pointer
Each array element occupies consecutive memory locations and array name is a pointer that points to the first element. Beside accessing array via index we can use pointer to manipulate array. This program helps you visualize the memory address each array elements and how to access array element using pointer.
#include
  void main()
 { 
constint size = 5; 
int list[size] = {2,1,3,7,8}; 
 int* plist = list;
 // print memory address of array elements
 for(int i = 0; i  {
 printf("list[%d] is in %d\n",i,&list[i]);
 } 
 // accessing array elements using pointer
 for(i = 0; i  {
 printf("list[%d] = %d\n",i,*plist); 
 /* increase memory address of pointer so it go to the next
 element of the array */
 plist++;
. }}
Here is the output
list[0] is in 1310568
list[1] is in 1310572
list[2] is in 1310576
list[3] is in 1310580
list[4] is in 1310584
list[0] = 2
list[1] = 1
list[2] = 3
list[3] = 7
list[4] = 8
You can store pointers in an array and in this case we have an array of
pointers. " int *ap[10];"
________________________________
12. Explain Random Access to file in C
 Random access means we can move to any part of a file and read or write data from it without having to read through the entirefile.  we can access the data stored in the file in two ways.
1.    sequentially 2.Randomly
if we want to access the forty fourth record then first forty three record read sequentially to reach forty four record .In random access data can be accessed  and processed directly .There is no need to read each record sequentially .if we want to   access a particular record random access takes less time than the sequential access.
C supports these function for random access file.
1.fseek( ) Function
2.ftell ( ) Function
How to use  fseek() function in C:
This function is used for setting the file position pointer at the specified bytes .fseek is a function  belonging to the ANCI C standard Library and included in the file stdio.h. Its purpose is to change the file position indicator for the specified stream.
Syntax :intfseek(FILE*stream_pointer, longoffset, intorigin);
Argument meaning:
  • stream_pointer is a pointer to the stream FILEstructure of which the position indicator should be changed;
  • offset is a long integer which specifies the number of bytes from origin where the position indicator should be placed;
  • origin is an integer which specifies the origin position. It can be:
    • SEEK_SET: origin is the start of the stream
    • SEEK_CUR: origin is the current position
    • SEEK_END: origin is the end of the stream
/* Program to understand the use of fseek function : */
#include
#include
#include
structemprecord
{
char name[30];
int age;
floatsal;
}emp;
void main()
{
int n;
FILE *fp;
fp=fopen("employee.dat","rb");
if (fp==NULL)
{
printf("/n error in opening file");
exit(1);
}
printf("enter the record no to be read");
scanf("%d",&n);
fseek(fp,(n-1)*sizeof(emp),0);
freed(&emp,sizeof(emp),1,fp);
printf("%s\t,emp.name);
printf("%d\t",emp.age);
printf("%f\n",emp.sal);
fclose(fp);
getch();
}
How to use ftell() Function in C:
This function return the current position of the file position pointer. The value is counted from the beginning of the file.
Syntax : long ftell (file * fptr);
/*program to understand the use of ftell ( )/*
#include
#include
#include
structemprecord
{
char name[30];
int age;
floatsal;
}emp;
void main()
{
FILE *fp;
fp=fopen("employee.dat","rb");
if (fp==NULL)
{
printf("/n error in opening file");
exit(1);
}
printf("position pointer in the beginning -> %1d ",ftell(fp));
while("fread(position pointer -> 1%d\n",ftell(fp));
printf("position pointer -> %1d\n",ftell(fp));
printf("%s\t",emp.name);
printf("%d\t",emp.age);
printf("%f",emp.sal);
}
printf("size of the file in bytes is %1d\n",ftell(fp));
fclose(fp);
getch();
}


13.Explain CLA or Command Line Argument in c
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:
void main ( intargc, 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

void main ( intargc, char *argv[] )
{
char x;
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 == NULL )
{
printf( "Could not open file\n" );
}
else
{ /* read one character at a time from file, stopping at EOF, whichindicates the end of the file.  Note that the idiom of "assignto a variable, check the value" used below works becausethe 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.

14. Explain Union in c
union is used to group a number of different variables together.
In structure number of different variables of different data type stored in different memory places but in union different variable of different data type are store in same place.
Example:

struct student
{
introllno;
char name[50];
float salary;
};

union student
{
introllno;
char name[50];
float salary;
};

C Program example List