Showing posts with label FUNCTIONS & POINTERS - C Language. Show all posts
Showing posts with label FUNCTIONS & POINTERS - C Language. Show all posts

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


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