Showing posts with label C Programming. Show all posts
Showing posts with label C Programming. Show all posts

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



Sunday, November 26, 2017

Variable Declaration using Different Types of Data

We know the how to declare variable. We saw some example in my previous post. Here we will discuss about how to declare different types of data.

Data Type Variable Declaration Initializing Declaration & Initializing
int int A; A = 12345; int A = 12345;
long long long long b; b = 123456789; long long b = 123456789;
float float c; c = 45.123456; float c = 45.123456;
double double D; D = 33.123456789; double D = 33.123456789;
char char ch; ch = 'k'; char ch = 'k';


Let's look into the following code


#include <stdio.h>

int main() 
{
      // variable declaration
      int variable1;
      long long variable2;
      float variable3;
      double variable4;
      char variable5;
 
      // initializing
      variable1 = 5;
      variable2 = 123456;
      variable3 = 454.123456789;
      variable4 = 34.123456789;
      variable5 = 'A';
            
     // printing 
      printf("%d\n",variable1);
      printf("%lld\n",variable2);
      printf("%f\n",variable3);
      printf("%lf\n",variable4);
      printf("%c\n",variable5);
 
 return 0;
}



NOTE
  • or are format specifier.
  • is used for creating newline. if you run the above program you will find each of those output in different line.




Previous Topic

Next topic



Data Types in C

In this section we will learn about data types. We all know that, before using any variable in C it should be declared. Data types used to define a variable and how much memory space need to allocate that variable.

In our variable section we compared variables with containers or boxes. Every box or container has its limit. Which container we need to store anything it depends on the size of what we want to store. Like that, we also need to take a decision to how much memory we need to allocate. We can’t always measure the exact space we need but we can easily calculate/guess approximate space we need.

Data Types in C language

Fundamental data type

  • Integer Type
  • Floating Type
  • Character Type

Derived Data Type

  • Array Type
  • Structure Type
  • Pointer Type

Fundamental Data Type

Integer Type

The following chart will show the details about integer type data
Type Size (bytes) Range Format Specifier
short 2 -32,768 to 32767 %hd
unsigned short 2 0 to 65,535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long 4 0 to 294,967,295 %lu
long long 8 -(2^63) to (2^63)-1 %lld
unsigned long long 8 0 to 18,446,744,073,709,551,615 %llu

Note:
  • First column indicates the reserve words or keywords.
  • We can’t store decimal values into integer data. If we assign 7.36 into any integer variable then it will store 7 (only the integer part)


Floating Type

The following chart will show the details about floating type data
Type Size (bytes) Range Precision Format Specifier
float 4 1.2E-38 to 3.4E+38 6 decimal places %f
double 8 2.3E-308 to 1.7E+308 15 decimal places %lf
long double 12 3.4E-4932 to 1.1E+4932 19 decimal places %Lf

Note:
  • First column indicates the reserve words or keywords.
  • Float data type allows to store decimal values.
  • Floating point variable has precision of 6 digits and double has 15 digits precision.


Character Type

The following chart will show the details about character type data
Type Size (bytes) Range Format Specifier
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
char 1 -128 to 127 or 0 to 255 %c

Note:
  • First column indicates the reserve words or keywords.
  • A character type data only allow to store character.

We will discuss about Derived Data Type later as it requires some advance knowledge.

Previous Page

Next Page



Saturday, November 25, 2017

Variable Declaration in C

Now we can print using C program but it is not the only thing we want to do. A lots of things are still remaining.

If we want sum of two numbers from calculator then first we need to put one number and then we need a command (+ sign for addition) which operation we want to do and then we need to put another number. After that if we press equal (= sign) only then calculator will show summation of that two numbers by doing addition operation.


How can calculator remember this two number or calculator stores those number and command? Can you figure out this answer? Let me know if you can.

Let’s back to the topic, variables. What is variable? Simply a variable is a name or identifier by which we can identify them. If we want to use any character, number or others data in our program we need to store them first.


We can compare variable with a container or box. If we have 5 boxes and each one has an unique name then we can easily identify them by their name. Like this, a variable is an unique name of a particular location of memory in our computer. This location in a memory is used to store data.


Before using any variable we need to declare it first. How to declare a variable? Let’s see some example :

If you look into the above example then you already figured out a common pattern in variable declaration. Every variable has two part.First part is its data type and second part is its name.


Structure/Syntax of a variable(in declaration) :

In our above example for first two variables data type is int (ex 2, 3, 10) and for the third variable is double (ex 1.3, 4.87) and all these three variables are unique by their name so that we can identify them.


We can declare same or different types variable as many as we want but their name should be different.


Setting / Assigning Value

If we want to set a number in our variable, how can we do this? Simple! just use a equal sign to set any value. For an example if i want to set 10 in a variable name value;

Declaring variable int Number;
Assigning value Number = 10;

Or we can do this in another way
Declaring & Assigning value int Number = 10;

Both are same. We can use both in our program.



Rules for naming a C variable:

  • A variable can have both uppercase and lowercase letters, digits and underscore.
  • First character of a variable should be an alphabet or underscore.
  • We can’t use any digit in beginning of an variable.
  • We can’t use special character in variables except underscore.
  • An variable can’t be any keyword.

Rules for naming a variable and identifier are same because variables are also a type of identifier.



Thursday, November 23, 2017

Identifies and Keywords

Any C program only allow us to use Alphabets, Digits and Special characters. C is a Case Sensitive language. That means in c programming A is not similar to a. One is uppercase letter and another is lowercase letter.



Uppercase
A B C D E F G H I
J K L M N O P Q R
S T U V W X Y Z


Lowercase
a b c d e f g h l
j k l m n o p q r
s t u v w x y z


Digits
0 1 2 3 4 5 6 7 8 9


Special Character
# , < > . | ( ) ; $
: % ' ^ - [ ] - ? &
{ } " " / \ * _ +


What is identifier ? In general, by which we identify anything is an identifier (like my name is an identifier). In C programming an identifier is a name used to identify any user defined item like variable, function. Probably you are thinking what is variable ? let it go now, we will discuss it in the next topic/variables section.


  • An identifier can have both uppercase and lowercase letters, digits and underscores.
  • First character of an identifier should be an alphabet or underscore. We can’t use any digit in beginning of an identifier.
  • We can’t use special character in identifier except underscore.
  • An identifier can’t be any keyword. (we will discuss about keyword here).


In C programming some words are already been used in compiler. Keywords are part of the syntax. That’s why keywords are reserved. We can’t use those word as an identifier. If we can remember our basic c programming code then there we used return which is a keyword. We can’t use return as a identifier.

The following list shows the keyword or simply reserve word in C language.

Reserve Words (Keywords)
auto else long switch break case char const continue
default do double struct typedef union int if goto
for float extern return enum register short signed sizeof
static unsigned void volatile while _Packed


Previous Topic

Next Topic



Comments

Now we are familiar with the basic structure of a simple c program, right?. Now it's time to talk about another important thing.

Here we will discuss about how to put a Comment on a C/C++ program:

Comments are specially important for large projects where thousands of lines of source code or many contributors are working on the same source code. When we use our pre written code or simply older code, sometime it is tough to understand everything properly.
That’s why there is a way for adding comment in our program so that we can add some hints which will help us or other contributors when they use the same source code.


Process of adding a comment is more simpler than our above explanation :D There are two different way we can use in C/C++ programming to add a comment.



Let’s look into the source code below :


#include <stdio.h>

int main() 
{
     // Way 1: This a single line comment.
 
     /* Way 2: This style
     allow you to add
     multiple lines 
     of  comments. */
  
     printf("This is an Example of adding Comments on a C program in different way.");
     return 0;
}

OUTPUT


If we use to any particular line in our source code then whatever we write after the sign on that line will be ignored by the compiler.


If we use to our code then whatever we write inside that will be ignored by the compiler.


Previous Topic

Next Topic



Wednesday, November 22, 2017

Environment Setup

Before going to the main part we need to make sure that we have a compiler. I think at this point all of you have a common question on your mind, what is Compiler?
Great!, We all know that machine only knows 0 and 1. But in many languages (like C/C++) we will write code using letters, digits and special characters. Which machine can’t read directly so we need something which can read our code and machine’s also.

Compiler converts human code into machine code so that machine understand it properly. This process called compilation.

If you have a compiler already then you can skip this post.


Now a days, there are two many option for setting up Environment. It’s tough to discuss all of this in this post. So here we will discuss about code blocks and show you the step how to install code blocks with GNU GCC compiler for windows/Linux users as it is most popular IDE also suitable for beginners.


For Mac OS users Code blocks is not a good option as it crashes frequently on mac but there is a cool alternative for that which is Xcode. We’ll discuss about Xcode also.


Let’s see the process step by step :


Step 1: Type code blocks in google search bar and go for it, you will find their official site in the first search result or you can go directly from here.

Step 2: There you will find Download option. Click on the Download option.

Step 3: Now you will find an option “Download the binary release”. Click on it.

Step 4: Here you will see some option like this :

  • Window XP / Vista / 7 / 8.x / 10
  • Linux 32-bit
  • Linux 64-bit
  • Mac OS X

Go for the suitable option depending on your operating system.
Any problem? if yes! then click here to go to that page directly.

Step 5: Windows user download codeblocks-16.01mingw-setup.exe by clicking on sourceforge.net .


NOTE: If you are facing any problem with the above procedure or it creates any confusions then you can watch this to clear your confusion. But remember this is an old video, if you want to download the latest version then you have to follow the above procedure. You can watch this to be sure about the procedure.


After complete downloading you need to install it. You can do in the same process like other application. Just follow the instruction.

Or you can follow this video .



You can also follow the same procedure given for windows user until the 4th option. But it is more easier to download through command line instead of downloading manually.

Step 1: Open command line (Press ).

Step 2: Enter the following command :

     sudo add-apt-repository ppa:damien-moore/codeblocks-stable
     sudo apt-get update 
     sudo apt-get install codeblocks
 


Step 1: Open the App Store.

Step 2: Search for Xcode. You will find it in the first option.

Step 3: Click on the Get option.

Step 4: Now you will see the Install App option visible. Click on it and wait.


congratulations! all of you are ready to go :)


Next Topic


Basic Structure of a C program


In this section we will try to understand basic structure of a simple C program.


Let’s consider we don’t know anything about C programming if we know already. So we have no idea about its syntax or anything. Before introducing the basic terminology i would like to show you the basic C code first.


Let’s look at the code below. It is a simple C program.


#include <stdio.h>
int main()
{
    return 0;
}

So what this code means? Does it print anything? NO, it’s not going to print anything because we didn’t use any command which can print.

Wait a minute! Let’s add another line to our previous code before going to the first question.


#include <stdio.h>
int main()
{
    printf(“Hello World”);
    return 0;
}

OUTPUT :



Let’s try to understand the above program line by line.

#include is a preprocessor command and <stdio.h> is a header. By including this, we get the access of using standard input/output form the C library before executing the code.


This line tells the compiler that there is a function called main, and this function returns an integer. Every C program must have exactly one main function. From the main function or this line, every C program starts execution.


Opening curly brace { indicates the beginning of all functions in C. In this case it is indicating the beginning of the main function.


This whole line is a statement and printf(“ ”) is a function which prints the output on the screen. Whatever you write inside the quotes “” it will show that on screen after executing the program. What about the semicolon? It indicates the end of the statement. In C programming you have to put a semicolon after every statement.


It indicates the END of the program. We return a value from main to the operating system (we discussed before that main function returns an integer). A return value 0 means your program executed successfully.


Closing curly brace } indicates the end of the function.


Challenge :



Previous Topic

Next Topic