Tuesday, March 10, 2020

ARRAYS, FUNCTIONS & POINTERS - C Language

Storage Class Specifiers
Storage class specifiers in C language tells the compiler where to store a variable, how to store the variable, what is the initial value of the variable and life time of the variable.
SYNTAX:
storage_specifier data_type variable _name;
TYPES OF STORAGE CLASS SPECIFIERS IN C:

There are 4 storage class specifiers available in C language. They are,
auto
extern
static
register

NOTE:
For faster access of a variable, it is better to go for register specifiers rather than auto specifiers.
Because, register variables are stored in register memory whereas auto variables are stored in main CPU memory.
Only few variables can be stored in register memory. So, we can use variables as register that are used very often in a C program.
1. EXAMPLE PROGRAM FOR AUTO VARIABLE IN C:
The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto variables by default.

Ex1:
#include<stdio.h>
void increment(void);
int main()
{
   increment();
   increment();
   increment();
   increment();
   return 0;
}

void increment(void)
{
   auto int i = 0 ;
   printf ( "%d ", i ) ;
   i++;
}

Output:
 0 0 0 0

2. EXAMPLE PROGRAM FOR STATIC VARIABLE IN C:
Static variables retain the value of the variable between different function calls.

//C static example
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( "%d ", i ) ;
i++;
}

Output:
0 1 2 3

3. EXAMPLE PROGRAM FOR EXTERN VARIABLE IN C:
The scope of this extern variable is throughout the main program. It is equivalent to global variable. Definition for extern variable might be anywhere in the C program.

Ex:
#include<stdio.h>

int x = 10 ;
int main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;

Output:
The value of x is 10
The value of y is 50

4. EXAMPLE PROGRAM FOR REGISTER VARIABLE IN C:
Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory.
Register variables will be accessed very faster than the normal variables since they are stored in register memory rather than main memory.
But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits)

Ex:
#include <stdio.h>
int main()
{
   register int i;
   int arr[5];// declaring array
   arr[0] = 10;// Initializing array
   arr[1] = 20;
   arr[2] = 30;
   arr[3] = 40;
   arr[4] = 50;
   for (i=0;i<5;i++)
   {
      // Accessing each variable
      printf("value of arr[%d] is %d \n", i, arr[i]);
   }
   return 0;
}

Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

Recursive functions

A function that calls itself is known as a recursive function. And, this technique is known as recursion.

The recursion continues until some condition is met to prevent it.
To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch makes the recursive call, and other doesn't.
Ex: Sum of Natural Numbers Using Recursion
#include <stdio.h>
int sum(int n);
void main()
{
    int n,res;
    printf("Enter a positive integer: ");
    scanf("%d", &n);
    res=sum(n);
    printf("sum = %d",res);
}
int sum(int n)
{
    if (n != 0)
        // sum() function calls itself
        return n + sum(n-1);
    else
        return n;
}

Output:
Enter a positive integer: 6
sum = 21

Ex2 : Factorial of a Number Using Recursion
#include<stdio.h>
long int fact(int n);
void main()
{
    int n;
    printf("Enter a positive integer: ");
    scanf("%d",&n);
    printf("Factorial of %d = %ld", n, fact(n));
}
long int fact(int n)
{
    if (n>=1)
        return n*fact(n-1);
    else
        return 1;
}

Output:
Enter a positive integer: 5
Factorial of 5 = 120

Towers of Hanoi
There is a story about an ancient temple in India has a large room with three towers surrounded by 64 golden disks. These disks are continuously moved by priests in the temple. According to a prophecy, when the last move of the puzzle is completed the world will end. These priests acting on the prophecy, follow the immutable rule by Lord Brahma of moving these disk one at a time. Hence this puzzle is often called Tower of Brahma(and also called Tower of Hanoi) puzzle.

Arrays
An array is a collection of homogeneous(all of the same type) data items,  accessed using a common name. You can store group of data of same data type in an array. Array might be belonging to any of the data types. Array size must be a constant value. Always, Contiguous (adjacent) memory locations are used to store array elements in memory.

EXAMPLE FOR C ARRAYS:
int a[10];       // integer array
char b[10];    // character array   i.e. string

Ex : Program to find size of any array
#include <stdio.h>
void main()
{
  int array[] = {15, 50, 34, 20, 10, 79, 100};
  int n=sizeof(array);
  printf("Size of the given array is %d\n", n/sizeof(int));
}

TYPES OF C ARRAYS:
There are 2 types of C arrays. They are,
One dimensional array
Multi dimensional array
      Two dimensional array
      Three dimensional array
      four dimensional array etc…

1. ONE DIMENSIONAL ARRAY IN C:
Syntax : Array declaration
data_type arr_name [arr_size];
Ex: Integer array:
int age [5]; 
int age[5]={0, 1, 2, 3, 4};

Ex: Character array:
char str[10];
char str[10]={‘H’,‘a’,‘i’};
(or)
char str[0] = ‘H’;
char str[1] = ‘a’;
char str[2] = ‘i;

EXAMPLE PROGRAM FOR ONE DIMENSIONAL ARRAY IN C:
#include<stdio.h>
 int main()
{
     int i;
     int arr[5] = {10,20,30,40,50};
            // declaring and Initializing array in C
        //To initialize all array elements to 0, use int arr[5]={0};
        /* Above array can be initialized as below also
        arr[0] = 10;
        arr[1] = 20;
        arr[2] = 30;
        arr[3] = 40;
        arr[4] = 50; */

     for (i=0;i<5;i++)
     {
         // Accessing each variable
         printf("value of arr[%d] is %d \n", i, arr[i]);
      }
}

Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50

2. TWO DIMENSIONAL ARRAY IN C:
Two dimensional array is nothing but array of array.
syntax : data_type array_name[num_of_rows][num_of_column];



float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns.


Similarly, you can declare a three-dimensional (3d) array. For example,
float y[2][4][3];
Here, the array y can hold 24 elements.

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

Ex:
#include<stdio.h>
void main()
{
   int i,j;
   // declaring and Initializing array
   int arr[2][2] = {10,20,30,40};
   /* Above array can be initialized as below also
      arr[0][0] = 10; // Initializing array
      arr[0][1] = 20;
      arr[1][0] = 30;
      arr[1][1] = 40; */
   for (i=0;i<2;i++)
   {
      for (j=0;j<2;j++)
      {
         // Accessing variables
         printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
      }
   }
}


Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

Passing individual array elements
Passing array elements to a function is similar to passing variables to a function.
Example 1: Passing an array
#include <stdio.h>
void display(int age1, int age2)
{
    printf("%d\n", age1);
    printf("%d\n", age2);
}

void main()
{
    int ageArray[] = {2, 8, 4, 12};

    // Passing second and third elements to display()
    display(ageArray[1], ageArray[2]);
 }

Output
8
4

Example 2: Passing arrays to functions
// Program to calculate the sum of array elements by passing to a function
#include <stdio.h>
float calculateSum(float age[]);
void main()
{
    float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};

    // age array is passed to calculateSum()
    result = calculateSum(age);
    printf("Result = %.2f", result);
}

float calculateSum(float age[])
{
  float sum = 0.0;
  for (int i = 0; i < 6; ++i)
 {
            sum += age[i];
  }
}

Output
Result = 162.50

Example 3: Passing two-dimensional arrays
#include <stdio.h>
void displayNumbers(int num[2][2]);
void main()
{
    int num[2][2];
    printf("Enter 4 numbers:\n");
    for (int i = 0; i < 2; ++i)
        for (int j = 0; j < 2; ++j)
            scanf("%d", &num[i][j]);

    // passing multi-dimensional array to a function
    displayNumbers(num);
}

void displayNumbers(int num[2][2])
{
    printf("Displaying:\n");
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 2; ++j) {
           printf("%d\n", num[i][j]);
        }
    }
}

Output
Enter 4 numbers:
2
3
4
5
Displaying:
2
3
4
5

Sparse Matrices
Any matrix is called a Sparse Matrix in C if it contains a large number of zeros. The mathematical formula behind this C Sparse Matrix is: T >= (m * n )/2, where T is the total number of zeros.
 
      Original Matrix                             Sparse Matrix Representation
 In above example matrix, there are only 6 non-zero elements ( those are 9, 8, 4, 2, 5 & 2) and matrix size is 5 X 6. We represent this matrix as shown in the above image. Here the first row in the right side table is filled with values 5, 6 & 6 which indicates that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values. Second row is filled with 0, 4, & 9 which indicates the value in the matrix at 0th row, 4th column is 9. In the same way the remaining non-zero values also follows the similar pattern.

Ex : program to check given matrix is a Sparse matrix or not.
/* C Program to check Matrix is a Sparse Matrix or Not */
 #include<stdio.h>
 void  main()
{
            int i, j, rows, columns, a[10][10], Total = 0;
            printf("\n Please Enter Number of rows and columns  :  ");
            scanf("%d %d", &i, &j);
            printf("\n Please Enter the Matrix Elements \n");
            for(rows = 0; rows < i; rows++)
            {
                        for(columns = 0;columns < j;columns++)
            {
                        scanf("%d", &a[rows][columns]);
            }
            }
            for(rows = 0; rows < i; rows++)
            {
                        for(columns = 0; columns < j; columns++)
            {
                        if(a[rows][columns] == 0)
                        {
                                    Total++;                     
                                    }
                        }
            }
            if(Total > (rows * columns)/2)
            {
                        printf("\n The Matrix that you entered is a Sparse Matrix ");
            }
            else
            {
                        printf("\n The Matrix that you entered is Not a Sparse Matrix ");
            }
}

 FUNCTIONS

1. WHAT IS C FUNCTION?
C functions are basic building blocks in a program. All C programs are written using functions to improve re-usability, understandability
A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed by “{  }” which performs specific operation in a C program. Actually, Collection of these functions creates a C program.

2. USES OF C FUNCTIONS:
C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.
We can call functions any number of times in a program and from any place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.

3.C FUNCTION DECLARATION, FUNCTION CALL AND FUNCTION DEFINITION:
There are 3 aspects in each C function. They are,

Function declaration or prototype  – This informs compiler about the function name, function parameters and  return value’s data type.
Function call – This calls the actual function
Function definition – This contains all the statements to be executed.
C functions aspects
syntax
function definition
Return_type function_name (arguments list)
{ Body of function; }
function call
function_name (arguments list);
function declaration
return_type function_name (argument list);

SIMPLE EXAMPLE PROGRAM FOR C FUNCTION:
As you know, functions should be declared and defined before calling in a C program.
In the below program, function “square” is called from main function.
The value of “m” is passed as argument to the function “square”. This value is multiplied by itself in this function and multiplied value “p” is returned to main function from function “square”.

Ex:
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );                              
// main function, program starts from here

int main( )              
{
    float m, n ;
    printf ( "\nEnter some number for finding square \n");
    scanf ( "%f", &m ) ;
    // function call
    n = square ( m ) ;                     
    printf ( "\nSquare of the given number %f is %f",m,n );
}

float square ( float x )   // function definition
{
    float p ;
    p = x * x ;
    return ( p ) ;
}

Output
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000

4. HOW TO CALL C FUNCTIONS IN A PROGRAM?
There are two ways that a C function can be called from a program. They are,

1.Call by value
2.Call by reference


1. CALL BY VALUE:
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
Note:

Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY VALUE):
In this program, the values of the variables “m” and “n” are passed to the function “swap”.
These values are copied to formal parameters “a” and “b” in swap function and used.

Ex:
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);         
void main()
{
    int m = 22, n = 44;
    // calling swap function by value
    printf(" values before swap  m = %d \nand n = %d", m, n);
    swap(m, n);                        
}

void swap(int a, int b)
{
    int tmp;
    tmp = a;
    a = b;
    b = tmp;
    printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}.

Output:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

2. CALL BY REFERENCE:
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both parameters.
EXAMPLE PROGRAM FOR C FUNCTION (USING CALL BY REFERENCE):
In this program, the address of the variables “m” and “n” are passed to the function “swap”.
These values are not copied to formal parameters “a” and “b” in swap function.
Because, they are just holding the address of those variables.
This address is used to access and change the values of the variables.

#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
void main()
{
    int m = 22, n = 44;
    //  calling swap function by reference
    printf("values before swap m = %d \n and n = %d",m,n);
    swap(&m, &n);        
}

void swap(int *a, int *b)
{
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
    printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

OUTPUT:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22

String
C Strings are nothing but array of characters ended with null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes.

EXAMPLE FOR C STRING:
char string[20] = {‘g’, ’u’, ‘u’, ‘u’, ‘o’, ‘f’, ‘s’, ‘t’, ‘u’, ’d’, ‘i’, ‘e’, ‘s’, ‘\0’};
(or)
char string[20] = “guruofstudies”;
(or)
char string []    = “guruofstudies”;

Difference between above declarations are, when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value.
When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program.

EXAMPLE PROGRAM FOR C STRING:
#include <stdio.h>
void main ()
{
   char string[20] = "gurunadh.pahimamguru.com";

   printf("The string is : %s \n", string );
 }

Output:
The string is : gurunadh.pahimamguru.com

C STRING FUNCTIONS:
Strings handling functions are defined under "string.h" header file. We need to include it in order to make use of these functions in our programs.
  
String functions
Description
Concatenates str2 at the end of str1
Copies str2 into str1
Gives the length of str1
Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2
Converts string to lowercase
Converts string to uppercase
Reverses the given string

Strcat()
strcat() concatenates (joins) two strings.
C strcat() Prototype
char *strcat(char *dest, const char *src)
It takes two arguments, i.e, two strings or character arrays, and stores the resultant concatenated string in the first string specified in the argument.
Ex:
#include <stdio.h>
#include <string.h>
void main()
{
    char str1[] = "This is ", str2[] = "pahimamguru.com";

    //concatenates str1 and str2 and resultant string is stored in str1.
    strcat(str1,str2);

    puts(str1);   
    puts(str2);
}

Output:
This is pahimamguru.com
pahimamguru.com

strcpy()
The strcpy() function copies the string to the another character array.
strcpy() Function prototype
char* strcpy(char* destination, const char* source);
The strcpy() function copies the string pointed by source (including the null character) to the character array destination.

The function also returns the copied array.
Ex:
#include <stdio.h>
#include <string.h>
void main()
{
    char str1[10]= "awesome";
    char str2[10];
    char str3[10];

    strcpy(str2, str1);
    strcpy(str3, "well");
    puts(str2);
    puts(str3);
}

Output:
awesome
well


Strlen()
The strlen() function takes a string as an argument and returns its length. The returned value is of type long int.
#include <stdio.h>
#include <string.h>
void main()
{
    char a[20]="Program";
    char b[20]={'P','r','o','g','r','a','m','\0'};

    printf("Length of string a = %ld \n",strlen(a));
    printf("Length of string b = %ld \n",strlen(b));
}

strcmp()
The strcmp() function compares two strings and returns 0 if both strings are identical.
strcmp() Prototype
int strcmp (const char* str1, const char* str2);

The strcmp() function takes two strings and returns an integer.
The strcmp() compares two strings character by character.

If the first character of two strings is equal, the next character of two strings are compared. This continues until the corresponding characters of two strings are different or a null character '\0' is reached.

Ex:
#include <stdio.h>
#include <string.h>
void main()
{
    char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
    int result;

    // comparing strings str1 and str2
    result = strcmp(str1, str2);
    printf("strcmp(str1, str2) = %d\n", result);

    // comparing strings str1 and str3
    result = strcmp(str1, str3);
    printf("strcmp(str1, str3) = %d\n", result);
}

Output:
strcmp(str1, str2) = 32
strcmp(str1, str3) = 0

strlwr()
The strlwr( ) function is a built-in function in C and is used to convert a given string into lowercase.
Syntax:
char *strlwr(char *str);
#include<stdio.h>
#include<string.h>
void main()
{
    char str[ ] = "ORACLE IS THE BEST";
      // converting the given string into lowercase.
    printf("%s\n",strlwr (str));
}

Output:
oracle is the best

strupr()
The strupr( ) function is used to converts a given string to uppercase.
Syntax:
char *strupr(char *str);

Ex:
#include<stdio.h>
#include<string.h>
void main()
{
    char str[ ] = "java is the best";
    //converting the given string into uppercase.
    printf("%s\n", strupr (str));
}

Output:
JAVA IS THE BEST


Strrev()
The strrev() function is a built-in function in C and is defined in string.h header file. The strrev() function is used to reverse the given string.
Syntax:
char *strrev(char *str);

Ex:
#include<stdio.h>
#include<string.h>
void main()
{
   char str[50] = "pahimam";
   printf("The given string is  %s\n",str);
   printf("After reversing string is =%s",strrev(str));
}

Ouput:
The given string is pahimam
After reversing string is pahimam

Pointer
Pointers in C language is a variable that stores/points the address of another variable.
Pointers (pointer variables) are special variables that are used to store addresses rather than values. A Pointer in C is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.

Pointer Syntax : data_type *var_name; Example : int *p;  char *p;

Where, * is used to denote that “p” is pointer variable and not a normal variable.

KEY POINTS TO REMEMBER ABOUT POINTERS IN C:
Normal variable stores the value whereas pointer variable stores the address of the variable.
The content of the C pointer always be a whole number i.e. address.
Always C pointer is initialized to null, i.e. int *p = null.
The value of null pointer is 0.
& symbol is used to get the address of the variable.
* symbol is used to get the value of the variable that the pointer is pointing to.

If a pointer in C is assigned to NULL, it means it is pointing to nothing.
Two pointers can be subtracted to know how many elements are available between these two pointers. But, Pointer addition, multiplication, division are not allowed. The size of any pointer is 2 byte (for 16 bit compiler).

Address in C
If you have a variable var in your program, &var will give you its address in the memory.
We have used address numerous times while using the scanf() function.
scanf("%d", &var);
Here, the value entered by the user is stored in the address of var variable.



Ex:
#include <stdio.h>
void main()
{
  int var = 5;
  printf("var: %d\n", var);
  // Notice the use of & before var
  printf("address of var: %p", &var);
}

Output:
var: 5
address of var: 2686778

Pointer Syntax
Here is how we can declare pointers.
int* p;
Here, we have declared a pointer p of int type.
You can also declare pointers in these ways.
int *p1;
int * p2;

Assigning addresses to Pointers
Ex:
int* pc, c;
c = 5;
pc = &c;
Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.

Get Value of Thing Pointed by Pointers
To get the value of the thing pointed by the pointers, we use the * operator.
Ex:
int* pc, c;
c = 5;
pc = &c;
printf("%d", *pc);   // Output: 5
Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we used *pc.

Note: In the above example, pc is a pointer, not *pc. You cannot and should not do something like *pc = &c;

By the way, * is called the dereference operator (when working with pointers). It operates on a pointer and gives the value stored in that pointer.

Changing Value Pointed by Pointers
Ex:
int* pc, c;
c = 5;
pc = &c;
c = 1;
printf("%d", c);    // Output: 1
printf("%d", *pc);  // Ouptut: 1
We have assigned the address of c to the pc pointer.

Then, we changed the value of c to 1. Since pc and the address of c is the same, *pc gives us 1.

Ex:
int* pc, c;
c = 5;
pc = &c;
*pc = 1;
printf("%d", *pc);  // Ouptut: 1
printf("%d", c);    // Output: 1
We have assigned the address of c to the pc pointer.
Then, we changed *pc to 1 using *pc = 1;. Since pc and the address of c is the same, c will be equal to 1.

Ex:
int* pc, c, d;
c = 5;
d = -15;
pc = &c; printf("%d", *pc); // Output: 5
pc = &d; printf("%d", *pc); // Ouptut: -15
Initially, the address of c is assigned to the pc pointer using pc = &c;. Since c is 5, *pc gives us 5.
Then, the address of d is assigned to the pc pointer using pc = &d;. Since d is -15, *pc gives us -15.

Ex:
#include <stdio.h>
void main()
{
   int* pc, c;
  
   c = 22;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c);  // 22
  
   pc = &c;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 22
  
   c = 11;
   printf("Address of pointer pc: %p\n", pc);
   printf("Content of pointer pc: %d\n\n", *pc); // 11
  
   *pc = 2;
   printf("Address of c: %p\n", &c);
   printf("Value of c: %d\n\n", c); // 2
}

Output:
Address of c: 2686784
Value of c: 22

Address of pointer pc: 2686784
Content of pointer pc: 22

Address of pointer pc: 2686784
Content of pointer pc: 11

Address of c: 2686784
Value of c: 2

Ex: write a program to print addresses of array elements.
#include <stdio.h>
void main()
{
   int x[4];
   int i;
   for(i = 0; i < 4; ++i) {
      printf("&x[%d] = %p\n", i, &x[i]);
   }
   printf("Address of array x: %p", x);
}

Output:
&x[0] = 1450734448
&x[1] = 1450734452
&x[2] = 1450734456
&x[3] = 1450734460
Address of array x: 1450734448

There is a difference of 4 bytes between two consecutive elements of array x. It is because the size of int is 4 bytes (on our compiler).

Notice that, the address of &x[0] and x is the same. It's because the variable name x points to the first element of the array.

From the above example, it is clear that &x[0] is equivalent to x. And, x[0] is equivalent to *x.

Similarly,

&x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
&x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
...
Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).

Ex1: Pointers and Arrays
#include <stdio.h>
void main()
 {
  int i, x[6], sum = 0;
  printf("Enter 6 numbers: ");
  for(i = 0; i < 6; ++i) {
  // Equivalent to scanf("%d", &x[i]);
      scanf("%d", x+i);

  // Equivalent to sum += x[i]
      sum += *(x+i);
  }
  printf("Sum = %d", sum);
}

Output:
Enter 6 numbers:  2
 3
 4
 4
 12
 4
Sum = 29

Ex 2:
#include <stdio.h>
int main()
{
   int *ptr, q;
   q = 50;
   /* address of q is assigned to ptr */
   ptr = &q;
   /* display q's value using ptr variable */
   printf("%d", *ptr);
   return 0;
}

Output: 50

Ex 3: Arrays and Pointers
#include <stdio.h>
void main()
{
  int x[5] = {1, 2, 3, 4, 5};
  int* ptr;

  // ptr is assigned the address of the third element
  ptr = &x[2];

  printf("*ptr = %d \n", *ptr);   // 3
  printf("*(ptr+1) = %d \n", *(ptr+1)); // 4
  printf("*(ptr-1) = %d", *(ptr-1));  // 2
}

Output:
*ptr = 3
*(ptr+1) = 4
*(ptr-1) = 2

In this example, &x[2], the address of the third element, is assigned to the ptr pointer. Hence, 3 was displayed when we printed *ptr.
And, printing *(ptr+1) gives us the fourth element. Similarly, printing *(ptr-1) gives us the second element.


Ex: Passing Pointers to Functions
#include <stdio.h>
void addOne(int* ptr) {
  (*ptr)++; // adding 1 to *ptr
}
void  main()
{
  int* p, i = 10;
  p = &i;
  addOne(p);

  printf("%d", *p); // 11
}

Output:
11

Structures
Structure is a group of variables of different data types represented by a single name. We use struct keyword to create a structure in C.
Ex:
struct struct_name
{
   DataType member1_name;
   DataType member2_name;
   DataType member3_name;
 };

Ex:
struct Person
{
    char name[50];
    int citNo;
    float salary;
};
Here struct_name can be anything of your choice. Members data type can be same or different. Once we have declared the structure we can use the struct name as a data type like int, float etc.

Declaration of variable of a structure
struct  struct_name  var_name;
or

struct struct_name
{
   DataType member1_name;
   DataType member2_name;
   DataType member3_name;
  
 } var_name;

Accessing data members of a structure using a struct variable
var_name.member1_name;
var_name.member2_name;

Assigning values to structure members
There are different ways to assign values to structrure.
1) Using Dot(.) operator
Ex : var_name.memeber_name = value;

2) All members assigned in one statement
Ex :
struct struct_name var_name = {value for memeber1, value for memeber2 ůso on for all the members}

Ex : Program
#include <stdio.h>
/* Created a structure here. The name of the structure is
 * StudentData.
 */
struct StudentData
{
    char *stu_name;
    int stu_id;
    int stu_age;
};
void main()
{
     /* student is the variable of structure StudentData*/
     struct StudentData student;

     /*Assigning the values of each struct member here*/
     student.stu_name ="Guru";
     student.stu_id = 556677;
     student.stu_age = 25;

     /* Displaying the values of struct members */
     printf("Student Name is: %s", student.stu_name);
     printf("\nStudent Id is: %d", student.stu_id);
     printf("\nStudent Age is: %d", student.stu_age);
}


Ex1:
#include <stdio.h>
/* Creation of structure,here the name of the structure is student.*/
struct student
{
    char *name;
    int id;
    int age;
};
void main()
{
     /* std is the variable of structure student*/
     struct student std;

     /*Assigning the values of each struct member here*/
     std.name = "Virag";
     std.id = 667788;
     std.age = 25;

     /* Displaying the values of struct members */
     printf("Student Name is: %s", std.name);
     printf("\nStudent Id is: %d", std.id);
     printf("\nStudent Age is: %d", std.age);
}

Nested Structure in C: Struct inside another struct
We can use a structure inside another structure, which is fairly possible. Once we declared a structure, the struct struct_name acts as a new data type so you can include it in another structure just like the data type of other data members.

Ex:
Structure 1: std_address

struct std_address
{
     int street;
     char *state;
     char *city;
     char *country;
};

Structure 2: std_data
struct std_data
{
    int stu_id;
    int stu_age;
    char *stu_name;
    struct std_address stdAddr;
};

Assignment for struct inside struct (Nested struct)
struct  std_data  mydata;
mydata.stu_id = 1001;
mydata.stu_age = 18;
mydata.stdAddr.state = "UP"; //Nested struct assignment


Ex2: Program using Nestead Structure
#include <stdio.h>
struct std_address
{
     int street;
     char *state;
     char *city;
     char *country;
};
struct std_data
{
    int stu_id;
    int stu_age;
    char *stu_name;
    struct std_address stdAddr;
};
void main()
{
  struct  std_data  mydata;
  mydata.stu_id = 1001;
  mydata.stu_age = 18;
  mydata.stu_name="Kamal";
  mydata.stdAddr.street = 777; //Nested struct assignment
  mydata.stdAddr.state = "Andhra Pradesh"; //Nested struct assignment
  mydata.stdAddr.city = "Visakhapatnam"; //Nested struct assignment 
  mydata.stdAddr.country = "India"; //Nested struct assignment
  /* Displaying the values of struct members */
  printf("\nStudent Id is: %d", mydata.stu_id);
  printf("\nStudent Age is: %d", mydata.stu_age);
  printf("\nStudent Name is: %s", mydata.stu_name);
  printf("\nStudent Adress is :\n");
  printf("\nStudent Street No: %d", mydata.stdAddr.street);
  printf("\nStudent State : %s", mydata.stdAddr.state);
  printf("\nStudent City : %s", mydata.stdAddr.city);
  printf("\nStudent Country : %s", mydata.stdAddr.country);
}


Ex3: program to generate student report card.

#include <stdio.h>
struct student
{
    //char name[50];
    char* name;
    int rollno;
    int m1,m2,m3,m4,m5;
    ;
};
void main()
{
    struct student s;
    int state=0;
    printf("Enter information:\n");
    printf("\nEnter roll number: ");
    scanf("%d", &s.rollno);
    printf("\nEnter name: ");
    scanf("%s", s.name);
    //fgets(s.name, sizeof(s.name), stdin);
    printf("\nEnter marks: ");
    scanf("%d\n", &s.m1);
    scanf("%d\n", &s.m2);
    scanf("%d\n", &s.m3);
    scanf("%d\n", &s.m4);
    scanf("%d\n", &s.m5);
    int tot=s.m1+s.m2+s.m3+s.m4+s.m5;
    float avg=tot/5;
    if(s.m1>=50 && s.m2>=50 &s.m3>=50&&s.m4>=50&&s.m5>=50)
    {
        state=1;
        if(avg>=75)
          state=2;
    }
    printf("Displaying Information:\n");
    printf("Name: ");
    printf("%s", s.name);
    printf("Roll number: %d\n", s.rollno);
    if(state>0)
    {
        printf("Subject 1 Marks: %d\n", s.m1);
        printf("Subject 2 Marks: %d\n", s.m2);
        printf("Subject 3 Marks: %d\n", s.m3);
        printf("Subject 4 Marks: %d\n", s.m4);
        printf("Subject 5 Marks: %d\n", s.m5);
        printf("Total Marks: %d\n",tot);
        printf("Average  Marks: %.1f\n",avg);
        if(state=1)
           printf("Result : PASS");
        else
           printf("Result : PASS with Distinction");
    }
    else
           printf("Result : FAIL");
}

Structures
Structure is a group of variables of different data types represented by a single name. We use struct keyword to create a structure in C.

Ex:
struct struct_name {
   DataType member1_name;
   DataType member2_name;
   DataType member3_name;
   ů
};

Ex:
struct Person
{
    char name[50];
    int citNo;
    float salary;
};
Here struct_name can be anything of your choice. Members data type can be same or different. Once we have declared the structure we can use the struct name as a data type like int, float etc.

Declaration of variable of a structure
struct  struct_name  var_name;
or

struct struct_name {
   DataType member1_name;
   DataType member2_name;
   DataType member3_name;
   ů
} var_name;

Accessing data members of a structure using a struct variable
var_name.member1_name;
var_name.member2_name;

Assigning values to structure members
There are different ways to assign values to structrure.
1) Using Dot(.) operator
Ex : var_name.memeber_name = value;

2) All members assigned in one statement
Ex :
struct struct_name var_name = {value for memeber1, value for memeber2 ůso on for all the members}

Ex : Program
#include <stdio.h>
/* Created a structure here. The name of the structure is
 * StudentData.
 */
struct StudentData
{
    char *stu_name;
    int stu_id;
    int stu_age;
};
void main()
{
     /* student is the variable of structure StudentData*/
     struct StudentData student;

     /*Assigning the values of each struct member here*/
     student.stu_name ="Guru";
     student.stu_id = 556677;
     student.stu_age = 25;

     /* Displaying the values of struct members */
     printf("Student Name is: %s", student.stu_name);
     printf("\nStudent Id is: %d", student.stu_id);
     printf("\nStudent Age is: %d", student.stu_age);
}


Ex1:
#include <stdio.h>
/* Creation of structure,here the name of the structure is student.*/
struct student
{
    char *name;
    int id;
    int age;
};
void main()
{
     /* std is the variable of structure student*/
     struct student std;

     /*Assigning the values of each struct member here*/
     std.name = "Virag";
     std.id = 667788;
     std.age = 25;

     /* Displaying the values of struct members */
     printf("Student Name is: %s", std.name);
     printf("\nStudent Id is: %d", std.id);
     printf("\nStudent Age is: %d", std.age);
}

Nested Structure in C: Struct inside another struct
We can use a structure inside another structure, which is fairly possible. Once we declared a structure, the struct struct_name acts as a new data type so you can include it in another structure just like the data type of other data members.

Ex:
Structure 1: std_address

struct std_address
{
     int street;
     char *state;
     char *city;
     char *country;
};

Structure 2: std_data
struct std_data
{
    int stu_id;
    int stu_age;
    char *stu_name;
    struct std_address stdAddr;
};

Assignment for struct inside struct (Nested struct)
struct  std_data  mydata;
mydata.stu_id = 1001;
mydata.stu_age = 18;
mydata.stdAddr.state = "UP"; //Nested struct assignment


Ex2: Program using Nestead Structure
#include <stdio.h>
struct std_address
{
     int street;
     char *state;
     char *city;
     char *country;
};
struct std_data
{
    int stu_id;
    int stu_age;
    char *stu_name;
    struct std_address stdAddr;
};
void main()
{
  struct  std_data  mydata;
  mydata.stu_id = 1001;
  mydata.stu_age = 18;
  mydata.stu_name="Kamal";
  mydata.stdAddr.street = 777; //Nested struct assignment
  mydata.stdAddr.state = "Andhra Pradesh"; //Nested struct assignment
  mydata.stdAddr.city = "Visakhapatnam"; //Nested struct assignment 
  mydata.stdAddr.country = "India"; //Nested struct assignment
  /* Displaying the values of struct members */
  printf("\nStudent Id is: %d", mydata.stu_id);
  printf("\nStudent Age is: %d", mydata.stu_age);
  printf("\nStudent Name is: %s", mydata.stu_name);
  printf("\nStudent Adress is :\n");
  printf("\nStudent Street No: %d", mydata.stdAddr.street);
  printf("\nStudent State : %s", mydata.stdAddr.state);
  printf("\nStudent City : %s", mydata.stdAddr.city);
  printf("\nStudent Country : %s", mydata.stdAddr.country);
}


Ex3: program to generate student report card.
#include <stdio.h>
struct student
{
    //char name[50];
    char* name;
    int rollno;
    int m1,m2,m3,m4,m5;
    ;
};
void main()
{
    struct student s;
    int state=0;
    printf("Enter information:\n");
    printf("\nEnter roll number: ");
    scanf("%d", &s.rollno);
    printf("\nEnter name: ");
    scanf("%s", s.name);
    //fgets(s.name, sizeof(s.name), stdin);
    printf("\nEnter marks: ");
    scanf("%d\n", &s.m1);
    scanf("%d\n", &s.m2);
    scanf("%d\n", &s.m3);
    scanf("%d\n", &s.m4);
    scanf("%d\n", &s.m5);
    int tot=s.m1+s.m2+s.m3+s.m4+s.m5;
    float avg=tot/5;
    if(s.m1>=50 && s.m2>=50 &s.m3>=50&&s.m4>=50&&s.m5>=50)
    {
        state=1;
        if(avg>=75)
          state=2;
    }
    printf("Displaying Information:\n");
    printf("Name: ");
    printf("%s", s.name);
    printf("Roll number: %d\n", s.rollno);
    if(state>0)
    {
        printf("Subject 1 Marks: %d\n", s.m1);
        printf("Subject 2 Marks: %d\n", s.m2);
        printf("Subject 3 Marks: %d\n", s.m3);
        printf("Subject 4 Marks: %d\n", s.m4);
        printf("Subject 5 Marks: %d\n", s.m5);
        printf("Total Marks: %d\n",tot);
        printf("Average  Marks: %.1f\n",avg);
        if(state=1)
           printf("Result : PASS");
        else
           printf("Result : PASS with Distinction");
    }
    else
           printf("Result : FAIL");
}

UNION
C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a union is called member. Union and structure in C  are same in concepts, except allocating memory for their members. Structure allocates storage space for all its members separately. Whereas, Union allocates one common storage space for all its members.

We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately.
Many union variables can be created in a program and memory will be allocated for each union variable separately.

Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union.

Ex: EXAMPLE PROGRAM FOR C UNION:
#include <stdio.h>
#include <string.h>

union student
{
            char name[20];
            char subject[20];
            float percentage;
};
 void main()
{
    union student record1;
    union student record2;

    // assigning values to record1 union variable
       strcpy(record1.name, "Nammu");
       strcpy(record1.subject, "Maths");
       record1.percentage = 86.50;

       printf("Union record1 values example\n");
       printf(" Name       : %s \n", record1.name);
       printf(" Subject    : %s \n", record1.subject);
       printf(" Percentage : %f \n\n", record1.percentage);

    // assigning values to record2 union variable
       printf("Union record2 values example\n");
       strcpy(record2.name, "Guru");
       printf(" Name       : %s \n", record2.name);

       strcpy(record2.subject, "Computers");
       printf(" Subject    : %s \n", record2.subject);

       record2.percentage = 99.50;
       printf(" Percentage : %f \n", record2.percentage);
}

Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Guru
Subject : Computers
Percentage : 99.500000

Another way of declaring a Union
#include <stdio.h>
#include <string.h>
union student
{
            char name[20];
            char subject[20];
            float percentage;
}record;

Enumerated Data Types
In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used.
Syntax
enum flag {const1, const2, ..., constN};
By default, const1 is 0, const2 is 1 and so on. You can change default values of enum elements during declaration (if necessary).

Ex:
enum colors{red,green,blue,pink};
// Changing default values of enum constants
enum colors
{
    red=0,
    green=10,
    blue=20,
    pink=3
};
Ex1:
#include <stdio.h>
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
void main()
{
    // creating today variable of enum week type
    enum week today;
    today = Thursday;
    printf("Day %d",today+1);
}

Output:  Day 5


Thursday, March 5, 2020

Files In C Language

File : A file is a container in computer storage devices used for storing data.
Types of Files
1.Text files
2.Binary files

Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such as Notepad.

They take minimum effort to maintain, are easily readable, and provide the least security and takes bigger storage

space.

Binary files
Binary files are mostly the .bin files in your computer. Instead of storing data in plain text, they store it in the

binary form (0's and 1's). They can hold a higher amount of data, are not readable easily, and provides better

security than text files.

File Operations
In C, you can perform four major operations on files, either text or binary:
1.Creating a new file
2.Opening an existing file
3.Closing a file
4.Reading from and writing information to a file

Working with files
When working with files, you need to declare a pointer of type file. This declaration is needed for communication

between the file and the program.
Syntax : FILE *fptr;

Modes of opening a file
r    - open for reading
w   - open for writing
a   - open for append
r+  - open for both reading and writing
w+  - open for both reading and writing
a+   - open for both reading and appending

Predefined Functions in C Language
1.Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
2.Opening an existing file (fopen)
3.Reading from file (fscanf or fgetc)
4.Writing to a file (fprintf or fputs)
5.Moving to a specific location in a file (fseek, rewind)
6.Closing a file (fclose)

Opening a file - for creation and edit
Opening a file is performed using the fopen() function defined in the stdio.h header file.

The syntax for opening a file in standard I/O is:
ptr = fopen("fileopen","mode");

Ex:
fopen("D:\\test\\guru.txt","w");
Note :
If the file guru.txt doesn't exist in the location D:\test. The first function creates a new file named guru.txt and

opens it for writing as per the mode 'w'.

fopen("D:\\test\\guru.bin","rb");
Note:
Above function opens the existing file for reading in binary mode 'rb'. The reading mode only allows you to read

the file, you cannot write into the file.

Closing a File
The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using the fclose() function.

fclose(fptr);
Here, fptr is a file pointer associated with the file to be closed.

Example 1: Write to a text file
#include <stdio.h>
#include <stdlib.h>
void  main()
{
   int num;
   FILE *fptr;
   fptr = fopen("D:\\guru.txt","w");

   if(fptr == NULL)
   {
      printf("Error!"); 
      exit(1);           
   }
   printf("Enter num: ");
   scanf("%d",&num);
   fprintf(fptr,"%d",num);
   fclose(fptr);
}

Example 2: Program to Open a File, Write in it, And Close the File
# include <stdio.h>
# include <string.h>
void main( )
{
    // Declare the file pointer
    FILE *filePointer ;

    // Get the data to be written in file
    char dataToBeWritten[50]="gurunadh.pahimamguru.com";
    // Open the existing file GfgTest.c using fopen()
    // in write mode using "w" attribute
    filePointer = fopen("gurufile.c", "w") ;
     
    // Check if this filePointer is null
    // which maybe if the file does not exist
    if ( filePointer == NULL )
    {
        printf( "gurufile.c file failed to open." ) ;
    }
    else
    {
        printf("The file is now opened.\n") ;
        // Write the dataToBeWritten into the file
        if ( strlen (  dataToBeWritten  ) > 0 )
        {
            // writing in the file using fputs()
            fputs(dataToBeWritten, filePointer) ;   
            fputs("\n", filePointer) ;
        }
        // Closing the file using fclose()
        fclose(filePointer) ;
         
        printf("Data successfully written in file gurufile.c\n");
        printf("The file is now closed.") ;
    }
 }

Example 3: Program to Open a File, Read from it, And Close the File
# include <stdio.h>
# include <string.h>
void main( )
{
    // Declare the file pointer
    FILE *filePointer ;
    // Declare the variable for the data to be read from file
    char dataToBeRead[50];
 
    // Open the existing file gurufile.c using fopen()
    // in read mode using "r" attribute
    filePointer = fopen("gurufile.c", "r") ;
     
    // Check if this filePointer is null
    // which maybe if the file does not exist
    if ( filePointer == NULL )
    {
        printf( "gurufile.c file failed to open." ) ;
    }
    else
    {
        printf("The file is now opened.\n") ;
        // Read the dataToBeRead from the file
        // using fgets() method
        while( fgets ( dataToBeRead, 50, filePointer ) != NULL )
        {
            // Print the dataToBeRead 
            printf( "%s" , dataToBeRead ) ;
         }
        // Closing the file using fclose()
        fclose(filePointer) ;
        printf("Data successfully read from file gurufile.c\n");
        printf("The file is now closed.") ;
    }
}

Tuesday, February 25, 2020

Graphs In Data Structures

    

A graph is a non-linear data structure that consists of a finite set of nodes and a set of edges connecting them. The nodes are sometimes also referred to as vertices and the edges are lines or arcs that connect any two nodes.

A graph is a set of (V,E) pairs, where 
V - set of vertices - Represented as Circles -  Also know as Nodes
E - set pf edges     - Represented as Lines - connecting lines of vertices/nodes
Example 1:
















Note :
Tree : For a tree if N nodes are there then (N-1) edges will be there, one edge for each parent-child relationship.
Graph : For a Graph there are no rules for connections.
Example 2:
  Fig 1                                                                                                                                             Fig 2
Note : In the above two figures Fig 1 is a Tree and a Graph as well. Where as Fig 2 is only a Graph.
A pair (x,y) is referred to as an edge, which communicates that the x vertex connects to the y vertex.

A graph G is an ordered pair of set V of vertices and a set E of edges.
G=(V,E)
Ordered pair:
(a,b) is not equal to (b,a), if a is not equal to b
Unordered pait:
{a,b}={b,a}




Graphs are used to solve real-life problems that involve representation of the problem space as a network. Examples of networks include telephone networks, circuit networks, social networks (like LinkedIn, Facebook etc.).
Ex : Undirected Graph
For example, a single user in Facebook can be represented as a node (vertex) while their connection with others can be represented as an edge between nodes. Each node can be a structure that contains information like user’s id, name, gender, etc.


             Above Graph showis a Social Network (Nodes as users and Edges show connection)

Terminology
Node - Also know as  vertex
Edge - Connecting line between any two nodes
            These are two types. Directed Edge in which connection is one way and Undirected edge in
            which connection is two way.
            Directed  Edge (u,v) and Undirected Edge {u,v} 
Adjacent nodes - which are connected to both ends of an edge
Degree of a Node - No of edges connected to a node
Size of a graph - total no of edges in a graph
Path -   A path is a sequence of vertices where each adjacent pair is connected by an edge.
           
         


Types of Graphs
Directed Graph(unidirectional)
Un-Directed Graph(bidirectional) - no direction is specified on edges
Weighted Graph - weight is specified for each edge
Unweighted Graph  - weight is not specified for any edge
Cyclic Graph - A graph which contains cycles(loops)
Acyclic Graph - A graph which do not contain cycles(loops)

Directed Graph
In a directed graph, nodes are connected by directed edges – they only go in one direction. For example, if an edge connects node 1 and 2, but the arrow head points towards 2, we can only traverse from node 1 to node 2 – not in the opposite direction.

Un-Directed Graph
In an undirected graph, nodes are connected by edges that are all bidirectional. For example if an edge connects node 1 and 2, we can traverse from node 1 to node 2, and from node 2 to 1.



Ex : Directed Graph is useful in Web-Crawling is nothing but Graph Traversal , It is an act of visiting all nodes in a graph.


Weighted Graph - weight is specified for each edge

Unweighted Graph  - weight is not specified for any edge (or) All edges are having same edge
(OR)
A weighted graph with all edges having weight=1 unit
UnDirected Graph :
Ex :Intercity Road Network :  Network of Highways and 3 ways between cities. 

Directed Graph :
Ex: Intracity Road Network : Network within a city. One way roads.It is a weighted .
.

Edges in the above graph are waited and it is called as weighted graph.

**Social Network is unweighted and undirected graph
**WWW is unweighted and directed graph


Cyclic Graph - A graph which contains cycles(loops)
Acyclic Graph - A graph which do not contain cycles(loops)



Types of Graph Representations:
Adjacency List
To create an Adjacency list, an array of lists is used. The size of the array is equal to the number of nodes.
A single index, array[i] represents the list of nodes adjacent to the ith node.
We make use of Linked List to represent "Adjacency List". For each vertex one Linked List is maintained.
Ex1:
Ex2:

Adjacency Matrix:
An Adjacency Matrix is a 2D array of size V x V where V is the number of nodes in a graph. A slot matrix[i][j] = 1 indicates that there is an edge from node i to node j.
[OR]
It is a Matrix a[n][n], where n is number of Vertices and a[i][j]=1 if i & j are adjacent
other wise a[i][j]=0.
Ex:

The Matrix representation of above Graph is given below

Graph Traversal
Graph traversal is a technique used for a searching vertex in a graph. The graph traversal is also used to decide the order of vertices is visited in the search process. A graph traversal finds the edges to be used in the search process without creating loops. That means using graph traversal we visit all the vertices of the graph without getting into looping path.

There are two graph traversal techniques and they are as follows...

DFS (Depth First Search)
BFS (Breadth First Search)

DFS (Depth First Search)
DFS traversal of a graph produces a spanning tree as final result. Spanning Tree is a graph without loops. We use Stack data structure with maximum size of total number of vertices in the graph to implement DFS traversal.
We use the following steps to implement DFS traversal...

Back tracking : Means coming back to the vertex from which we reached the current vertex.

Step 1 - Define a Stack of size total number of vertices in the graph.
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it on to the Stack.
Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the top of stack and push it on to the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at the top of the stack.
Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from the stack.
Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused edges from the graph

Ex : consider the following example





Wednesday, February 5, 2020

Binary Tree Introduction Graphically


Tyes Of Binary Trees

Full Binary Tree / Strictly Binary Tree

Incomplete Binary Tree / Almost Complete Binary Tree
The following is not an Incomplete BinaryTree. Because for node “E” we have  child “J” which is filled from Right instead of Left side. So it is not satisfying the condition of Incomplete Binary Tree.
Complete Binary Tree
The following is Not a Complete Binary Tree as it is not satisfying the condition of Complete Binary Tree.i.e 2nd Level does not contain 4 nodes.

 Left Skewed Binary Tree
 Left Skewed Binary Tree  & Right Skewed Binary Tree
 All Binary Trees Together

Thursday, January 23, 2020

Java Database Connectivity with Oracle

Java Database Connectivity with Oracle

Connecting to Oracle Datatabase using a Java Application
About JDBC
JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers:
1.JDBC- ODBC bridge driver
2.Native -API driver (partially java driver)
3.Network Protocol driver (fully java driver)
4.Thin driver (fully java driver) – recommended to use

There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
Register the Driver class
Create connection
Create Statement/Prepare Statement
Execute queries
Close connection

1.Diver class: The driver class for the oracle database is "oracle.jdbc.driver.OracleDriver."
   Syntax : Class.forName("Diver class")
2.Connection URL: The connection URL for the oracle10G database is “jdbc:oracle:thin:@localhost:1521:xe”  where jdbc is the API, oracle is the database, thin is the driver, localhost is the server name on which oracle is  running, we may also use IP address, 1521 is the port number and XE is the Oracle service name. You may get all these information from the tnsnames.ora file.
  
   jdbc - api
   oracle - databaes
   thin   - driver type
   1521 - exculusive port number of oracle listener
   Syntax : Connection con=DriverManager.getConnection("Connection URL");

3.Username: The default username for the oracle database is system.

4.Password: It is the password given by the user at the time of installing the oracle database.

5. Get downloaded file "ojdbc14.jar" and copy the file in the folder  jre/lib/ext
    Ex: C:\Program Files (x86)\Java\jre1.8.0_60\lib\ext

Program to Connect to Oracle and retrieve the data from a table.
import java.sql.*; 
class OracleCon
{ 
  public static void main(String args[])
 { 
    try
   { 
     //step1 load the driver class 
     Class.forName("oracle.jdbc.driver.OracleDriver"); 
     //step2 create  the connection object 
    Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr"); 
         //step3 create the statement object 
     //Statement stmt=con.createStatement();
     PreparedStatement ps=con.prepareStatement("select * from emp"); 
     ResultSet rs=ps.executeQuery();
      //step4 execute query 
      //ResultSet rs=stmt.executeQuery("select * from employees"); 
      while(rs.next()) 
          System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3)); 
 
      //step5 close the connection object 
        con.close(); 
   }
   catch(Exception e)
   {
      System.out.println(e);
   } 
} 
}

Output:
E:\>javac OracleCon.java
E:\>java OracleCon
111  NAMMU  ANALYST
222  MOHAN  CLERK
333  GURU  MANAGER
444  KRISHNA  ENGINEER

Java ResultSetMetaData Interface
If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is used
Commonly used methods of ResultSetMetaData interface
Commonly used methods of ResultSetMetaData interface
Method                                                                          Description
public int getColumnCount()throws SQLException               it returns the total number of
                                                                                          columns in the ResultSet object.
public String getColumnName(int index)     it returns the column name of the specified
throws SQLException                                  column index.
public String getColumnTypeName(int index)   it returns the column type name
throws SQLException                                        for the specified index.
public String getTableName(int index)           it returns the table name for the
throws SQLException                                    specified column index.


Write a program to Display Resultset Metadata

import java.sql.*; 
class rsmd{ 
public static void main(String args[]){ 
try{ 
Class.forName("oracle.jdbc.driver.OracleDriver"); 
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","hr","hr"); 
 
PreparedStatement ps=con.prepareStatement("select * from emp"); 
ResultSet rs=ps.executeQuery(); 
ResultSetMetaData rsmd=rs.getMetaData(); 
 
System.out.println("Total columns: "+rsmd.getColumnCount()); 
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1)); 
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); 
 
con.close(); 
}catch(Exception e){ System.out.println(e);} 
} 
} 
Output:
E:\>javac rsmd.java
E:\>java rsmd
Total columns: 5
Column Name of 1st column: EMPNO
Column Type Name of 1st column: NUMBER

Towers Of Hanoi Program

//Program to demonstrate Towers Of Hanoi 
import java.util.Scanner;
class tb

// Java recursive function to solve tower of BRAHMA/HANOI puzzle 
 static int c=0;   
 static void th(int n, char ST, char DT, char TT) 
    { 
        if (n == 1) 
        { 
            System.out.println("Move disk 1 from PEG " +  ST + " to PEG " + DT); 
            c++;
            return; 
        } 
        th(n-1, ST, TT, DT); 
        System.out.println("Move disk " + n + " from PEG " +  ST + " to PEG " + DT); 
        c++;
        th(n-1, TT, DT, ST);
         
    }
    public static void main(String args[]) 
    { 
        Scanner s=new Scanner(System.in);
        System.out.println("Enter Number Of Disks To Move:");
        int n = s.nextInt(); // Number of disks 
        th(n, 'A', 'C', 'B');  // A, B and C are names of PEG/TOWERS
        System.out.println("\nTotal Number Of Moves Occurred: "+c); 
    }
}

Output:
E:\>java tb
Enter Number Of Disks To Move:
1
Move disk 1 from PEG A to PEG C

Total Number Of Moves Occurred: 1

E:\>java tb
Enter Number Of Disks To Move:
2
Move disk 1 from PEG A to PEG B
Move disk 2 from PEG A to PEG C
Move disk 1 from PEG B to PEG C

Total Number Of Moves Occurred: 3

E:\>java tb
Enter Number Of Disks To Move:
3
Move disk 1 from PEG A to PEG C
Move disk 2 from PEG A to PEG B
Move disk 1 from PEG C to PEG B
Move disk 3 from PEG A to PEG C
Move disk 1 from PEG B to PEG A
Move disk 2 from PEG B to PEG C
Move disk 1 from PEG A to PEG C

Total Number Of Moves Occurred: 7

Towers Of Brahma or Towers of Hanoi

There is a story about an ancient temple in India has a large room with three towers surrounded by 64 golden disks. These disks are continuously moved by priests in the temple. According to a prophecy, when the last move of the puzzle is completed the world will end. These priests acting on the prophecy, follow the immutable rule by Lord Brahma of moving these disk one at a time. Hence this puzzle is often called Tower of Brahma(and also called Tower of Hanoi) puzzle.

https://www.hackerearth.com/blog/become-better-developer

What is the game of Tower of Hanoi?
Tower of Hanoi consists of three pegs or towers with n disks placed one over the other.
The objective of the puzzle is to move the stack to another peg following these simple rules.
Only one disk can be moved at a time.
No disk can be placed on top of the smaller disk

But what about the prophecy for the tower of Hanoi where the priests are using 64 disks?
Suppose that these priests are highly powerful and can move these massive disks at a speed of 1 per second per hour every day. At this speed, they would need 2^64 -1 move to complete the task.
That is, 18,446,744,073,709,551,615 moves to complete, which would take about 580 billion years

Tower of hanoi recursion explained, Tower of Hanoi, Tower of Hanoi recursion, Recursion explained, Tower of Hanoi explain

Wednesday, January 1, 2020

 Merge Sort ::  Data structure | Merge Sort using JAVA code

File Name : Mrgsrt.java
import java.util.*;
public class Mrgsrt
{
    public static void main(String[] args)
   {
      int a[],n,i;
      Scanner s=new Scanner(System.in);
      System.out.println("Enter size of the aay: ");
      n=s.nextInt(); 
      a=new int[n];
      System.out.println("Enter "+n+" Elements : ");
      for (i=0;i<n;i++)
      a[i]=s.nextInt();
      System.out.println("Elements in Array Before Merge Sort is: ");
      for (i=0;i<n; i++)
      System.out.print(a[i] + " ");
      System.out.println("\n");
      a=Merge_sort(a, n);
      System.out.println("Elements in Array After Merge Sort is: ");
      for (i=0;i<n; i++)
      System.out.print(a[i] + " ");
      System.out.println("\n");
   }

      static int[] Merge_sort(int a[], int size)
     {
        if (size>1)
       {
        int mid=size /2,first[],second[];
        first = Arrays.copyOfRange(a, 0, mid);
        first = Merge_sort(first, mid); // recursive call for first half aay
        second = Arrays.copyOfRange(a, mid, size);
        second = Merge_sort(second, size - mid); // recursive call for second half aay
        a=Merge_arrays(first, second, mid, size - mid);
     }
      return a;
  }

  static int[] Merge_arrays(int first[], int second[], int n, int m) // respectively
 {
    int a[] = new int[n + m];
    int i = 0, f = 0, s = 0;
    while(f<n && s<m)
    {
       a[i++]=(first[f]<second[s])?first[f++]:second[s++];
     }
    while(f <n)
      a[i++] = first[f++];
    while(s<m)
      a[i++]=second[s++];
    return a;
  }
}


Compilation
E:\>javac Mrgsrt.java
Execution
E:\>java Mrgsrt
Output
Enter size of the aay:
6
Enter 6 Elements :
23
5
66
1
8
99
Elements in Array Before Merge Sort is:
23 5 66 1 8 99

Elements in Array After Merge Sort is:
1 5 8 23 66 99

Hadoop Commands

HADOOP COMMANDS OS : Ubuntu Environment Author : Bottu Gurunadha Rao Created: 31-Jan-2022 Updated: 31-Jan-2022 Release  : 1.0.1 Purpose: To ...

Search This Blog