C Language Structure Programming Class 10 Computer Science

C Language Structure Programming Class 10 Computer Science

C Language Structure Programming Class 10 Computer Science
C-programming Language


Introduction
Computer cannot do anything by itself. It requires proper instructions to do any sort of tasks. A set of these instructions is called a program. A program is created to solve a particular task and a group of these programs is called software. We have already known that there are different types of programming language to write programs such as High-Level Language, Assembly Language and Low Level Language. There are several approaches of programming which include Structured, Unstructured, Procedural, Modular, Object Oriented programming etc.

Structured Programming
Structured programming (sometimes known as modular programming) follows a top-down approach, in which programmer separates the overall program structure into different subsections. A defined function or set of similar functions is coded in a separate module or sub module, which means that code can be loaded into memory more efficiently and that modules can be reused in other programs. After a module has been tested individually, it is then integrated with other modules into the overall program structure. Some examples of structured programming languages are Pascal, C, PLII, Ada etc.

Features of Structured Programming:
1.         Top-Down Design
The top-down approach is the process of breaking down the complex problem into simpler ones. In programming also, top-down approach is the stepwise process of breaking down large and complex program into several simpler modules to organize and code in an efficient way.


2.         Single–Entry, Single–Exit Concept
One of the main features of structured programming is that its modules have only one entry and exit points. It does not support Go To statement. This feature makes easier to understand the flow of control of the program.

Advantages of Structured Programming
l   Reduced Complexity
l   Easy to Code
l   Take less time
l   Easy to debug
l   Reuse of modules
l   Flow of control is clear

C        Programming
Introduction
C Language is a high-level structured programming language. Normally this language is used to develop system software. It is one of the most popular general-purpose programming languages. It is also called as middle level language as it has the features of both high level and low level programming language. The C programming language was developed by Dennis Ritchie at Bell Labs during the early 1970s. Quite unpredictably it derived from a computer language named B and from an earlier language BCPL. Initially designed as a system programming language under UNIX, it expanded to have wide usage on many different systems. C++ language is an expanded version of C.

Types of C language
There are two types of C language.
·            Common C
·            ANSI C

Common C
The C language developed in the Bell Telephone Laboratories is known as Common C. It is also called Bell Labs C.
 
ANSI C
Since C language is powerful and flexible programming language, programmers use C language to develop system software like operating system, device driver programs, utility programs and variety of application software. Due to the powerful and flexible capabilities different organizations began utilizing their own version of C, which made problems in implementations of C language. So in 1983, the American National Standards Institute (ANSI) formed committee to establish a standard definition of C, which became ANSI C. ANSI C incorporates a few improvements over the old common C. 
 
Features of C Language
There are certain features of C language. They are:

a. Structured
C is a Structured Programming Language. Like QBASIC, we break down a program in several small modules in C. The module is called function. It makes the programmer easier to manage and debug the code

b. Middle Level Language
It combines elements of a high level language with some features of assembler. As a middle level language, C language manipulates memory address.

c. Fast
It is many time faster than BASIC. Due to the variety of data type and a list of powerful operators, programs written in C are fast and efficient.

d. Case Sensitive
C is a case-sensitive programming language. It understands the capital alphabets and small alphabets as different values. For example, “Computer” and “COMPUTER” are different values for C Language.

e. Extendable
C is also an Extendable Programming Language.  We can develop functions in C Language and can be added in library for the purpose of using in other programs.

Limitation of C Language
C has some limitation though it is a powerful programming language. Some of its limitation are:
a.          No Run Time Type Checking
b.         Does not support object oriented programming
c.          C doesn't have the feature of reusability of source code extensively
d.         C language has only 32 Keywords
e.          C provides no data protection
f.           C compilers can only identify errors and are incapable of handling exceptions (run-time errors).

Advantages of C language
a.         Programs are easy to read.
b.         Programs are easy to maintain.
c.         Programs are easy to port across different computer platforms.
d.         Programs written in C can be reused.
 
Application of C Language
C was initially used for system development work, in particular, the programs that make-up the operating system. It is mainly because it produces code that runs nearly as fast as code written in assembly language. But C language is not limited to develop system software.
a.          Operating System
b.         Language Compilers/Interface
c.          Assemblers
d.         Text Editors
e.          Print Spoolers
f.           Network Devices
g.         Modern Programs
h.         DBMS
i.           Utilities etc.

Source Code and Object Code
Computer program written in a high level language has to be converted into the binary format. Compilers or interpreters transfer such programs into machine codes. The machine-readable code which is obtained after the translation is called binary code or object code. The instructions written in C language is known as source code.

C language and QBASIC
Both the C and the QBASIC are the high level programming language. But they have some similarities and differences.

Similarities in C and QBASIC
  1. They can be used to developed structured programs.
  2. They support local and global variables.
  3. They support procedures.

Differences between C and QBASIC   

QBASIC

C language

It is high level language

It is middle level language

It supports both sub and function procedure

It supports only function procedure

It is basically used for developing application software

It can be used to develop system as well as application software

It supports limited data types

It supports wide range of data types


 
Basic Elements of C Language
In every programming language, there are basic elements of the language like character set, variables, constants, operators, keywords etc. Just like QBASIC, C language also has its own basic elements.

C Character set
Character Set is a group of valid characters and symbols supported by a programming language.
A character denotes any alphabet, digit or special symbol used to represent information. The below table shows the valid alphabets, numbers and special symbols supported by C language.
Alphabets
Uppercase : A,B,C………………………….. X, Y, Z
Lowercase : a,b,c……………………………. x,y,z
Digits: 
0, 1, 2, 3, 4 …………. 9
Special characters
 

,

< 

> 

.

_

-

(

)

;

$

:

\

%

[

]

#

?

~

'

&

{

}

"

+

^

!

*

/

|

 



Identifiers
Identifiers are the names given to the entities such as variables, functions, arrays structures and unions.
For example:
int price;
float total;
Here, price and total are called identifiers.
Rules for naming Identifiers:
i)          The Identifier must start with an alphabet or an under score (_).
ii)        Identifier can be made from the combination of alphabets, digits and under score.
iii)      No any C keyword can be used as an Identifier.
iv)      Identifier must be unique and can be used for a single purpose only.

Format Specifier
The format specifier is used during input and output operation. It tells the compiler what type of data is stored in a variable during the input and output operation such as taking data from keyboard and display data on the screen. Some examples are %c, %d, %f, etc.
 

Data type

Format specifier

short int

%hd

unsigned short int

%hu

unsigned int

%u

int

%d

long int

%ld

unsigned long int

%lu

char

%c

float

%f

double

%lf

 
Data Types in C
C Language supports two types of data:
a.          Basic Data Types
b.         Derived Data Types
 

Basic Data Types

Derived Data Types

Int (Integer)

Arrays

Char (Character)

Pointers

Float

Structure

Double

Unions

Void

Enums (Enumerations)

 
 
Basic Data Types of C Language
1.                                 int (Integer)
An Integer is a whole number either positive, negative or zero but no decimal values. For example, 0, -5, 10
Sub-types of Integer
C supports the different types of integer. Different integer types also have different ranges upto which they can store numbers. These ranges may vary from compiler to compiler. Below is list of ranges along with the memory requirement and format specifies on 32-bit gcc compiler.
 

Data Types

Storage Size

Range

Format Specifier

short int

2 Bytes

-32,768 to 32,767

%hd

unsigned short int

2 Bytes

0 to 65,535

%hu

unsigned int

4 Bytes

0 to 4,294,967,295

%u

int

4 Bytes

-2,147,483,648 to 2,147,483,647

%d

long int

4 Bytes

-2,147,483,648 to 2,147,483,647

%ld

unsigned long int

4 Bytes

0 to 4,294,967,295

%lu

 
 
Declaring an integer variable
int a, b;
In the above example, the int keyword is used to declare a and b as integer variables.
unsigned int d;
Likewise, we can declare integer variable in this way as well.
Here, the type of the variable is declared as unsigned int. It takes 4 bytes of memory and can hold the integers between 0 and 4,294,967,295.
2.            float
It accepts Floating point values.

Data Types

Storage Size

Range

Digits of precision

Format Specifier

float

4 Bytes

1.2E-38 to 3.4E+38

6

%f

 
Declaring float type variable float b; b = 1.732; 
3. double
It also accepts the real numbers like float data type but its range is higher than float data type.

Data Types

Storage Size

Range

Digits of precision

Format Specifier

double

8 Bytes

2.3E-308 to 1.7E+308

15

%fd

 
Declaring double type variable double x; x = 67823.34456;
4.         char
It holds only one character at a time.

Data Types

Storage Size

Format Specifier

char

1 Byte

%c

 
Declaring char type variable char m; void void means “nothing” or “null value”. We cannot create any variable of void type. For example, void hello (void)
{
………………….
}
The above function “hello” does not require any parameter and also does not return any value.

C keywords (reserved word)
Keyboard is a set of special words which are already defined for some tasks. C has only a set of 32 keywords, which have their predefined meaning and cannot be used as a variable name. These words are also known as “reserved words”.

auto

double

int

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

continue

for

signed

void

do

if

static

while

default

goto

sizeof

volatile

const

float

short

unsigned

 

Variables in C
A variable is used to hold data within your program. A variable represents a location in your computer's memory. Every variable has two parts, a name and a data type. 

Variable declaration
A variable declaration states the types of the variable, variable name and if necessary initializes the variable to a given value.
For e.g.
int count;
int number_of_students = 30;

Now, let’s look a whole program in C:
 

/* This is my C program */

#include <stdio.h>

 #include <conio.h> void main()

{      int a,b,c;

        printf ("Enter the first number "); 

        scanf("%d",&a);

        printf ("Enter the second number "); 

scanf("%d",&b);    

c=a+b;

        printf("Sum = %d",c);           

getch();

}


 













The above C program asks any two numbers from the keyboard and displays their sum. In this program, three variables a,b and c are used and their types are declared as integer (int). Unlike QBASIC, we need to declare the type and name of the variables in the beginning of the program.

Operators in C
An operator is a symbol that operates on a certain data type and produces the output as the result of the operation. In C, you can combine various operators of the similar categories and perform an operation. The operators used in C are listed below:
1.         Arithmetic operators in C Program 
There are basically four types of arithmetic operations:
  • Addition
  •  Subtraction
  •  Multiply
  •  Division
To perform the above arithmetic operations, C language supports the below arithmetic operators:
List of Arithmetic Operators in C
If A=10 and B=20,

Operator

Description

Example

Result

+ (Plus) - Addition

Adds two operands

A+B

30

- (Minus) – Subtraction

Subtracts second operand from first operand

A-B

-10

* (Asterisk) – Multiplication

Multiply two operands

A*B

200

/ (Slash) – Division

Divides first operand by second operand

B/A

2

% (Percentage Symbol) –

Modulus Division

Provides remainder when first operand is divided by second operand

B%A

0

++ (Plus Plus) – Increment

Operator

Increases the value of operand by 1

A++

11

-- (Minus Minus) –

Decrement Operator

Decreases the value of operand by 1

B--

19

 
 
2.         Relational Operators
Relational operators compare two expressions and return result in term of true (non zero) of false (zero). The following relational operators are used in C language.

Operators

Meaning

Expression

< 

Less than

a<b

 

<=

Less than or equal to

(a+b)<=c

> 

Greater than

(b+c)>(a+5)

>=

Greater than or equal to

(a+b)>=c

= =

Equal to 

b = = a

! =

Not equal to

(c!=3)

 
3.         Logical Operator
A logical operator is used to combine relational expressions and returns the result either in true or false. The logical operators used in C language are listed below:

Operator

Meaning

Expression

&&

Logical AND

(a>b) && (a>c)

||

Logical OR

(a+b>) || (b+c>a)

!

Logical NOT

! (a = = b)

 
4.         Assignment Operator
An assignment operator (=) is used to assign a constant or a value of one variable to another.
Example:
a=5;
b=a;
Note:
You can use the assignment for multiple assignments as a=b=c=10;
In C language you can combine arithmetic operator and the assignment operator together to perform both arithmetic operation and assignment task. Such combined operations are known as Arithmetic Assignment operators. The Arithmetic operators used in C language are listed below:

Operator

Meaning

Example

Expands As

+=

Add then assign

sum+=3

sum=sum+3

-=

Subtract then assign

count- =4

count=count-4

*=

Multiply then assign

factorial*=num

factorial=factorial*num

/=

Divide then assign

num/=10

num=num/10

%=

Get remainder then assign

a%=3

a=a%3

 
C Expression
An expression consists of at least one operand with one or more operators. It is a legal combination of symbols that represents a value.
For example, 
C=A+B
 
C Program
There are four steps of writing program in C. Each step has its own importance and must be completed stepwise.



Step 1:
At first, the program is written in C Compiler editor. It is called source code. This source code can be saved as a program file and its extension is .C. This source code can be edited at any time.

Step 2:
The second step is to compile the source code. During compilation, syntax error is checked and removed from the source code. After compiling, the source code is changed into binary format and creates a new file with the extension .obj. It is called object program which cannot be edited.

Step 3:
The third step is called linking process. In this process, the required libraries are linked to the program. Libraries prepare an appropriate environment to execute the C program.

Step 4:
After the linking process, an executable file is created with the extension .exe. This executable file can be run in any other computer without compiler.

Structure of C Program
Pre-Processor directives Global Declarations main ()
{
                Local declarations
                Program Statements
 
                 Calling user defined for (optional)
}

Example of a C Program

           /* To find the product of any two numbers */         Comments

#include <stdio.h>

#include<conio.h>  Pre-processor directives

void main() {         

int a,b,c;     

       clrscr();

        printf ("Type first number "); 

        scanf ("%d",&a);       

       printf ("Type second number ");

       scanf ("%d",&b);   

       c=a*b;

        printf ("Product = %d",c); 

        getch();

}

 

 

 

 

Note: clrscr() function is similar to CLS statement in QBASIC. It erases the previous contents of the output screen. The clrscr() function is defined in the header file <conio.h>


Parts of a C Program


i)Pre-processor directives

As part of compilation, the C compiler runs a program called the C pre-processor. The preprocessor is able to add and remove code from your source file. One of the major functions of C preprocessor is Tokenizing. The final step of the preprocessor is to link the resulting program with necessary programs and library.

While writing program in C, we need to include different header files in the beginning. In the above program, printf ( ) and scanf ( ) functions are used for output and input operation. These functions are defined in the header file <stdio.h>. So, this header file is included at the beginning of program which contains the code of printf() and scanf() functions. All the code of header files will be added to the program during compilation.


C Header Files

Different library functions are used to do different tasks in C language. For example, we use scanf() function to ask data from keyboard. Each function is defined in a special type of file. These files are called Header File and have extension .h. These header files must be included using #include directive otherwise the compiler doesn’t understand the library function we use and gives an error message. Here is the list of some commonly used Header file and their purposes:

Header

Purpose

Functions Declared

stdio.h

Used for standard input and output (I/O) operations.

printf(), scanf(), getchar(), putchar(), gets(), puts(), getc(), putc(), fopen, fclose(), feof()

conio.h

Contains declaration for console I/O functions.

clrscr(), exit()

ctype.h

Used for character-handling or testing characters.

isupper(), is lower, isalpha()

math.h

Declares mathematical functions and macros.

pow(), squr(), cos(), tan(), sin(), log()

stdlib.h

Used for number conversions, storage allocations.

rand(), srand()

string.h

Used for manipulating strings.

strlen(), strcpy(), strcmp(), strcat(), strlwr(), strupr(), strrev()

 

ii)        Global Directives

In this section of C program, Global variables and User-defined function are declared.

iii)     main () function

C program must start with main() function. This is the entry point of the program.

iv)      { } Parenthesis

In C language, each function is defined inside parenthesis ({ }).

v)        User-defined function

As in QBASIC, we can create different user-defined function as per our requirements.


Library Functions in C

The functions which are declared in header files are known as library functions. When you use a library functions you need to include corresponding header file in the program otherwise compiler generates errors. Some library functions are listed below

 

Output Function in C

Output function is used to show the calculated result or output on the screen. In C language, printf() is one of the output function defined in <stdio.h> header file.

printf() function

In C Language, printf() function is used to print the valued on the screen. It is defined in <stdio.h> header file. So, the header file <stdio.h> must be added to use this function.

Syntax:

printf(“format string”,argument list); format string is the combination of format identifier, escape sequence or string constant.

Escape Sequence

Escape Sequence is a pair of character that is used with printf() function to display non-printing character or a special character on the screen.

Some Examples of Escape Sequence:

\n

-

new line

\t

-

tab

\b

-

backspace

\o

-

null character

\?

-

question mark

\\

-

slash

\'

-

single quote

\”

-

double quote


Format Identifier

We need to include format identifier to tell the data type in the area of format string of printf() function. For example, 

Variable

Format Identifier

char

%c

int

%d

long int

%ld

float

%f

 

String Constant

String constant is a message to be displayed along with the other values stored in variables. It is enclosed within double quotation (" ").


Argument List

It is a list of variables to be used in printf ( ) function.

For example,

#include <stdio.h>

#include <conio.h>

void main()

{

int a=5; b=10;

clrscr();

printf("\n Value of a and b are %d and %d ",a ,b);           

getch();

}

In the above program,

\n prints from a new line

"Value of a and b are" → String Constant  %d → Format Identifier of int data type  a,b → Arugement List (Variables)

The output of the above program:





                                                                     

Note: Each C statement must be terminated by a semicolon(;).


Input Function in C

Input function is used to ask data for processing. In C language, scanf() is one of the input function defined in <stdio.h> header file.

scanf() Function

scanf() is one of the most important functions of C Program. This function is also defined in the header file <stdio.h> and used to ask value from keyboard.

Syntax:

scanf("format string", argument list); format string is the combination of format identifier, escape sequence or string constant.

For Example:

#include <stdio.h>

#include <conio.h>

void main()

{

        int a;

        clrscr();

        printf ("Type an integer ");    

        scanf ("%d", &a);

       printf ("\n The value of a is %d.", a);

       getch();

}

In the above program, scanf ("%d",&a);

%d → Format Identifier of int data type

&a → & – address operator, a – variable 

This function in the above program asks an integer form keyboard and stores in the variable ‘a’.

The output of the above program





getch() function getch() function is another input function of C language. This function is defined in the header file <conio.h>. This function is used to ask any one character from keyboard.

For example,

#include <conio.h>

#include <stdio.h>

void main()

{

        char ch;          

clrscr();      

ch=getch();

     printf("The typed character is %c.",ch);

     getch();

}


Note: You can see the use of getch() function in every example of C program in this book. The purpose of using this function in the sample program is to let the user to read output on the screen. If such type of function is not used, the output screen will be closed immediately after showing the output and returns to the coding window. In the above program, after showing the output by printf() function, getch() asks a character and get chance to see the output until the character is not typed.

 

C program Examples:

1. Program to find the sum of two integer numbers.

#include <stdio.h>

#include<conio.h>

void main() {   

 

    int a, b, sum;

    printf("Enter first number: ");

    scanf("%d", &a);

    printf("Enter second number: ");

    scanf("%d", &b);

 

    // calculating sum

    sum = a+ b;     

   

    printf(“sum of numbers is %d”, sum);

    getch();

}

 

2. Program to Multiply Two Numbers

#include <stdio.h>

int main() {

    double a, b, product;

    printf("Enter two numbers: ");

    scanf("%lf %lf", &a, &b); 

 

    // Calculating product

    product = a * b;

 

    // %.2lf displays number up to 2 decimal point

    printf("Product = %.2lf", product);

   

    return 0;

}

 

3. Program to Check Even or Odd

#include <stdio.h>

int main() {

    int num;

    printf("Enter an integer: ");

    scanf("%d", &num);

 

    // true if num is perfectly divisible by 2

    if(num % 2 == 0)

        printf("%d is even.", num);

    else

        printf("%d is odd.", num);

   

    return 0;

}

 

Looping in C Language Class 10 Computer Science


Looping refers to the repetition of some statements for several number of time to achieve the desired result in the program. Looping Statements in C execute the sequence of statements many times until the stated condition becomes false. A loop in C consists of two parts, a body of a loop and a control statement. The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false. The purpose of the C loop is to repeat the same code a number of times.

Types of Loops in C

Depending upon the position of a control statement in a program, looping statement in C is classified into two types:

1. Entry controlled loop

2. Exit controlled loop


In an entry control loop in C, a condition is checked before executing the body of a loop. It is also called as a pre-checking loop.

In an exit controlled loop, a condition is checked after executing the body of a loop. It is also called as a post-checking loop.

 

The control conditions must be well defined and specified otherwise the loop will execute an infinite number of times. The loop that does not stop executing and processes the statements number of times is called as an infinite loop. An infinite loop is also called as an “Endless loop.” Following are some characteristics of an infinite loop:


1. No termination condition is specified.

2. The specified conditions never meet.


The specified condition determines whether to execute the loop body or not.

‘C’ programming language provides us with three types of loop constructs:


1. The while loop: In while loop, a condition is evaluated before processing a body of the loop. If a condition is true, then and only then the body of a loop is executed. 

2. The do-while loop: In a do…while loop, the condition is always executed after the body of a loop. It is also called an exit-controlled loop.

3. The for loop compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.

 

While Loop in C

A while loop is the most straightforward looping structure. While loop syntax in C programming language is as follows:

Properties of while loop

  1. A conditional expression is used to check the condition. The statements defined inside the while loop will repeatedly execute until the given condition fails.
  2. The condition will be true if it returns 0. The condition will be false if it returns any non-zero number.
  3. In a while loop, the condition expression is compulsory.
  4. Running a while loop without a body is possible.
  5. We can have more than one conditional expression in the while loop.
  6. If the loop body contains only one statement, then the braces are optional.

 

Syntax of While Loop in C:

while (condition) {

             statements;

}

It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the loop. If a condition is true, then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false. Once the condition becomes false, the control goes out of the loop.


After exiting the loop, the control goes to the statements which are immediately after the loop. The body of a loop can contain more than one statement. If it contains only one statement, then the curly braces are not compulsory. It is a good practice though to use the curly braces even we have a single statement in the body.


In a while loop, if the condition is not true, then the body of a loop will not be executed, not even once. It is different in do-while loop which we will see shortly.


Following program illustrates while loop in C programming example:

#include<stdio.h>

#include<conio.h>

int main()

{

      int num=1;             //initializing the variable

      while(num<=10)    //while loop with condition

      {

                      printf("%d\n",num);

                      num++;                  //incrementing operation

      }

      return 0;

}

 

Output:

1

2

3

4

5

6

7

8

9

10

The above program illustrates the use of while loop. In the above program, we have printed series of numbers from 1 to 10 using a while loop.

 

1.      have initialized a variable called num with value 1. We are going to print from 1 to 10 hence the variable is initialized with value 1. If you want to print from 0, then assign the value 0 during initialization.

2.      In a while loop, we have provided a condition (num<=10), which means the loop will execute the body until the value of num becomes 10. After that, the loop will be terminated, and control will fall outside the loop.

3.      In the body of a loop, we have a print function to print our number and an increment We operation to increment the value per execution of a loop. An initial value of num is 1, after the execution, it will become 2, and during the next execution, it will become 3. This process will continue until the value becomes 10 and then it will print the series on console and terminate the loop.

\n is used for formatting purposes which means the value will be printed on a new line.

 

Program to print table for the given number using while loop in C

#include<stdio.h>  

int main(){    

int i=1,number=0,b=9;    

printf("Enter a number: ");    

scanf("%d",&number);    

while(i<=10){    

printf("%d \n",(number*i));    

i++;    

}    

return 0;  

}   


Enter a number: 50

50

100

150

200

250

300

350

400

450

500

 

Do-While loop in C

A do…while loop in C is similar to the while loop except that the condition is always executed after the body of a loop. It is also called an exit-controlled loop.

Syntax of do while loop in C programming language is as follows:

Syntax of Do-While Loop in C:

 do {

  statements

} while (expression);

 

As we saw in a while loop, the body is executed if and only if the condition is true. In some cases, we have to execute a body of the loop at least once even if the condition is false. This type of operation can be achieved by using a do-while loop.


In the do-while loop, the body of a loop is always executed at least once. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.


Similar to the while loop, once the control goes out of the loop the statements which are immediately after the loop is executed.

The critical difference between the while and do-while loop is that in while loop the while is written at the beginning. In do-while loop, the while condition is written at the end and terminates with a semi-colon (;)

The following loop program in C illustrates the working of a do-while loop:

Below is a do-while loop in C example to print a table of number 2:

#include<stdio.h>

#include<conio.h>

int main()

{

      int num=1;             //initializing the variable

      do           //do-while loop

      {

                      printf("%d\n",2*num);

                      num++;                  //incrementing operation

      }while(num<=10);

      return 0;

}

 

Output:

2

4

6

8

10

12

14

16

18

20


In the above example, we have printed a multiplication table of 2 using a do-while loop. Let’s see how the program was able to print the series.

 

1.   First, we have initialized a variable ‘num’ with a value 1. Then we have written a do-while loop.

2.   In a loop, we have a print function that will print the series by multiplying the value of num with 2.

3.   After each increment, the value of num will increase by 1, and it will be printed on the screen.

4.   Initially, the value of num is 1. In a body of a loop, the print function will be executed in this way: 2*num where num=1, then 2*1=2 hence the value two will be printed. This will go on until the value of num becomes 10. After that loop will be terminated and a statement which is immediately after the loop will be executed. In this case return 0.


For loop in C

A for loop is a more efficient loop structure in ‘C’ programming. The general structure of for loop syntax in C is as follows:

Syntax of For Loop in C:

for (initial value; condition; incrementation or decrementation )

{

  statements;

}

  1. The initial value of the for loop is performed only once.
  2. The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.
  3. The incrementation/decrementation increases (or decreases) the counter by a set value.


Following program illustrates the for loop in C programming example:

#include<stdio.h>

int main()

{

      int number;

      for(number=1;number<=10;number++)             //for loop to print 1-10 numbers

      {

                      printf("%d\n",number);                        //to print the number

      }

      return 0;

}

 

Output:

1

2

3

4

5

6

7

8

9

10

 

The above program prints the number series from 1-10 using for loop.

 

1.   We have declared a variable of an int data type to store values.


2.   In for loop, in the initialization part, we have assigned value 1 to the variable number. In the condition part, we have specified our condition and then the increment part.


3.   In the body of a loop, we have a print function to print the numbers on a new line in the console. We have the value one stored in number, after the first iteration the value will be incremented, and it will become 2. Now the variable number has the value 2. The condition will be rechecked and since the condition is true loop will be executed, and it will print two on the screen. This loop will keep on executing until the value of the variable becomes 10. After that, the loop will be terminated, and a series of 1-10 will be printed on the screen.

In C, the for loop can have multiple expressions separated by commas in each part.

For example:

for (x = 0, y = num; x < y; i++, y--) {

  statements;

}

Also, we can skip the initial value expression, condition and/or increment by adding a semicolon.

For example:

int i=0;

int max = 10;

for (; i < max; i++) {

  printf("%d\n", i);

}

Notice that loops can also be nested where there is an outer loop and an inner loop. For each iteration of the outer loop, the inner loop repeats its entire cycle.

Consider the following example with multiple conditions in for loop, that uses nested for loop in C programming to output a multiplication table:

#include <stdio.h>

int main() {

int i, j;

int table = 2;

int max = 5;

for (i = 1; i <= table; i++) { // outer loop

  for (j = 0; j <= max; j++) { // inner loop

    printf("%d x %d = %d\n", i, j, i*j);

  }

  printf("\n"); /* blank line between tables */

}}


Output:

1 x 0 = 0

1 x 1 = 1

1 x 2 = 2

1 x 3 = 3

1 x 4 = 4

1 x 5 = 5

 

2 x 0 = 0

2 x 1 = 2

2 x 2 = 4

2 x 3 = 6

2 x 4 = 8

2 x 5 = 10

 

The nesting of for loops can be done up-to any level. The nested loops should be adequately indented to make code readable. In some versions of ‘C,’ the nesting is limited up to 15 loops, but some provide more.

The nested loops are mostly used in array applications which we will see in further tutorials.

Break Statement in C

The break statement is used mainly in in the switch statement. It is also useful for immediately stopping a loop.

We consider the following program which introduces a break to exit a while loop:

#include <stdio.h>

int main() {

int num = 5;

while (num > 0) {

  if (num == 3)

    break;

  printf("%d\n", num);

  num--;

}}

Output:

5

4

Continue Statement in C

When you want to skip to the next iteration but remain in the loop, you should use the continue statement.

For example:

#include <stdio.h>

int main() {

int nb = 7;

while (nb > 0) {

  nb--;

  if (nb == 5)

    continue;

 printf("%d\n", nb);

}}

 


Output:

6

4

3

2

1

So, the value 5 is skipped.


Which loop to Select?

Selection of a loop is always a tough task for a programmer, to select a loop do the following steps:

  1. Analyze the problem and check whether it requires a pre-test or a post-test loop.
  2. If pre-test is required, use a while or for a loop.
  3. If post-test is required, use a do-while loop.

 


Comments