Sunday, 15 May 2016

Loop Type & Description

while loop in C

while loop in C programming repeatedly executes a target statement as long as a given condition is true.

Syntax

The syntax of a while loop in C programming language is −
while(condition) {
   statement(s);
}
Here, statement(s) may be a single statement or a block of statements. Thecondition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, the program control passes to the line immediately following the loop.

Flow Diagram

while loop in C
Here, the key point to note is that a while loop might not execute at all. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 10;

   /* while loop execution */
   while( a < 20 ) {
      printf("value of a: %d\n", a);
      a++;
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

for loop in C

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

The syntax of a for loop in C programming language is −
for ( init; condition; increment ) {
   statement(s);
}
Here is the flow of control in a 'for' loop −
  • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
  • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and the flow of control jumps to the next statement just after the 'for' loop.
  • After the body of the 'for' loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.
  • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the 'for' loop terminates.

Flow Diagram

for loop in C

Example

#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;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

do...while loop in C

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop in C programming checks its condition at the bottom of the loop.
do...while loop is similar to a while loop, except the fact that it is guaranteed to execute at least one time.

Syntax

The syntax of a do...while loop in C programming language is −
do {
   statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop executes once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop executes again. This process repeats until the given condition becomes false.

Flow Diagram

do...while loop in C

Example

#include <stdio.h>
 
int main () {

   /* local variable definition */
   int a = 10;

   /* do loop execution */
   do {
      printf("value of a: %d\n", a);
      a = a + 1;
   }while( a < 20 );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

nested loops in C

C programming allows to use one loop inside another loop. The following section shows a few examples to illustrate the concept.

Syntax

The syntax for a nested for loop statement in C is as follows −
for ( init; condition; increment ) {

   for ( init; condition; increment ) {
      statement(s);
   }
 
   statement(s);
}
The syntax for a nested while loop statement in C programming language is as follows −
while(condition) {

   while(condition) {
      statement(s);
   }
 
   statement(s);
}
The syntax for a nested do...while loop statement in C programming language is as follows −
do {

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

}while( condition );
A final note on loop nesting is that you can put any type of loop inside any other type of loop. For example, a 'for' loop can be inside a 'while' loop or vice versa.

Example

The following program uses a nested for loop to find the prime numbers from 2 to 100 −
#include <stdio.h>
 
int main () {

   /* local variable definition */
   int i, j;
   
   for(i = 2; i<100; i++) {
   
      for(j = 2; j <= (i/j); j++) 
         if(!(i%j)) break; // if factor found, not prime
         if(j > (i/j)) printf("%d is prime\n", i);
   }
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

C - Decision Making & Lopping

Decision making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.
Show below is the general form of a typical decision making structure found in most of the programming languages −
Decision making statements in C
C programming language assumes any non-zero and non-null values as true, and if it is either zero or null, then it is assumed as false value.
C programming language provides the following types of decision making statements.
S.N.Statement & Description
1if statement
An if statement consists of a boolean expression followed by one or more statements.
2if...else statement
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
3nested if statements
You can use one if or else if statement inside another if or else ifstatement(s).
4switch statement
switch statement allows a variable to be tested for equality against a list of values.
5nested switch statements
You can use one switch statement inside another switchstatement(s).

The ? : Operator

We have covered conditional operator ? : in the previous chapter which can be used to replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined like this −
  • Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire ? expression.
  • If Exp1 is false, then Exp3 is evaluated and its value becomes the value of the expression.

    C-Loops

You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages −
Loop Architecture
C programming language provides the following types of loops to handle looping requirements.
S.N.Loop Type & Description
1while loop
Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body.
2for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3do...while loop
It is more like a while statement, except that it tests the condition at the end of the loop body.
4nested loops
You can use one or more loops inside any other while, for, or do..while loop.

Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.
C supports the following control statements.
S.N.Control Statement & Description
1break statement
Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
2continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
3goto statement
Transfers control to the labeled statement.
To know about the statements & loops click on that .

C - Flow Control Statements


C provides two sytles of flow control:
  • Branching
  • Looping
Branching is deciding what actions to take and looping is deciding how many times to take a certain action.

Branching:

Branching is so called because the program chooses to follow one branch or another.

if statement

This is the most simple form of the branching statements.
It takes an expression in parenthesis and an statement or block of statements. if the expression is true then the statement or block of statements gets executed otherwise these statements are skipped.
NOTE: Expression will be assumed to be true if its evaulated values is non-zero.
if statements take the following form:
if (expression)
  statement;

or

if (expression)
  {
    Block of statements;
  }

or

if (expression)
  {
    Block of statements;
  }
else
  {
    Block of statements;
  }

or

if (expression)
  {
    Block of statements;
  }
else if(expression)
  {
    Block of statements;
  }
else
  {
    Block of statements;
  }

? : Operator

The ? : operator is just like an if ... else statement except that because it is an operator you can use it within expressions.
? : is a ternary operator in that it takes three values, this is the only ternary operator C has.
? : takes the following form:
if condition is true ? then X return value : otherwise Y value;

switch statement:

The switch statement is much like a nested if .. else statement. Its mostly a matter of preference which you use, switch statement can be slightly more efficient and easier to read.
switch( expression )
     {
        case constant-expression1: statements1;
        [case constant-expression2: statements2;]    
        [case constant-expression3: statements3;]
        [default : statements4;]
     }

Using break keyword:

If a condition is met in switch case then execution continues on into the next case clause also if it is not explicitly specified that the execution should exit the switch statement. This is achieved by using break keyword.
Try out given example Show Example

What is default condition:

If none of the listed conditions is met then default condition executed.
Try out given example Show Example

Looping

Loops provide a way to repeat commands and control how many times they are repeated. C provides a number of looping way.

while loop

The most basic loop in C is the while loop.A while statement is like a repeating if statement. Like an If statement, if the test condition is true: the statments get executed. The difference is that after the statements have been executed, the test condition is checked again. If it is still true the statements get executed again.This cycle repeats until the test condition evaluates to false.
Basic syntax of while loop is as follows:
while ( expression )
{
   Single statement 
   or
   Block of statements;
}

for loop

for loop is similar to while, it's just written differently. for statements are often used to proccess lists such a range of numbers:
Basic syntax of for loop is as follows:
for( expression1; expression2; expression3)
{
   Single statement
   or
   Block of statements;
}

In the above syntax:
  • expression1 - Initialisese variables.
  • expression2 - Condtional expression, as long as this condition is true, loop will keep executing.
  • expression3 - expression3 is the modifier which may be simple increment of a variable.

do...while loop

do ... while is just like a while loop except that the test condition is checked at the end of the loop rather than the start. This has the effect that the content of the loop are always executed at least once.
Basic syntax of do...while loop is as follows:
do
{
   Single statement
   or
   Block of statements;
}while(expression);

break and continue statements

C provides two commands to control how we loop:
  • break -- exit form loop or switch.
  • continue -- skip 1 iteration of loop.
You already have seen example of using break statement. Here is an example showing usage ofcontinue statement.
#include 

main()
{
    int i;
    int j = 10;

    for( i = 0; i <= j; i ++ )
    {
       if( i == 5 )
       {
          continue;
       }
       printf("Hello %d\n", i );
    }
}
This will produce following output:
Hello 0
Hello 1
Hello 2
Hello 3
Hello 4
Hello 6
Hello 7
Hello 8
Hello 9
Hello 10

For easily understand goto the link and watch the video online or download it :




Friday, 22 April 2016

Get E-book of Gotfried on C programming

Click on the link
(Clicking on the link you will reach my another site & from there you can easily download E-book of Gotfried on C programming)

https://gopalbasak.wordpress.com/2016/04/22/get-e-book-of-gotfried-on-c-programming/

Get E-book of Dennis Ritchhe on C Programming

Click on the link (Clicking on link you will reach another site of mine & form there, you can directly download E-book of Dennis Ritchhe on C Programming).

Thursday, 7 April 2016

File Handling or File Management in C

File Handling in C Language

file represents a sequence of bytes on the disk where a group of related data is stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following are the functions,
Functiondescription
fopen()create a new file or open a existing file
fclose()closes a file
getc()reads a character from a file
putc()writes a character to a file
fscanf()reads a set of data from a file
fprintf()writes a set of data to a file
getw()reads a integer from a file
putw()writes a integer to a file
fseek()set the position to desire point
ftell()gives current position in the file
rewind()set the position to the begining point

Opening a File or Creating a File

The fopen() function is used to create a new file or to open an existing file.
General Syntax :
*fp = FILE *fopen(const char *filename, const char *mode);
Here filename is the name of the file to be opened and mode specifies the purpose of opening the file. Mode can be of following types,
*fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or created) file.
modedescription
ropens a text file in reading mode
wopens or create a text file in writing mode.
aopens a text file in append mode
r+opens a text file in both reading and writing mode
w+opens a text file in both reading and writing mode
a+opens a text file in both reading and writing mode
rbopens a binary file in reading mode
wbopens or create a binary file in writing mode
abopens a binary file in append mode
rb+opens a binary file in both reading and writing mode
wb+opens a binary file in both reading and writing mode
ab+opens a binary file in both reading and writing mode

Closing a File

The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp );
Here fclose() function closes the file and returns zero on success, or EOF if there is an error in closing the file. This EOF is a constant defined in the header file stdio.h.

Input/Output operation on File

In the above table we have discussed about various file I/O functions to perform reading and writing on file.getc() and putc() are simplest functions used to read and write individual characters to a file.
#include<stdio.h>
#include<conio.h>
main()
{
 FILE *fp;
 char ch;
 fp = fopen("one.txt", "w");
 printf("Enter data");
 while( (ch = getchar()) != EOF) {
    putc(ch,fp);
 }
 fclose(fp);
 fp = fopen("one.txt", "r");
 while( (ch = getc()) != EOF)
    printf("%c",ch);
 fclose(fp);
}

Reading and Writing from File using fprintf() and fscanf()

#include<stdio.h>
#include<conio.h>
struct emp
{
   char name[10];
   int age;
};

void main()
{
   struct emp e;
   FILE *p,*q;
   p = fopen("one.txt", "a");
   q = fopen("one.txt", "r");
   printf("Enter Name and Age");
   scanf("%s %d", e.name, &e.age);
   fprintf(p,"%s %d", e.name, e.age);
   fclose(p);
   do
   {
      fscanf(q,"%s %d", e.name, e.age);
      printf("%s %d", e.name, e.age);
   }
   while( !feof(q) );
   getch();
}
In this program, we have create two FILE pointers and both are refering to the same file but in different modes. fprintf() function directly writes into the file, while fscanf() reads from the file, which can then be printed on console usinf standard printf() function.

Difference between Append and Write Mode

Write (w) mode and Append (a) mode, while opening a file are almost the same. Both are used to write in a file. In both the modes, new file is created if it doesn't exists already.
The only difference they have is, when you open a file in the write mode, the file is reset, resulting in deletion of any data already present in the file. While in append mode this will not happen. Append mode is used to append or add data to the existing data of file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at the end of the present data in the file.

Reading and Writing in a Binary File

A Binary file is similar to the text file, but it contains only large numerical data. The Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements, 
   number_of_elements, pointer-to-file);
fread() is also used in the same way, with the same arguments like fwrite() function. Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";   
FILE *bfp= fopen("test.txt", "wb");   
if (bfp) {     
   fwrite(mytext, sizeof(char), strlen(mytext), bfp) ;     
   fclose(bfp) ;   
} 

fseek(), ftell() and rewind() functions

  • fseek() - It is used to move the reading control to different positions using fseek function.
  • ftell() - It tells the byte location of current position of cursor in file pointer.
  • rewind() - It moves the control to beginning of the file.

Some File Handling Program Examples

  • Create a File and Store Information in it
  • List all the Files present in a Directory
  • Finding Size of a File
  • Copy Content of one File into Another File
  • Reverse the Content of File and Print it

    Error Handling

    C language does not provide direct support for error handling. However few method and variable defined inerror.h header file can be used to point out error using return value of the function call. In C language, a function return -1 or NULL value in case of any error and a global variable errno is set with the error code. So the return value can be used to check error while programming.
    C language uses the following functions to represent error
    • perror() return string pass to it along with the textual represention of current errno value.
    • strerror() is defined in string.h library. This method returns a pointer to the string representation of the current errno value.

    Example

    #include <stdio.h>       
    #include <errno.h>       
    #include <stdlib.h>       
    #include <string.h>       
     
    extern int errno;
     
    main( )
    {
      char *ptr = malloc( 1000000000UL);  //requesting to allocate 1gb memory space  
      if ( ptr == NULL )        //if memory not available, it will return null  
      {  
         puts("malloc failed");
         puts(strerror(errno));
         exit(EXIT_FAILURE); //exit status failure       
      }
      else
      {
         free( ptr);
         exit(EXIT_SUCCESS); //exit status Success       
      }
    }
    
    Here exit function is used to indicate exit status. Its always a good practice to exit a program with a exit status.EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successfull exit. It is defined as 0. EXIT_Failureis used in case of any failure in the program. It is defined as -1.

    Dynamic Memory Allocation

    The process of allocating memory at runtime is known as dynamic memory allocation. Library routines known as "memory management functions" are used for allocating and freeing memory during execution of a program. These functions are defined in stdlib.h.
    FunctionDescription
    malloc()allocates requested size of bytes and returns a void pointer pointing to the first byte of the allocated space
    calloc()allocates space for an array of elements, initialize them to zero and then return a void pointer to the memory
    freereleases previously allocated memory
    reallocmodify the size of previously allocated space

    Memory Allocation Process

    Global variables, static variables and program instructions get their memory in permanent storage area whereas local variables are stored in area called Stack. The memory space between these two region is known as Heap area. This region is used for dynamic memory allocation during execution of the program. The size of heap keep changing.
    dynamic memory allocation in c

    Allocating block of Memory

    malloc() function is used for allocating block of memory at runtime. This function reserves a block of memory of given size and returns a pointer of type void. This means that we can assign it to any type of pointer using typecasting. If it fails to locate enough space it returns a NULL pointer.
    Example using malloc() :
    int *x;
    x = (int*)malloc(50 * sizeof(int));    //memory space allocated to variable x
    free(x);                    //releases the memory allocated to variable x
    
    calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is normally used for allocating memory to derived data types such as arrays and structures. If it fails to locate enough space it returns a NULL pointer.
    Example using calloc() :
    struct employee
    {
     char *name;
     int salary;
    };
    typedef struct employee emp;
    emp *e1;
    e1 = (emp*)calloc(30,sizeof(emp));
    
    realloc() changes memory size that is already allocated to a variable.
    Example using realloc() :
    int *x;
    x=(int*)malloc(50 * sizeof(int));
    x=(int*)realloc(x,100); //allocated a new memory to variable x
    

    Diffrence between malloc() and calloc()

    calloc()malloc()
    calloc() initializes the allocated memory with 0 value.malloc() initializes the allocated memory with garbage values.
    Number of arguments is 2Number of argument is 1
    Syntax :
    (cast_type *)calloc(blocks , size_of_block);
    Syntax :
    (cast_type *)malloc(Size_in_bytes);

    Command Line Argument

    Command line argument is a parameter supplied to the program when it is invoked. Command line argument is an important concept in C programming. It is mostly used when you need to control your program from outside. command line arguments are passed to main() method.
    Syntax :
    int main( int argc, char *argv[])
    
    Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed to the program.

    Example for Command Line Argument

    #include <stdio.h>
    #include <conio.h>
    int main( int argc, char *argv[] )
    {
      int i;
      if( argc >= 2 )
       {
        printf("The arguments supplied are:\n");
        for(i=1;i< argc;i++)
        {
         printf("%s\t",argv[i]);
        }
       }
       else
       {
         printf("argument list is empty.\n");
       }
     getch();
     return 0;
    }
    
    Remember that argv[0] holds the name of the program and argv[1] points to the first command line argument and argv[n] gives the last argument. If no argument is supplied, argc will be one.

Recent Post

C videos in Hindi language

Hello friends , in the following links you will get whole C Programming videos in Hindi Language (availability is not guaranteed & th...

Popular Posts

visit counter