Friday 18 October 2019

c programming



LESSON  1 - GETTING STARTED...


WHAT  IS  C ?





C is a general-purpose programming language that is extremely popular, simple and flexible.
It is machine-independent, structured programming language which is used extensively in various applications.




C was the basics language to write everything from operating systems to complex programs like the Oracle database,
Git, Python interpreter and more.

It is said that 'C' is a god's programming language.
One can say, C is a base for the programming.
If you know 'C,' you can easily grasp the knowledge of the other programming languages that uses the concept of 'C'

It is essential to have a background in computer memory mechanisms because ,
it is an important aspect when dealing with the C programming language.







Data types in C Language -:



Data types specify how we enter data into our programs and what type of data we enter. 
C language has some predefined set of data types to handle various kinds of data that we can use in our program. 
These datatypes have different storage capacities.





C language supports 2 different type of data types -:


Primary data types -:



These are fundamental data types in C namely integer(int), 
floating point(float), character(char) and void.



Derived data types -:

Derived data types are nothing but primary datatypes but a little twisted or grouped together like array, 
stucture, union and pointer. These are discussed in details later.

Data type determines the type of data a variable will hold. 
If a variable x is declared as int. it means x can hold only integer values. 
Every variable which is used in the program must be declared as what data-type it is.






primary data types in c -:






Integer type -:

Integers are used to store whole numbers -:


Size and range of Integer type on 16-bit machine -:

Type                Size(bytes) Range

int or signed int                  2 -32,768 to 32767
unsigned int                  2 0 to 65535
short int or signed short int  1 -128 to 127
unsigned short int                  1 0 to 255
long int or signed long int         4 -2,147,483,648 to 2,147,483,647
unsigned long int                       4 0 to 4,294,967,295




Floating point type -:

Floating types are used to store real numbers -:

Size and range of Integer type on 16-bit machine -:


Type Size(bytes) Range


Float         4  3.4E-38 to 3.4E+38
double         8  1.7E-308 to 1.7E+308
long double 10  3.4E-4932 to 1.1E+4932



Character type -:

Character types are used to store characters value-:


Size and range of Integer type on 16-bit machine

Type           Size(bytes) Range

char or signed char   1        -128 to 127
unsigned char         1        0 to 255






void type -:

void type means no value. This is usually used to specify the type of functions which returns nothing. 
We will get acquainted to this datatype as we start learning more advanced topics in C language, 
like functions, pointers etc.



Other data types defined in C programming are -:

bool Type -:
Enumerated type -:
Complex types -:



Derived Data Types -: 



Data types that are derived from fundamental data types are derived types. 
For example: arrays, pointers, function types, structures, etc.










variables in c -:





variable -:
A variable is nothing but a name given to a storage area that our programs can manipulate. 
Each variable in C has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

The primary purpose of variables is to store data in memory for later use. Unlike constants which do not change during the program execution, variables value may change during execution. If you declare a variable in C, that means you are asking to the operating system for reserve a piece of memory with that variable name.


syntax -:

type variable_name;
       or 
type variable_name, variable_name, variable_name;



initialization -:
int    width, height=5;
char   letter='A';
float  age, area;
double d;

/* actual initialization */width = 10;
   age = 26.5;

 variable assignment -:

  int width = 60;
   int age = 31;




rules for choosing variables name-:

  • A variable name can consist of Capital letters A-Z, lowercase letters a-z, digits 0-9, and the underscore character.
  • The first character must be a letter or underscore.
  • Blank spaces cannot be used in variable names.
  • Special characters like #, $ are not allowed.
  • C keywords cannot be used as variable names.
  • Variable names are case sensitive.
  • Values of the variables can be numeric or alphabetic.
  • Variable type can be char, int, float, double or void.



c program to print value of a variable-:

void main()
{
int person_age = 30;
printf(" age of the person = %d",age);
getch();
}

output -:
                age of the person = 30







LESSON 2 - FUNCTIONS AND OPERATORS...




A function is a group of statements that together perform a task. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.

A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.

A function can also be referred as a method or a sub-routine or a procedure, etc.



Defining a Function -:

The general form of a function definition in C programming language is as follows -

return_type function_name( parameter list ) {
   body of the function
}



A function definition in C programming consists of a function header and a function body. Here are all the parts of a function -

Return Type - A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

Function Name - This is the actual name of the function. The function name and the parameter list together constitute the function signature.

Parameters - A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

Function Body - The function body contains a collection of statements that define what the function does.




Example -:

//function returning the max between two numbers //

int max(int num1, int num2) {

  
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result; 

}





Function Declarations -:


A function declaration tells the compiler about a function name and how to call the function. 
The actual body of the function can be defined separately.



A function declaration has the following parts -:



return_type function_name( parameter list );
For the above defined function max(), the function declaration is as follows -

int max(int num1, int num2);
Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration -

int max(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. 
In such case, you should declare the function at the top of the file calling the function.



Calling a Function -:


While creating a C function, you give a definition of what the function has to do. 
To use a function, you will have to call that function to perform the defined task.

When a program calls a function, the program control is transferred to the called function. 
A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

To call a function, you simply need to pass the required parameters along with the function name, and if the function returns a value, then you can store the returned value. For 


example -:


#include <stdio.h>
int max(int num1, int num2);
int main () {

  
   int a = 100;
   int b = 200;
   int ret;
   ret = max(a, b);
   printf( "Max value is : %d\n", ret );
   return 0;
}
int max(int num1, int num2) {

   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;
   return result; 
}




Function Arguments -:

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.



Call by value -:

This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

Call by reference -:

This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.



C Programming Operators -:




An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.





C Arithmetic Operators -:


An arithmetic operator performs mathematical operations such as 
addition, 
subtraction,
 multiplication, 
division   etc on numerical values (constants and variables).



Operator Meaning of Operator

 + addition 
 - subtraction 
 * multiplication
 / division
 % remainder after division (modulo division)









example of arithmetic operators -:


#include<stdio.h>
#include<conio.h>
void main()
{
int a=2,b=2;
clrscr();
printf("a+b =%d",a+b);
printf("\n a-b =%d",a-b);
printf("\n a*b =%d",a*b);
printf("\n a/b =%d",a/b);
printf("\n a%b =%d",a%b);
getch();
}


C Increment and Decrement Operators -:




C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.

Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.



EXAMPLE OF INCREMENT AND DECREMENT OPERATOR -:



#include<stdio.h>
#include<conio.h>
void main()
{
int a=2,b=4;
clrscr();
printf("\n increment in a ");
printf("\n post increment a (a++) = %d",a++)
printf("\n pre increment in a (++a) = %d",++a);
printf("\n post decrement in b (b--) = %d",b--);
printf("\n pre decrement in b (--b) =% d", --b);
getch();
}




C Assignment Operators -:



An assignment operator is used for assigning a value to a variable. The most common assignment operator is =

Operator Example          Same as

=       a =  b      a =  b
+=       a += b      a = a+b
-=       a -= b      a = a-b
*=       a *= b      a = a*b
/=      a /= b      a = a/b
%=      a %= b      a = a%b







C Relational Operators -:






A relational operator checks the relationship between two operands. 
If the relation is true, it returns 1; if the relation is false, it returns value 0.



Relational operators are used in decision making and loops.

Operator Meaning of Operator Example

==         Equal to               5 == 3 is evaluated to 0
>        Greater than       5 > 3 is evaluated to 1
<        Less than               5 < 3 is evaluated to 0
!=       Not equal to               5 != 3 is evaluated to 1
>=      Greater than or equal to       5 >= 3 is evaluated to 1
<=      Less than or equal to       5 <= 3 is evaluated to 0


Example  of Relational Operators -:

#include <stdio.h>
#include<conio.h>
void  main()
{
    int a = 5, b = 5, c = 10;
      printf("%d == %d is %d \n", a, b, a == b);
      printf("%d == %d is %d \n", a, c, a == c);
    printf("%d > %d is %d \n", a, b, a > b);
    printf("%d > %d is %d \n", a, c, a > c);
    printf("%d < %d is %d \n", a, b, a < b);
    printf("%d < %d is %d \n", a, c, a < c);
    printf("%d != %d is %d \n", a, b, a != b);
    printf("%d != %d is %d \n", a, c, a != c);
    printf("%d >= %d is %d \n", a, b, a >= b);
    printf("%d >= %d is %d \n", a, c, a >= c);
    printf("%d <= %d is %d \n", a, b, a <= b);
    printf("%d <= %d is %d \n", a, c, a <= c);
    getch();
}


Output -:

5 == 5 is 1
5 == 10 is 0
5 > 5 is 0
5 > 10 is 0
5 < 5 is 0
5 < 10 is 1
5 != 5 is 0
5 != 10 is 1
5 >= 5 is 1
5 >= 10 is 0
5 <= 5 is 1
5 <= 10 is 1  




C Logical Operators -:






An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming.






Operator    Meaning               response 

&&                   Logical AND.       True only if all operands are true
||                   Logical OR.          True only if either one operand is true
!                   Logical NOT.       True only if the operand is 0



example of  logical operators -:



#include <stdio.h>
                #include<conio.h>
    void main()
   {
                 int a = 5, b = 5, c = 10, result;
                 result = (a == b) && (c > b);
                   printf("(a == b) && (c > b) is %d \n", result);
                 result = (a == b) && (c < b);
                 printf("(a == b) && (c < b) is %d \n", result);
                   result = (a == b) || (c < b);
                 printf("(a == b) || (c < b) is %d \n", result);
                 result = (a != b) || (c < b);
                   printf("(a != b) || (c < b) is %d \n", result);
                    result = !(a != b);
                  printf("!(a == b) is %d \n", result);
                 result = !(a == b);
                  printf("!(a == b) is %d \n", result);
                   getch();
              }





Output -:

(a == b) && (c > b) is 1 
(a == b) && (c < b) is 0 
(a == b) || (c < b) is 1 
(a != b) || (c < b) is 0 
!(a != b) is 1 
!(a == b) is 0 


C Bitwise Operators-:




During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.

Bitwise operators are used in C programming to perform bit-level operations.



Operators           Meaning of operators

&                       Bitwise AND
|                       Bitwise OR
^                              Bitwise exclusive OR
~                     Bitwise complement
<<                      Shift left
>>                     Shift right



Other Operators -:

Comma Operator -:

Comma operators are used to link related expressions together. For example:

int a, c = 5, d;


The sizeof operator -:

The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).

#include <stdio.h>
#include<conio.h>
void main()
{
    int a;
    float b;
    double c;
    char d;
    printf("Size of int=%lu bytes\n",sizeof(a));
    printf("Size of float=%lu bytes\n",sizeof(b));
    printf("Size of double=%lu bytes\n",sizeof(c));
    printf("Size of char=%lu byte\n",sizeof(d));
    getch();
}


Output -:

Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte




lesson 3 - control flow structure...





If statement in C programming with example -:


When we need to execute a block of statements only when a given condition is true then we use if statement. 
In the next tutorial, we will learn C if..else, nested if..else and else..if.




Example of if statement -:



#include <stdio.h>
#include<conio.h>
void main()
{
    int x = 20;
    int y = 22;
    if (x<y)
    {
        printf("Variable x is less than y");
    }
    grtch();
}



Output -:


Variable x is less than y





else-if statements in C -:

it is like another if condition, it's used in a program when if statement having multiple decisions.


example of if else condition in c -:





#include<stdio.h>
#include<conio.h>
void main()
{
int a=2,b=4,c=8;
printf(" find largest variable amoung three");
if(a>b&&a>c)
{
printf(" a is greater ");
}
else if(b>a&&b>c)
{
printf("\n b is greater ");
}
else 
                                                                  {
                                                            prinft(" c is greater");
                                                                }

                                                            getch();
                                                                  }





output -:

c is greater




What are Loops ?





In looping, a program executes the sequence of statements many times until the stated condition becomes false. 
A loop consists of two parts, a body of a loop and a control statement. The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false.


Types of Loops -:

Depending upon the position of a control statement in a program, a loop is classified into two types -:

1. Entry controlled loop

2. Exit controlled loop

In an entry controlled loop, a condition is checked before executing the body of a loop. 
It is also called as a pre-checking loop.

In an exit controlled loop, a condition is checked after executing the body of a loop. 
It is also called as a post-checking loop.




The control conditions must be well defined and specified otherwise the loop will execute an infinite number of times. 
The loop that does not stop executing and processes the statements number of times is called as an infinite loop. 

An infinite loop is also called as an "Endless loop." Following are some characteristics of an infinite loop -:

1. No termination condition is specified.

2. The specified conditions never meet.





The specified condition determines whether to execute the loop body or not.

'C' programming language provides us with three types of loop constructs -:

1. The while loop

2. The do-while loop


3. The for loop





While Loop -:




A while loop is the most straightforward looping structure. The basic format of while loop is as follows -:



while (condition) 

{
             
statements;

}




It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false. Once the condition becomes false, the control goes out of the loop.

After exiting the loop, the control goes to the statements which are immediately after the loop. The body of a loop can contain more than one statement. If it contains only one statement, then the curly braces are not compulsory. It is a good practice though to use the curly braces even we have a single statement in the body.

In while loop, if the condition is not true, then the body of a loop will not be executed, not even once. It is different in do while loop which we will see shortly.


EXAMPLE OF WHILE LOOP -:



#include<stdio.h>
#include<conio.h>
int main()
{
int num=1;
while(num<=10)
{
printf("%d\n",num);
num++;
}
return 0;
}



Output -:


1

2
3
4
5
6
7
8
9
10


The above program illustrates the use of while loop. 
In the above program, we have printed series of numbers from 1 to 10 using a while loop.




Do-While loop -:




A do-while loop is similar to the while loop except that the condition is always executed after the body of a loop. 
It is also called an exit-controlled loop.



The basic format of while loop is as follows -:






 do 

   {

  statements;

     } while (expression);



As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to execute a body of the loop at least once even if the condition is false. This type of operation can be achieved by using a do-while loop.

In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.

Similar to the while loop, once the control goes out of the loop the statements which are immediately after the loop is executed.

The critical difference between the while and do-while loop is that in while loop the while is written at the beginning. In do-while loop, the while condition is written at the end and terminates with a semi-colon (;)



The following program illustrates the working of a do-while loop -:


We are going to print a table of number 2 using do while loop -:



#include<stdio.h>
#include<conio.h>
int main()
{
int num=1;
do  
{
printf("%d\n",2*num);
num++;
}while(num<=10);
return 0;
}



Output -:

2
4
6
8
10
12
14
16
18
20

In the above example, we have printed multiplication table of 2 using a do-while loop. 
Let's see how the program was able to print the series.


For loop -:




A for loop is a more efficient loop structure in 'C' programming. The general structure of for loop is as follows -:



   for (initial value; condition; incrementation or decrementation ) 
        {
          statements;
           }


The initial value of the for loop is performed only once.
The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.
The incrementation/decrementation increases (or decreases) the counter by a set value.


Following program illustrates the use of a simple for loop -:




         #include<stdio.h>
         int main()
        {
int number;
for(number=1;number<=10;number++)
{
printf("%d\n",number);
}
return 0;
           }
Output -:

1
2
3
4
5
6
7
8
9
10


The above program prints the number series from 1-10 using for loop.





For example -:



for (x = 0, y = num; x < y; i++, y--) 
  statements; 
}




For example -:



int i=0;
int max = 10;
for (; i < max; i++) {
  printf("%d\n", i);
}


Consider the following example, that uses nested for loops output a multiplication table -:



#include <stdio.h>
int main() {
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) { // outer loop
  for (j = 0; j <= max; j++) { // inner loop
    printf("%d x %d = %d\n", i, j, i*j);
  }
  printf("\n"); /* blank line between tables */
}}



Output -:

1 x 0 = 0
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5

2 x 0 = 0
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10




Break Statement -:


The break statement is used mainly in in the switch statement. It is also useful for immediately stopping a loop.

We consider the following program which introduces a break to exit a while loop -:



#include <stdio.h>
int main() {
int num = 5;
while (num > 0) {
  if (num == 3)
    break;
  printf("%d\n", num);
  num--;
}}


Output:

5
4



Continue Statement -:


When you want to skip to the next iteration but remain in the loop, you should use the continue statement.





For example -:



#include <stdio.h>
int main() {
int nb = 7;
while (nb > 0) {
  nb--;
  if (nb == 5)
    continue;
 printf("%d\n", nb);
}}


Output:

6
4
3
2
1
0
So, the value 5 is skipped.


What is a Switch Statement ?



A switch statement tests the value of a variable and compares it with multiple cases. 
Once the case match is found, a block of statements associated with that particular case is executed.

Each case in a block of a switch has a different name/number which is referred to as an identifier. 
The value provided by the user is compared with all the cases inside the switch block until the match is found.

If a case match is found, then the default statement is executed, and the control goes out of the switch block.



syntax -:


switch( expression )
{
case value-1:
Block-1;
Break;
case value-2:
Block-2;
Break;
case value-n:
Block-n;
Break;
default:
Block-1;
Break;
}

Statement-x; 



Flow Chart Diagram of Switch Case -:







Example -:


Following program illustrates the use of switch -:



#include <stdio.h>
    int main() {
        int num = 8;
        switch (num) {
            case 7:
                printf("Value is 7");
                break;
            case 8:
                printf("Value is 8");
                break;
            case 9:
                printf("Value is 9");
                break;
            default:
                printf("Out of range");
                break;
        }
        return 0;
    }


Output -:



Value is 8







LESSON 3 - ARRAYS...



C Array -:


An array is defined as the collection of similar type of data items stored at contiguous memory locations. 
Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number.

C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.




Properties of Array -:

The array contains the following properties-:


Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element.


Advantage of C Array -:


1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.

Disadvantage of C Array -:

1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. 
So, it doesn't grow the size dynamically like LinkedList which we will learn later.

Declaration of C Array -:

We can declare an array in the c language in the following way.

data_type array_name[array_size];  
Now, let us see the example to declare the array.

int marks[5];  
Here, int is the data_type, marks are the array_name, and 5 is the array_size.









Initialization of C Array -:




The simplest way to initialize an array is by using the index of each element. 
We can initialize each element of the array by using the index. 

Consider the following example-:


marks[0]=80;//initialization of array  
marks[1]=60;  
marks[2]=70;  
marks[3]=85;  
marks[4]=75;  




C array example -:


#include<stdio.h>  
int main(){      
int i=0;    
int marks[5];//declaration of array       
marks[0]=80;//initialization of array    
marks[1]=60;    
marks[2]=70;    
marks[3]=85;    
marks[4]=75;    
//traversal of array    
for(i=0;i<5;i++){      
printf("%d \n",marks[i]);    
}//end of for loop     
return 0;  
}





    
Output -:

80
60
70
85
75




Declaration with Initialization  -:


We can initialize the c array at the time of declaration. Let's see the code.

int marks[5]={20,30,40,50,60};
  
In such case, there is no requirement to define the size. So it may also be written as the following code.

int marks[]={20,30,40,50,60}; 

Let's see the C program to declare and initialize the array in C-:


#include<stdio.h>  
int main(){      
int i=0;    
int marks[5]={20,30,40,50,60};//declaration and initialization of array    
 //traversal of array    
for(i=0;i<5;i++){      
printf("%d \n",marks[i]);    
}    
return 0;  


   
Output -:
20
30
40
50
60





 Sorting an array -:


In the following program, we are using bubble sort method to sort the array in ascending order.



#include<stdio.h>    
void main ()    
{    
    int i, j,temp;     
    int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};     
    for(i = 0; i<10; i++)    
    {    
        for(j = i+1; j<10; j++)    
        {    
            if(a[j] > a[i])    
            {    
                temp = a[i];    
                a[i] = a[j];    
                a[j] = temp;     
            }     
        }     
    }     
    printf("Printing Sorted Element List ...\n");    
    for(i = 0; i<10; i++)    
    {    
        printf("%d\n",a[i]);    
    }    
}  








   
Program to print the largest and second largest element of the array-:





#include<stdio.h>  
void main ()  
{  
    int arr[100],i,n,largest,sec_largest;  
    printf("Enter the size of the array?");  
    scanf("%d",&n);  
    printf("Enter the elements of the array?");  
    for(i = 0; i<n; i++)  
    {  
        scanf("%d",&arr[i]);  
    }  
    largest = arr[0];  
    sec_largest = arr[1];  
    for(i=0;i<n;i++)  
    {  
        if(arr[i]>largest)  
        {  
            sec_largest = largest;  
            largest = arr[i];  
        }  
        else if (arr[i]>sec_largest && arr[i]!=largest)  
        {  
            sec_largest=arr[i];  
        }  
    }  
    printf("largest = %d, second largest = %d",largest,sec_largest);  
      
}  









Two Dimensional Array in C -:




The two-dimensional array can be defined as an array of arrays. 
The 2D array is organized as matrices which can be represented as the collection of rows and columns. 
However, 2D arrays are created to implement a relational database lookalike data structure. 
It provides ease of holding the bulk of data at once which can be passed to any number of functions wherever required.



Declaration of two dimensional Array in C -:


The syntax to declare the 2D array is given below-:


data_type array_name[rows][columns];  



int twodimen[4][3];  
Here, 4 is the number of rows, and 3 is the number of columns.




Initialization of 2D Array in C -:


In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two-dimensional array can be declared and defined in the following way.

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};  







Two-dimensional array example in C -:


#include<stdio.h>  
int main(){      
int i=0,j=0;    
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};     
//traversing 2D array    
for(i=0;i<4;i++){    
 for(j=0;j<3;j++){    
   printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);    
 }//end of j    
}//end of i    
return 0;  




   
Output -:



arr[0][0] = 1
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 2
arr[1][1] = 3
arr[1][2] = 4
arr[2][0] = 3
arr[2][1] = 4
arr[2][2] = 5
arr[3][0] = 4
arr[3][1] = 5
arr[3][2] = 6






Storing elements in a matrix and printing it-:



#include <stdio.h>    
void main ()    
{    
    int arr[3][3],i,j;     
    for (i=0;i<3;i++)    
    {    
        for (j=0;j<3;j++)    
        {    
            printf("Enter a[%d][%d]: ",i,j);                
            scanf("%d",&arr[i][j]);    
        }    
    }    
    printf("\n printing the elements ....\n");     
    for(i=0;i<3;i++)    
    {    
        printf("\n");    
        for (j=0;j<3;j++)    
        {    
            printf("%d\t",arr[i][j]);    
        }    
    }    



   
Output -:

Enter a[0][0]: 56   
Enter a[0][1]: 10   
Enter a[0][2]: 30  
Enter a[1][0]: 34  
Enter a[1][1]: 21 
Enter a[1][2]: 34    

Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78   

 printing the elements .... 
56      10      30  
34      21      34  
45      56      78










Passing Array to Function in C -:


In C, there are various general problems which requires passing more than one variable of the same type to a function. 
For example, consider a function which sorts the 10 elements in ascending order. 
Such a function requires 10 numbers to be passed as the actual parameters from the main function. 
Here, instead of declaring 10 different numbers and then passing into the function, we can declare and initialize an array and pass that into the function. This will resolve all the complexity since the function will now work for any number of values.

As we know that the array_name contains the address of the first element. Here, we must notice that we need to pass only the name of the array in the function which is intended to accept an array. 
The array defined as the formal parameter will automatically refer to the array specified by the array name defined as an actual parameter.




functionname(arrayname);//passing array 


Methods to declare a function that receives an array as an argument



There are 3 ways to declare the function which is intended to receive an array as an argument -:


First way -:


return_type function(type arrayname[])  
Declaring blank subscript notation [] is the widely used technique.



Second way -:


return_type function(type arrayname[SIZE])  
Optionally, we can define size in subscript notation [].

Third way -:
return_type function(type *arrayname)  





C language passing an array to function example -:



#include<stdio.h>  
int minarray(int arr[],int size){    
int min=arr[0];    
int i=0;    
for(i=1;i<size;i++){    
if(min>arr[i]){    
min=arr[i];    
}    
}//end of for    
return min;    
}//end of function    
    
int main(){      
int i=0,min=0;    
int numbers[]={4,5,7,3,8,9};//declaration of array    
  
min=minarray(numbers,6);//passing array with size    
printf("minimum number is %d \n",min);    
return 0;  




   
Output -:


minimum number is 3










C function to sort the array -:





#include<stdio.h>   
void Bubble_Sort(int[]);  
void main ()    
{    
    int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};     
    Bubble_Sort(arr);    
}    
void Bubble_Sort(int a[]) //array a[] points to arr.   
{  
int i, j,temp;     
    for(i = 0; i<10; i++)    
    {    
        for(j = i+1; j<10; j++)    
        {    
            if(a[j] < a[i])    
            {    
                temp = a[i];    
                a[i] = a[j];    
                a[j] = temp;     
            }     
        }     
    }     
    printf("Printing Sorted Element List ...\n");    
    for(i = 0; i<10; i++)    
    {    
        printf("%d\n",a[i]);    
    }  
}




  
Output -:




Printing Sorted Element List ...
7  
9  
10  
12  
23 
23  
34  
44  
78  
101


  
Returning array from the function -:


As we know that, a function can not return more than one value. 
However, if we try to write the return statement as return a, b, c; to return three values (a,b,c), the function will return the last mentioned value which is c in our case. In some problems, we may need to return multiple values from a function. In such cases, an array is returned from the function.

Returning an array is similar to passing the array into the function. The name of the array is returned from the function. 
To make a function returning an array.


 the following syntax is used-:



int * Function_name() {  
//some statements;   
return array_type;  



To store the array returned from the function, we can define a pointer which points to that array.
We can traverse the array by increasing that pointer since pointer initially points to the base address of the array.

Consider the following example that contains a function returning the sorted array-:



#include<stdio.h>   
int* Bubble_Sort(int[]);  
void main ()    
{    
    int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};     
    int *p = Bubble_Sort(arr), i;  
    printf("printing sorted elements ...\n");  
    for(i=0;i<10;i++)  
    {  
        printf("%d\n",*(p+i));  
    }  
}    
int* Bubble_Sort(int a[]) //array a[] points to arr.   
{  
int i, j,temp;     
    for(i = 0; i<10; i++)    
    {    
        for(j = i+1; j<10; j++)    
        {    
            if(a[j] < a[i])    
            {    
                temp = a[i];    
                a[i] = a[j];    
                a[j] = temp;     
            }     
        }     
    }     
    return a;  


Output -:

Printing Sorted Element List ...
7  
9   
10  
12  
23 
23  
34  
44  
78  
101  








Pointers-:



Pointer  in C language is a variable that stores/points the address of another variable. 
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).



EXAMPLE PROGRAM FOR POINTERS IN C -:


#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;
}
1
2
3
4
5
6
7
8
9
10
11

OUTPUT -:

50