AnnaUniversity First Year Unit 4

Overview of C

1.1     Syntax

The C code you write is called the SOURCE CODE or the SYNTAX.

Syntax is a mixture of:

C keywords like int, for and return.

Constants and variables.

Operators like + (arithmetic “addition”), || (logical “or”) and & (the “address of” operator).

Note that C is CASE SENSITIVE! For example, words like cat, Cat, cAt and CAT are all considered different from one another.

Also, the amount of WHITE SPACE you use in a C program does not affect the way it’s compiled. Use extra spaces and line breaks to make your programs more readable – indentation of code is very common. Obviously, you can NOT put spaces or line breaks in the middle of keywords like this: str uct !!

1.2     Commenting Your Code

You can add comments to your code by enclosing your remarks within /* and */. However, nested comments aren’t allowed.

A few properties of comments:

• 

They can be used to inform the person viewing the code what the code does. This is helpful when you revisit the code at a later date.

• 

The compiler ignores all the comments. Hence, commenting does not affect the efficiency of the program.

• 

You can use /* and */ to comment out sections of code when it comes to finding errors, instead of deletion.

Here are examples of commented code:

/* Comments spanning several */
/* lines can be commented*/
/* out like this!*/
 
/* But this is a
 simpler way
 of doing it! */
 
// These are C++
// style comments
// and should NOT 
// be used with C!!
 
/* /* NESTED COMMENTS
ARE ILLEGAL!! */ */

1.3     Creating Executable Programs

There are several tasks that need to be performed before you can run a program: coding, compiling and linking.

1.

You have to write the SOURCE CODE in C. You declare which header files you want to include within the source code. The source code must be saved with the extension .c.

2.

Then you run the COMPILER, which translates the source code into machine code. This produces output in a format that the computer can understand. It is worth repeating that computers do NOT understand C!

3.

Sometimes the source code is still lacking some parts, so after going through the compiler, the code is passed through a LINKER. This basically “links” the source code to other library or object files so that the final program is produced. Imagine the program being a jigsaw puzzle – the linker simply puts together missing pieces to complete the program.

 

#include <stdio.h>
 
int main() {
  printf("Hello World!\n");
  return 0;
}

1.4     Tip

When saving in Notepad you should surround a filename with quote marks, for example, “world.c“. This ensures that the filename will be saved with the correct extension, rather than world.c.txt, which is incorrect.

1.5     Compiling

Compilation obviously varies from compiler to compiler – please read your compiler’s help file or ask your course tutor.

1.6     #include

If a line starts with a hash, denoted by #, it tells the compiler that a command should be sent to the C PREPROCESSOR. The C preprocessor is a program that is run before compilation takes place (hence the name). #include is one of the many C preprocessor commands you’ll use.

Basically, when the preprocessor finds #include it looks for the file specified and replaces #include with the contents of that file. In a way, this makes the code more readable and easier to maintain if you needed to use common library functions. More preprocessor commands in the later sections…..

1.7     Header Files

Header files have the extension .h and the full filename follows from the #include directive.

They contain declarations to certain functions that you may or may not have used in your program.

For example, the stdio.h file is required if you have used functions like printf and scanf in your program. More about these two functions in the Standard Input and Output section.

There are two ways to include a header file:
#include "stdio.h"
and
#include <stdio.h>

If you use the double quote marks, it means that the directory you’re currently in, will be searched for first for the header file, before any other directories are searched.

If you use the angled brackets, directories other than the one you’re currently in, will be searched for the header file. Usually this will be the default directory for header files specified in your compiler, so you’ll probably be using square brackets all the time.

1.8     The main Function

A FUNCTION is like a subroutine where a group of instructions are evaluated when the function is CALLED.

All C programs must have a main function. You can only have one, but you can place it anywhere within the code.

The program always start with the main function and ends when the end of main is reached. Functions RETURN a value too, in other words, passes back a value to the program.

If a function returns nothing, its return type is of type void – i.e. nothing is returned.

The main function is special, as it returns an integer by default, which is why you’ll see me write return 0; at the end of the program. Zero is usually returned to indicate error-free function termination.

Another way to terminate a program is to use the exit function – there’s an example later on.

Here’s the program again:

#include <stdio.h>
 
int main() {
  printf("Hello World!\n");
  return 0;
}

1.9     printf

As you might have guessed, printf is a function that outputs text to the program window. For now, all you need to remember is that you pass it a STRING (a sequence of characters), which gets outputted. The \n character is the NEWLINE character, which allows you to start a new line in the output to make things neater.

Notice that there is a semicolon at the end of the line. Semicolons are used to terminate STATEMENTS, which are instructions for the computer to process. Here we are instructing the computer to “print hello world”.

 

 

As a programming language, C is rather like Pascal or Fortran. Values are stored in variables. Programs are structured by defining and calling functions. Program flow is controlled using loops, if statements and function calls. Input and output can be directed to the terminal or to files. Related data can be stored together in arrays or structures.

Of the three languages, C allows the most precise control of input and output. C is also rather more terse than Fortran or Pascal. This can result in short efficient programs, where the programmer has made wise use of C’s range of powerful operators. It also allows the programmer to produce programs which are impossible to understand.

Programmers who are familiar with the use of pointers (or indirect addressing, to use the correct term) will welcome the ease of use compared with some other languages. Undisciplined use of pointers can lead to errors which are very hard to trace. This course only deals with the simplest applications of pointers.

It is hoped that newcomers will find C a useful and friendly language. Care must be taken in using C. Many of the extra facilities which it offers can lead to extra types of programming error. You will have to learn to deal with these to successfully make the transition to being a C programmer.

The course aims to introduce programmers to the C language. Previous programming experience is assumed, so we can quickly progress to looking at the features of C and their uses. Students with little programming experience will need to do some homework in order to keep up with the lectures.

1.9.1     Structure of a C Program

Example

/*A simple C example program*/
#include <stdio.h>
void main(void)
{
               printf(”Hello World”);
}

The output of the program is shown below. This is what appears on the screen when the program runs.

Hello World

Let’s examine the program line by line. Here’s the first line.

/*A simple C example program*/

Other than the two forward slash marks that begin the line, it looks pretty much like ordinary English. The /* marks the beginning of a comment. The compiler ignores everything from the double slash to the end of the line. That means you can type anything you want on that line and the complier will never complain. To end the comment you must close it with */

Although comments are not required, they are very important to programmers. Real programs are much more complicated than the example above, and comments help explain what’s going on.

The next line looks like this:

#include <stdio.h>

Because this line starts with a #, it is called a preprocessor directive. The preprocessor reads your program before it is complied and only executes those lines beginning with a # symbol. The word inside the angular brackets <> is a header file name, which is required to do the work of Input / Output. The contents of stdio.h are included at the point where the #include statement appears. The preprocessor directives should not end with a semicolon because preprocessors are messages to the compiler.

The next line reads:

void main(void)

This starts the beginning of a function. A function can be thought of as a group of one or more programming statements that collectively has a name. The name of this function is main, and the set of parentheses enclosing the word void indicate that it is a function.

Although most C programs have more than one function, every C program must have a function called main. It is the starting point of the program. If you are reading someone else’s C program and want to find where it starts, just look for the function called main.

The next line is a

     {

This is called the left brace and marks the opening or beginning of a function, in our case main. All statements of the main are enclosed in a set of braces.

After the opening brace you see the following line:

               printf(“Hello World”);

This statement displays the string Hello World on screen. We will discuss more about the printf()later on in this chapter.

The last line is a

               }

This marks the end of the function main. Since main is the only function in the program it also marks the end of our program.

A special mention of the semicolon

A semicolon ; is used to mark the end of a statement in C. This allows the complier to understand that the end of a line has been reached. Usually a common mistake is that programmers omit the semicolon and try to compile the program.

1.9.2     The C Character Set

A character denotes any alphabet, digit or special symbol used to represent information. The C character set can be defined as a set of characters permissible under the C language to represent information. Under C, the upper case letters A-Z, the lower case letters a-z, the digits 0-9 and certain special symbols are all valid characters that can be used as building blocks to construct basic program elements.

Following is a table of character sets that are available under C

Alphabets
A, B, C, ………………… Z
a, b, c, ………………… z

Digits
0, 1, 2, 3, 4, 5, 6, 7, 8, 9

Special Characters or Symbols
+ – * & ^ % $ # @ ! ? > < { } [ ] ( ) | \ / “ ‘ : ; . , _

Variables

 

IDENTIFIERS

 

The identifiers are name given to various program elements such as variables, functions and arrays.

 

  • Identifiers consist of letters and digits in any order, except that

the First character must be a letter.

  • The identifier can be in lowercase or uppercase.
  • The upper and lower case are interchangeable.
  • The underscore ( _ ) can be included and it can also begin with underscore.
  • The identifiers should not contain a blank space, hyphen or quotes.

 

Valid Identifiers

 

            sum , Sum, SuM, a112, total_sum

 

Invalid Identifiers

 

            “sum”                      quotes(“) is illegal

 

            total-sum                        Illegal character ( )

 

            total sum                        Blank space should not be there

 

 

VARIABLES

Variable Declaration and Definition, Variable Initialization and Sample programs

·        A variable is a very basic part of every programming-language.

  • A variable is a block of memory that you can store, change and read information from/to.
  • A variable is an identifier that is used to represent some specified type of information within the program.

 

The basic format for declaring variables is

 

data type   var, var, … ;

 

where data type is one of the four basic types, an integer, character, float, or double type.

 

E.g.:  

int   Sum, a, x;

 

char name;

 

C is case sensitive, so even though the two variables listed below have the same name, they are considered different variables in C.

sum

Sum

User defined variables must be declared before they can be used in a program.

 

 

DATA TYPES

 

The four basic data types are

 

1. INTEGER

 

·        These are whole numbers, both positive and negative.

·        The integer can store data between –32768 to 32767.

 

The keyword used to define integers is,

 

int

 

An example of an integer value is 32. An example of declaring an integer variable called sum is,

 

     int sum;

     sum = 20;

 

 

 

2. FLOATING POINT

 

·        These are numbers, which contain fractional parts, both positive and negative.

 

The keyword used to define float variables is,

 

float

 

An example of a float value is 34.12. An example of declaring float variable called money is,

 

float money;

money = 0.12;

 

 

3. DOUBLE

 

·        These are exponetional numbers, both positive and negative.

 

 The keyword used to define double variables is,

 

double

 

An example of a double value is 3.0E2. An example of declaring a double variable called big is,

 

            double big;

            big = 312E+7;

 

 

4. CHARACTER

 

 These are single characters. The keyword used to define character variables is,

 

char

 

An example of a character value is the letter A. An example of declaring a character variable called letter is,

 

            char letter;

     letter = ‘A’;

 

You can also perform the declaration and assignment in the same statement.

Example:

 

            char letter = ‘A’;

 

Note the assignment of the character A to the variable letter is done by enclosing the value in single quotes.

 

 

Remember the Rule:             Single character – Use single quotes.

 

 

Sample program illustrating each data type

 

 

        #include < stdio.h >

 

        main()

        {

          int   sum;

          float money;

          char  letter;

          double pi;

 

          sum = 10;             /* assign integer value */

          money = 2.21;         /* assign float value */

          letter = ‘A’;         /* assign character value */

          pi = 2.01E6;          /* assign a double value */

 

          printf(“value of sum = %d\n”, sum );

          printf(“value of money = %f\n”, money );

          printf(“value of letter = %c\n”, letter );

          printf(“value of pi = %e\n”, pi );

        }

 

        Sample program output

        value of sum = 10

        value of money = 2.210000

        value of letter = A

                   value of pi = 2.010000e+06

 

 

NOTE

 

Data Type                              Description                                     Memory Requirement

 

   int                                      Integer Quantity                                   2 bytes or 1 Word

 

  char                                                Single character                                  1 Byte

 

  float                                  Floating Point Number (A                    1 word ( 4 bytes )

            number containing decimal

            point or exponent )

 

  double                               Double precision floating                         2 Words ( 8 bytes )

                                                point number ( A exponent

                                                with large magnitude )

 

 

CONSTANTS   Constants-

Integer Constants, Real Constants, Floating point Constants, Character Constant, String Constant,

Constants are identifiers whose values once set in the program, never changes.

·        The simplest constants are decimal integers, e.g. 0, 1, 2, 123.

·        The constants can be Integer, floating point or character.

·        We also have constants for specifying characters and strings.

 

DECLARATIONS

 

A declaration tells the compiler the name and type of a variable you’ll be using in your program. In its simplest form, a declaration consists of the type, the name of the variable, and a terminating semicolon

 

char c;

int i;

float f;

 

You can also declare several variables of the same type in one declaration, separating them with commas:

 

int i1, i2;

 

  • The placement of declarations is significant.
  • They must either be placed at the beginning of a function, or at the beginning of a brace-enclosed block of  statements, or outside of any function.

 

You may wonder why variables must be declared before use. There are two reasons:

 

1. It makes things somewhat easier on the compiler; it knows right away what kind of

    storage to allocate and what code to emit to store and manipulate each variable.

  

2. It gives the opportunity to give the initial ‘default values’ to the variables in one common place as soon as they are declared.

 

EXPRESSIONS

 

Any arrangement of variables, constants or operators that specifies a computation is called an expression.

 

a + 10;

 

is an expression. When the computation specified in the expression is performed then the result is usually a value. So if a is 5 then the result of the expression is 15.

 

OPERATORS

Assignment Operators, Conditional Operators, Arithmetic Operators, Relational Operators, Logical Operators, Bitwise Operators, and Unary operators.

 

ARITHMETIC OPERATORS

 

The basic operators for performing arithmetic are the same in many computer

languages:

 

+                            Addition

                          Subtraction

*                            Multiplication

/                            Division

%                          Modulus (remainder)

 

Operation            Operator            Equation            Value of Sum before            Value of sum after

 

Addition                 +                      sum = sum + 2            4                                  6

Subtraction                                  sum = sum –2             4                                  2

Multiply                  *                      sum = sum * 2                        4                                  8

Divide                    /                       sum = sum / 2             4                                  2

Modulus                %                    sum = sum % 3            4                                  1

 

UNARY OPERATORS

 

C includes a class of operators that act upon a single operand to produce a new value. Such operators are called unary operators. The most common unary operator is minus, where a minus precedes a numerical constant, variable or expression. Other unary operators are ++ and . These are called as increment operators.

Eg :

 

743            (a + b)         0.2

Operation            Operator            Equation            Value of Sum before            Value of sum after

 

Increment              ++                      ++sum             4                                  5

Decrement                                   sum             4                                  3

 

RELATIONAL OPERATORS

 

The relational operators in C are ,

 

Operator                     Meaning

 

    = =                            equal to

    !=                             not equal

    <                              less than

    <=                             less than or equal to

    >                               greater than

    >=                            greater than or equal to

 

These allow the comparison of two or more variables. So they are also called Comparison Operators. These six operators are used to form logical expressions representing conditions that are either True or False. The resulting expression will be of type integer, since True is represented by the integer value 1 and False is represented by the value 0.

 

Eg :

 

 Let a, b and c take values 1, 2 and 3 respectively.

 

 

Expression                              Interpretation                                     Value

 

 a < b                                            True                                                        1

 

(a + b) >= c                                  True                                                        1

 

(b + c) > (a + 5)                          False                                                       0

 

c != 3                                          False                                                       0

 

b = =  2                                        True                                                        1

 

LOGICAL OPERATORS

These are the usual And, Or and Not operators.

 

Symbol            Meaning

 

  &&                  AND

    ||                      OR

    !                    NOT

They are frequently used to combine relational operators, for example

Let a be a integer variable whose value is 7 and i be a character variable representing q.

Expression                                          Interpretation                                     Value

 

 (a >= 6) && ( i = = ‘q’)                            True                                                        1

 

(a >= 6) || ( i  = = 120)                           True                                                        1

 

(a >= 6) && ( i  = = 120)                           False                                                       0

 

 

 

Not operates on a single logical value, its effect is to reverse its state. Here is an example of its use.

 

 

if( !acceptable)

        printf(“Not Acceptable !!\n”);

 

ASSIGNMENT OPERATORS

 

The assignment operator = assigns a value to a variable.  Assignment expressions that make use of this operator are written in the form

 

identifier  =     expression

 

where identifier represents a variable and expression represents a constant, variable or a complex expression.

Eg :

 

x = 1

 

sets x to 1, and

 

a = b;

 

sets a to whatever b’s value is. The expression

 

i = i + 1;

 

is  the standard programming idiom for increasing a variable’s value by 1. This expression takes i’s old value, adds 1 to it, and stores it back into i.

 

CONDITIONAL OPERATOR

 

Simple conditional operation can be carried out with the conditional operator ( ?🙂

An expression using this operator is called a conditional expression. The general syntax is,

 

expression 1 ? expression 2 : expression 3

 

expression 1 is evaluated first. if the expression 1 is True then expression 2 is evaluated and this becomes the value of conditional expression. However if expression 1 is false then expression 3 is evaluated and this becomes the value of conditional expression.

Eg :

 

(i < 0 ) ? 0 : 100

 

The expression ( i < 0) is evaluated first. If it is true( i.e if the value of i is less than 0) then the entire conditional expression takes the value 0. Otherwise the conditional expression takes the value 100.

 

PROGRAM STRUCTURE

 

Managing Input and Output operators-Introduction, Reading a character, Writing a character, Formatted input and Formatted output, sample programs

 

STRUCTURE OF C PROGRAM

 

Every C program should consist of :

  • One or more functions, one of which must be called main.
  • The program will always begin by executing the main function.
  • Additional function definitions may precede or follow main.

 

Each function must contain,

 

1. A function heading, which consist of a function name. Followed by an optional list of arguments enclosed in parenthesis

 

2. A list of argument declarations, if arguments are included in the heading (Arguments are symbols that represent information being passed between the functions and other parts of the program)

 

3. A compound statement, which comprises of the remainder of function.

 

DATA INPUT

 

The header file required by the standard input/output library functions is called stdio.h

 

getchar Function

 

  • Single characters can be entered into the program using the C library function getchar.
  • The getchar function is a part of a standard C language I/O library.
  • It returns a single character from the standard input device.
  • The function does not require any arguments though a pair of empty parenthesis should follow the word getchar.

 

The general syntax is,

Character variable = getchar ( )

 

Where character variable refers to previously declared character variable.

Eg :

 

char c;

 

……

 

c = getchar();

 

scanf function

 

  • A library function used to Input data into the computer from a standard device.

 

  • This function can be used to enter any combination of  numerical values, single characters and strings.

 

In general scanf function can be written as

 

scanf (control string, arg1, arg2 , arg3 , ….., arg n)

 

Where control string refers to a string containing certain required formatting information and arg1,arg2 … arg n are arguments that represent the individual input data items.

 

  • The control string comprises of individual group of characters, with one character group for each input data item.

 

  • Each character group must begin with a percent sign ( % ) followed by a conversion character.

 

 The most frequently used conversion characters are,

 

Character                                                                   Meaning

 

   c                                                       data item is a single character

   d                                                       data item is a decimal integer

   e                                                       data item is a double value

   f                                                        data item is a floating point value

   s                                                        data item is a string followed by white space

Eg :

 

#include <stdio.h>

 

main()

{

            char item[20] ;

            int number;

            float cost;

            ………

            scanf(“%d, %f ”,&number, &cost);

            ………

}

 

the control string is “%d, %f “. It contains two character groups.

 

  • The first character group, %d, indicates that the first argument( number) represents a decimal integer value

 

  • The second character group, %f, indicates that the second argument(cost) represents floating point number.

 

  • All arguments other than array names should be preceded by an ampersand as in number and cost.

 

DATA OUTPUT

 

putchar Function

 

  • Single characters can be displayed using the C library function putchar.
  • The putchar function is complementary to the getchar function.
  • It transmmits a single character to the standard output device.
  • It must be expressed as an argument to the function, enclosed in parenthesis.

 

The general syntax is,

 

putchar(character variable)

 

Where character variable refers to previously declared character variable.

 

Eg :

 

char c;

 

……

 

putchar(c);

 

 The first statement declares c as a character type variable. The second statement causes a current value c to be transmitted to the standard output device.

printf Function

 

  • It is a library function which is used to output data from the computer onto a standard output device
  • This function can be used to output any combination of numerical values, single characters and strings.
  • The printf function moves data from the computers memory to the standard output device.

 

In general printf  function can be written as

 

            printf ( control string, arg1, arg2 , arg3 , ….., arg n )

 

Where control string refers to a string containing certain required formatting information and arg1,arg2 … arg n are arguments that represent the individual input data items.

 

  • The control string comprises of individual group of characters, with one character group for each input data item.

 

  • Each character group must begin with a percent sign ( % ) followed by a conversion character.

 

  • The conversion characters used are same as the one used in scanf function.

 

Eg :

 

#include <stdio.h>

 

main()

{

            int number;

            float cost;

 

            ………

 

            printf(“%d, %f ”, number, cost);

            ………

}

 

The control string is “ %d, %f “. It contains two character groups. The first character group, %d, indicates that the first argument( number) represents a decimal integer value

The second character group, %f, indicates that the second argument(cost) represents floating point number.

 

Note : All the arguments are not preceded by an ampersand.

 

 This differ from the scanf function which requires ampersands for all arguments other than array names.

 

 

 

 

 

 

 

Decision MakingIntroduction, Decision making with IF statements, SWITCH statements, Break statements, Continue statements and GOTO statements

 

CONTROL STRUCTURE

 

IF ELSE

 

The if statements allows branching (decision making) depending upon the value

or state of variables.

This allows statements to be executed or skipped, depending upon

decisions.

 

The basic syntax is,

 

 

if (expression)

   statement1 or block ;

else

   statement2 or block ;

                       

 

The expression is evaluated and if the expression is True, statement1 is executed. If the expression is False (if the expression is zero) then statement 2 is executed.

Eg :

 

if(result >= 45)

   printf(“Pass “);

else

   printf(” Fail”);

 

Here the expression (result >= 45) is evaluated and if the value of the result variable is

greater than or equal to 45 then Pass is printed. If the value is less than 45 then Fail is printed.

 

BLOCK 

 

If we wish to have more than one statement following if or the else, they should be grouped together between curly brackets. Such a grouping is called a compound statement or a block.

 

Example of use of a statement:

 

if(result >= 45)

printf(“Passed\n”);

else

printf(“Failed\n”);

 

 

 

 

 

 

Example of use of a block:

 

if(result >= 45)

{ 

    printf(“Passed\n”);

    printf(“Congratulations\n”)

}

else

{  

    printf(“Failed\n”);

    printf(“Better luck next time\n”);

}

 

NESTED IF

 

  • Is the way of doing a multi-way decision based on several conditions.
  • The way it is done is  by using the else if variant on the if statement.
  • Works by cascading several comparisons.
  • As soon as one of these gives a true result, the following statement or block is executed, and no further comparisons are performed.

 

 The general syntax for this is

 

if(expression1)

{

   statements ;

}

else if(expression2)

{

   statements ;

}

else if(expression3)

{

   statements ;

}

Consider the example to award grades depending on the exam result.

 

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”);

 

In this example, all comparisons test a single variable called result. In other cases, each test may involve a different variable or some combination of tests. The same pattern can be used with more or fewer else if’s, and the final lone else may be left out. It is up to the programmer to devise the correct structure for each programming problem.

 

 

 

SWITCH

The Switch statement is a multi-way decision that tests whether an expression matches one of a number of constant  values, and branches accordingly.

 The general syntax is,

 

            switch(expression) {

 

case value1:

program statement;

program statement;

          ……

break;

case valuen:

          program statement;

     …….

break;

default:

          …….

…….

break;

}

 

  • The keyword break must be included at the end of each case statement.
  • The default clause is optional, and is executed if the cases are not met. The right brace at the end signifies the end of the case selections.

Eg :

#include <stdio.h>

 

main()

{

int menu, numb1, numb2, total;

 

     printf(“Enter in two numbers –>”);

     scanf(“%d %d”, &numb1, &numb2 );

     printf(“Enter in choice\n”);

     printf(“1=Addition\n”);

     printf(“2=Subtraction\n”);

     scanf(“%d”, &menu );

 

     switch(menu) {

             case 1: total = numb1 + numb2;

 break;

     case 2: total = numb1 numb2;

 break;

                 default: printf(“Invalid option selected\n”);

             }

if(menu == 1)

printf(“%d plus %d is %d\n”,numb1,numb2, total);

else if( menu == 2 )

printf(“%d minus %d is %d\n”,numb1,numb2, total);

 

}

 

Sample Program Output

 

   Enter in two numbers –> 25 10

   Enter in choice

   1=addition

   2=subtraction

   2

   25 minus 10 is 15

 

NOTE

 

Switch is well structured, but can only be used in certain cases where

  • Only one variable is tested, all branches must depend on the value of that variable.
  • Each possible value of the variable can control a single branch. A final, catch all, default branch may optionally be used to trap all unspecified cases.

 

 

Branching and Looping-Introduction, WHILE statements, DO statements, FOR statements, Jumps in loops

 

LOOPS

C gives you a choice of three types of loop, while, do while and for.

 

  • WHILE
  • DO WHILE
  • FOR

 

WHILE LOOP

 

  • The while loop keeps repeating an action until an associated test returns false.
  • This is useful where the programmer does not know in advance how many times the loop will be traversed.

 

The Syntax is,

 

while(expression)

 

{

statement1 ;

            statement2 ;

            statement3 ;

            ..…..

            …….

            ….…

statementn ;

}

 

 

 

 

 

 

 

Eg :

 

#include <stdio.h>

 

main()

{

int i = 1;

while ( i <  5 )

{

                        printf ( “%d\n”,i);

                        i++;

}

 

}

 

Sample Program Output:

 

1

2

3

4

 

Here the while loop first checks the value of i and if its less than 5 it prints the value and the value of i is incremented by 1.The loop continues till the expression ( i <  5 ) becomes false i.e  if the value of i is greater than or equal to 5.

 

DO WHILE

 

  • The do while loops is similar, but the test occurs after the loop body is executed.
  • This ensures that the loop body is run at least once.

 

 

 The syntax is,

 

do

{

            statements;

}

while(expression) ;

 

 

  • The statements are executed and then expression is evaluated.

 

 

 

Eg :

 

#include <stdio.h>

 

main()

{

int i = 1;

 

do

{

                        printf(“%d\n”,i);

                        i++;

}

while(i < 5) ;

}

 

Sample Program Output :

 

1

2

3

4

 

 

The output is same as the example in while loop.

The only difference is that the condition is tested at the end.

The same example using while loop is shown below:

 

 

#include <stdio.h>

 

main()

{

int i = 1;

while(i < 5)

{

printf(“%d\n”,i);

                        i++;

}

 

}

 

Sample Program Output:

 

1

2

3

4

 

A COMMON EXAMPLE

 

while loop

 

 

#include <stdio.h>

 

main()

{

int i, j ;

i = 1;

j = i + 1;

while(j < 1)

{

                        printf(“%d\n”,j);

}

}

Sample Program output

 

Nothing will be printed

 

v     The value of i is initialized to 1

v     Then j is assigned a value i+1.

v     Now j will have a value 2.

v     The while loop condition fails as value of j is greater than 1.

v     So a nothing will be printed because the printf statement will not be executed.

do while Loop

 

 

#include <stdio.h>

 

main()

{

int i ,j ;

i = 1;

j = i + 1;

do

{

                        printf(“%d\n”,j);

}

while(j < 1) ;

}

 

 

Sample Program output

 

2

 

v     The value of i is initialized to 1

v     Then j is assigned a value i+1.

v     Now j will have a value 2.

v     Here the condition is tested only at the end. So the value of j is printed once even though the condition fails.

 

NOTE

 

Difference between while and do while :

 

            WHILE                                                           DO-WHILE

 

1.         Entry control structure                                   Exit control structure

2.         Loop may or may not be executed                     Loop is executed at least once

 

for Loop

 

 

  • The for loop is frequently used, usually where the loop will be traversed a fixed number of times.
  • It is very flexible.

 

The general syntax is,

 

for(expression1 ; expression2 ; expression3)

{

            statements ;

}

 

Eg :

 

Printing ten numbers using the while loop:

 

#include <stdio.h>

 

main() 

{

int  count=1;

     while(count<=10)

     {

printf(“%d “,count);

count = count+1 ;

            }

     printf(“\n”);

}

 

The same example using the for loop equivalent to while loop:

 

#include <stdio.h>

 

main() 

{

  int  count;

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

     {

printf(“%d “,count);

            }

     printf(“\n”);

}

 

 

Sample Program Output

 

1 2 3 4 5 6 7 8 9 10

 

v     The integer variable count is initialized to 1.

v     The for loop continues as long as the condition  (count <= 10 ) is True.

v     At the beginning of the program the value of count is 1 and the condition count <= 10 is satisfied, so the printf statement is executed.

v     The count is incremented by the condition count = count +1.

v     This process continues till the value of count reaches 11.

v     When the value of count is 11 then the condition fails and loop is exited.

 

 

BREAK

 

  • The break statement provides an early exit from loops.
  • The Break causes the innermost enclosing loop to be exited.
  • It can be used within while, dowhile, for or switch statement.

 

It is generally written as,

 

break;

Eg :

 

switch(choice)

{

 

            case ‘G’            :            { printf(“Green “);

                                                break; }

           

            case ‘Y’            :            { printf(“Yellow “);

                                                break; }

 

            case ‘R            :            { printf(“Red “);

                                                break; }

 

            case ‘V’            :            { printf(“Violet “);

                                                break; }

           

}

 

Here depending on the value of the variable choice, the corresponding block will be executed.

 Note : A break is given at each block  in order to transfer control out of the particular block and to prevent execution of the of succeeding group of statements.

 

CONTINUE

  • The continue statement is used to bypass the remainder of the current pass through a loop.
  • The loop does not terminate when a continue statement is encountered.
  • The remaining loop statements are skipped and the computation proceeds directly to the next pass of the loop.

 

It is simply written as ,

 

            continue;

Eg : A program to Print odd Numbers.

 

#include <stdio.h>

 

main()

{

int i;

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

{

if( (i%2)== 0 )

{ continue;}

printf(“%d\n”,i);

}

 

}

 

Sample Program output

 

1

3

5

7

9

 

  • In the for loop i is divided by 2 and the remainder is obtained by the modulus operator.
  • If the remainder is 0 then it’s a even number and is NOT printed.
  • So a continue here skips the printf statement  and proceeds to the next iteration.
  • Thus only the odd numbers between 1 and 10 are printed.

 

GOTO

 

The goto statement is used to alter the normal execution of the program by transferring the control to some other part of the program. The general syntax is,

 

goto label;

 

  • Label is the identifier used to label the target the statement to which the control is to be transferred.

 

NOTE : Each label in the program must have a unique label and no two

               labels should have the same label.

 

The target statement should appear as,

 

Label :              statements

 

Eg :

………

 

            if(x < 0) goto error;

 

            ………

 

error :            printf(“The Number is less than 0”);

 

 

 

All variables declared outside of a function are GLOBAL.

 ! Global variables have global scope, i.e., they are seen in ALL the functions.

 

! All variables declared within a function are LOCAL to that function.

 

! Local variables have local scope. They “exist” only within the function that declares them.

 

Pre-execution (checking) loops: (may never execute) for loop while loop

 

Post-execution (checking) loop: (executes at least once) do-while loop

 

for( init. cond. ; logic cond. ; increment )

{

statement(s) ;

}

 

Example:

for( x = 34; x < 1104; x++)

printf(“looping ”); //shortcut notation

 

while ( logic condition )

{

statement(s) ;

}

Example:

short x = 0;

while( x > 5)

x –;

 

do

{

statement(s) ;

}

while ( logic condition ) ;

Example:

do

x = x + 123; //shortcut notation

while( x < 12345 );

 

Preprocessors: General (1)

Preprocessors are executed before the program is compiled.

They specify how to the program should be compiled.

They can not be changed during the program execution.

All preprocessors start with the pound

sign (#) and do not have a semicolon at the end

 

Applications:

Write programs for different operating systems

Debugging!

Preprocessor Examples:

 

 

  1. ishwariya
    October 11, 2010 at 3:06 AM

    i want unit 3 portion of notes for fundamentals of computing and programming

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: