Best Industrial Training in C,C++,PHP,Dot Net,Java in Jalandhar

Tuesday, 18 March 2014

Test Your C Skills with Solution

1. 
How will you free the allocated memory ?
remove(var-name);
free(var-name);
delete(var-name);
dalloc(var-name);
 Answer: Option B

2. 
What is the similarity between a structure, union and enumeration?
A.
All of them let you define new values
B.
All of them let you define new data types
C.
All of them let you define new pointers
D.
All of them let you define new structures
Answer: Option B

3. What will be the output of the program ?
#include<stdio.h>

int main()
{
    union a
    {
        int i;
        char ch[2];
    };
    union a u;
    u.ch[0]=3;
    u.ch[1]=2;
    printf("%d, %d, %d\n", u.ch[0], u.ch[1], u.i);
    return 0;
}
Answer: Option A
Explanation:
The system will allocate 2 bytes for the union.
The statements u.ch[0]=3; u.ch[1]=2; store data in memory as given below.












4. #include<stdio.h>

int main()
{
    union var
    {
        int a, b;
    };
    union var v;
    v.a=10;
    v.b=20;
    printf("%d\n", v.a);
    return 0;
}
Answer: Option B
5. Point out the error in the program?
struct emp
{
    int ecode;
    struct emp *e;
};

Error: in structure declaration
Linker Error
No Error
None of above


Answer: Option C

6.If the two strings are identical, then strcmp() function returns
-1
1
0
Yes
Answer: Option C
Explanation:
Declaration: strcmp(const char *s1, const char*s2);
The strcmp return an int value that is
if s1 < s2 returns a value < 0
if s1 == s2 returns 0
if s1 > s2 returns a value > 0

7.How will you print \n on the screen?
printf("\n");
echo "\\n";
printf('\n');
printf("\\n");
Answer: Option D
Explanation:
The statement printf("\\n"); prints '\n' on the screen.


8.Which of the following function is correct that finds the length of a string?
int xstrlen(char *s)
{
    int length=0;
    while(*s!='\0')
    {    length++; s++; }
    return (length);
}
int xstrlen(char s)
{
    int length=0;
    while(*s!='\0')
        length++; s++;
    return (length);
}
int xstrlen(char *s)
{
    int length=0;
    while(*s!='\0')
        length++;
    return (length);
}
int xstrlen(char *s)
{
    int length=0;
    while(*s!='\0')
        s++;
    return (length);
}

(a)
9.What function should be used to free the memory allocated by calloc() ?
dealloc();
malloc(variable_name, 0)
free();
memalloc(variable_name, 0)

(c)

10.
How will you free the memory allocated by the following program?
#include<stdio.h>
#include<stdlib.h>
#define MAXROW 3
#define MAXCOL 4

int main()
{
    int **p, i, j;
    p = (int **) malloc(MAXROW * sizeof(int*));
    return 0;
}
memfree(int p);
dealloc(p);
malloc(p, 0);
free(p);

Answer: Option D







11. What will be the output of the program?
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *p;
    p = (int *)malloc(20); /* Assume p has address of 1314 */
    free(p);
    printf("%u", p);
    return 0;
}

(a)

12. What will be the output of the program (16-bit platform)?
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *p;
    p = (int *)malloc(20);
    printf("%d\n", sizeof(p));
    free(p);
    return 0;
}
Answer: Option A


13. What will be the output of the program?
#include<stdio.h>
#include<string.h>

int main()
{
    char *s;
    char *fun();
    s = fun();
    printf("%s\n", s);
    return 0;
}
char *fun()
{
    char buffer[30];
    strcpy(buffer, "RAM");
    return (buffer);
}

Answer: Option B

14.Point out the error in the following program.
#include<stdio.h>
#include<stdlib.h>

int main()
{
    int *a[3];
    a = (int*) malloc(sizeof(int)*3);
    free(a);
    return 0;
}
Error: unable to allocate memory
Error: We cannot store address of allocated memory in a
Error: unable to free memory
No error

Answer: Option B

15.
malloc() returns a float pointer if memory is allocated for storing float's and adouble pointer if memory is allocated for storing double's.
True
False
Answer: Option B
16. Which is an indirection operator among the following?
a) &
b) *
c) ->
d) .
Answer: Option B
17. Which of the following does not initialize ptr to null (assuming variable declaration of a as int a=0;?
a) int *ptr = &a;
b) int *ptr = &a – &a;
c) int *ptr = a – a;
d) All of the mentioned


18. What is the output of this C code?
    #include <stdio.h>
    int x = 0;
    void main()
    {
        int *ptr = &x;
        printf("%p\n", ptr);
        x++;
        printf("%p\n ", ptr);
    }
a) Same address
b) Different address
c) Compile time error
d) Varies
19. For a typical program, the input is taken using.
a) scanf
b) Files
c) Command-line
d) None of the mentioned
Answer: Option A
20. The value of EOF is_____.
a) -1
b) 0
c) 1
d) 10
Answer: Option A
21. Which is true?
a) The symbolic constant EOF is defined in 
b) The value is typically -1,
c) Both a & b
d) Either a or b
Answer: Option C
22. What is the use of putchar()?
a) The character written
b) EOF is an error occurs
c) Nothing
d) Both a & b
Answer: Option C
23. Which of the following statements about stdout and stderr are true?
a) Same
b) Both connected to screen always.
c) Both connected to screen by default.
d) stdout is line buffered but stderr is unbuffered.
(d)

24. What is the output of this C code?
    #include <stdio.h>
    void main()
    {
        int x = 0;
        int *ptr = &5;
        printf("%p\n", ptr);
    }

(d)

25.
What does fp point to in the program ?
#include<stdio.h>

int main()
{
    FILE *fp;
    fp=fopen("trial", "r");
    return 0;
}
The first character in the file
A structure which contains a char pointer which points to the first character of a file.
The name of the file.
The last character in the file.
Answer: Option B

26. What does the following segment of code do?
    fprintf(fp, “Copying!”);
a) It writes “Copying!” into the file pointed by fp
b) It reads “Copying!” from the file and prints on display
c) It writes as well as reads “Copying!” to and from the file and prints it
d) None of the mentioned

Answer: Option A

27.What is (void*)0?
Representation of NULL pointer
Representation of void pointer
Error
None of above
Answer: Option A

28.In which header file is the NULL macro defined?
stdio.h
stddef.h
stdio.h and stddef.h
math.h
Answer: Option C
Explanation:
The macro "NULL" is defined in locale.h, stddef.h, stdio.h, stdlib.h, string.h, time.h, and wchar.h.
29. The first and second arguments of fopen are
a) A character string containing the name of the file & the second argument is the mode.
b) A character string containing the name of the user & the second argument is the mode.
c) A character string containing file poniter & the second argument is the mode.
d) None of the mentioned of the mentioned
Answer:a
30. Which of the following mode argument is used to truncate?
a) a
b) f
c) w
d) t
Answer:c

Thursday, 13 March 2014

fread and fwrite in File Handling(C- Langauage)

fread :
1.     This Function is Used in Binary Mode.
2.    Function Reads Block of Data from Binary Mode File and Assign it to the Region of Memory Specified.[i.e Reads Block of Data From Binary File and Assign it to Some Memory ]
3.    Returns : Total number of Values Read.
Syntax :
int fread(void *Buffer,int Size,int Count,FILE *ptr);
Parameters :
·         “Buffer” is Variable of Pointer Type.
·         Data read is Assigned to “Buffer” which Holds Starting Address of the Block.
·         Size Specifies the Size in Bytes of Individual Data Item being read.
·         Count Specifies “Number of Items to Be Read“.
Examples :
1. To Write Variable x of type Float to File
float x;
FILE *fptr;
int fread(&x,sizeof(x),1,fptr);



fwrite :
1.     This Function is Used in Binary Mode.
2.    Function Writes Block of Data to Binary Mode File.[i.e Writes Block to Binary File]
Syntax :
int fwrite(void *Buffer,int Size,int Count,FILE *ptr);


Parameters :
·         “Buffer” is Variable of Pointer Type.
·         “Buffer” Holds Starting Address of the Block to be Written on File.
·         Size Specifies the Size in Bytes of Individual Data Item.
·         Count Specifies “Number of Items to Be Written Onto File“.

Examples :
1. To Write Variable x of type Float to File
float x;
FILE *fptr;
int fwrite(&x,sizeof(x),1,fptr);


2 . Write Array of 100 Elements
float x[100];
FILE *fptr;
int fwrite(&x,sizeof(x),100,fptr);
100 Specifies That Write 100 Floating Values to File Starting From Address Specified in Variable ‘x’.


Reading and Writing Records

When processing large amounts of data, it is often easier to group information together, instead of dealing with lots of individual variables. For example, to keep track of a customer's name, account balance, and account number, we will sometime want to group this information in a structure:
   struct customer {
       char fname[20],lname[20];
       int acct_num;
       float acct_balance;
   };

In C , we can read and write an entire structure at once instead of reading and writing every part individually.
Note that these files are not text files.  For example, the float in the file would be the actual bytes, not the human readable form. Since characters take one byte each, you could probably read the first and last names.



fwrite()

The function to write a struct in C is fwrite().
   fwrite (* struct, size, count, file);
The first argument is the location of the structure to write. The second argument is the byte size of that structure. The third argument is how many of those structures to write. The fourth argument is the output file.
So, given this declaration,
   struct account my_acct; 
we could write the entire structure with this command:
   fwrite (&my_acct, sizeof (struct account), 1, outfile); 
Given an array of 15 of these structures,
   struct account my_acct[15]; 
we could write all 15 elements
   fwrite (my_acct, sizeof (struct account), 15, outfile); 
Here is an example program to read some data from the keyboard then write the data into a file.
/**********************************
C Demo of how to WRITE using fwrite.
**********************************/

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

// a structure to read and write
struct customer {
   char  fname[20],lname[20];
   int   acct_num;
   float acct_balance;
};

/**************************************/
void main ()
{
   FILE *outfile;
   struct customer input;

   // open Accounts file for writing
   outfile = fopen ("accounts.dat","w");
   if (outfile == NULL)
     {
      fprintf(stderr, "\nError opening accounts.dat\n\n");
      exit (1);
     }

   // instructions to user
   printf("Enter \"stop\" for First Name to end program.");

   // endlessly read from keyboard and write to file
   while (1)
     {
      // prompt user
      printf("\nFirst Name: ");
      scanf ("%s", input.fname);
      // exit if no name provided
      if (strcmp(input.fname, "stop") == 0)
         exit(1);
      // continue reading from keyboard
      printf("Last Name : ");
      scanf ("%s", input.lname);
      printf("Acct Num  : ");
      scanf ("%d", &input.acct_num);
      printf("Balance   : ");
      scanf ("%f", &input.acct_balance);

      // write entire structure to Accounts file
      fwrite (&input, sizeof(struct customer), 1, outfile);
     }
}



fread()

The C function to read a structure is fread(). The format is:
   fread (* struct, size, count, file);
So, the arguments to fread() are the same as fwrite().
Here is C program to read the file that the above program writes. Notice that it does not use feof() to check for end-of-file. Instead it reads until fread() returns a 0, meaning zero bytes were read.
/**********************************
C Demo how to READ with fread.
**********************************/

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

struct customer {
   char  fname[20],lname[20];
   int   acct_num;
   float acct_balance;
};

void main ()
{
   FILE *infile;
   struct customer input;

   /*** open the accounts file ***/
   infile = fopen ("accounts.dat","r");
   if (infile == NULL)
     {
      fprintf(stderr, "\nError opening accounts.dat\n\n");
      exit (1);
     }

   while (fread (&input, sizeof(struct customer), 1, infile))
      printf ("Name = %10s %10s   Acct Num = %8d   Balance = %8.2f\n",
              input.fname, input.lname, input.acct_num, input.acct_balance);
}



Example Run

Here is those two programs run back to back.
> write_demo
Enter "stop" for First Name to end program.
First Name: Steve
Last Name : Dannelly
Acct Num  : 1234
Balance   : -99.99

First Name: Bob
Last Name : Jones
Acct Num  : 321
Balance   : 8888.88

First Name: Sally
Last Name : Smith
Acct Num  : 567
Balance   : 47.95

First Name: stop

> read_demo
Name =      Steve   Dannelly   Acct Num =     1234   Balance =   -99.99
Name =        Bob      Jones   Acct Num =      321   Balance =  8888.88
Name =      Sally      Smith   Acct Num =      567   Balance =    47.95


Tuesday, 25 February 2014

Ftell,Fseek,Rewind in C

 ftell()

Tells you where a particular file is about to read from or write to.
Prototypes
#include <stdio.h>

long ftell(FILE *stream);

Description
This function is the opposite of fseek(). It tells you where in the file the next file operation will occur relative to the beginning of the file.
It's useful if you want to remember where you are in the file, fseek() somewhere else, and then come back later. You can take the return value from ftell() and feed it back into fseek() (with whenceparameter set to SEEK_SET) when you want to return to your previous position.

Return Value

Returns the current offset in the file, or -1 on error.

Example

long pos;

// store the current position in variable "pos":
pos = ftell(fp);

// seek ahead 10 bytes:
fseek(fp, 10, SEEK_CUR);

// do some mysterious writes to the file
do_mysterious_writes_to_file(fp);

// and return to the starting position, stored in "pos":
fseek(fp, pos, SEEK_SET);


 fseek(), rewind()

Position the file pointer in anticipition of the next read or write.

Prototypes

#include <stdio.h>

int fseek(FILE *stream, long offset, int whence);
void rewind(FILE *stream);

Description

When doing reads and writes to a file, the OS keeps track of where you are in the file using a counter generically known as the file pointer. You can reposition the file pointer to a different point in the file using the fseek() call. Think of it as a way to randomly access you file.
The first argument is the file in question, obviously. offset argument is the position that you want to seek to, and whence is what that offset is relative to.
Of course, you probably like to think of the offset as being from the beginning of the file. I mean, "Seek to position 3490, that should be 3490 bytes from the beginning of the file." Well, it can be, but it doesn't have to be. Imagine the power you're wielding here. Try to command your enthusiasm.
You can set the value of whence to one of three things:

SEEK_SET

offset is relative to the beginning of the file. This is probably what you had in mind anyway, and is the most commonly used value for whence.
SEEK_CUR

offset is relative to the current file pointer position. So, in effect, you can say, "Move to my current position plus 30 bytes," or, "move to my current position minus 20 bytes."

SEEK_END

offset is relative to the end of the file. Just like SEEK_SET except from the other end of the file. Be sure to use negative values for offset if you want to back up from the end of the file, instead of going past the end into oblivion.
Speaking of seeking off the end of the file, can you do it? Sure thing. In fact, you can seek way off the end and then write a character; the file will be expanded to a size big enough to hold a bunch of zeros way out to that character.
Now that the complicated function is out of the way, what's this rewind() that I briefly mentioned? It repositions the file pointer at the beginning of the file:

fseek(fp, 0, SEEK_SET); // same as rewind()
rewind(fp);             // same as fseek(fp, 0, SEEK_SET)

Return Value

For fseek(), on success zero is returned; -1 is returned on failure.

The call to rewind() never fails.
Example
fseek(fp, 100, SEEK_SET); // seek to the 100th byte of the file
fseek(fp, -30, SEEK_CUR); // seek backward 30 bytes from the current pos
fseek(fp, -10, SEEK_END); // seek to the 10th byte before the end of file

fseek(fp, 0, SEEK_SET);   // seek to the beginning of the file
rewind(fp);               // seek to the beginning of the file

Error Handling in Files C

Error Handling

C language does not provide direct support for error handling. However few method and variable defined in error.h header file can be used to point out error using return value of the function call. In C language, a function return -1 or NULL value in case of any error and a global variable errno is set with the error code. So the return value can be used to check error while programming.
C language uses the following functions to represent error
  • perror() return string pass to it along with the textual represention of current errno value.
  • strerror() is defined in string.h library. This method returns a pointer to the string representation of the current errno value.

Example

#include< stdio.h>       
#include< errno.h>       
#include< stdlib.h>       
#include< string.h>       
 
extern int errno;
 
main( )
{
 
char *ptr = malloc( 1000000000UL);  //requesting to allocate 1gb memory space  

if ( ptr == NULL )        //if memory not available, it will return null  
{  
puts("malloc failed");
puts(strerror(errno));
exit(EXIT_FAILURE); //exit status failure       
}
else  //
{
free( ptr);
exit(EXIT_SUCCESS); //exit status Success       
}
}
Here exit function is used to indicate exit status. Its always a good practice to exit a program with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successfull exit. It is defined as 0. EXIT_Failure is used in case of any failure in the program. It is defined as -1.