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

Wednesday, 16 April 2014

Command line arguments in C:

Command line arguments in C:

      It is possible to pass some values from the command line to your C programs when they are executed. These values are called command line arguments and many times they are important for your program specially when you want to control your program from outside instead of hard coding those values inside the code.
The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program. 
argc      - Number of arguments in the command line including program name
argv[]   – This is carrying all the arguments
  • In real time application, it will happen to pass arguments to the main program itself.  These arguments are passed to the main () function while executing binary file from command line.
  • For example, when we compile a program (test.c), we get executable file in the name “test”.
  • Now, we run the executable “test” along with 4 arguments in command line like below.
this is a program
Where,
argc             =       5
argv[0]         =       “test”
argv[1]         =       “this”
argv[2]         =       “is”
argv[3]         =       “a”
argv[4]         =       “program”
argv[5]         =       NULL

Example program for argc() and argv() functions in C:

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

int main(int argc, char *argv[])   //  command line arguments
{
if(argc!=5) 
{
   printf("Arguments passed through command line " \
          "not equal to 5");
   return 1;
}

   printf("\n Program name  : %s \n", argv[0]);
   printf("1st arg  : %s \n", argv[1]);
   printf("2nd arg  : %s \n", argv[2]);
   printf("3rd arg  : %s \n", argv[3]);
   printf("4th arg  : %s \n", argv[4]);
   printf("5th arg  : %s \n", argv[5]);

return 0;
}

 Output:

Program name : test
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
IN OTHER WORDS:
C provides a fairly simple mechanism for retrieving command line parameters entered by the user. It passes an argv parameter to the main function in the program. argv structures appear in a fair number of the more advanced library calls, so understanding them is useful to any C programmer.
Enter the following code and compile it:
#include <stdio.h>

int main(int argc, char *argv[])
{
    int x;

    printf("%d\n",argc);
    for (x=0; x<argc; x++)
        printf("%s\n",argv[x]);
    return 0;
}
In this code, the main program accepts two parameters, argv and argc. The argv parameter is an array of pointers to string that contains the parameters entered when the program was invoked at the UNIX command line. The argc integer contains a count of the number of parameters. This particular piece of code types out the command line parameters. To try this, compile the code to an executable file named aaa and type aaa xxx yyy zzz. The code will print the command line parameters xxx, yyy and zzz, one per line.
The char *argv[] line is an array of pointers to string. In other words, each element of the array is a pointer, and each pointer points to a string (technically, to the first character of the string). Thus, argv[0] points to a string that contains the first parameter on the command line (the program's name), argv[1] points to the next parameter, and so on. The argc variable tells you how many of the pointers in the array are valid. You will find that the preceding code does nothing more than print each of the valid strings pointed to by argv.
Because argv exists, you can let your program react to command line parameters entered by the user fairly easily. For example, you might have your program detect the word help as the first parameter following the program name, and dump a help file to stdout. File names can also be passed in and used in your fopen statements.

Thursday, 3 April 2014

Last Year C Questions??

1. // program to count characters,spaces,tabs,new lines in a file //
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
int c;
int b=0,t=0,nl=0;
clrscr();
fp=fopen("good.txt","w");
printf("enter the string:");
while((c=getchar())!=EOF)
{
if(c==' ')
++b;
if(c=='\t')
++t;
if(c=='\n')
++nl;
}
fprintf(fp,"input has %d blanks,%d tabs and %d newlines\n",b,t,nl);
fclose(fp);
getch();

}





2. what do you mean by structure? How they are declared and initialized? How they are different from arrays?

STRUCTURES—these are the collection of heterogeneous elements in simple words we can say that is a collection of different data types. Each element in structure is called member. If you want to access structure members in C language ,structure variable should be declared. Many structure variable can be declared for same structure and memory will be allocated for each separately.

STRUCTURE DECLARATION—
A structure declaration specifies the grouping of variables of different types in a single unit. It simply acts as a temple or blueprint that may be used to create structure variables.
The syntax for declaring a structure in C is:

Struct struct_name
{
data_type member1;
data_type member2;
……………………
data_type membern;
};

STRUCTURE INITIALIZATION—
Lets us consider an example of employee structure which is declared as follows’
Struct employee
{
int emp_no;
char emp_name[20];
int dapt_code;
double salary;
}
we can define and initialize structure variable emp1 of type employee as follows,
employee emp1={101,”raghav”,05,23453.50};

PROGRAM TO ILLUSTRATE—
#
#
struct employee
{
int empid;
char name[50];
char add[50];
float salary;
char email[50];
}s1;
void main()
{
clrscr();
scanf(“%d”,&s1.empid);
scanf(“%s”,&s1.name);
scanf(“%s”,&s1.add);
scanf(“%f”,&s1.salary);
scanf(“%s”,&s1.email);
printf(“%d”,s1.empid);
printf(“%s”,s1.name);
printf(“%s”,s1.add);
printf(“%f”,s1.salary);
printf(“%s”,s1.email);
getch();
}

DIFFERENCE BETWEEN STRUCTURES AND ARRAYS

STRUCTURES                                                      ARRAYS
1.they are a group of heterogeneous               1.they are defined as a finite set
elements.                                                             of homogeneous elements.
 2.syntax                                                                                                         
 struct struct_name                                                2.syntax:
{                                                                             storage_class datatype arrayname[size];
datatype  variable name;
----------------------------
----------------------------
};
3.initialization:                                                      3.initialization:
employee emp1={101,”raghav”,05,23453.50};    float digit[3]={0.25,0,0.50};
  

Diffrence between Pointer to Array and Array of Pointers?????


Wednesday, 2 April 2014

Self Referential Structures

Self Referential Structures
A structure may have a member whose is same as that of a structure itself.
Such structures are called self-referential.
Self-Referential Structure are one of the most useful features.
They allow you to create data structures that contains references to data of the same type as themselves.
Self-referential Structure is used in data structure such as binary tree, linked list, stack, Queue etc.
Example : Single linked list is implemented using following data structures
struct node {
int value;
struct node *next;

};














































In Other Words.Link List is:


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();
}