Friday, 21 July 2017

Pointer in C

Pointer is an extremely powerful programming tool. A pointer is a variable which used to store the address of another variable of same  data type. It means that if we want to store the address of integer type then pointer type must be of integer and so on.
In C language, we have a special type of pointer named void (*), which contains the address of any type of variable. This pointer is also known as Generic Pointer.

Syntax :

      Data_type *Variable_name ;

     int *p ;
                             
Astrik (*) sign denotes that p is pointer variable not a normal variable.

Key Points :
  • Pointer contains the the address of another variable.
  • * sign denotes the pointer variable. It shows the value of the variables that address stored for a pointer variable.
  • To access address of a variable to a pointer, we use the unary operator (ampersand) that returns the address of that variable.
  • Pointer contains 2 bytes of memory for 16 bit processor.
  • If a pointer is assigned to NULL, it means it is pointing to nothing.
Example :


#include <stdio.h>

int main()
{
    int x;
    // Prints address of x
    printf("%p", &x);
    return 0;
}

Output :

0x7ffe6ee753ee

Example 2:

#include <stdio.h>

int main()
{
// A normal integer variable
int Var = 10;

// A pointer variable that holds address of var.
int *ptr = &Var;

// This line prints value at address stored in ptr.
// Value stored is value of variable "var"
printf("Value of Var = %d\n", *ptr);

// The output of this line may be different in different
// runs even on same machine.
printf("Address of Var = %p\n", ptr);

// We can also use ptr as lvalue (Left hand
// side of assignment)
*ptr = 20; // Value at address is now 20

printf("After doing *ptr = 20, *ptr is %d\n", *ptr);

return 0;
}

Output :

Value of Var = 10
Address of Var = 0x7ffc23954c74
After doing *ptr = 20, *ptr is 20

Array of Pointer :

There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer −


int *ptr[con];

Example :

#include <stdio.h>
int main()
{
    // Declare an array
    int v[3] = {10, 100, 200};
    // Declare pointer variable
    int *ptr;
    // Assign the address of v[0] to ptr
    ptr = v;
    
     for (int i = 0; i < 3; i++)
    {
        printf("Value of *ptr = %d\n", *ptr);
        printf("Value of ptr = %p\n\n", ptr);
        // Increment pointer ptr by 1
        ptr++;
    }
}

Output :


Value of *ptr = 10

Value of ptr = 0x7ffcae30c710

Value of *ptr = 100
Value of ptr = 0x7ffcae30c714

Value of *ptr = 200
Value of ptr = 0x7ffcae30c718


Thursday, 20 July 2017

String in C

A string is an array of characters. The end of the string is marked with a special character, the null character, which is simply represented by '\0'. Strings are enclosed by double quotes whereas, character is enclosed by single quotes always.

Declaration :

Strings are array of char data type. It is declared as follow :

           char s[5] ;
                                      Declaration of strings in C language
                       

Initialization :     

      char message [20] = "Hello world !";
      
      char message [20] = {'H', 'e', 'l', 'l', 'o', '\0'};

      char message [] = "Hello!"

when we declare "char message[20]”, 20 bytes of memory space is allocated for the string value. And when we declare "char message[]”, memory space will be allocated as per the requirement during execution time of program.

Example1 :

#include<stdio.h>
int main()
{
      char message[10] = "Hello!";
      char message1[] = " world" ;
      printf("%s, %s, message, message1);
      return 0;
}

Output :

Hello! world


Example2:

#include<stdio.h>
int main()
{
      char value[];
      printf("Enter any string : ");
      scanf("%s",&value);
      printf("Entered String = %s ", value);
      return 0;
}

Output :

Enter any string :
GoProgramming
Entered String = GoProgramming

scanf() function doesn't control the value with space. For this we use gets() instead of scanf().

gets(variable);

Example3:

#include<stdio.h>
int main()
{
      char value[];
      printf("Enter any string : ");
      gets(value);
      printf("Entered String = %s ", value);
      return 0;
}

Output :

Enter any string :
Go Programming
Entered String = Go Programming


String Handling Functions :

Sometimes, we need to manipulate string in our program according to our needs. For this C programming language provide us some in-built String Manipulation Functions which are available in <string.h> header file.
These functions are listed below :

  • strlen() :

strlen() function is used to count the number of characters in a string.

Example :

#include<stdio.h>
#include<string.h>
int main()
{
      char value[] = "Hello World";
      int length;

      length = strlen(value);

      printf("String length = %d", length);
      
      return 0;
}

Output :

String length = 11

  • strrev()

It reverses the given string.

Example :

#include<stdio.h>
#include<string.h>
int main()
{

      char value[] = "Hello";
      char value1[];

      length = strrev(value);

      printf("String  = %s", value);
      printf("Reversed String = %s, value1);
      
      return 0;

}

Output :


String = Hello World

Reversed String = olleH

  • strcpy()

This function copies a string value into another string.

Example :


#include<stdio.h>
#include<string.h>
int main()
{


      char value[] = "Hello";
      char value1[] = "World";
      char value2[];


      strcpy(value2, value);
      strcpy(value2, value1);

      printf("String 1 = %s", value);
      printf("String 2 = %s", value1);
      printf("New String = %s", value2);
      
      return 0;
}


Output :


String 1 = Hello
String 2 = World
New String = HelloWorld



  • strcmp() :
strcmp() function is used to compare two strings. If both strings are equal then function will return value zero(0). If first string is greater than second than function return value >0 otherwise  <0. This function is case sensitive.

Example :


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

int main()
{
    char str1[] = "abcd", 
            str2[] = "abCd", 
          
    int result;

    // comparing strings str1 and str2
    result = strcmp(str1, str2);
     
    if(result < 0)
    {
       printf("str1 is less than str2");
    }
    else if(result > 0) 
    {
       printf("str2 is less than str1");
    }
    else 
    {
        printf("str1 is equal to str2");
    }

    return 0;
}

Output :

str2 is less than str1

  • strcat()


This function  is used  to concatenate two or more strings.

Syntax :

      strcat(str1, str2);
      strcat(str1, strcat(str2,str3));







Wednesday, 19 July 2017

Array in C

In C language, arrays are referred to as structured data types. An array is a collection of data that holds fixed number of values of same data type.

Arrays store a fixed-size sequential collection of elements of the same type. In other words, if we want to group similar type of value in conjunctive memory location then we use Array.

Points :
  • Array might be belonging to any of the data types
  • Array size must be a constant value.
  • Always, adjacent memory locations are used to store array elements in memory.
  • Array should be initialized with zero or null while declaring, if we don’t assign any values to array.

The size and type of arrays cannot be changed after its declaration.

Arrays are of two types:
  1. One-dimensional arrays
  2. Multidimensional arrays

One-dimensional Arrays :

 Group of values in adjacent memory location in x or y direction is 1-D array.

Declaration of One-dimensional array :

    data_type array_name[array_size];

For example :

    float val[10];
array declaraction in c

Here, we declared an array, val of floating-point type and size 10. Meaning, it can hold 10 floating-point values.

Key notes:
  • Arrays have 0 as the first index. In this example, val[0]
  • If the size of an array is n, then last element will be (n-1). In this example, val[9]
  • Suppose the starting address of val[0] is 2124d. Then, the next address, val[1], will be 2128d, address of val[2] will be 2132d and so on. Because size of float data type is 4 bytes.

Initialization of 1-D Array :

After an array is declared, it’s elements must be initialized. In C programming an array can be initialized at either of the following stages:
  • At compile time
  • At run time

Compile time initialization :

Compile time initialization of array elements is same as normal variable initialization. The general form of initialization of array is :


type array-name[size] = { list of values };

The values in the list are separated by commas. For ex, the statement

int number[3] = { 0,5,4 };

will declare the variable’ number’ as an array of size 3 and will assign the values to each element. If the number of values in the list is less than the number of elements, then only that many elements will be initialized. The remaining elements will be set to zero automatically.
Remember, if we have more initializers than the declared size, the compiler will produce an error.

Example :

#include <stdio.h>

int main () {

   int n[ 10 ] ;           /* n is an array of 10 integers */
    int i, j ;

   /* initialize elements of array n to 0 */         
    for ( i = 0; i < 10; i++ ) {
          n[ i ] = i + 100;        /* set element at location i to i + 100 */
   }
   
   /* output each array element's value */
   for (j = 0; j < 10; j++ ) {
      printf("Element[%d] = %d\n", j, n[j] );
   }

   return 0;
}

Output :

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Run time initialization :

An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing large array, or to initialize array with user specified values. 

Example :


#include<stdio.h>
int main()
{
int array[5],i;

    printf("Enter 5 numbers to store them in array : \n");

    for(i=0;i<5;i++)
    {
scanf("%d",&array[i]);
    }

    printf("Element in the array are : \n \n");

    for(i=0;i<5;i++)
    {
printf("Element stored at a[%d] : %d \n",i,array[i]);
    }
    return 0;
}

Output :

Enter 5 elements in the array : 23   45   32   25   45
Elements in the array are :
Element stored at a[0] : 23
Element stored at a[0] : 45
Element stored at a[0] : 32
Element stored at a[0] : 25
Element stored at a[0] : 45

Multi dimension Array :

In C, we can define multidimensional arrays in simple words as array of arrays. Data in multidimensional arrays are stored in tabular form.


General form of declaring N-dimensional arrays:

data_type  array_name[size1][size2]....[sizeN];

where,
data_type: Type of data to be stored in the array. 
           Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions


Two dimensional Array :

The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays.

Declaration :


    type array-name[row-size][column-size] 

    int a[3][4];
two dimensional array in c
Initialization :


int a[3][4] = {  
   {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
   {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
   {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
};

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Example :


#include <stdio.h>
int main () {

   /* an array with 5 rows and 2 columns*/
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
   int i, j;
   /* output each array element's value */
   for ( i = 0; i < 5; i++ ) {

      for ( j = 0; j < 2; j++ ) {
         printf("a[%d][%d] = %d\n", i,j, a[i][j] );
      }
   }
   
   return 0;
}

Output :

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

Three dimensional Array :

 Three-Dimensional array is same as that of Two-dimensional arrays. The difference is as the number of dimension increases so the number of nested braces will also increase.


Initialization of a three dimensional array :

You can initialize a three dimensional array in a similar way like a two dimensional array. Here's an example,

int test[2][3][4] = { 
                     { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
                     { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
                 };

Example :


#include<iostream>
using namespace std;
int main()
{
    // initializing the 3-dimensional array
    int x[2][3][2] =
    {
        { {0,1}, {2,3}, {4,5} },
        { {6,7}, {8,9}, {10,11} }
    };
    // output each element's value
    for (int i = 0; i < 2; ++i)
    {
        for (int j = 0; j < 3; ++j)
        {
            for (int k = 0; k < 2; ++k)
            {
                cout << "Element at x[" << i << "][" << j
                     << "][" << k << "] = " << x[i][j][k]
                     << endl;
            }
        }
    }
    return 0;
}

Output:

Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11

C Input / Output

C programming has several in-built functions to perform input and output tasks.
Two commonly used functions for I/O (Input/Output) are printf() and scanf().
printf() and scanf() functions are inbuilt functions in C programming environment which are available in C library by default. These functions are declared and related with “stdio.h” which is a header file in C language.

printf() method in C :

printf() function sends formatted output to the standard output(screen). printf() is used to show any message or value of any data type.
We use printf() function with %d format specifier to display the value of an integer variable. Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable.

To generate a newline,we use “\n” in C printf() statement.

Example 1 :

#include <stdio.h>      //This is needed to run printf() function.
int main()
{
    printf("C Programming");     //displays the content inside quotation
    return 0;


Output :

C Programming

Example 2 :

#include<stdio.h>
int main()
{
     int a = 5, b = 7;
     printf("Value of a = %d \n, a);
     printf("Value of b = %d, b);
     return 0;
}

Output :

Value of a = 5
Value of b =7 



scanf() method in C :

 scanf() function is used to read character, string, numeric data from keyboard.

Syntax :

scanf ("control string", &variable_name);

Example :


#include <stdio.h>
int main()
{
   char ch;
   char str[100];

   printf("Enter any character :\n");
   scanf("%c", &ch);

   printf("Entered character is %c \n", ch);

   printf("Enter any string : \n");
   scanf("%s", &str);

   printf("Entered string is %s \n", str);
}

Output :

Enter any character :
k
Entered character is k
Enter any string :
hello
Entered string is hello