Wednesday, January 24, 2018

Scope Control in C programming

In this topic, we will discuss the scope of a variable in C programming, more specifically we will see the behavior of Global and Local variables. In C programming variables are separated by their accessibility. There are some rules/limitation in using variables.


Local Variable

Variables that are declared inside a function or block are called Local variable for that function.

Let's see an example



#include <stdio.h>

int main() 
{
    int n; // n is a local variable to main() function
    return 0;
}


void function_01() 
{
   int n1; // n1 is a local variable to function_01() function
}


void function_02() 
{
   int n2; // n2 is a local variable to function_02() function
}


The following chart will show the accessibility of variables
Function Name Accessible Variable
main n
function_01 n1
function_02 n2


Global Variable

Variables that are declared outside of all functions are called Global variable.

Let's see an example



#include <stdio.h>

int x; // x is a global variable.

int main() 
{
    int n; // n is a local variable to main() function
    return 0;
}

void function_01() 
{
   int n1; // n1 is a local variable to function_01() function
}

The following chart will show the accessibility of variables
Function Name Accessible Variable
main n, x
function_01 n1, x


Important

Whenever we call any function with parameters that function just receive the value of their corresponding parameters. Remember function never receive any variable (same placeholder) directly just receive the values and creates temporary variables to store those values ( which are the local variables of that function ).

Let's see an example



#include <stdio.h>

int x = 10; /* global variable */

void display(int a, int b)
{
    printf ("value of a = %d, b = %d \n", a, b);

    int sum = x + a + b; // sum = 10 + 20 + 30
    printf ("sum = %d \n", sum);
}


int main ()
{
    /* local variable declaration */
    int a, b;

    /* Variable initialization */
    a = x + 10; // a = 10 + 10 = 20
    b = x + 20; // b = 10 + 20 = 30

    display(a, b); /* calling a void function */

    return 0;
}

Note
  • In line 23 we are calling a void function with parameter (a, b). here we are not passing the exact variable directly, we just passing their corresponding value (20, 30)
  • In our main function we have variables a and b also in our display function we have another two temporary variables named a and b (we can also use different names). Though their names and values are same they are not same. Like in every city there are many people who have the same name.
  • In this program x is the only global variable so we can use it both main and display function


Let’s see another Example to understand above points



#include <stdio.h>

int x = 10; /* global variable */

void display(int a1, int b1)
{
    /* a1 and b1 is the local variable to this function. */
    /* a1 holds the value of a and b1 holds the value of b*/
    printf ("value of a = %d, b = %d \n", a1, b1);
    printf ("value of x = %d \n", x);
}

void changeValue(int a, int b)
{
    /* changing the value of all variable */
    a = 1;
    b = 2;
    x = 3;
}


int main ()
{
    /* local variable declaration */
    int a, b;

    /* Variable initialization */
    a = 100;
    b = 200;
    x = x + 10; // x = 10 + 10;


    display(a, b); /* calling a void function */


    changeValue(a, b); /* calling changeValue function with parameters (100, 200) */

    /* printing all the variable accessible from main() function */
    printf("\nprinting all the variable accessible from main() function\n");

    printf ("value of a = %d, b = %d \n", a, b);
    printf ("value of x = %d \n", x);

    return 0;
}


Note
  • In line # we pass the value only not the variable.



Previous Page

Next Page



User defined Function in C programming

A function is a self-contained block of statements which we can use whenever we want. A user-defined function is a type of function which is defined by the user.


Types of user-defined function in C
  • Function with no arguments and no return value.
  • Function with arguments and no return value.
  • Function with no arguments and a return value.
  • Function with arguments and a return value.

Type 1: Function with no arguments and no return value.

// example of a void function with no arguments.

#include <stdio.h>

void Add()
{
    int a, b;               // declaring variables.
    scanf("%d %d",&a, &b);  // taking input from user.
    
    int sum = a + b;        // storing the summation of given two numbers.
    printf("Summation of given two numbers = %d \n", sum);
}


int main()
{
    Add(); // calling function from the main.
    return 0;
}

Note
  • Above Function has no arguments and no return value. So it is a void function.
  • After calling this function from the main, this function will take input from the user and print the sum of two numbers.

Type 2: Function with arguments and no return value.

// This is an example of a void function with arguments.

#include <stdio.h>

void Add(int a, int b)
{
    int sum = a + b;        // storing the summation of given two numbers.
    printf("Summation of given two numbers = %d \n", sum);
}


int main()
{
    int x, y;               // declaring variables.
    scanf("%d %d",&x, &y);  // taking input from user.

    Add(x, y); // calling function from the main.

    return 0;
}

Note
  • Above Function has arguments but no return value. So it is also a void function.
  • Above function is passing parameters from the main after that, Add function will print the summation of these two numbers.

Type 3: Function with no arguments and a return value.

// This is an example of a no argument function which has a return value.

#include <stdio.h>

int Add()
{
    int a, b;               // declaring variables.
    scanf("%d %d",&a, &b);  // taking input from user.

    int sum = a + b;        // storing the summation of given two numbers.
    return sum;             // return the sum value
}


int main()
{
    int result = Add();  // calling function from the main and receiving the return value.

    printf("Summation of given two numbers = %d \n", result);
    return 0;
}
Note
  • When we call the function from the main it will return a value.
  • For receiving the return value we used result variable and assigned the Add() function into that variable so that the return data can be stored into the variable called result.
  • We can use different names for the variable but the datatype of the must be same as the function return data type.

Type 4: Function with arguments and a return value.

// This is an example of a function which has arguments and a return value also.

#include <stdio.h>

int Add(int a, int b)
{
    int sum = a + b;        // storing the summation of given two numbers.
    return sum;             // return the sum value
}


int main()
{
    int x, y;                // declaring variables.
    scanf("%d %d",&x, &y);   // taking input from user.

    int result = Add(x, y);  // calling function from the main.

    printf("Summation of given two numbers = %d \n", result);
    return 0;
}
Note
  • In this case we take input into the main function and passed it through the Add() function which is the only difference from the previous example.


Previous Topic

Next Topic



Structure of a Function in C programming

At that point we should have a good idea on C programming so it is time to move on a topic like Function. What is function? It is little bit difficult to explain in a sentence. We know what is loop and what it does, right? We used loop to execute any block of code several times but what if I want to repeat any block of code at any time/part of our program! Exactly, we can do this using function.


Function is a self contained block of statements which we can use whenever we want. Every Program has at least one function in C programming called ‘main()’.


Structure of a function
return_type  function_name ( parameter_list )
{
     // Function body
}

return_type : return_type is the date type which any function returns in C. Function in C must have a return type.

Functions may or may not return any value. If it does not returns any value then the return_type will be void. void function indicates it returns nothing.

function_name : function_name is simply the name of the function.

parameter_list : Parameters are like placeholder. Any function may have zero or more parameters. Any types of parameters can be used in a function. If there are more than one parameters then every parameter will be separated by a comma.

Types of Function in C
  • Standard Library Functions ( ex. scanf(), printf(), etc )
  • User Defined Functions

Look at the following example for better understanding

#include <stdio.h>

int add ( int a, int b )
{
    int result = a + b;
    return result; 
}

int main()
{
    int a, b;
    scanf("%d %d",&a, &b);
    
    int sum = add(a, b);   // calling function from main.
    printf("Summation of given two number is %d \n", sum);

    return 0;
}


Note
  • Above function has a return value of integer.
  • return keyword is used in C to return value from function.
  • To use any function in C programming, it must be called from the main function otherwise it won't work.

Advantages of using Function in C
  • We can reuse our code at anywhere in our program.
  • It makes debugging and editing more easier.
  • It makes program more readable.
  • It makes code more optimized.


Previous Topic

Next Topic



Saturday, December 9, 2017

Continue Statement In C

We know loop continues execution of its body statements until the condition is false. If I want to skip some statements inside loop or terminate execution before the loop condition becomes false. How can we handle this issue ?

To solve this issue there are some case control statements in C programming.

  • break
  • continue
  • switch

Continue Statement

  • Continue statement is used in C programming to skip remaining code after the continue statement inside the body of any loop.
  • To write continue statement in our program we use decision making statement ( if - else ).

Syntax of Continue Statement : continue;

Example

#include <stdio.h>

int main()
{
    int i;
    for(i = 1; i <= 10; i++)
    {
        if(i == 3 || i == 5 || i == 7)
        {
            continue;
        }

        printf("%d \n", i);
    }
    return 0;
}



Output
1
2
4
6
8
9
10

Explanation of above program

If you notice the output section then you will see 3, 5 and 7 is missing though we set the loop for all number between 1 to 10 inclusive. We set another condition in the body of the for loop which means that if the number is 3, 5 or 7 only then it will skip the remaining body statents and it will start the next iteration.



Previous Topic

Next Topic



Break Statement In C

We know loop continues execution of its body statements until the condition is false. If I want to skip some statements inside loop or terminate execution before the loop condition becomes false. How can we handle this issue ?

To solve this issue there are some case control statements in C programming. Here we will discuss about

  • break
  • continue
  • switch

Break Statement

  • Break statement is used to terminate surrounding loop immediately without checking loop condition.
  • To write break statement in any program we use decision making statement ( if - else ).

Syntax of Break Statement : break ;

Example


#include <stdio.h>

int main()
{
    int i;
    for(i = 1; i <= 10; i++)
    {
        if(i > 5)
        {
            break;
        }

        printf("%d \n", i);
    }
    return 0;
}

Output
1
2
3
4
5

Explanation of above program

We know how for loop works.In this case, for loop should work for 10 iteration. Everytime it executes it body statements it checks the condition in the body statement ( i > 5 ) either true or false. For the first 5 times it is false so break statement does not works there, goes to the next statement and executes the print command but in the 6th iteration the condition became true and it terminate the loop though the loop condition ( i <= 10 ) was still true.



Previous Topic

Next Topic



Friday, December 8, 2017

Nested Loop In C Programming

One loop inside another loop is called Nested loop. Here we will discuss about this.

Syntax of a Nested for loop


for ( variable initialization ;  condition ;  variable update )
{
      for ( variable initialization ;  condition ;  variable update )
      {
          // body statement.
      }
}


Example of a Nested for loop. This program will print “Outer Loop” 3 times. After every time it will print “Inner Loop” 2 times.


#include <stdio.h>

int main() 
{
     for(int i = 1;  i <= 3;  i++)
     {
           printf( “%d. Outer Loop \n”, i );
           for(int j = 1;  j <= 2;  j++)
           {
                 printf ( " Inner Loop \n", j );
           }
           printf(“ \n ”);
     }
     return 0;
}

Output

1. Outer Loop
Inner Loop
Inner Loop

2. Outer Loop
Inner Loop
Inner Loop

3. Outer Loop
Inner Loop
Inner Loop

Note : We can use any loop inside any other loop. For an example we can use while loop inside a for loop or vice versa.



Previous Topic

Next Topic



Do While Loop In C Programming

We used loops to execute a block of code several times. do while loop is similar as while loop but in do while loop conditional expression appears at the bottom of the loop instead of the beginning.

Syntax of a While loop


do
{
     // body statement.
}
while ( Condition );

Note
  • Before checking the condition do while loop must be executed once.
  • Conditional expression / statement appears in the bottom of the loop. And there is a semicolon after the conditional expression.

Condition : After checking the condition it decides whether loop needs to continue or not. If the condition is false then the loop will not be executed.


Let’s look into the following program which will print “Hello world” 5 times.


#include <stdio.h>

int main() 
{
      int i = 1;
      do
      {
           printf("Hello World \n");
           i++;  // Update.
      }
      while ( i <= 5 );

      return 0;
}


Output
Hello World 
Hello World 
Hello World 
Hello World 
Hello World 

How it works

Step 1 : First it will go to the body statement, there is a print command and it will be executed.

Step 2 : After that, Update statement will be executed

Step 3 : Start repeating from Step 1.

Step 4 : Then it will check either the condition ( i <= 5 ) is true or not. If the condition is true only then it will start repeating (go to the body statement) from Step 1. Otherwise it will be terminated.



Previous Topic

Next Topic



While Loop In C Programming

We used loops to execute a block of code several times.

Syntax of a While loop


while ( Condition )
{
     // body statement.
}

Condition : After checking the condition it decides whether loop needs to continue or not. If the condition is false then the loop will not be executed.


Let’s look into the following program which will print “Hello world” 5 times.

#include <stdio.h>

int main() 
{
     int i = 1;
     while ( i <= 5 )
     {
         printf("Hello World \n");
         i++;  // Update.
     }
     return 0;
}

Output

Hello World 
Hello World 
Hello World 
Hello World 
Hello World 

How it works

Step 1 : First it will check either the condition ( i <= 5 ) is true or not. If the condition is true only then it will go to the body statement. Otherwise it will be terminated.

Step 2 : In the body statement, there is a print command and it will be executed.

Step 3 : After that, Update statement will be executed

Step 4 : Start repeating from Step 1.



Previous Topic

Next Topic



For Loop in C Programming

We used loops to execute a block of code several times.

Syntax of for loop
for ( variable initialization ;  condition ;  variable update )
{
      // body statement.
}

Variable Initialization : It allows us to assign value into a pre-declared variable or we can declare here at the same time, Variable initialization statement is executed once in the beginning of execution.

Condition : It decides whether loop needs to continue or not after checking the condition. If the condition is false then the loop will not be executed.

Variable update : We can update our variables here. Like increment, decrement etc.


Let’s look into the following program which will print “Hello world” 5 times.

#include <stdio.h>

int main() 
{
      for(int i = 1;  i <= 5;  i++)
      {
           printf("Hello World \n");
      }
      return 0;
}

Output
Hello World 
Hello World 
Hello World 
Hello World 
Hello World 

How it works

Step 1 : First we declare a variable name i and assign value of 1.

Step 2 : Then it will check either the condition ( i <= 5 ) is true or not. If the condition is true then it will go to the body statement. Otherwise it will be terminated.

Step 3 : In the body statement, there is only one print command and it will be executed.

Step 4 : After that, Update statement will be executed first time ( note that update statement will be executed form 2nd iteration and from 2nd iteration variable initialization will be ignored )

Step 5 : Start repeating from Step 2.


Look at program below


#include <stdio.h>

int main() 
{
      int i = 1;
      for( ;  i <= 5 ;  )
      {
           printf("Hello World \n");
           i++;
      }
      return 0;
}

Both programs are valid. In for loop we can either declare variable inside the loop or outside the loop as it will be executed only once. In this case we declare outside of for loop. Same as for updating variable. We increases variable inside the loop as we need to update the value every time.

Note : Semicolon separates each of these section. Any section can be empty but the semicolon must have to be there.



Previous Topic

Next Topic



Loops in C programming

Did you ever write a single word hundred or thousand times as a punishment in your school life ? I guess most of us are familiar with this type of punishment. If yes, then it is very easy to understand what is loop and what it does.

Sometimes you have to repeat some particular block of code several times. Simply you can write those code several times. Surely this is a solution but not the efficient one. Using loop we can execute any block of code several times.

Look at the following example, where I want to print “Hello World” 5 times. You don’t have to be worry about the program/syntax (loop part) right now, we will discuss it on this section. Just see how simply we can repeat any block of code.


#include <stdio.h>

int main() 
{
      printf(“Hello World \n”);
      printf(“Hello World \n”);
      printf(“Hello World \n”);
      printf(“Hello World \n”);
      printf(“Hello World \n”);

      return 0;
}


Using while loop

#include <stdio.h>

int main() 
{
      int cnt = 1;
      while(cnt <= 5)
      {
           printf(“Hello World \n”);
           cnt++;
      }
      return 0;
}


Which one you will prefer when you have to write it millions of time ?

We can follow any of those process as both are valid but loops save our code, effort and time also. Repeating 5 times is not a big deal we can type this 5 times but when we have to do the same thing thousand or million time then loops are the best option.

Note
  • It saves code and time.
  • Makes program simple.

This section we will talk about

  • for loop
  • while loop
  • do while loop
  • Nested loop
  • Infinite loop


Previous Topic

Next Topic



Friday, December 1, 2017

If - else Statement in C

if else statements are used in C for making decision from one or more conditions.

In this section we will talk about
  • Single if Statement
  • If else Statement
  • Nested if else Statement


Single if Statement

Single if statement is used in C to execute the body( a block of statements ) if the condition is true. The structure of an if statement is given bellow


if( condition )
{
     // This is the body of the if statement.
}

Note
  • if statement will be executed when the condition is true.
  • Between the braces { } is the statement body/block, whatever we write between these braces will be executed if the condition is true.

Let’s look at the following program which will identify either a given number is greater than 0 or not.


#include <stdio.h>

int main()
{
    int var;
    printf(" Enter a number: ");
    scanf(" %d", &var);

    if(var > 0)
    {
        printf(" Given number is greater than 0.");
    }
    return 0;
}


Output




If - else Statement

An if - else statement is used in C to make a decision from a list of condition. The structure of an if - else statement is given bellow


if( condition1 )
{
     // This body statement will be executed when condition1 is true.
}
else
{
     // This body statement will be executed when condition1 is false. 
}

Note
  • if statement will be executed if condition1 is true otherwise else statement will be executed.
  • Both if and else statement can’t be executed at a time.

Let’s look at the following example


#include <stdio.h>

int main()
{
    int num;
    printf(" Enter a number: ");
    scanf(" %d", &num);

    if(num % 2 == 0)
    {
        printf(" Given number is Even.");
    }
    else
    {
        printf(" Given number is Odd.");
    }
    return 0;
}

Sample Output


Sample Output

Note It is not necessary that you have to check only two condition .You can add multiple condition Let’s look into another example


#include <stdio.h>

int main()
{
    int var;
    printf(" Enter a positive integer : ");
    scanf(" %d", &var);


    if(var == 1)
    {
        printf(" Given number is 1.");
    }
    else if( var == 2)
    {
        printf(" Given number is 2.");
    }
    else if( var == 3)
    {
        printf(" Given number is 3.");
    }
    else
    {
        printf(" Given number is greater than 3.");
    }

    return 0;
}


Sample Output




Nested if - else Statement

You can use if - else statement into another if - else statement. Let’s look at the following code.

#include <stdio.h>

int main()
{
    int var;
    printf(" Enter a positive number : ");
    scanf(" %d", &var);


    if(var < 10)
    {
        if(var < = 5)
        {
            printf(" Given number is less than or equal 5.");
        }
        else
        {
            printf(" Given number is greater than 5 and less than 10.");
        }
    }
    else if( var < 20)
    {
        if(var < = 15)
        {
            printf(" Given number is less than or equal to 15.");
        }
        else
        {
            printf(" Given number is greater than 15 and less than 20.");
        }
    }
    else
    {
        printf(" Given number is greater than or equal to 20.");
    }

    return 0;
}

Sample Output



Previous Topic

Next Topic



Wednesday, November 29, 2017

Operators in C

In this section we will learn about various Operators. An operator is a symbol which performs for specific mathematical or logical operation. For an example, plus (+) operator is used for addition and minus (-) operator is used for subtraction.


Here we will talk about the following operators

  • Arithmetic Operators
  • Increment / Decrement Operators
  • Assignment Operators
  • Relational Operators
  • Logical Operators


Arithmetic Operators

Arithmetic Operators are used to perform mathematical operation like addition, subtraction, division and multiplication. Following table shows the arithmetic operators with example. Let, X = 5 and Y = 2

Operator Operation Description Example
+ Addition Adds two operands X + Y = 7
- Subtraction Subtracts second operand from the first X - Y = 3
* Multiplication Multiplies both operands. X * Y = 10
/ Division Divides numerator by denominator. X / Y = 2.5
% Modulus Gives remainder value after divides the first operands by second operands X % Y = 1



Increment / Decrement Operators

Increment (++) Operator increases value by one and Decrement (--) Operator decreases value by one. Following table shows Increment / Decrement operators with example. Let, X = 5 and Y = 2

Operator Operation Description Example
++ Increment increases value by one X++ is equal to 6
-- Decrement decreases value by one Y-- is equal to 1



Assignment Operator

Assignment Operators are used to assign value into variables. Following table shows the Assignment operators with example.

Operator Description Example Same As
= Assigns values from right side operands to left side operand X = Y X = Y
+= Add and assignment operator X += Y X = X + Y
-= Subtract and assignment operator X -= Y X = X - Y
*= Multiply and assignment operator X *= Y X = X * Y
/= Divide and assignment operator X /= Y X = X / Y
%= Modulus and assignment operator X %= Y X = X % Y



Relational Operators

Relational Operators are used to compare between two operands. Following table shows the Relational operators with example. Let, X = 5 and Y = 2

Operator Description Example True/False
== Is Equal to X == Y. (5 == 2) False
!= Is Not Equal to X != Y (5 != 2) True
> Greater than X > Y (5 > 2) True
< Less than X < Y (5 < 2) False
>= Greater than or Equal to X >= Y (5 >= 2) True
<= Less than or Equal to X <= Y (5 <= 2) False



Logical Operators

Logical Operators are used in decision making. Following table shows the Logical operators with example. let X = True and Y = False

Operator Description Example True/False
&& Checks both operands are True (X && Y) False
|| At least one of the Operands is True (X || Y) True
! It checks the reverse condition is true or not !(X) False



Previous Topic

Next Topic



Tuesday, November 28, 2017

Input and Output Functions in C - scanf() / printf()

So far we can write simple C programs, know about variables,identifiers,keywords and data types and also know how to assign different types of data into variable. Now it is time to know how to take different types of data as an input from user/keyboard and how to print them.


What it means by taking input from user/keyboard? Well, I don’t want to assign any data in my variable directly in our program. We want to assign it manually when our program will run.

There are several built in function to take input from user and display it. Here we will learn about them.

Input

scanf() function

Syntax of scanf() function is given below

scanf(“format_specifier”, &variable);

Note
  • scanf() function performs to read input from user.
  • Inside the double quote “” different Format Specifiers are used to take different type of data as an input. We saw a list of format specifier in Data Types section.
  • To take different types of data as an input from user we need to use corresponding format specifier.
  • Ampersand sign & is used before variable name to point the address in memory location.

Look into the following program to understand how to use format specifier in scanf() function.


#include <stdio.h>

int main(void) 
{
     //integer type data
     int var1;                       // variable declaration.
     scanf("%d", &var1);     // taking input from user.
     
     //long long type data
     long long var2;
     scanf("%lld", &var2);
     
     //double type data
     double var3;
     scanf("%lf", &var3);
     
     //float type data
     float var4;
     scanf("%f", &var4);
     
     //character type data
     char var5;
     scanf("%c", &var5);
     
     return 0;  
}



Output Function

printf() function

Syntax of printf() function is given below

printf(“format_specifier”,variable);

Note
  • printf() function performs to display output result on the screen.
  • Format specifiers are used inside the double quote “” to display corresponding data. We saw a list of format specifier in Data Types section.
  • To display different types of data as an output we should use corresponding format specifier.
  • No need of any Ampersand sign in this case.

Look into the following program to understand how to use format specifier in both scanf() printf() function.


#include <stdio.h>

int main(void) 
{
      //character type data
     char var5;
     scanf("%c", &var5);
     printf("This is a character type data = %c \n", var5);
     
     //integer type data
     int var1;
     scanf("%d", &var1);
     printf("This is an integer type data = %d \n",var1);
     
     //long long type data
     long long var2;
     scanf("%lld", &var2);
     printf("This is a long long type data = %lld \n",var2);
     
     //double type data
     double var3;
     scanf("%lf", &var3);
     printf("This is a double type data = %lf \n",var3);
     
     //float type data
     float var4;
     scanf("%f", &var4);
     printf("This is a float type data = %f \n", var4);
     
     
     return 0;
     
}

output


Note

Did you notice that every printf() function starts printing from new line. Why? \n is used in C programming to create new line. After printing it goes to the next line. Remove all \n from printf() function and Run this program on your machine and see the differences.

getchar() and putchar() functions

Instead of using scanf() and printf() we can also use getchar and putchar() function for the same purpose.

Note:
  • We can also use getchar() function to take character type input.
  • putchar() function used to display character type data.


#include <stdio.h>

int main() 
{
     char ch;            // variable declaration
     ch = getchar();     // taking input.
     putchar(ch);        // printing character 
 
     return 0;
}



Previous Topic

Next Topic