Chakravyuh [TCS Codevita Question]

#include <stdio.h>
 int main()
 {
    int a[5][5];
    int c=1, i, j, k, n;
    for(i=0;i<3;i++)
    {
        if(a[2][2]==25)
        {
            break;
        }
        for(j=0+i;j<=4-i;j++)
        {
            a[i][j]=c;
            c++;
        }
        n=j-1;
        for(k=1+i;k<=4-i;k++)
        {
            a[k][n]=c;
            c++;
        }
        n=k-1;
        for(j=3-i;j>=0+i;j--)
        {
            a[n][j]=c;
            c++;
        }
        n=j+1;
        for(k=3-i;k>=1+i;k--)
        {
            a[k][n]=c;
            c++;
        }
    }
    for(i=0;i<5;i++)
    {
        for(j=0;j<5;j++)
        {
            printf("%d\t", a[i][j]);
        }
        printf("\n\n");
    }
    return 0;
 }


 1     2    3    4    5
 16   17   18   19    6
 15   24   25   20    7
 14   23   22   21    8
 13   12   11   10    9

Patterns using Loop

After learning the basics of the C Programming, let's play with the language and code some patterns. To able to code the patterns, you need to have proper knowledge ie. working of the loops, basically nesting of loops. Patterns are generated with the help of the loops. 

Let's revise the nesting of loops. So to create the pattern we need rows and columns. For rows and columns, we need two loops ie. one for changing the rows and other for changing the column. 

Suppose, you need to create in 5x5 then you need to set the loop counter to 1 and run till greater than or equal to 5. Let's see the codes for it. 
#include <stdio.h>
 int main()
 {
    int i, j;
    for(i=1;i<=5;i++)
    {
        for(j=1;j<=5;j++)
        {
            printf("*");
        }
        printf("\n");
    }
    return 0;
 }
*****
*****
*****
*****
*****
In the above program, we have declared two variables i and j. Variable i is for rows and Variable j is for columns. The for loop having variable i is for changing the rows and the second for loop which is having variable j is for changing the columns and inside that loop, it is printing * everytime. Then once the condition of the second loop is break, then the second statement after loop, is printing the break line. So, once the loop is executed for 5 times then the control goes to new line. And again, the first loop is executed. 

Like this we can manipulate with the loops and can generate different patterns.

Find length of string without built-in function

#include <stdio.h>
 int main()
 {
   char s[1000];
   int i=0;
   printf("Enter a string: ");
   scanf("%s", s);
   while(s[i] != '\0')
   {
      i++;
   }
   printf("Length of string: %d", i);
   return 0;
 }
Explaination of the Program : Here, in this program, we have declared one char data type variable named s and other variable of integer data type which is initialized to 0. Accepting the string from the user of whom the length is to be found. While loop is used and then condition is the loop will until the null character isn't identified. Inside the loop, we are incrementing the value of i and so we can get the value of the length which i itself at the end of the loop.

Concat two strings without built-in function

#include <stdio.h>
 int main()
 {
   char s1[100], s2[100], i, j;
   printf("Enter first string: ");
   scanf("%s", s1);
   printf("Enter second string: ");
   scanf("%s", s2);
   for(i = 0; s1[i] != '\0'; ++i);
   for(j = 0; s2[j] != '\0'; ++j, ++i)
   {
      s1[i] = s2[j];
   }
   s1[i] = '\0';
   printf("After concatenation: %s", s1);
   return 0;
 }
Explaination Of the Program : Here, we are declaring two char data type variables which can store two strings. We are accepting two strings and storing them in s1 and s2. Now in the first for loop, the condition is that for loop will work it the s1's null character isn't identified. Once, it is identified the loop will get terminated. The first for loop only gets the i counter to the end of the first string. Now in the second for loop, we are going to copy the data 
of the s2 in s1 and the data will get copied at the end of the s1 because the counter has reached there. Adding the null character after the copying is done and then we are printing the string s1 which concates the data of s2 inside s1.

Copy string without built-in function

 #include <stdio.h>
 int main()
 {
   char s1[100], s2[100], i;
   printf("Enter string s1: ");
   scanf("%s",s1);
   for(i = 0; s1[i] != '\0'; i++)
   {
      s2[i] = s1[i];
   }
   s2[i] = '\0';
   printf("String s2: %s", s2);
   return 0;
 }
Explaination of the Program : Here, we declared two variables of data type char which can store two strings. In one string, we are going to enter the string which the users will input. And then we will use for loop, the condition will be till the null character of string isn't identified. Then inside the loop, we are copy the data from one string to another string and the loop gets terminated when the null character is identified. Now we are adding the null character to string two and then printing it's value.

Program : Factorial Using Recursion

#include <stdio.h>
 long int fact(int n);
 int main()
 {
    int n;
    printf("Enter a Positive Integer: ");
    scanf("%d", &n);
    printf("Factorial of %d = %ld", n, fact(n));
    return 0;
 }
 long int fact(int n)
 {
    if (n == 0)
        return 1;   
    else
        return n*fact(n-1);
 }
Enter a positive integer: 6
 Factorial of 6 = 720
Explaination : In this program, we accept a positive integer from the user of whom we are going to find the factorial. The integer number is then passed in the User-defined Function named "fact". The condition is like, if the number gets equal to zero, then the it will return 1 or else it will return number times the fact of (n-1) i.e the function is calls itself. So, again the function "fact" will run for (n-1) and then like this goes on and on until the n values get 0 and it finally returns the value 1 so the functions terminates and returns that value to the main function.

Recursion

Recursion is very useful concept. Recursion, in very simple words, function calling itself. Sometimes, we need to repeat the function many times, for that concept, we have to use Recursion. Let's take an example of Factorial for Recursion. In factorial, we need to go to next number by substracting and perform the same task on it. So, Recursion is used. 

Click Here for Factorial Program using Recursion.

In Recursion, the stack memory is used. We need to break the Recursion condition to make it finite or else, it will run for Infinity times and give will Runtime, as stack memory gets full. So, to make the Recursion condition break, we can use the if else statements. We can write the Breaking condition in if statement and in else condition, the Recursion part is there.

factorial of n (n!) = 1*2*3*4....n

And Breaking Condition for this, can be if(n==0) then return 1; You will get to know about the Recursion in the Factorial Example.

Call by Value and Call by Reference

Call by value and Call by reference is the extended part of Functions. Let's see what's it? For this, you need to understand the concept of Formal Parameters and Actual Parameters. When the function is called, the parameters which we pass are known as actual parameters. And the parameters which get pass from the User-defined function are known as formal parameters. 

To need understand the concept more clearly, let's understand how to functions a little bit deeper. Let's take an example of swapping the values of two variables with the help of User-defined Function. Also we need to include pointer in this example.
#include <stdio.h>
 void swap(int *a, int *b);
 int main()
 {
    int x, y;
    printf("Enter the value of variable 1 = ");
    scanf("%d", &x);
    printf("Enter the value of variable 2 = ");
    scanf("%d", &y);
    printf("Before Swapping\nx = %d\ny = %d\n", x, y);
    swap(&x, &y);
    printf("After Swapping\nx = %d\ny = %d\n", x, y);
    return 0;
 }
 void swap(int *a, int *b)
 {
    int t;
    t  = *b;
    *b = *a;
    *a = t;
 }
Explaination : In this program, we are swapping the values of variables using pointers and using User-defined Function. So, firstly we have declared the swap function. Then in main function, we have scanned 2 variables. And then we have passed the address of the variables x and y and not the values. So, this is called Call By Reference. Call by Value is simple, which we use. In the functions, if have used Call by Value, then we will pass the variables and not the address of the variable. In the User-defined functions, if the pointers variables are passed and simple variables are passed then in memory they have create their own space and after the function returns any value or the functions get terminate the variables get destroy but here, the pointers are passed so, the operations are done on the variable's address' value and not on the variable directly. The above program is working under Call by Reference method.

Structures and Union

Unlike the array, which stores the data in the variables of the same data type, Structures and Union are used for data storage in variables but of different data types. Suppose, you need to take the information of an Employee, the information which you want to collect from them is : Employee Name, DOB (Date of Birth), Salary.
As you can see, Employee Name will be having data type "char", DOB can also have data type "char" and Salary is stored in "integer" data type. For this, we can use structures.

Difference Between Structures & Union?

# Structures & Union are one and the same thing but the only difference is in the memory allocation in both. Structures assign memory to every variable which is declared, and Union only assigns the memory which the last variable in the list is declared to. 

Both Structures and Union have the same data type. Only in structure, you need to use the keyword "struct" and in Union, you need to use the keyword "union".

Let's see the syntax.

struct structureName;
{
 dataType nameOfVariable[size];
 dataType nameOfVariable[size];
 .....
 .....
}noOfObjects;

Here, noOfObjects means of many times people, you need to take the information of. Let's learn with the help of example. 

struct student;
{
 char name[20];
 int marks[20];
}student1, student2; OR }student[1];

Explaination : We have created a student structure which is having name as a variable of data char and size of it is 20. Same way, we have variable marks of the data type integer and size of it is 20. After }, you have the number of times, you need to take the data. Here, student[1], so the value will be stored as student0, student1.

How to assign values to structure?

struct student;
{
 char name[20];
 int marks[20];
}student1, student2; OR }student[1];

for(i=0;i<=1;i++)
{
 printf("Name = ");
 scanf("%s", student.name[i]);
 printf("Marks = ");
 scanf("%d", student.marks[i]);
}

How to print the structure? 

You can use the for Loop for it. 

for(i=0;i<=1;i++)
{
 printf("Name = %s", student.name[i]);
 printf("Marks = %d", student.marks[i]);
}

Pointers

So, now let's begin with the Advanced Part of C Programming. The first concept, we are going to learn about is pointers. So what are pointers? A pointer provides access to the variable by using the address of the variable. A pointer variable stores the value of another variable. 

Why to use Pointers?

# Pointers are used when we pass arguments in the functions. They are two methods to call the function, you will learn about them in next tutorial, 1. Call by Value and 2. Call by reference. The Call by reference works with pointers. Because in functions, the arguments we pass are formal arguments. So once the function returns the value or gets close, the variables are destroyed. To prevent it, we use Pointers.
Example : Swapping of two variables using Pointers

How to declare Pointer Variable?

dataType *pointerName;

That's all, and a variable named pointerName will be created, which capable to store the address of another variable.

How to store address of the Variable in Pointer Variable?

To store the address, first declare the variable whose address is to be stored. And then declare pointer variable and assign the address value of the variable to it using "&". Let's see how.

int x = 10;
int *ptr;
ptr = &x;

Explaination : Here, x is a variable in which 10 value is stored. Then pointer variable named ptr is declared. Then the address value of x is stored in variable ptr using "&".

Functions

Functions are basically the block of codes which we have to use multiple times in the program like loops. Functions can reduce the number of lines of codes. Functions are executed when they are called from the main function. 

Functions are of two types :-

</a> In-built Functions 
In-built Functions are printf, scanf, the ones which are predefined in the header file.

</b> User-defined Functions
User-defined Functions are the functions which the users create to reduce the number of lines of codes.

How to Call a function?

Before working in the main function, you need to tell the compiler that we have a Sub-function i.e User-defined function is there below the main function. To call the function,  you need to follow the following syntax.

functionName(dataTypeOfVariable1 nameOfVariable, dataTypeOfVariable2 nameOfVariable, ...);  // This should be before the initialization of main function.

How to declare a function?

returnDataType functionName(dataTypeOfVariable1 nameOfVariable, dataTypeOfVariable2 nameOfVariable, ...)
{
 ......
 // block of codes
 ......
 return(variable);
}

There are 4 types of User-defined Functions :-

</a> Function with No Arguments and no Return Value
In this type of User-defined Function, there is no argument and no return value. We simply need to call the Function from main. Then what about printing the value? It is done in the User-defined Function.
Click Here for the Example Of Function with No Arguments and no Return Value.

</b> Function with No Arguments and a Return Value
Here, in this User-defined Function, still we aren't passing any argument, but return a value from the User-defined Function to the main function.
Click Here for the Example Of Function with No Arguments and a Return Value.

</c> Function with Arguments and no Return Value
With Arguments and no Return Value means the User-defined Function is passed with the Argument and in it, it has the printing statements. 
Click Here for the Example Of Function with Arguments and no Return Value.

</d> Function with Arguments and a Return Value
In this, we have both the Argument along with the Return Value.
Click Here for the Example Of Function with Arguments and a Return Value.

Just to Remind You : dataType functionName(argument, arguments, ...)