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

Thursday, 27 March 2014

C Questions With Solutions



1)  What are strings and explain standard library functions?
The string in C programming language is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};








Example

#include <stdio.h>
 
int main ()
{
   char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
 
   printf("Greeting message: %s\n", greeting );
 
   return 0;
}
 
S.N.
Function & Purpose
1
strcpy(s1, s2);
Copies string s2 into string s1.
2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3
strlen(s1);
Returns the length of string s1.
4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
 
 
 
 
 
The Standard Library Functions
Some of the "commands" in C are not really "commands" at all but are functions. For example, we have been using printf and scanf to do input and output, and we have used rand to generate random numbers - all three are functions.
There are a great many standard functions that are included with C compilers and while these are not really part of the language, in the sense that you can re-write them if you really want to, most C programmers think of them as fixtures and fittings. Later in the course we will look into the mysteries of how C gains access to these standard functions and how we can extend the range of the standard library. But for now a list of the most common libraries and a brief description of the most useful functions they contain follows:
1.   stdio.h: I/O functions:
1.   getchar() returns the next character typed on the keyboard.
2.   putchar() outputs a single character to the screen.
3.   printf() as previously described
4.   scanf() as previously described

2.   string.h: String functions
1.   strcat() concatenates a copy of str2 to str1
2.   strcmp() compares two strings
3.   strcpy() copys contents of str2 to str1

3.   ctype.h: Character functions
1.   isdigit() returns non-0 if arg is digit 0 to 9
2.   isalpha() returns non-0 if arg is a letter of the alphabet
3.   isalnum() returns non-0 if arg is a letter or digit
4.   islower() returns non-0 if arg is lowercase letter
5.   isupper() returns non-0 if arg is uppercase letter

4.   math.h: Mathematics functions
1.   acos() returns arc cosine of arg
2.   asin() returns arc sine of arg
3.   atan() returns arc tangent of arg
4.   cos() returns cosine of arg
5.   exp() returns natural logarithim e
6.   fabs() returns absolute value of num
7.   sqrt() returns square root of num

5.   time.h: Time and Date functions
1.   time() returns current calender time of system
2.   difftime() returns difference in secs between two times
3.   clock() returns number of system clock cycles since program execution

6.   stdlib.h:Miscellaneous functions
1.   malloc() provides dynamic memory allocation, covered in future sections
2.   rand() as already described previously
3.   srand() used to set the starting point for rand()

 

Wednesday, 26 March 2014

Code for ILLUSTRATION OF fseek & ftell FUNCTIONS in C Programming

#include <stdio.h>                                             
   main()                                                           
   {                                                                
       FILE  *fp;                                                   
       long  n;                                                     
       char c;                                                      
       fp = fopen("RANDOM", "w");                                   
       while((c = getchar()) != EOF)                                
           putc(c,fp);                                              
                                                                    
       printf("No. of characters entered = %ld\n", ftell(fp));      
       fclose(fp);                                                  
       fp = fopen("RANDOM","r");                                    
       n = 0L;                                                      
                                                                    
       while(feof(fp) == 0)                                         
       {                                                            
           fseek(fp, n, 0);  /*  Position to (n+1)th character */
   
           printf("Position of %c is %ld\n", getc(fp),ftell(fp));  
           n = n+5L;                                                
       }                                                            
       putchar('\n');                                               
                                                                    
       fseek(fp,-1L,2);     /*  Position to the last character */
do                                                           
         {                                                          
             putchar(getc(fp));                                     
         }                                                          
         while(!fseek(fp,-2L,1));                                     
         fclose(fp);                                                  
   }                                                                


Output                                                           
                                                                    
   ABCDEFGHIJKLMNOPQRSTUVWXYZ^Z                                     
   No. of characters entered = 26                                   
   Position of A is 0                                               
   Position of F is 5                                               
   Position of K is 10                                              
   Position of P is 15                                              
   Position of U is 20                                              
   Position of Z is 25                                              
   Position of   is 30                                              
                                                                    
   ZYXWVUTSRQPONMLKJIHGFEDCBA   

Monday, 24 March 2014

Last year C Solved Questions

Explain various pointer notations with examples?

A POINTER IS A VARIABLE THAT CONTAINS YHE ADDRESS OF OTHER VARIABLE.
POINTERS ARE ALSO KNOWN AS POINT TO VARIABLE

Address operator or reference operator




We see that the computer has selected memory location 65524 as the place to store the value 3.  The important point is, i’s address in memory is a number .We can print this address number through the following program:
Main()
{
Int i=3;
printf(“address of i=%u”,&i);
printf(“\nvalue of i=%d”,i);
}
The output of the above program would be:
Address of i=65524
Value of i=3
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’operator. The expression &i returns the address of the variable i, which in this case happens to be 65524. Since 65524 represents an address, there is no question of a sign being associated with it. Hence it is printed out using %u, which is a format specifier for printing an unsigned integer. We have been using the ‘&’ operator all the time in the scanf() statement.
The other
 pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.


Indirection or deference operator

It is used to indirectly access the value of the variable whose address  is stored in the pointer variable . it is known as deference operator because it returns the value of the variable.

Let us observe a program
#include<stdio.h>
#include<conio.h>
Void main()
{
Int i=5;
Int  *j=&I;
Printf(“value stored at address of ptr=%d”,*ptr);
Getch();
}
Note that printing the value of *j is same as printing the value of i.
The
 expression &i gives the address of the variable i. This address can be collected in a variable
But remember that ptr is not an ordinary
 variable like any other integer variable. It is a variable that contains the address of other variable (i in this case). Since j is a variable the compiler must provide it space in the memory. Once again, the following memory map would illustrate the contents of i and j.








As you can see I’s value is 3 and j’s value is I’s add
This declaration tells the compiler that j will be used to store the address of an integer value. In other words j points to an integer. How do we justify the usage of * in the declaration,
int *j ;
Let us go by the meaning of *. It stands for ‘value at address’. Thus, int *j would mean, the value at the address contained in j is an int.
Here is a program that demonstrates the relationships we have been
 discussing.
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "\nAddress of i = %u", &i ) ;
printf ( "\nAddress of i = %u", j ) ;
printf ( "\nAddress of j = %u", &j ) ;
printf ( "\nValue of j = %u", j ) ;
printf ( "\nValue of i = %d", i ) ;
printf ( "\nValue of i = %d", *( &i ) ) ;
printf ( "\nValue of i = %d", *j ) ;
}

The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
Value of i = 3
Value of i = 3
Pointer to a pointer
Every variable has an address so a pointer variable also has an address. Pointer to a pointer means that a variable can be declared which can store the address of a pointer variable










In this example ,I is a variable ,j is a pointer variable pointing to I, ,k acts as a pointer to pointer pointing to I.**k access the value pointed by j whose address is stored in it.Program;
Void main()
{
Int i=5,*j,**k;                                                                                          
Clrscr();
J=&I;
K=&j;
Printf(“value of i=%d”,i);
Printf(“value of *j=%d”,*j);
Printf(“value of **k=%d”,**k):
Getch();
}

Output
Value of i=5
Value of *j=5
Value of **k=5


Explain various functions fopen , fclose ,fread, fwrite with examples ?
The various functions are ;
1 fopen
2 fclose
3 fread
4 fwrite

Fopen():
 it create a new file 0r open an existing file

syntax
fopen(“name of file”,”mode”);

example
fopen(“abc.txt”,”r”);

                                                        Fclose():
 it create a new file 0r open an existing file

syntax
fclose(file pointer);
example
fclose(fp);

example of fopen and fclose
/*example of fopen and fclose*/
#include <stdio.h>
void main()
{
   FILE *fopen(), *fp;
   int c;
   fp = fopen("prog.c","r");
   c = getc(fp) ;
   while (c!= EOF)
   {
     putchar(c);
  c = getc(fp);
   }
   fclose(fp);}
                       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


 Very Important Question from Exam Point of View:

Program to count vowels coming consecutively
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *p;
char ch;
char a[20],d[20];
int c,v=0,i;
clrscr();
p=fopen("bca.txt","w");
printf("\n output");
printf("\n enter a line");
gets(a);
for(i=0;a[i]!='\0';i++)
{
c=toupper(a[i]);
if(c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
{
d[i+1]=toupper(a[i+1]);
if(d[i+1]=='A'||d[i+1]=='E'||d[i+1]=='I'||d[i+1]=='O'||d[i+1]=='U')
{
++v;}
}}
fprintf(p,"\nvowels coming consecutively:%d",v);

fclose(p);
getch();
}