C Programming
This presentation is the property of its rightful owner.
Sponsored Links
1 / 106

C Programming Class I PowerPoint PPT Presentation


  • 91 Views
  • Uploaded on
  • Presentation posted in: General

C Programming Class I. Introduction to C. Generation of ‘C’ Language In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language) In 1970, Ken Thompson created a language using many features of BCPL and called it simply B.

Download Presentation

C Programming Class I

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


C programming class i

C Programming

Class I


Introduction to c

Introduction to C

Generation of C Language

  • In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language)

  • In 1970, Ken Thompson created a language using many features of BCPL and called it simply B.

  • In 1972, C is Introduced by Dennis Ritchie at Bell laboratories and in the UNIX operating system.


Why are using c

Why are using C

  • It is a Structured Programming Language

  • High Level Language

  • Machine Independent Language

  • It allows software developers to develop programs without worrying about the hardware platforms where they will be implemented

TYPES OF C COMPILER

1. Borland C Compiler

2. Turbo C Compiler

3. Microsoft C Compiler

4. ANSI C Compiler


Steps in learning c

Steps in Learning C

Character set

Files

Data Structures

Structures and

Unions

Algorithms

Constants, variable

And Data types

Control statements

Pointers

Programs

Functions

Arrays


C s program structure

CS Program Structure

Documentation section

Preprocessor section

Definition section

Global declaration section

main()

{

Declaration part;

Executable part;

}

Sub program section

{

Body of the subprogram

}


C s character set

Cs Character set


C programming class i

C TOKENS

C TOKENS

Constants

Strings

-15.5

100

ABC

YEAR

Identifiers

Operators

Grant_total

Amount

a1

+ - * /

Keywords

Special Symbols

float

while

[ ]

{ }


C s keyword

Cs keyword

  • Basic Building Block of the Program

  • This are the Reserved words

  • This words cant be changed


C s variables

Cs Variables

  • A variable is a data name as well as identifier that may be used to store a data value.

    Rules for Naming the Variables

  • A variable can be of any combination of alphabets, digits and underscore.

  • The first character of the variable cant be digits.

  • The length of the variable cant be exceeded by 8.(ANSI C 32 Character)

  • No commas, blanks or special symbol are allowed within a variable name.

  • Uppercase and lowercase are significant. That is, the variable Total is not the same as total or TOTAL.

  • It should not be a keyword.

  • White space is not allowed.


C s variables cont

Cs Variables cont.


C s variables cont1

Cs Variables cont.


C s constant

Cs constant

The item whose values cant be changed during execution of program are called constants


C s constant conti

Cs constant Conti

Integer constant

eg: roll_number = 12345;

Real Constant

eg: pi = 3.14;

Decimal Constant

Eg. 35

Octal constant

Eg. 043

Hexadecimal constant

Eg. 0x23

Single Precision Constant

Double Precision Constant


Data types

Data Types

  • This are the type of the data that are going to access within the program.


C s data types cont

Cs Data types cont.

The primary data types are further classified as below.

Integers are the whole numbers, both positive and negative.


C s data types cont1

Cs Data types cont.

Float are the numbers which contain fractional parts, both

Positive and Negative.


C s data types cont2

Cs Data types cont.

Char are the characters which contain alpha-numeric character.

Characters are usually stored in 8 bits (one byte) of internal storage

The void is the Null Data type.


C delimiters

C Delimiters

Delimiters are the symbols, which has some syntactic meaning and has

got significance.


C statements

C Statements

  • Statement can be defined as set of declarations (or) sequence of action

  • All statements in C ends with semicolon(;) except condition and

  • control statement


Expression statement

Expression Statement

1. An Expression is a combination of constant, variables, operators, and function calls written in any form as per the syntax of the C language.

2. The values evaluated in these expressions can be stored in variables and used as a part for evaluating larger expressions.

3. They are evaluated using an assignment statement of the form.

variable = expression;

4. For Example,

age = 21;

result = pow(2,2);

simple_interest = (p * n * r) / 100;


Compound statements

Compound Statements

1. A group of valid C expression statements placed within an opening flower brace { and closing flower brace } is referred as a Compound Statements.

2. For Example,

{

X = (A + (B * 3) C);

Y = A + B * 3;

Z = A * (B * 3 C);

}

Control Statements

1. This statement normally executed sequentially as they appear in the program.

2. In some situations where we may have to change the order of execution of statements until some specified conditions are met.

3. The control statement alter the execution of statements depending upon the conditions specified inside the parenthesis.

4. For Example,

if (a == b)if ((x < y) && (y > z))

{{

-------------------

-------------------

}}


Operators

Operators

An operator is a symbol that specifies an operation to be performed on the operands

  • Some operator needs two operands (binary)

  • Eg: a+b;

    + is an operator and a and b are the operands

  • Some operator needs one operand (unary)

  • Eg: ++a;

    ++ is an operator and a is the operand


Types of operators

Types of Operators


Arithmetic operators

This operators help us to carryout basic arithmetic operations such addition, subtraction, multiplication, division

Arithmetic Operators


Relational operator

This are used to compare two or more operands.

Operands can be variables, constants or expression.

eg: comparison of two marks or two values.

Relational Operator


Logical operator

This operators are used to combine the results of two or more conditions.

LogicalOperator


Assignment operator

Assignment Operator

  • This are used to assign a value or an expression or a variable to another variable

  • eg: a = 10; n1 = 20;

    Syntax:

    identifier = expression;

  • Compound Assignment

    This operator are used to assign a value to a variable in order to assign a new value to a variable after performing a specified operation.

    eg: a+=10,n1-=20;

  • Nested Assignment (Multiple)

    This operator are used to assign a single value to multiple variables

    eg: a=b=c=d=e=10;


List of shorthand or compound assignment operator

List of Shorthand or Compound Assignment Operator


Increment and decrement operator

C provide two operator for incrementing a value or decrementing a value

a) ++ Increment operator (adds one to the variable)

b) -- Decrement operator (Minus one to the variable)

eg: a++ (if a= 10 then the output would be 11)

Increment and Decrement operator


Increment and decrement operator conti

Increment and Decrement operator Conti

If the value of the operand x is 3 then the various expressions and their results are

The pre increment operation (++X) increments x by 1 and then assign the value to x. The post increment operation (X++) assigns the value to x and then increments 1. The pre-decrement operation ( --X) decrements 1 and then assigns to x. The post decrement operation (x--) assigns the value to x and then decrements 1. These operators are usually very efficient, but causes confusion if your try to use too many evaluations in a single statement.


Conditional operator

It is used check the condition and execute the statement depending upon the condition

Conditional Operator


Bitwise operator

Bitwise Operator

  • This are used to manipulate the data at bit level

  • It operates only on integers


Bitwise operator cont

The truth table for Bitwise AND,OR and XOR

Bitwise Operator cont.

Eg: x = 3 = 0000 0011

y = 4 = 0000 0100

x&y = 0000 0000

Eg: x = 3 = 0000 0011

y = 4 = 0000 0100

x|y = 0000 0111

Eg: x = 3 = 0000 0011

y = 4 = 0000 0100

x ^ y = 0000 0111


Bitwise operator cont1

Bitwise Operator cont.

Bitwise Ones Complement

The ones complement operator (~) is a unary operator, which causes the bits of the operand to be inverted (i.e., ones becomes zeros and zeros become ones)

For Example, if x = 7

i.e 8 bit binary digit is 0 0 0 0 0 1 1 1

The Ones Complement is 1 1 1 1 1 0 0 0

Bitwise Left Shift Operator

The Left shift operator (<<) shifts each bit of the operand to its Left. The general form or the syntax of Left shift operator is

variable << no. of bits positions

if x = 7 (i.e., 0 0 0 0 0 1 1 1) the value of y in the expression

y = x <<1 is 14

0 0 0 0 1 1 1 0 = 14 since it shifts the bit position to its left by one bit. The value stored in x is multiplied by 2N (where n is the no of bit positions) to get the required value. For example, if x = 7 the result of the expression y = x << 2 is y = x * 22 (i.e. 28)


Bitwise operator cont2

Bitwise Operator cont.

Bitwise Right Shift Operator

The Right shift operator (>>) shifts each bit of the operand to its Right. The general form or the syntax of Right shift operator is

variable >> no. of bits positions

if x = 7 (i.e., 0 0 0 0 0 1 1 1) the value of y in the expression

y = x >> 1 is 3

0 0 0 0 0 0 1 1 = 3 since it shifts the bit position to its right by one bit. The value stored in x is divided by 2N (where n is the no of bit positions) to get the required value. For example, if x = 7 the result of the expression y = x << 2 is y = x / 22 (i.e. 1). If you use the left shift operator i.e. x = x << 1 the value of x will be equal to 2 (i.e., 0 0 0 0 0 0 1 0) since the lost bit cannot be taken back.


Operator precedence and associativity of operator

Operator Precedence and Associativity of Operator


What is precedence rule and associative rule

What is Precedence Rule and Associative Rule

  • Each operator in C has a precedence associated with it.

  • This precedence is used to determine how an expression involving more than one operator is evaluated.

  • These are distinct levels of precedence and an operator may belong to one of these levels.

  • The operators at the higher level of precedence are evaluated first.

  • The operators of the same precedence are evaluated either from left to right or from right to left, depending on the level.

  • That is known as the associativity property of an operator.


Arithmetic operators precedence

The precedence of an operator gives the order in which operators are applied in expressions: the highest precedence operator is applied first, followed by the next highest, and so on.

eg: Arithmetic operator precedence

Arithmetic operators precedence

The arithmetic expression evaluation is carried out using two phases from left to right through the expressions


Relational operators precedence

Relational operators precedence

Example:

if (x == 10 +15 && y <10)

The precedence rules say that the addition operator has a higher priority than the logical operator (&&) and the relational operators (== and <). Therefore, the addition of 10 and 15 is executed first. This is equivalent to:

if (x == 25 && y < 10)

The next step is to determine whether x is equal to 25 and y is less than 10, if we assume a value of 20 for x and 5 for y, then

x == 25 is FALSE (0)

y <10 is TRUE (1)

Note that since the operator < enjoys a higher priority compared to ==, y < 10 is tested first and then x ==25 is tested.

Finally we get,

if (FALSE && TRUE)

Because one of the conditions is FALSE, the complex condition is FALSE.

In the case of &&, it is guaranteed that the second operand will not be evaluated if the first is zero and in the case of || , the second operand will not be evaluated if the first is non zero.


Precedence and associativity table

The following table lists all the operators, in order of precedence, with their associativity

Precedence and Associativity Table


Precedence and associativity table cont

Precedence and Associativity Table cont.


Precedence and associativity table cont1

Precedence and Associativity Table cont.


Precedence and associativity table cont2

Precedence and Associativity Table cont.


Sample expression

Sample Expression

  • Exp = a - 2 * a * b + b / 4

    Let us have a=10,b=20

    exp = 10 - 2 * 10 * 20 + 20 / 4

    Phase I exp = 2*10*20 , 20/4 will be evaluated.

    phase II exp = 10-400+5 will be evaluated.

    Result exp = -395.


Expression evaluation

Expression Evaluation

Let us see some examples for evaluating expression.

Let a = 5, b = 8, c = 2.

x=b / c + a*c

10

4

14


C programming class i

Expression Evaluation

Let us see some examples for evaluating expression.

Let a = 5, b = 8, c = 2.

y=a + (b * 3)-c

24

29

27


C programming class i

TYPE CONVERSION

OR

TYPE CASTING


C programming class i

What is Type Conversion or Type Casting

Type Casting means One data type converted into another data type. This is called Type conversion or Type casting.

Example:

1. Integer into floating point number

2. Character into integer

3. Floating point number into Integer Number

Type conversion is classified into two types.

1. Implicit Type Conversion (Automatic Type Conversion)

2. Explicit Type Conversion (Manual Type Conversion)

Type Conversion

Implicit

Conversion

Explicit

Conversion

Automatic

Conversion

Casting

Operation


C programming class i

Type Conversion Hierarchy

long double

Implicit Type Conversion

double

float

unsigned long int

long int

unsigned int

int

Explicit Type Conversion

short

char


C programming class i

Implicit Type Conversion

  • The Implicit Type Conversion is known as Automatic Type Conversion.

  • C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance.

  • Implicit type Conversion also known as Converted Lower order data type into Higher order data type.

  • Implicit Type Conversion also known as Widening.

  • Example:

  • int a, b;

  • float c;

  • c = a + b;

  • Print c;

  • float a,b;

  • int c;

  • c = a + b;// This is Wrong

  • Print c;


C programming class i

Explicit Type Conversion

  • The Explicit Type Conversion is, there are instances when we want to force a type conversion in a way that is different from the automatic conversion.

  • The Explicit Type Conversion is Converted Higher order data type into Lower order data type.

  • The Explicit type Conversion is also known as borrowing.

  • The Explicit type conversion forces by a casting operator.

Disadvantage of Explicit Type Conversion

  • float to int causes truncation of the fractional part.

  • double to float causes rounding of digits.

  • Long int to int causes dropping of the excess higher order bits.

The general form of the casting is

(type_name) expression;

Where type_name is one of the standard C data type.

The expression may be a constant, variables or an expression.

For Example:

float a, b;

int c;

c = (int) a + (int) b;

Print c;


Use of casts

Use of Casts


Input and output functions

Input And Output Functions


Ip op statements

We have two methods for providing data to the program.

a) Assigning the data to the variables in a program.

b) By using the input/output statements.

c language supports two types of Ip / Op statements

This operations are carried out through function calls.

Those function are collectively known as standard I / O library

Ip / Op Statements


Ip op statements cont

Ip / Op Statements cont.


Unformatted ip op statements

These statements are used to input / output a single / group of characters from / to the input / output device.

Single character Input/output function

Unformatted Ip / Op statements


Unformatted ip op statements cont

Group of character Input / output function.

Gets() and puts are used to read / display the string from / to the standard input / output device.

Unformatted Ip / Op statements cont.


Unformatted ip op statements cont1

Single character Input / output function with files.

Gets() and puts are used to read / display the string from / to the standard input / output device.

Unformatted Ip / Op statements cont.


Sample program

Sample Program

#include<stdio.h>

Void main()

{

char name[10];

char address[20];

Puts(Enter the name : );

gets(name);

puts(Enter the address : );

gets(address);

puts(Name = )

puts(name);

puts(Address = );

puts(address);

}


Formatted ip op statements

Formatted Ip / Op statements

  • It refers to Input / Output that has been arranged in a particular format.

  • Using this statements, the user must specify the type of data, that is going to be accessed.


Formatted ip op statements1

Control strings

i) It is the type of data that user is going to access via the input statement

ii) These can be formatted . iii) Always preceded with a % symbol.

Formatted Ip / Op statements


Printf

Printf()


Control statements decision making

Control Statements(Decision Making)


Control statements

Control Statements


Types of selection statement

Types of Selection Statement

  • Simple if Selection statement

  • if else Selection statement

  • Nested if else Selection statement

  • else if ladder Selection statement


Simple if selection statement

Simple if Selection statement

It is used to control the flow of execution of the statements and also to

test logically whether the condition is true or false.

if the condition is true then the statement following the if is executed if

it is false then the statement is skipped.

Syntax:

if ( condition )

{

statement ;

}

Test Condition

True

Executable X - Statement


C programming class i

//Biggest of Two Numbers

#include <stdio.h>

void main()

{

int a, b;

clrscr();

printf(Enter the A and B Value:\n);

scanf(%d, &a);

if (a > b)

{

printf(A is Big);

}

getch();

}


The if else statement

The if else statement

Syntax:

if ( condition )

{

statement 1 ; (if the condition is true this statement will be executed)

}

else

{

statement 2 ; (if the condition is false this statement will be executed)

}

It is used to execute some statements when the condition is true and execute some other statements when the condition is false depending on the logical test.

Test Condition

False

True

Executable Y - Statement

Executable X - Statement


C programming class i

// Biggest of Two Numbers

#include <stdio.h>

void main()

{

int a, b;

clrscr();

printf(Enter the A and B Value:\n);

scanf(%d%d, &a,&b);

if (a > b)

{

printf(A is Big);

}

else

{

printf(B is Big);

}

getch();

}


C programming class i

// Given Number is ODD or EVEN Number

#include <stdio.h>

void main()

{

int n;

clrscr();

printf(Enter the Number:\n);

scanf(%d, &n);

if (n % 2 == 0)

{

printf(Given Number is Even Number);

}

else

{

printf(Given Number is Odd Number);

}

getch();

}


C programming class i

when a series of ifelse statements are occurred in a program, we can write an entire ifelse statement in another ifelse statement called nesting

Nested if.. else statement

Syntax:

if ( condition 1)

{

if ( condition 2)

statement 1 ;

else

statement 2 ;

}

else

{

if (condition 3)

statement 3;

else

statement 4;

}


C programming class i

Test Condition_1

FALSE

TRUE

Test Condition_2

FALSE

TRUE

Executable X2 - Statement

Executable X1 - Statement

Test Condition_3

FALSE

TRUE

Executable X4 - Statement

Executable X3 - Statement


C programming class i

When a series of decisions are involved we have to use more than one if else statement called as multiple ifs. Multiple if else statements are much faster than a series of if else statements, since theif structure is exited when any one of the condition is satisfied.

else if Ladder or Multiple if else Statements

Syntax:

if (condition_1)

executed statement_1;

else if (condition_2)

executed statement_2;

else if (condition_3)

executed statement_3;

----------------------

----------------------

else if (condition_n)

executed statement_n;

else

executed statement_x;


C programming class i

Test Condition_1

FALSE

TRUE

Exec. Stat_1

Test Condition_2

FALSE

TRUE

Exec. Stat_2

Test Condition_3

FALSE

TRUE

Exec. Stat_3

Test Condition_n

FALSE

TRUE

Exec. Stat_X

Exec. Stat_n


Else if ladder

else if Ladder

if (result >= 75)

printf ( Passed: Grade A\n ) ;

else if (result >= 60)

printf ( Passed: Grade B\n ) ;

else if (result >= 45)

printf ( Passed: Grade C\n ) ;

else

printf ( Failed\n ) ;


The switch statement

THE SWITCH STATEMENT

  • The control statements which allow us to make a decision from the number of choices is called switch (or) Switch-case statement.

  • It is a multi way decision statement, it test the given variable (or) expression against a list of case value.

switch (expression)

{

case constant 1:

simple statement (or)

compound statement;

case constant 2:

simple statement (or)

compound statement;

case constant 3:

simple statement (or)

compound statement;

}

switch (expression)

{

case constant 1:

simple statement (or)

compound statement;

case constant 2:

simple statement (or)

compound statement;

default :

simple statement (or)

compound statement;

}


Example without break statement

Example With Break Statement

Example Without Break Statement

#include<stdio.h>

void main ()

{

int num1,num2,choice;

printf(Enter the Two Numbers:\n);

scanf(%d%d,&num1,&num2);

printf(1 -> Addition\n);

printf(2->Subtraction\n);

printf(3->Multiplication\n);

printf(4->Division\n);

printf(Enter your Choice:\n);

scanf(%d,&choice);

switch(choice)

{

case 1:

printf(Sum is %d\n, num1+num2);

break;

case 2:

printf(Diif. is %d\n, num1-num2);

break;

case 3:

printf(Product is %d\n, num1*num2);

break;

case 4:

printf(Division is %d\n, num1/num2);

break;

default:

printf (Invalid Choice..\n);

}

getch();

}

#include<stdio.h>

void main ()

{

int num1,num2,choice;

printf(Enter the Two Numbers:\n);

scanf(%d%d,&num1,&num2);

printf(1 -> Addition\n);

printf(2->Subtraction\n);

printf(3->Multiplication\n);

printf(4->Division\n);

printf(Enter your Choice:\n);

scanf(%d,&choice);

switch(choice)

{

case 1:

Printf(Sum is %d\n, num1+num2);

case 2:

Printf(Diif. is %d\n, num1-num2);

case 3:

Printf(Product is %d\n, num1*num2);

case 4:

Printf(Division is %d\n, num1/num2);

default:

printf (Invalid Choice..\n);

}

getch();

}


Rules for switch

Rules for Switch

  • The expression in the switch statement must be an integer or character constant.

  • No real numbers are used in an expression.

  • The default is optional and can be placed anywhere, but usually placed at end.

  • The case keyword must be terminated with colon (:);

  • No two case constant are identical.

  • The values of switch expression is compared with case constant in the order specified i.e from top to bottom.

  • A switch may occur within another switch, but it is rarely done. Such statements are called as nested switch statements.

  • The switch statement is very useful while writing menu driven programs.


Iteration statements

Iteration Statements

  • Iteration statements is also known as Looping statement.

  • A segment of the program that is executed repeatedly is called as a loop.

  • Some portion of the program has to be specified several number of times or until a particular condition is satisfied.

  • Such repetitive operation is done through a loop structure.

  • The Three methods by which you can repeat a part of a program are,

    1. while Loops

    2. do.while loops

    3. for Loop

    Loops generally consist of two parts :

    Control expressions: One or more control expressions which control the execution of the

    loop,

    Body : which is the statement or set of statements which is executed over and

    over


C programming class i

Any looping statement , would include the following steps:

  • Initialization of a condition variable

  • Test the control statement.

  • Executing the body of the loop depending on the condition.

  • Updating the condition variable.


While loop

While Loop

A while loop has one control expression, and executes as long as that expression is true. The general syntax of a while loop is

A while loop is an entry controlled loop statement.

initialize loop counter;

while (condition)

{

statement (s);

increment or decrement loop counter

}


C programming class i

Start

Initialize

Test Condition

False

Stop

True

Body of Loop

Increment or Decrement


C programming class i

Example:

// Summation of the series 1 + 2 + 3 + 4 + .

#include <stdio.h>

void main()

{

int i, sum;

clrscr();

i = 1;

sum = 0;

while(i<=10)

{

sum = sum + i

printf(The Sum Value is:%d\n,i);

++i;

}

getch();

}

// Print the I Values

#include <stdio.h>

void main()

{

int i;

clrscr();

i = 0;

while(i<=10)

{

printf(The I Value is :%d\n,i);

++i;

}

getch();

}


The do while loop

THE do-while LOOP

  • The body of the loop may not be executed if the condition is not satisfied in while loop.

  • Since the test is done at the end of the loop, the statements in the braces will always be executed at least once.

  • The statements in the braces are executed repeatedly as long as the expression in the parentheses is true.

    Make a note that do while ends in a ; (semicolon)

    Note that Do While Looping statement is Exit Controlled Looping statement

initialize loop counter;

do

{

statement (s);

increment or decrement loop counter

}

while (condition);


C programming class i

Start

Initialize

Body of Loop

Increment or Decrement

Test Condition

True

False

Stop


C programming class i

Difference Between While Loop and Do While Loop


C programming class i

Example:

// Print the I Values

#include <stdio.h>

void main()

{

int i;

clrscr();

i = 1;

while(i<=10)

{

printf(The I Value is :%d\n,i);

i++;

}

getch();

}

// Print the I Values

#include <stdio.h>

void main()

{

int i;

clrscr();

i = 1;

do

{

printf(The I Value is :%d\n,i);

i++;

}while(i<=10);

getch();

}


For loop

for Loop

  • The for loop is another repetitive control structure, and is used to execute set of instruction repeatedly until the condition becomes false.

  • To set up an initial condition and then modify some value to perform each succeeding loop as long as some condition is true.

    The syntax of a for loop is

    The three expressions :

    expr1 - sets up the initial condition,

    expr2 - tests whether another trip through the loop should be taken,

    expr3 - increments or updates things after each trip.

for( expr1; expr2 ;expr3)

{

Body of the loop;

}


C programming class i

Start

Initialize; test_condition; Increment / Decrement

Body of Loop

Stop


Example

Example

Given example will print the values from 1 to 10.

#include<stdio.h>

void main()

{

for (int i = 1; i <= 10; i++)

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

}

There is no need of { } braces for single line statement and for multiple line it is

essential else it will consider only next line of for statement.


Additional features of for loop

Additional Features of for Loop

Case 1:

The statement

p = 1;

for (n = 0; n < 17; ++ n)

can be rewritten as

for (p = 1, n = 0; n < 17;++n)

Case 2:

The second feature is that the test condition may have any compound relation and

the testing need not be limited only to the loop control variable.

sum = 0;

for (i = 1; i < 20 && sum < 100; ++ i)

{

sum = sum + i;

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

}


Additional features of for loop conti

Additional Features of for Loop Conti

Case 3:

It also permissible to use expressions in the assignment statements of initialization

and increments sections.

For Example:

for (x = (m + n) / 2; x > 0; x = x / 2)

Case 4:

Another unique aspect of for loop is that one or more sections can be omitted, if

necessary.

For Example:

m = 5;

for ( ; m ! = 100 ;)

{

printf(%d\n,m);

m = m + 5;

}

Both the initialization and increment sections are omitted in the for statement. The initialization has been done before the for statement and the control variable is incremented inside the loop. In such cases, the sections are left blank. However, the semicolons separating the sections must remain. If the test condition is not present, the for statement sets up an infinite loop. Such loops can be broken using break or goto statements in the loop.


C programming class i

Additional Features of for Loop Conti

Case 5:

We can set up time delay loops using the null statement as follows:

for ( j = 1000; j > 0; j = j 1)

1. This is loop is executed 1000 times without producing any output; it simply causes a

time delay.

2. Notice that the body of the loop contains only a semicolon, known as a null statement.


Nesting of for loop

Nesting of for Loop

The One for statement within another for statement is called Nesting for Loop.

Syntax:

for (initialize; test_condi; incre. / decre.)

{

---------------

---------------

for (initialize; test_condi; incre. / decre.)

{

-----------

-----------

}

---------------

---------------

}

-----------------

-----------------

Outer for Loop

Inner for Loop


Example1

Example

// Print the I and J Value

#include<stdio.h>

#include<conio.h>

void main()

{

int I, j;

clrscr();

for (i = 1; I < = 10 ; I ++)

{

printf (The I Value is %d \n", i);

for (j = 1; j < = 10; j ++)

{

printf (The J Value is %d \n", j);

}

}

getch();

}


Jumps in loops

JUMPS IN LOOPS


C programming class i

  • Loops perform a set of operations repeatedly until the control variable fails to satisfy the test condition.

  • The number of times a loop is repeated is decided in advance and the test condition is written to achieve this.

  • Sometimes, when executing a loop it becomes desirable to skip a part of the loop or to leave the loop as soon as a certain condition occurs.

  • Jumps out of a Loop is Classified into three types

  • 1. break;

  • 2. continue;

  • 3. goto;


C programming class i

  • The break Statement

  • A break statement is used to terminate of to exit a for, switch, while or do while statements and the execution continues following the break statement.

  • The general form of the break statement is

  • The break statement does not have any embedded expression or arguments.

  • The break statement is usually used at the end of each case and before the start of the next case statement.

  • The break statement causes the control to transfer out of the entire switch statement.

break;


C programming class i

#include <stdio.h>

void main()

{

int i;

clrscr();

i = 1;

while (i < = 10)

{

printf (The I Value is: %d \n, i);

if (i = = 6)

{

printf (The I value is Reached 6, So break of the programs\n);

break;

}

i++;

}


C programming class i

  • The continue Statement

  • The continue statement is used to transfer the control to the beginning of the loop, there by terminating the current iteration of the loop and starting again from the next iteration of the same loop.

  • The continue statement can be used within a while or a do while or a for loop.

  • The general form or the syntax of the continue statement is

  • The continue statement does not have any expressions or arguments.

  • Unlike break, the loop does not terminate when a continue statement is encountered, but it terminates the current iteration of the loop by skipping the remaining part of the loop and resumes the control tot the start of the loop for the next iteration.

continue;


C programming class i

#include <stdio.h>

void main()

{

int i;

clrscr();

i = 1;

while (i < = 10)

{

printf (The I Value is: %d \n, i);

if (i = = 6)

{

printf (The I value is Reached 6, But Continue this Programs\n);

continue;

}

i++;

}


C programming class i

Differences Between Break and Continue Statement


C programming class i

  • The goto Statement

  • The goto statement is used to transfer the control in a loop or a function from one point to any other portion in that program.

  • If misused the goto statement can make a program impossible to understand.

  • The general form or the syntax of goto statement is

  • The goto statement is classified into two types

  • a. Unconditional goto

    • b. Conditional goto

goto label;

Statement (s);

.

label:

statement (s);


C programming class i

Unconditional Goto

The Unconditional goto means the control transfer from one block to another block without checking the test condition.

Example:

#include <stdio.h>

void main()

{

clrscr();

Start:

printf(Welcome\n);

goto Start;

getch();

}


C programming class i

Conditional Goto

The Conditional goto means the control transfer from one block to another block with checking the test condition.

#include <stdio.h>

void main()

{

int a, b;

clrscr();

printf (Enter the Two Value:\n);

scanf (%d, &a, &b);

if (a > b)

goto output_1;

else

goto output_2;

output_1:

printf (A is Biggest Number);

goto Stop;

output_2:

printf (B is Biggest Number);

goto Stop;

Stop:

getch();

}


C programming class i

Thank You!


  • Login