while loop in C programming

So far we’ve seen sequential flow of our programs. Next we saw decision control statements like if, if else, else if etc. Now lets learn about loop control statements present in C programming language.

In this video tutorial lets learn about while loop in particular.

Related Read:
Programming Interview / Viva Q&A: 5 (Infinite or Indefinite while loop)

General Syntax of while loop

 
#include < stdio.h >

int main()
{
    while(pre_test_condition)
      statement1;

    return 0;
}

Here while is the keyword. Inside parenthesis we need to write the condition. These conditions must evaluate to Boolean value. i.e., true(non-zero number) or false(0);

The ‘body of while’ loop keeps executing until the condition is true. Control exits while loop once the condition is false.

 
#include < stdio.h >

int main()
{
    while(pre_test_condition)
   {
      statement1;
      statement2;
   }
    return 0;
}

Enclose the statements with curly braces if there are multiple statements within while loop or body of while loop.

while loop in C programming Language


[youtube https://www.youtube.com/watch?v=2Mkc80-uqrs]

YouTube Link: https://www.youtube.com/watch?v=2Mkc80-uqrs [Watch the Video In Full Screen.]


Example Source Code: while loop

 
#include < stdio.h >

int main()
{
    int count = 1;

    while(count <= 5)
    {
        printf("%d\n", count);
        count = count + 1;
    }

    printf("End of loop\n");

    return 0;
}

Output:
1
2
3
4
5
End of loop

In above C source code, variable count is initialized to 1. Inside while condition we check if variable count is less than or equal to 5. Until variable count is less than or equal to 5, the while loop keeps executing. Inside body of the while loop we increment the value of count by 1 upon each execution of the loop. The condition is checked on execution of the loop. Once variable count is more than 5, the condition becomes false count <= 5 (once count value is 6, the condition becomes false), the execution control exits while loop.

Note: Here the loop execution counter is called ‘loop counter’ or ‘index variable’.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Ternary Operator / Conditional Operator In C

In this video tutorial we will show you how to use Conditional Operator. They are also called Ternary Operators as they take 3 arguments.

General Form of Ternary Operator

(expression_1) ? (expression_2) : (expression_3);

expression_1 is a comparison/conditional argument. expression_2 is executed/returned if expression_1 results in true, expression_3 gets executed/returned if expression_1 is false.

Ternary operator / Conditional Operator can be assumed to be shortened way of writing an if-else statement.

C Program: Ternary Operator / Conditional Operator

 
#include < stdio.h >

int main()
{
    int a = 1, b = 1, c;

    // (expression1) ? (expression2) : (expression3);

     (a+b) ? (c = 10) : (c = 20);

    printf("Value of C is %d\n", c);

    return 0;
}

Output:
Value of C is 10

a+b is 2 which is non-zero, so it is considered as true. So c = 10 gets executed.

 
#include < stdio.h >

int main()
{
    int a = 1, b = 1, c;

    // (expression1) ? (expression2) : (expression3);

     (a-b) ? (c = 10) : (c = 20);

    printf("Value of C is %d\n", c);

    return 0;
}

Output:
Value of C is 20

a-b is 0 which is zero, so it is considered as false. So c = 20 gets executed.

 
#include < stdio.h >

int main()
{
    int a = 1, b = 1, c;

    // (expression1) ? (expression2) : (expression3);

    c = (a+b) ? (10) : (20);

    printf("Value of C is %d\n", c);

    return 0;
}

Output:
Value of C is 10

 
#include < stdio.h >

int main()
{
    int a = 1, b = 1, c;

    // (expression1) ? (expression2) : (expression3);

    c = (a-b) ? (10) : (20);

    printf("Value of C is %d\n", c);

    return 0;
}

Output:
Value of C is 20

Ternary Operator / Conditional Operator In C


[youtube https://www.youtube.com/watch?v=wubWvdcjMcw]

YouTube Link: https://www.youtube.com/watch?v=wubWvdcjMcw [Watch the Video In Full Screen.]


For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

if else statement in C

In our previous video tutorial we saw how to use the decision control instruction if. In this tutorial we shall see how we can use if else statement in division of 2 numbers example.

We illustrate the use of if else statement in this video tutorial with the help of a division of 2 numbers example program.

Division of 2 Numbers: if else construct in C

Single statement in both if and else block

 
#include < stdio.h >

int main()
{
    int a, b;

    printf("Enter value of a and b for division (a/b)\n");
    scanf("%d%d", &a, &b);

    if( b != 0)
        printf("Division of %d and %d is %d\n", a, b, a/b);
    else
        printf("You can't divide a number by 0\n");

    return 0;
}

Output 1:
Enter value of a and b for division (a/b)
10
2
Division of 10 and 2 is 5

Output 2:
Enter value of a and b for division (a/b)
50
0
You can’t divide a number by 0

Note: When condition for if is true, if block gets executed. When condition in if is false, else block code gets executed.

Multiple statements in both if and else block

 
#include < stdio.h >

int main()
{
    int a, b, c;

    printf("Enter value of a and b for division (a/b)\n");
    scanf("%d%d", &a, &b);

    if( b != 0)
    {
        c = a / b;
        printf("Division of %d and %d is %d\n", a, b, c);        
    }
    else
    {
       printf("You can't divide a number by 0\n");
       printf("Please run the program once again and give proper value\n");
    }


    return 0;
}

Output 1:
Enter value of a and b for division (a/b)
10
2
Division of 10 and 2 is 5

Output 2:
Enter value of a and b for division (a/b)
50
0
You can’t divide a number by 0
Please run the program once again and give proper value

In above example we are enclosing if and else block code in curly braces as both if and else has multiple lines of code or block of code to be executed.

Scanf(): For user input

In above c program we are asking user to enter the values for variable a and b. You can know more about scanf() method/function in this video tutorial: Using Scanf in C Program

if else Construct in C: Division of 2 numbers logic


[youtube https://www.youtube.com/watch?v=WLLJn3hcFa0]

YouTube Link: https://www.youtube.com/watch?v=WLLJn3hcFa0 [Watch the Video In Full Screen.]


This video was produced as building block for our simple calculator application.

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Decision Control Instruction In C: IF

So far we’ve seen that the code in C program gets executed in sequential order i.e., as and when the code appears in the source code. But today lets see how we can change the sequence of or order of execution using decision control instruction like if statement.

General form of if statement

if( some_condition )
statement;

By default, if statement executes only the next instruction present under it. But if you want to execute some block of code, then you must enclose it inside curly braces as shown below.

if( some_condition )
{
statement_1;
statement_2;
some_logic;
function_calls;
etc;
}

in above code, some_condition can be anything from a simple true(non-zero number) or false(0) or any expression returning 0 or any non-zero number.

Statements inside if statements curly braces can be anything from multi-line statements, function calls, some arithmetic operations etc.

 
#include < stdio.h >

int main()
{
    int a;
    printf("IBM\n");
    printf("Enter value for a \n");
    scanf("%d", &a);

    if(a > 10)
    {
        printf("Microsoft\n");
        printf("Oracle\n");
    }

    printf("Amazon\n");
    printf("Apple\n");    

    return 0;
}

Output:
IBM
Enter value for a
5
Amazon
Apple

Here user entered value for variable a is less than 10. So the code inside if block doesn’t get executed. So printing of Microsoft and Oracle gets skipped.

 
#include < stdio.h >

int main()
{
    int a;
    printf("IBM\n");
    printf("Enter value for a \n");
    scanf("%d", &a);

    if(a > 10)
    {
        printf("Microsoft\n");
        printf("Oracle\n");
    }

    printf("Amazon\n");
    printf("Apple\n");    

    return 0;
}

Output:
IBM
Enter value for a
14
Microsoft
Oracle
Amazon
Apple

For the same program, user entered value for variable a as 14, which is greater than 10. So all the company names gets printed on the console window as shown in above output section.

We can even remove condition statement inside if statement

 
#include < stdio.h >

int main()
{
    int a;
    printf("IBM\n");
    printf("Enter value for a \n");
    scanf("%d", &a);

    if(a)
    {
        printf("Microsoft\n");
        printf("Oracle\n");
    }

    printf("Amazon\n");
    printf("Apple\n");    

    return 0;
}

Output 1:
IBM
Enter value for a
1
Microsoft
Oracle
Amazon
Apple

Output 2:
IBM
Enter value for a
0
Amazon
Apple

Output 3:
IBM
Enter value for a
-5
Microsoft
Oracle
Amazon
Apple

In above example, when user enters 0 the condition becomes false, so the block of code inside if statement doesn’t get executed. When the user enters any number other than 0, its considered as true, so the code inside if statement gets executed.

Scanf(): For user input

In above c program we are asking user to enter the values for variable a and b. You can know more about scanf() method/function in this video tutorial: Using Scanf in C Program

Decision Control Instruction In C: IF


[youtube https://www.youtube.com/watch?v=ih-gHCBoQ0U]

YouTube Link: https://www.youtube.com/watch?v=ih-gHCBoQ0U [Watch the Video In Full Screen.]


For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Removing Documents: MongoDB

Lets learn how to remove documents from the collection using remove() and drop() methods.

remove drop mongodb

test database, names collection

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2
}
{
        "_id" : ObjectId("53c63b26b003603dfdcf8c52"),
        "Company" : "Xiaomi",
        "Product" : "Mi3",
        "No" : 3
}
{
        "_id" : ObjectId("53c63bd1b003603dfdcf8c53"),
        "Product" : "Smart Watch",
        "No" : 4,
        "Company" : "Sony"
}

We have 4 documents in “names” collection.

remove() method, with simple condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
> db.names.remove({"No": 4});
WriteResult({ "nRemoved" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c63b26b003603dfdcf8c52"),
        "Company" : "Xiaomi",
        "Product" : "Mi3",
        "No" : 3,
        "IT" : "true"
}

Here the document with “No: 4” was removed from the collection.

Removing Documents: MongoDB


[youtube https://www.youtube.com/watch?v=so0_5Tdb_bQ]

YouTube Link: https://www.youtube.com/watch?v=so0_5Tdb_bQ [Watch the Video In Full Screen.]



remove() method, with comparison condition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
> db.names.remove({"No": {$gt: 2}});
WriteResult({ "nRemoved" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
{
        "_id" : ObjectId("53c639392eea8062e084cb58"),
        "Company" : "Apple",
        "Product" : "Mac",
        "No" : 2,
        "IT" : "true"
}

Here whatever documents which has “No” greater than 2 got removed.

remove() method to remove all documents from the collection

1
2
3
4
5
6
7
8
9
10
11
> db.names.remove({});
WriteResult({ "nRemoved" : 2 })
 
> db.names.find().pretty()
 
> show collections
names
system.indexes
 
> db.system.indexes.find().pretty()
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "test.names" }

If we pass empty argument to remove() method, it matches with all the documents present in the collection, hence removes all the documents one-by-one.

But it doesn’t remove the contents/documents/index present in “system.indexes” collection.

drop() method

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
> db.names.find()
 
> db.names.insert({"Company": "Apple", "Product": "iPhone", "No": 1});
WriteResult({ "nInserted" : 1 })
 
> db.names.insert({"Company": "Google", "Product": "Nexus", "No": 2});
WriteResult({ "nInserted" : 1 })
 
> db.names.find().pretty()
{
        "_id" : ObjectId("53c6c5d95879b1ff1f0b8356"),
        "Company" : "Apple",
        "Product" : "iPhone",
        "No" : 1
}
{
        "_id" : ObjectId("53c6392a2eea8062e084cb57"),
        "Company" : "Google",
        "Product" : "Nexus",
        "No" : 1,
        "IT" : "true"
}
 
> db.names.drop();
true
 
> db.names.find().pretty()
 
> db.system.indexes.find().pretty()

Since “names” collection was empty, we inserted 2 documents into it. Now we applied drop() method on the collection, which drops all the document present in the collections at once. It also removes the document/index/content present inside “system.indexes” collection.

Note: If you want to remove/drop all the documents present inside the collection, make use of drop() method, as it removes all the documents at once, its more efficient than remove({}) method which removes documents one by one. Use remove() method, when you want to remove one or a set of documents from the collection.