Monday, January 31, 2022

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 learn Hadoop distributed file system commands.
History: N/A

Note :To execute hadoop commands every command need to be preceded by hadoop fs or hdfs dfs combination.
Actually hadoop is deprecated and so we recommended to use hdfs dfs combination.

1. To check your location.
id -u
if you get zero, it means you are in root, since a UID of 0 (zero) means "root".
If you get any other number, it indicates that you are not in root.

2. To check current ubuntu version
lsb_release -a

3.Creating / Adding a new user
Syntax: sudo adduser <username>
        sudo adduser guru
Note : It asks for password and confirm password provide it. Keep on pressing enter keys for rest of questions. But for last one type yes and press enter key.

4.Deleting an existing user.
Syntax : sudo deluser <username>
         sudo deluser guru
Note : Now no longer it is useful, but its name is visible in home. To remove it permanently use rm command.

5.Deleting a user using rm.
Syntax: sudo rm -r <username>
        sudo rm -r guru

6.List all the available user in home.
ls /home

7.Display contents in local filesystem.
ls

8.Display contents in distributed(hadoop/hdfs) filesystem.
hadoop fs -ls /
or
hdfs dfs -ls /

9.To check health of hadoop file system.
hadoop fsck /
or
hdfs fsck /

checking the health of a file in the directory
hadoop fsck /d1 -files  ( here d1 is the directory)

10.To know hadoop version
hadoop version or hdfs version

11.To check hadoop root
hadoop fs -ls /
or
hdfs dfs -ls /

12.creating a directory in hadoop filesystem
hdfs dfs -mkdir -p /tst    
Note : In above command tst is directory and -p is option to create a directory

13.creating an empty file in hadoop filesystem root
hdfs dfs -touchz /n1.txt

14.creating an empty file in hadoop filesystem sub directory
hdfs dfs -touchz /d2/t2.txt
Note: In the above command d2 is directory and t2.txt is an empty file.

15.copying a file from local file system to hadoop file system.
Method1: Using appendToFile command
hdfs dfs -appendToFile - /d1/gurus.txt

Note1:Once above command is issued cursor waits for user to enter some text..after entering some text save it by pressing CTRL+D.
Note2:To check weather it is created or not use the following command.
hdfs dfs -cat /d1/gurus.txt  







 

Wednesday, January 26, 2022

HADOOP (3.3.0) INSTALLATION

Hadoop(3.3.0) Installation in Ubuntu Environment
Author : Bottu Gurunadha Rao
Created: 26-Jan-2022
Updated: 30-Jan-2022
Release  : 1.0.1
Purpose: Hadoop(3.3.0) distributed Installation steps in Ubuntu
History: N/A

 **Its cakewalk to install Hadoop, if you follow these steps.

 1.Update ubuntu OS
   command : sudo apt update (or) sudo apt-get update  &
                      sudo apt upgrade (or) sudo apt-get upgrade

2.Install latest java Software
  sudo apt-get install default-jdk

3. After installation, Check java version
  java -version   
  javac -version  

4. If you are not in root switch to root. Do the following to go to root.
Syntax: sudo su
Then it asks for root password provide it.

5.Do it from root. Create a new User for hadoop, you may use any username. Here we used hduser.
Note: it is not mandatory to use sudo before any command, it is an optional if you are in root.
sudo adduser hduser

6. Now change from current user to new user, it is "hduser"
Syntax to change user: su <username>, then it asks for new user password provide it.
su hduser
then it asks for password, provide it.


7. Register new user(here it is hduser) details in sudoers file.  sudoers file is in the /etc path.
sudoers file controls who can run what commands as what users on what machines and can also control special things such as whether you need a password for particular commands.

cd /etc
sudo nano sudoers

**In the sudoers file add hduser as follows
# User privilege specification
     root    ALL=(ALL:ALL) ALL
     hduser ALL=(ALL:ALL) ALL

8.Install the OpenSSH server and client
  sudo apt install openssh-server openssh-client -y

9.Generate an ssh keypair using keygen
  ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa

10. Append generated keys and also store the public key as authorized_keys in the ssh directory, using cat command.
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

11.Set the permissions for your user(here hduser)
  chmod 0600 ~/.ssh/authorized_keys

12.Verify everything is set up correctly by using the hduser user to SSH to localhost
hduser@ubuntu:$ ssh localhost

13.Download and Install Hadoop
 Method1:
 wget https://downloads.apache.org/hadoop/common/hadoop-3.3.0/hadoop-3.3.0.tar.gz
In the above method tar file will be downloaded in the current
location.
Method2:
https://hadoop.apache.org/releases.html
In this method hadoop3.3.0 binary will be downloaded in to
download folder. In this method need to un-tar it and copy the hadoop folder to required location.

14.Extract files
tar xzvf hadoop-3.3.0.tar.gz

15.Single Node Hadoop Deployment,
The following files need to be configured
.bashrc, hadoop-env.sh, core-site.xml, hdfs-site.xml,
 mapred-site-xml, yarn-site.xml

16.Configure Hadoop Environment Variables (in .bashrc file)
hduser@ubuntu:~/hadoop-3.3.0$ sudo nano ~/.bashrc

17.Define the Hadoop environment variables-add the following var @ end of the file
#Hadoop environment variables
export HADOOP_HOME=/home/hduser/hadoop-3.3.0
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
export HADOOP_INSTALL=$HADOOP_HOME
export HADOOP_MAPRED_HOME=$HADOOP_HOME
export HADOOP_COMMON_HOME=$HADOOP_HOME
export HADOOP_HDFS_HOME=$HADOOP_HOME
export YARN_HOME=$HADOOP_HOME
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export PATH=$PATH:$HADOOP_HOME/sbin:$HADOOP_HOME/bin
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib/native"

18.To apply above changes to current session do the following
hduser@ubuntu:~/hadoop-3.3.0$ exec bash
hduser@ubuntu:~/hadoop-3.3.0$ source ~/.bashrc

19.Edit hadoop-env.sh file
hduser@ubuntu:~/hadoop-3.3.0$ sudo nano $HADOOP_HOME/etc/hadoop/hadoop-env.sh
   
Note: To know what java path to be added do the following.
To know java installation path :
command: which java
output: /usr/bin/java

To know java installation link:
command: readlink -f /usr/bin/java
output: /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  
In the above output JAVA_HOME is "/usr/lib/jvm/java-11-openjdk-amd64",
use it to set environment variable.
   
20.UN-comment the $JAVA_HOME variable in the "hadoop-env.sh" file and add the following
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64

21.Edit core-site.xml File -core-site.xml file defines HDFS and Hadoop core properties
hduser@ubuntu:~/hadoop-3.3.0$ sudo nano /home/hduser/hadoop-3.3.0/etc/hadoop/core-site.xml

<configuration>
   <property>
     <name>hadoop.tmp.dir</name>
       <value>/home/hduser/tmpdata</value>
     </property>
   <property>
      <name>fs.default.name</name>
      <value>hdfs://localhost:9000</value>
   </property>
</configuration>
   
22.Edit hdfs-site.xml File - Configure the file by defining the NameNode and DataNode storage directories.
hduser@ubuntu:~/hadoop-3.3.0$ sudo nano /home/hduser/hadoop-3.3.0/etc/hadoop/hdfs-site.xml
   
<configuration>
  <property>
    <name>dfs.data.dir</name>
    <value>/home/hduser/dfsdata/namenode</value>
  </property>
  <property>
    <name>dfs.data.dir</name>
    <value>/home/hduser/dfsdata/datanode</value>
  </property>
  <property>
    <name>dfs.replication</name>
    <value>1</value>
  </property>
</configuration>

23.Edit mapred-site.xml File - define MapReduce values:
hduser@ubuntu:~$ sudo nano /home/hduser/hadoop-3.3.0/etc/hadoop/mapred-site.xml
<configuration>
  <property>
    <name>mapreduce.framework.name</name>
    <value>yarn</value>
  </property>
</configuration>

24.Edit yarn-site.xml File - configurations for the Node Manager, Resource Manager,
   Containers, and Application Master.
   hduser@ubuntu:~$ sudo nano /home/hduser/hadoop-3.3.0/etc/hadoop/yarn-site.xml
   
<configuration>
  <property>
    <name>yarn.nodemanager.aux-services</name>
    <value>mapreduce_shuffle</value>
  </property>
  <property>
    <name>yarn.nodemanager.aux-services.mapreduce.shuffle.class</name>
    <value>org.apache.hadoop.mapred.ShuffleHandler</value>
  </property>
  <property>
    <name>yarn.resourcemanager.hostname</name>
    <value>127.0.0.1</value>
  </property>
  <property>
    <name>yarn.acl.enable</name>
    <value>0</value>
  </property>
  <property>
    <name>yarn.nodemanager.env-whitelist</name>
 <value>JAVA_HOME,HADOOP_COMMON_HOME,HADOOP_HDFS_HOME,HADOOP_CONF_DIR,CLASSPATH_PERPEND_DISTCACHE,HADOOP_YARN_HOME,HADOOP_MAPRED_HOME</value>
  </property>
</configuration>

25.Run hadoop services from this location "/home/hduser/hadoop-3.3.0/sbin"
 command : hadoop namenode -format

26.Start dfs services, from sbin of HadoopHome (/home/hduser/hadoop-3.3.0/sbin)
 Notes: It starts NameNode, DataNode, SecondaryNameNode services
command : ./start-dfs.sh

27.Start Yarn Services, from sbin of HadoopHome (/home/hduser/hadoop-3.3.0/sbin)
Note : It starts ResourceManager and NodeManager
command : ./start-yarn.sh.

28.Instead of using step25 & 26 we can run all services in a single command.
command : ./start-all.sh    [It is not recommended by experts]

29.To check whether all the services are up and running successfully type jps in terminal.
command: jps

output:
8161 Jps
6482 DataNode
6754 SecondaryNameNode
6308 NameNode
7029 ResourceManager
7211 NodeManager

Note:
If all the above listed six services are visible then you are successful in Hadoop Installation.
If any name is  missed in the output, it indicates that your installation is not successful-go through all steps again.
 
30.To safely stop all Hadoop Services use following command.(from this location: /home/hduser/hadoop-3.3.0/sbin)
command : ./stop-all.sh

Wednesday, November 11, 2020

Introduction to Django

 Python Installation 

Download Python from the following website
https://www.python.org/downloads/

python-3.9.0-amd64.exe will be downloaded. Double click on it to install. 

After installation go to the command prompt and check python is installed or not?

C:\Users\student>python
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

">>>" This symbol is command prompt for python interpreter.
To exit from python beside command prompt type "exit()" and press enter key.

To check the version of python issue the following command.
C:\Users\student>python --version
Python 3.9.0

Installation of Django
Go to the command prompt and issue the following command.
C:\Users\student>pip install django

The above command installs "Django" software along with several packages.

After installation checks its version with the following command.

C:\Users\student>python -m django --version
3.1.3

Creating First Web Application Using Django
To create a web application, first, we need to create a project.

Procedure to create a Project
Assume that you are in "D" drive and "Gurujang" folder.

1) D:\Gurujang>django-admin startproject Guruproject

Note1:
Now a folder named "Guruproject" will be created inside "D:\Gurujang".
Inside "D:\Gurujang\Guruproject"
the same folder named "Guruproject" and a file named "manage.py" will be created.

Note2:
Again "D:\Gurujang\Guruproject\Guruproject" contains the following important files.


2)Now inside "Guruproject" we have to create app.

D:\Gurujang>cd Guruproject
D:\Gurujang\Guruproject>

Command to create App
D:\Gurujang\Guruproject>python manage.py startapp GuruApp

Note1:
With the above command, "GuruApp" will be created inside D:\Gurujang\Guruproject.
Note2:
D:\Gurujang\Guruproject\GuruApp Contains following important files.
      __init__, "admin.py", "models.py", "views.py"

3) Now make an entry "GuruApp" in the following location. In the file    D:\Gurujang\Guruproject\Guruproject\settings.py.

"GuruApp" should be added to "INSTALLED_APPS" section of "settings.py"

Ex: settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'GuruApp'
]

Now Project is Ready, To know the project is running or not, First, we need to start the "server".
Command to start/run the server

D:\Gurujang\Guruproject>python manage.py runserver

You will find the following screen after "Starting the Server"



















4) Now open any browser(Ex: Google Chrome / IE ) and give the URL we are viewing on the server
    Type the URL http://127.0.0.1:8000/ in the browser followed by enter key.
If you see the following screen, you assure that your project is working Successfully.


























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