Showing posts with label C Programming & Concepts. Show all posts
Showing posts with label C Programming & Concepts. Show all posts

Operator Overloading |C++

Operator Overloading


Operator overloading is one of the important feature in c++. For operator overloading there are certain restriction and limitations such as:
  1. Only existing operator can be overloaded new operator can not be created.
  2. The overloaded operator have at least one operand that is of user define type.
  3. We can not change the basic meaning of operator.
  4. Overloaded operator follow the syntax rule of original operator that can not be violated.
  5. Unary operator overloaded by means of member function, take no explicit argument and return no explicit value.But those operator overloaded by means of friend function take one reference argument i.e the object of relevant class.
  6. Binary operator overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit argument.
  7. When using binary operator overloaded through a member function the left hand operand must be an object of relevant class.
  8. Binary arithmetic operator such as '+' , '-' , '*' , '/' must explicitly to change their own arguments.
  9. There are some operator that can not be overloaded such as
    • size of operator ( sizeof )
    • Membership operator ( . )
    • Pointer to membership operator ( * )
    • Scope resolution operator (: :)
    • Conditional Operator ( ? : )
  10. We can not use friend function to overload certain operator.
    • Assignment operator ( = )
    • Function call operator ( )
    • Sub scripting operator ( [ ] )
    • Class member access operator ( -> )

Unary Operator Overloading


Before understanding unary operator overloading let we discuss about unary operators.
Unary operators operates on a single operand to produce new value.

Type Unary Operator

  • Increment (+ +)
  • Decrement (- -)
  • Not ( ! )
  • Unary minus ( - )
  • Sizeof operator (sizeof( ) )
  • Addressof operator ( & )

Example

Copy Code
#include <iostream>

using namespace std;
class unary
{
    int a;
    public:
    unary operator -- ()
    {
        a = - a;
        
    }
    void read()
    {
        cout<<"Enter Number:";
        cin>>a;
    }
    void print()
    {
        cout<<"a="<<a<<"\n";
    }
};


int main()
{
  unary u1;
  u1.read();
  --u1;
  u1.print();
  return 0;
}

Output:

Enter Number:5
a=-5

Binary Operator Overloading


Before understanding binary operator overloading let we discuss about binary operators.
Binary operators operates on two operand to produce new value.

Type Binary Operator

  • Equal (= =)
  • Not equal to (! =)
  • Less than ( < )
  • Greater than ( > )
  • Less than equal to (< =)
  • Greater than equal to (> =)
  • Logical AND ( && )
  • Logical OR (| |)
  • Plus ( + )
  • Minus ( - )
  • Multiplication ( * )
  • Division ( / )

Example

Copy Code
#include <iostream>

using namespace std;
class binary
{
    int a,b;
    public:
    binary operator + (binary ob)
    {
        a=a+ob.a;
        b=b+ob.b;
    }
    void read()
    {
        cout<<"Enter real:";
        cin>>a;
        cout<<"Enter imagenary:";
        cin>>b;
    }
    void print()
    {
        cout<<a<<"+"<<b<<"i"<<"\n";
    }
};


int main()
{
  binary b1,b2,b3;
  b1.read();
  b1.print();
  b2.read();
  b2.print();
  b3=b1-b2;
  b1.print();

    return 0;
}

Output:

Enter real:2
Enter imagenary:3
2+3i
Enter real:5
Enter imagenary:6
5+6i
7+9i


Bitwise Operator in C

Bitwise Operator


Bitwise operators are used to perform operation on individual bits of a number. It is used only for integer type of values. It can not perform operation on other values except integer such as float,duble etc.

Let we discuss about bitwise operator in C.There are following bitwise operator used in C such as:

  1. Bitwise AND Operator (&)
  2. Bitwise OR Operator ( | )
  3. Bitwise NOT Operator ( ~ )
  4. Bitwise XOR Operator ( ^ )
  5. Bitwise Left Shift Operator ( << )
  6. Bitwise Right Shift Operator ( >> )

 Bitwise AND Operator (&)


It is a binary operator. It has two operands. It perform bitwise AND on two operands. It return true if both are true or we can say that return 1 if both bit are 1.

Let we understand the truth table of bitwise AND.


A B Bitwise AND (A & B)
0 0 0
0 1 0
1 0 0
1 1 1

Copy Code

Example : Write a program to perform Bitwise AND (&) operation.


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

void main()
{
    int a;
    a=1;
    b=2;
    printf("Bitwise AND return =%d",a&∼a);
    getch();    
}


Bitwise OR Operator ( | ) 


It is a binary operator. It has two operands. It perform bitwise OR on two operands. It return true if any of them is true or both of them are true. we can say that return 1 if any of  bit  is 1 or both bit are 1.

Let we understand the truth table of Bitwise OR.


A B Bitwise OR (A | B)
0 0 0
0 1 1
1 0 1
1 1 1

Copy Code

Example : Write a program to perform Bitwise OR (|) operation.


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

void main()
{
    int a,b;
    a=1;
    b=2;
    printf("Bitwise OR return =%d",a|b);
    getch();    
}


 Bitwise NOT Operator (∼)


It is a unary operator. It has single operands. It perform bitwise NOT on single operand.

Let we understand the truth table of Bitwise NOT.


A Bitwise NOT (∼ A)
0 1
1 0

Copy Code

Example : Write a program to perform Bitwise NOT (∼) operation.


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

void main()
{
    int a;
    a=1;
    printf("Bitwise NOT return =%d",a);
    getch();    
}


 Bitwise XOR (Exclusive OR) Operator (^)


It is a binary operator. It has two operands. It perform bitwise XOR on two operands. It is represented by (^). It is same as Bitwise OR but if both A and B are true or we can say if both bit are 1 than it return false or 0 in XOR.

Let we understand the truth table of bitwise XOR.


A B Bitwise XOR (A ^ B)
0 0 0
0 1 1
1 0 1
1 1 0

Copy Code

Example : Write a program to perform Bitwise XOR (^) operation.


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

void main()
{
    int a,b;
    a=1;
    b=2;
    printf("Bitwise XOR return =%d",a^b);
    getch();    
}


 Bitwise Left Shift Operator (<<)


It is a binary operator. It has two operands. It perform bitwise Left Shift on two operands. It is represented by (<<). It is equivalent to multiply left operand by 2Right Operand
First Operand >> Second Operand
here First operand shows what bit we shift left and the second operand shows how many number of place to shift the bit.
Let we understand with the help of example.
a << 1
if a=4
Represent 4 in 8-bit binary number we get
0000 0100
Now in (a<<1), here 1 represent how many number of bits are shifted to left.Here it is 1 means we will shift 1 bit towards left such as

Note:

It is equivalent to multiply left operand by  2Right Operand.Let we see how this statement is true. Suppose from above example i.e
(a << 1)
4 << 1 = 2
4 multiply by 21= 8

Examples: Implementation of Left Shift Operator

Copy Text
#include <stdio.h>

int main()
{
   int  a=4;
   printf("4<<1=%d",a<<1);

    return 0;
}

Output: 4<<1 = 8

Copy Text
#include <stdio.h>

int main()
{
   int  a=4;
   printf("4<<1=%d",a<<1);

    return 0;
}

Output: 4<<1= 8

 

Bitwise Right Shift Operator (>>)


It is a binary operator. It has two operands. It perform bitwise Right Shift on two operands. It is represented by (>>).
First Operand >> Second Operand
here First operand shows what bit we shift right and the second operand shows how many number of place to shift the bit.
It is noted when bits are shifted right then leading positions are filled with zeros.
It is equivalent to divide left operand by 2Right Operand

Note:

It is equivalent to divide left operand by  2Right Operand.Let we see how this statement is true. Suppose from above example i.e
(a >> 1)
4 >> 1 = 2
4 divide by 21= 2

Examples: Implementation of Right Shift Operator

Copy Text
#include <stdio.h>

int main()
{
   int  a=4;
   printf("4>>1=%d",a>>1);

    return 0;
}

Output: 4>>1= 2

Copy Text
#include <stdio.h>

int main()
{
   char  a=4;
   printf("4>>1=%d",a>>1);

    return 0;
}

Output: 4>>1= 2


File Handling in C

File Handling


File handling is a concept by which we can access and create any file in our local system.We know that a file is allocation of data or set of characters.Basically there are two type of file is used in C language such as Sequential and Random access file.Working with sequential files are easy compare to random file.In sequential file all the data are stored and retrieve in sequential manner But in random file data are stored and retrieve in random manner.

C language provide standard Input and Output library which contain many features such as character I/O, String I/O and Stream I/O.These features are differ from compiler to compiler.

Let we discuss these features one by one:


Character I/O


  1. getchar() :This function is used to read alphanumeric characters from user by any standard I/O device such as keyboard.
  2. putchar() :This function is used to display alphanumeric characters on the standard output device such as screen.
  3. getch() :This function does not accept any parameter but it return single character from keyboard.This function is used to stop accessing the keyboard as soon as any key is pressed.We can say that the running screen is hold until we press any key.
  4. putch() :This function is used to display alphanumeric characters on the standard output device such as screen.

If we want to use above functions than we must include <stdio.h> header file in our progream.

Example:

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

int main()
{
    int ch;
    printf("Enter a character\n");
    ch=getchar();
    printf("Display character\n");
    putchar(ch);
    printf("\n");
   
    printf("Enter a character\n");
    ch=getch();
    printf("\n");
    printf("Display character\n");
    putch(ch); //Not run in some compiler
}

String I/O


  1. gets() :Reads a string from the keyboard.
  2. puts() :Write a string to the screen
  3. getc(stdin) :Read a single character from a stream (input stream such as stdin).
  4. putc(character,stdout) :Write a character character from a stream (output stream such as stdout).It has two parameters such as character and stdout

    Example: Write a program to implement gets(),puts(),getc(),putc().

    Copy Code
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>

     void main()
    {
        char name[20];
        char ch='a';
        printf("Enter the name using gets():\n");
        gets(name);
        printf("Display name using puts():\n");
        puts(name);
       
        printf("Enter the name using getc():\n");
        getc(stdin);
        printf("Display the name using putc():\n");
        putc(ch,stdout);
    }
  5. sscanf() :This function is same as scanf function.But the difference is that it read the data form memory instead of keyboard.

    Example: Write a program to implement gets(),puts(),getc(),putc().

    Copy Code
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>

     void main()
    {
        char str[]="amit singh;bhopal;20";
        char name[20];
        char city[10];
        unsigned int age;
        sscanf(str,"%[a-zA-Z ];%[a-zA-Z ];%d",name,city,&age);
        //[a-zA-Z ]-> means read a to z & A to Z & a space only
        // OR
        sscanf(str,"%[^;];%[^;];%d",name,city,&age);
        // [^;] means read all character except ;(semicolon) read as not semicolon
        printf("%s age is %d lived in %s",name,age,city);
    }

  6. sprintf() :This function is same as the printf function.But the difference is that it write any thing in memory in the place of screen.In this function one parameter must be a character array.

    Example: Write a program to implement gets(),puts(),getc(),putc().

    Copy Code
    #include<stdio.h>
    #include<conio.h>
    #include<stdlib.h>

     void main()
    {
        char str[100];//="amit singh;bhopal;20";
        char name[20]="Shailendra";
        char city[10]="Bhopal";
        unsigned int age=40;
       
        sprintf(str,"%s age is %d lived in %s",name,age,city);
        // we store name city & age in variable str in formatted way
        printf("%s",str);
    }

Opening and Closing of Files

For opening and closing of any files we use following functions:

  • fopen()
  • fclose()

fopen()

fopen function is used to open file from the disk.This function have two parameters first is "file name" and second is "mode".

Syntax:

fptr=fopen(filename,mode);

fptr is a FILE pointer or pointer to a FILE type.
filename is a character string type.
mode means for what porpose we open a file such as for reading purpose,for writting purpose,for appending purpose.There abbreviation are given below.
  • "w" :This is a writting mode.In this mode open a file for writting purpose if exist and if not exist than create it.
  • "r" :This is a reading mode.In this mode open a existing file for reading content of file.If not exist NULL return to FILE pointer.
  • "a" :This a appending mode.In this mode open a existing file for appending the content of file.
  • "r+" :This mode is used to open an existing file for updating a existing file.
  • "w+" :This mode is used to create a new file for reading and writting.
  • "a+" :This mode is used for appending the content of file.If file does not exist then create it.

fclose()

fclose function is used to close the file that is used by program.Here close means remove the link form FILE pointer to the file name.

Syntax:

fclose(fptr); // fptr is a FILE pointer

Formatted Input and Output

  1. fprintf() :The stdio.h library provide fprintf() function for formatting Input/Output.Like printf() function fprintf also print the content but instead of printing in screen fprintf will write content into a given file.

    Syntax:

    fprintf(fptr,"control string",list)
    wherefptr is a file pointer.

  2. fscanf() :The stdio.h library provide fprintf() function for formatting Input/Output.Like scanf() function fscanf also read the content but instead of reading from keyboard fscanf will read content from a given file.

    Syntax:

    fprintf(fptr,"control string",&list)
    wherefptr is a file pointer.

  3. fgets() :The fgets function is used to read a set of characters as a string from a given file and copy the string to a given memory location generally in an array.This function will read the full line from a given file.

    Syntax:

    fgets(str,n,fptr)
    wherefptr is a file pointer.n is a maximum number of character in a string str.str is a array of string.

  4. fputs() :This function is used to write a string to a given file.

    Syntax:

    fputs(str,fptr)
    wherefptr is a file pointer.str is a array of string.

Example 1: Write a program to create a text file and store student record such as (Student Name, Student Rollno, Student Course, Student Branch, Student Rollno, Subjetct,Marks)

Copy Code
#include<conio.h>
#include<stdio.h>
void main()
{
    FILE *fptr;
    char name[30];
    char course[30];
    char branch[30];
    char subject[30];
    int marks,rollno;  
       
    fptr=fopen("D:\\student_rec.txt","a"); //We can write "a"-Append OR "w"-Write

    if(fptr==NULL)
    {
        printf("File does not exist\n");
        return;
    }

    printf("Enter name:\n");
    gets(name);
    fprintf(fptr,"Name    =%s\n",name);

    printf("Enter branch:\n");
    gets(branch);
    fprintf(fptr,"Branch   =%s\n",branch);

    printf("Enter course:\n");
    gets(course);
    fprintf(fptr,"Course   =%s\n",course);
   
    printf("Enter subject:\n");
    gets(subject);
    fprintf(fptr,"Subject   =%s\n",subject);  

    printf("Enter rollno:\n");
    scanf("%d",&rollno);
    fprintf(fptr,"Rollno     =%d\n",rollno);
   
    printf("Enter marks:\n");
    scanf("%d",&marks);
    fprintf(fptr,"Marks   =%d\n",marks);

    fclose(fptr);
    getch();
}

Output:



Example 2: Write a program to write text of 5 lines in file.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","w");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Enter text :\n");
        // Write 5 lines in text file
        for(i=1;i<=5;i++)
        {
            gets(str);
            fputs(str,fptr);
            fputs("\n",fptr);
        }
   
    }
    fclose(fptr);
}

Output:

Example 3: Write a program to read text of 5 lines from file in screen.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","r");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Data in the file is :\n");
        // Read 5 line of text from file
        for(i=1;i<=5;i++)
        {
            fgets(str,100,fptr);            
            puts(str);
        }    
    }
    fclose(fptr);
}


Output:

Example 4: Write a program to append text of 5 lines in existing file.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","a");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Enter text :\n");
        // Write 5 lines in text file
        for(i=1;i<=5;i++)
        {
            gets(str);
            fputs(str,fptr);
            fputs("\n",fptr);
        }
   
    }
    fclose(fptr);
}

Output:

Example 5: Write a program to append text of 10 lines in existing file.

Copy Code
#include<stdio.h>
#include<conio.h>
void main()
{
    char str[100];
    int i;
    FILE *fptr;
    fptr=fopen("data.txt","r");
    if(fptr==NULL)
    {
        printf("File does not exist");
    }
    else
    {
        printf("Data in the file is :\n");
        // Read 10 line of text from file
        for(i=1;i<=10;i++)
        {
            fgets(str,100,fptr);            
            puts(str);
        }    
    }
    fclose(fptr);
}



Read about more functions in hile handling such as:

  • getw()
  • putw()
  • fread()
  • fwrite()
  • feof()
  • ferror()
  • fflush()
  • freopen()
  • unlink()
  • open()
  • creat()
  • read()
  • write()
  • close()
  • lseek()
  • fseek()
  • ftell()
  • rewind()

Dynamic Memory Allocation in C

Dynamic Memory Allocation in C


We know the memory allocation is classified into Static and Dynamic allocation.In brief Static memory is allocated before execution of any program. Here let we discuss about dynamic memory allocation in detail.

Dynamic memory allocation simply means allocation of memory at run time. Dynamic memory is some time more preferable when we are not able to decide the exact size. Suppose in the case of array if the sufficient size is not define then that causes program failure occur. For overcoming such type of failure dynamic memory is needed.

Dynamic memory have following advantages such as:

  • For Reduce the wastage of memory , we can easily understand by taking an example suppose if we use any array of size 100 in our program and static memory allocation is used for allocation memory.At the time of execution if we are using only 50% of allocated memory than the rest of 50% is waste.That means allocated memory is not properly utilised. But in the place of static,if we use dynamic memory allocation then we overcome such a wastage because in dynamic memory is allocated at runtime or execution time.
  • Provide Flexibility in change the size of array.In any static memory allocation scheme changing the size of array in not possible because it is fix but not in dynamic memory allocation scheme.

For managing such a memory management scheme at runtime , C language provide four library functions such as:

  1. Malloc()
  2. Calloc()
  3. Realloc()
  4. Free()

These functions are declared in <stdlib.h> and <alloc.h> header files in C library.These functions are helpful for building complex programs such as creating a linked list.


Let we know about the memory allocation process:


For understand memory allocation process we must know about the storage structure of C.The storage is divided into many regions and each regions can store different things in it such as Local variables,Global variables,Program instructions etc.Let we discuss about those regions such as:

  • Stack : This region is responsible to store local variables.
  • Heap : This region is responsible to store those variable which is dynamic allocated during execution.Here the size of heap keeps changing when program is executed due to creation and destruction of variables that are local in blocks of functions.
  • Permanent Storage area : This region is responsible to store program instructions and global/static variables.

Let we discuss about library function in detail:

Malloc()

Malloc stands for memory allocation. Malloc function is used to allocate a single block of memory.It reserve the space in memory according to the size variable that linked with a pointer.This pointer contain the starting address of memory.The memory allocation is in continuous manner.Here allocated space is not filled with zero but it returns 0 or NULL if the space in the heap is not sufficient to satisfy the request.So we must check the memory allocation before using memory pointer.

Syntax:

ptr=(cast-type*)malloc(byte-size);

Example 1:

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

void main()
{
   void * ptr;
   ptr=malloc(4);
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

In the above example void *ptr means pointer points to any datatype we are not specify any datatype.Generally malloc() returns NULL pointer it does not point any datatype.If we want that malloc() point any datatype than we must specify the datatype such as (cast-type*)malloc(any unsigned integer);,Here cast-type is data type where we cast one type to another such as (float)x where x is integer so integer is converted into float.

Example 2:

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

void main()
{
   int * ptr;
   ptr=(int*)malloc(4);
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

In above example if we don't know how many bytes the datatype takes than we can use sizeof () to find the length or number of byte will consume by datatype.

Example 3:

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

void main()
{
   int *ptr;
   ptr=(int*)malloc(sizeof(int));
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

Calloc()

Calloc stands for calculated allocation.It is used to allocate memory location for derived data type at run time.Derived data type such as arrays and structures. Calloc can allocate multiple block of memory space of same size.It fill allocated memory space with 0 automatically.It return starting address of memory if allocation is successful and return 0 or NULL if allocation fails.

Syntax:

ptr=(cast-type*)calloc(element,element-size);

Example :


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

void main()
{
    int n;
   char *ptrc;
   ptrc=(char*)calloc(n,sizeof(char));
   if(ptrc==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated\n");
   }
}

Realloc()

It is used to modify memory space that allocated previously.That means we can increase or decrease the block size of heap memory according to required size.During this process we preserve the starting address and data of block.

Syntax:

ptr=realloc(ptr,ptr-size);

Example :

Copy Code
#include <stdio.h>
#include <stdlib.h>
void main()
{
   int *ptr;
   ptr=(int*)malloc(50);
   if(ptr==NULL)
   {
       printf("Memory is full\n");
   }
   else
   {
       printf("Memory is allocated by malloc()\n");
   }
   //After fill the memory of 50 byte we will extend upto 100 more byte.
   ptr=(int*)realloc(ptr,100);
}

Free()

This function is used to free the memory allocated by alloc(),malloc(),calloc() or realloc() and the space is available in the heap for further activity.It is recommended that before termination program execution you must free memory used by program.

Syntax:

free(ptr);


Examples 

Program 1 :


Copy Code
#include<stdlib.h>
#include<stdio.h>
void main()
{
    int *A,*B;
    int n;
    printf("Enter size of array:");
    scanf("%d",&n);
    if(A==NULL)
    {
        printf("Memory is full!");
    }
   
    A=(int*)calloc(n,sizeof(int));
   
    for(int i=0;i<n;i++)
    {
        A[i]=i+1;
    }
     printf("\nA:");
    for(int i=0;i<n;i++)
    {
        printf("%d\t",A[i]);
    }
    B=(int*)realloc(A,10*sizeof(int));
   
    printf("\nB:");
   
    for(int i=0;i<n;i++)
    {
        printf("%d\t",B[i]);
    }
   
}

Program 2 :

Copy Code
#include<stdlib.h>
#include<stdio.h>
void main()
{
    int *A,*B;
    int n;
    printf("Enter size of array:");
    scanf("%d",&n);
    if(A==NULL)
    {
        printf("Memory is full!");
    }
   
    A=(int*)malloc(sizeof(int));
   
    for(int i=0;i<n;i++)
    {
        A[i]=i+1;
    }
     printf("\nA:");
    for(int i=0;i<n;i++)
    {
        printf("%d\t",A[i]);
    }
    B=(int*)realloc(A,10*sizeof(int));
   
    printf("\nB:");
   
    for(int i=0;i<n;i++)
    {
        printf("%d\t",B[i]);
    }    
}

Know more about pointers


Command-Line Arguments in C

Command-Line Arguments

I would like to explain this topic with one question i.e Can we pass any argument in main function of C language ? Some time this question is arrise in our mind.We know main() is also a function like other functions.Can we assign any argument in main?.Main is the first function which is executing at the time of RUNNING any program from any IDE such as TURBO C, BLOCKCODE, CODELITE, DEV C++, KDevelop, Xcode, Qt Creator, NetBeans, Eclipse, CLion, Visual Studio etc. Its depend on IDEs how they provide facility to assign arguments in main function at the time of execution.

But if you are working in command line window or (cmd prompt)  than we can easily place arguments at the time of execution. At the time of defining main function we must pass some arguments such as argc and argv. 

Now Let we know about argc and argv.

👉argc is integer type and count the number of arguments.
👉argv is character array pointers which contain all arguments passed at run time.It is noted that the first argument is program itself.

Example 1: Write a program to implement command line argument.

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

void main(int argc,char *argv[ ])
{
    printf("argc=%d\n",argc);
    for(int i=0;i<argc;i++)
    {
        printf("argv[%d]=%s\n",i,argv[i]);
    }
}

OutPut

argc=1   // Show 1 argument that is program itself.
argv[0] = Show the name/path of program saved (depend on IDE used)




If we provide some more input values as a argument such as [4 5 2] all values are separated by space only.

OutPut:

argc= 4
argv[0]= Show the name/path of program or program name (depend on IDE used)
argv[1]=4
argv[2]=5
argv[3]=2




Example 2: Write a program to multiply by  2 with input values by using command line arguments.

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

void main(int argc,char *argv[ ])
{
    int i=0;
    printf("argc=%d\n",argc);
    printf("argv[%d]=%s\n",i,argv[0]);
    for(i=1;i<argc;i++)
    {
       int m=strtol(argv[i],NULL,10); //convert string into int
        printf("argv[%d]=%d\n",i,m*2);
    }
}

If we provide some more input values as a argument such as [4 5 2] all values are separated by space only.

OutPut:

argc= 4
argv[0]= Show the name/path of program or program name (depend on IDE used)
argv[1]= 8
argv[2]= 10
argv[3]= 4

Example 3: Write a program to find the product all input values by using command line arguments.

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

void main(int argc,char *argv[ ])
{
    int i=0,a=1;
    printf("argc=%d\n",argc);
    printf("argv[%d]=%s\n",i,argv[0]);
    for(i=1;i<argc;i++)
    {
       int m=strtol(argv[i],NULL,10);//convert string into int
       a=a*m;
       printf("argv[%d]=%s\n",i,argv[i]);
    }
    printf("Product of argv=%d\n",a);
}
If we provide some more input values as a argument such as [4 5 2] all values are separated by space only.

OutPut:

argc= 4
argv[0]= Show the name/path of program or program name (depend on IDE used)
argv[1]= 4
argv[2]= 5
argv[3]= 2
Product of argv=40

Know more about pointers


Pointers to Pointers in C

Pointers to Pointers in C


A pointer provides the address of the data item to which it points. The data item indicated by the pointer may be the address of another data item. Therefore, a given pointer can be a pointer to the pointer of any data item. To access the data element of a given pointer, we need two levels of indirect. First, the given pointer is de-reference to get the pointer to the given data item, and then second, the pointer is delayed to get the data item.

Let we understand with the help of example:

int i=5; Let we show in memory
Above diagram show i will take 4 byte of memory
int *p; let we show in memory
p=&i; let we show in memory
Now, If we write *p = 10;that means the value at x is updated form 5 to 10 that show in diagram.
int **q; let we show in memory
q = &p; let we show in memory
int ***s;
s = &q; let we show in memory
Now all the variable are stored in the memory at any particular memory address.That show in figure.

Let we see what the value stored in variables


printf("*p=%d",*p);
Output:*p=10

printf("*q=%d",*q);
Output:*q=101

printf("**q=%d",**q);
Output:**q=10

printf("**s=%d",**s);
Output:**s=101

printf("***s=%d",***s);
Output:***s=10

****s=20;
printf("i=%d",i);

Now here if write ***s=20 than the value of i become change from 10 to 20 show in the diagram.
So from the above examples we can easily understand how the pointer to pointer works and how we change value of any variable indirectly or de referencing the pointers variables.


Example: Write a program to declare the pointer to pointer variable and to display the elements of pointer.


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

void main()
{
    int a;
    int *ptr1;
    int **ptr2;
    a=100;
    printf("a=%d\n",a);
    ptr1=&a;
    ptr2=&ptr1;
    printf("First pointer=%d\n",*ptr1);
    printf("Second pointer=%d\n",**ptr2);
    getch();
}

Output:

a=100
First pointer=100
Second pointer=100

Know more about pointers