Index-1              Index-2              Home Page
Showing posts with label for. Show all posts
Showing posts with label for. Show all posts

Loops in C

How to use Loops in C

In any programming language including C, loops are used to execute a set of statements repeatedly until a particular condition is satisfied.

How it Works

The below diagram depicts a loop execution,
loopflow diagram in C
As per the above diagram, if the Test Condition is true, then the loop is executed, and if it is false then the execution breaks out of the loop. After the loop is successfully executed the execution again starts from the Loop entry and again checks for the Test condition, and this keeps on repeating.
The sequence of statements to be executed is kept inside the curly braces { } known as the Loop body. After every execution of the loop body, condition is verified, and if it is found to be true the loop body is executed again. When the condition check returns false, the loop body is not executed, and execution breaks out of the loop.

Types of Loop

There are 3 types of Loop in C language, namely:
  1. while loop
  2. for loop
  3. do while loop

while loop

while loop can be addressed as an entry control loop. It is completed in 3 steps.
  • Variable initialization.(e.g int x = 0;)
  • condition(e.g while(x <= 10))
  • Variable increment or decrement ( x++ or x-- or x = x + 2 )
Syntax :
variable initialization;
while(condition)
{
    statements;
    variable increment or decrement; 
}

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )
{
    int x;
    x = 1;
    while(x <= 10)
    {
        printf("%d\t", x);
        /* below statement means, do x = x+1, increment x by 1*/
        x++;
    }
}
1 2 3 4 5 6 7 8 9 10

for loop

for loop is used to execute a set of statements repeatedly until a particular condition is satisfied. We can say it is an open ended loop.. General format is,
for(initialization; condition; increment/decrement)
{
    statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the condition. In this loop we can have more than one initialization or increment/decrement, separated using comma operator. But it can have only one condition.
The for loop is executed as follows:
  1. It first evaluates the initialization code.
  2. Then it checks the condition expression.
  3. If it is true, it executes the for-loop body.
  4. Then it evaluate the increment/decrement condition and again follows from step 2.
  5. When the condition expression becomes false, it exits the loop.

Example: Program to print first 10 natural numbers

#include<stdio.h>

void main( )
{
    int x;
    for(x = 1; x <= 10; x++)
    {
        printf("%d\t", x);
    }
}
1 2 3 4 5 6 7 8 9 10

Nested for loop

We can also have nested for loops, i.e one for loop inside another for loop. Basic syntax is,
for(initialization; condition; increment/decrement)
{
    for(initialization; condition; increment/decrement)
    {
        statement ;
    }
}

Example: Program to print half Pyramid of numbers

#include<stdio.h>

void main( )
{
    int i, j;
    /* first for loop */
    for(i = 1; i < 5; i++)
    {
        printf("\n");
        /* second for loop inside the first */
        for(j = i; j > 0; j--)
        {
            printf("%d", j);
        }
    }
}
1 21 321 4321 54321

do while loop

In some situations it is necessary to execute body of the loop before testing the condition. Such situations can be handled with the help of do-while loop. do statement evaluates the body of the loop first and at the end, the condition is checked using while statement. It means that the body of the loop will be executed at least once, even though the starting condition inside while is initialized to be false. General syntax is,
do
{
    .....
    .....
}
while(condition)

Example: Program to print first 10 multiples of 5.

#include<stdio.h>

void main()
{
    int a, i;
    a = 5;
    i = 1;
    do
    {
        printf("%d\t", a*i);
        i++;
    } 
    while(i <= 10);
}
5 10 15 20 25 30 35 40 45 50

Jumping Out of Loops

Sometimes, while executing a loop, it becomes necessary to skip a part of the loop or to leave the loop as soon as certain condition becomes true. This is known as jumping out of loop.

1) break statement

When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop.
break statement in loops in c language

2) continue statement

It causes the control to go directly to the test-condition and then continue the loop process. On encountering continue, cursor leave the current cycle of loop, and starts with the next cycle.
continue statement in loops in c language

C Programming Questions and Answers

// a) If a 5 digit number is input through the keyboard, write a program to print the sum.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       sum += remainder;
       number = number/10;
   }
   if(counter == 5){
       printf("Sum of digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 5 digit number.\n");
   }
   return 0;
}

// b) If a four digit number is input through the keyboard, write a program to find the sum of first and last digit.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       if(counter == 1 || counter == 4){
           sum += remainder;
       }
       number = number/10;
   }
   if(counter == 4){
       printf("Sum of digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 4 digit number.\n");
   }
   return 0;
}

// e) Write a program to show the advantage of using function in a program.

#include <stdio.h>

// a function return total of an array with given size
int sum(int *arr, int size){
    int total = 0;
    for(int i = 0; i < size; i++){
        total += arr[i];
    }
    return total;
}

int main(){
    int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int bellow_fifth = 0, all_sum = 0;
    bellow_fifth = sum(number_of_array, 5);
    all_sum = sum(number_of_array, 10);

    printf ("Total of bellow fifth %d\n", bellow_fifth);
    printf ("All total in an array %d\n", all_sum);

    return 0;
}


// Write a program for the addition of all values from an Array.
#include <stdio.h>

// a function return total of an array with given size
int sum(int *arr, int size){
    int total = 0;
    for(int i = 0; i < size; i++){
        total += arr[i];
    }
    return total;
}

int main(){
    int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int all_sum = 0;
    all_sum = sum(number_of_array, 10);

    printf("All total in an array %d\n", all_sum);

    return 0;
}

// a) If a 10 digit number is input , write a program to print the sum of all odd digits.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       if(remainder%2 != 0){
           sum += remainder;
       }
       number = number/10;
   }
   if(counter == 10){
       printf("Sum of odd digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 10 digit number.\n");
   }
   return 0;
}

// b) If a four digit number is input through the keyboard, write a program to find the sum of first and last digit.

#include <stdio.h>

int main(){
   int number, sum = 0, remainder = 0, counter = 0;
   printf("Enter an integer\n");
   scanf("%d", &number);
   while (number != 0){
       remainder = number%10;
       counter += 1;
       if(counter == 1 || counter == 4){
           sum += remainder;
       }
       number = number/10;
   }
   if(counter == 4){
       printf("Sum of digits of %d.\n", sum);
   }
   else{
       printf("\nIt was not 4 digit number.\n");
   }
   return 0;
}

// e) Write a program to check a prime number between 1 and 100.

#include <stdio.h>
int main(){
    for(int i = 1; i < 101; i++){
        int flag = 1;
        for(int m = 2; m < i; m++){
            if(i%m == 0){
                flag = 0;
                break;
            }
        }
        if(flag == 1){
            printf("This is a prime number %d\n", i);
        }
    }
    return 0;
}


// f) Write a program for the addition of all even values from an integer Array.

#include <stdio.h>

// a function return total of even from an array
int sum(int *arr, int size){
    int total = 0;
    for(int i = 0; i < size; i++){
        if(arr[i]%2 == 0){
            total += arr[i];
        }
    }
    return total;
}

int main(){
    int number_of_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    int all_sum = 0;
    all_sum = sum(number_of_array, 10);

    printf("All total in an array %d\n", all_sum);

    return 0;
}

Do-While :

a do while loop is a control flow statement that executes a block of code at least once, and then repeatedly executes the block, or not, depending on a given Boolean condition at the end of the block.

Syntax:

do{
statement(s);
}
while (Boolean condition)

Example:
do{
run();
}
while(edge)


While loop:

 a while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition.
Syntax:
while( Boolean condition) {
   statement(s);
}

Example:
while (edge)
{
run();
}


For loop:

for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

Syntax:

for ( init; condition; increment ) {
   statement(s);
}

#include <stdio.h>
 
int main () {
 
   int a;
         
   /* for loop execution */
   for( a = 10; a < 20; a = a + 1 ){
      printf("value of a: %d\n", a);
   }
 
   return 0;
}



Pointer and Arrays

When an array is declared, compiler allocates sufficient amount of memory to contain all the
elements of the array. Base address i.e address of the first element of the array is also
allocated by the compiler. Suppose we declare an array arr,

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

Assuming that the base address of arr is 1000 and each integer requires two bytes, the five
elements will be stored as follows:


Here variable arr will give the base address, which is a constant pointer pointing to the first
element of the array, arr[0]. Hence arr contains the address of arr[0] i.e 1000. In short, arr has two purpose - it is the name of the array and it acts as a pointer pointing
towards the first element in the array. arr is equal to &amp;arr[0] by default

We can also declare a pointer of type int to point to the array arr.
int *p;
p = arr;

// or,

p = &amp;arr[0]; //both the statements are equivalent.

Now we can access every element of the array arrusing p++ to move from one element to
another


Switch :

switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax

The syntax for a switch statement in C programming language is as follows −
switch(expression) {
 
   case constant-expression  :
      statement(s);
      break; /* optional */
         
   case constant-expression  :
      statement(s);
      break; /* optional */
  
   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

#include <stdio.h>
 
int main () {
 
   /* local variable definition */
   char grade = 'B';
 
   switch(grade) {
      case 'A' :
         printf("Excellent!\n" );
         break;
      case 'B' :
      case 'C' :
         printf("Well done\n" );
         break;
      case 'D' :
         printf("You passed\n" );
         break;
      case 'F' :
         printf("Better try again\n" );
         break;
      default :
         printf("Invalid grade\n" );
   }
   
   printf("Your grade is  %c\n", grade );
 
   return 0;
}
 

Go-to:

goto statement in C programming provides an unconditional jump from the 'goto' to a labeled statement in the same function

Syntax

The syntax for a goto statement in C is as follows −
goto label;
..
.
label: statement;

#include <stdio.h>
 
int main () {
 
   /* local variable definition */
   int a = 10;
 
   /* do loop execution */
   LOOP:do {
   
      if( a == 15) {
         /* skip the iteration */
         a = a + 1;
         goto LOOP;
      }
                 
      printf("value of a: %d\n", a);
      a++;
 
   }while( a < 20 );
 
   return 0;
}



C File I/O

A file represents a sequence of bytes, regardless of it being a text file or a binary file. C programming language provides access on high level functions as well as low level (OS level) calls to handle file on your storage devices. This chapter will take you through the important calls for file management.

Opening Files

You can use the fopen( ) function to create a new file or to open an existing file. This call will initialize an object of the type FILE, which contains all the information necessary to control the stream. The prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file, and access mode can have one of the following values −
Sr.No.
Mode & Description
1
r
Opens an existing text file for reading purpose.
2
w
Opens a text file for writing. If it does not exist, then a new file is created. Here your program will start writing content from the beginning of the file.
3
a
Opens a text file for writing in appending mode. If it does not exist, then a new file is created. Here your program will start appending content in the existing file content.
4
r+
Opens a text file for both reading and writing.
5
w+
Opens a text file for both reading and writing. It first truncates the file to zero length if it exists, otherwise creates a file if it does not exist.
6
a+
Opens a text file for both reading and writing. It creates the file if it does not exist. The reading will start from the beginning but writing can only be appended.
If you are going to handle binary files, then you will use following access modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

 

Closing a File

To close a file, use the fclose( ) function. The prototype of this function is −
int fclose( FILE *fp );
The fclose(-) function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
There are various functions provided by C standard library to read and write a file, character by character, or in the form of a fixed length string.

 

Writing a File

Following is the simplest function to write individual characters to a stream −
int fputc( int c, FILE *fp );
The function fputc() writes the character value of the argument c to the output stream referenced by fp. It returns the written character written on success otherwise EOF if there is an error. You can use the following functions to write a null-terminated string to a stream −
int fputs( const char *s, FILE *fp );
The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...) function as well to write a string into a file. Try the following example.
Make sure you have /tmp directory available. If it is not, then before proceeding, you must create this directory on your machine.
#include <stdio.h>
 
main() {
   FILE *fp;
 
   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}
When the above code is compiled and executed, it creates a new file test.txt in /tmp directory and writes two lines using two different functions. Let us read this file in the next section.

 

Reading a File

Given below is the simplest function to read a single character from a file −
int fgetc( FILE * fp );
The fgetc() function reads a character from the input file referenced by fp. The return value is the character read, or in case of any error, it returns EOF. The following function allows to read a string from a stream −
char *fgets( char *buf, int n, FILE *fp );
The functions fgets() reads up to n-1 characters from the input stream referenced by fp. It copies the read string into the buffer buf, appending a nullcharacter to terminate the string.
If this function encounters a newline character '\n' or the end of the file EOF before they have read the maximum number of characters, then it returns only the characters read up to that point including the new line character. You can also use int fscanf(FILE *fp, const char *format, ...) function to read strings from a file, but it stops reading after encountering the first space character.
#include <stdio.h>
 
main() {
 
   FILE *fp;
   char buff[255];
 
   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1 : %s\n", buff );
 
   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);
 
}
When the above code is compiled and executed, it reads the file created in the previous section and produces the following result −
1 : This
2: is testing for fprintf...
 
3: This is testing for fputs...