Thursday, 24 November 2022

Bharat College C Programming 2nd Unit

 

                                           Unit-II

Programming in C including features of C: It is a structured, high-level, machine independent language. The root of all modern languages is ALGOL, introduced in the early 1960s. ALGOL was the first computer language to use a block structure. Although it never became popular in USA, it was widely used in Europe. ALGOL gave the concept of structured programming to the computer science community. In 1967, Martin Richards developed a language called BPCL (Basic Combined Programming Language) primarily for writing system software. In 1970, Ken Thompson created a language using many features of BPCL and called it simply B. B was used to create early versions of UNIX operating system at Bell Laboratories. Both BPCL and B were “typeless” system programming languages.

            C was evolved from ALGOL, BPCL and B by Dennis Ritchie at Bell Laboratories in 1972. C uses many concepts from these languages and added the concept of data types and other powerful features. Since it was developed along with the UNIX operating system, it is strongly associated with UNIX. This operating system, which was also developed at Bell Laboratories, was coded almost entirely in C. UNIX is one of the most popular network operating systems in use today and the heart of the Internet data superhighway. For many years, C was used mainly in academic environments, but eventually with the release of many C compilers for commercial use and the increasing popularity of UNIX, it began to gain widespread support among computer professionals. Today, C is running under a variety of operating system and hardware platforms.

            During 1970s, C had evolved into what is now known as traditional C. The language became more popular after publication of the book “The C Programming Language” by Brian Kerningham and Dennis Ritchie in 1978. The rapid growth of C led to the development of different versions of the language that were similar but often incompatible. To assure that the C language remains standard, in 1983. American National Standards Institute (ANSI) appointed a technical committee to define a standard for C. The committee approved a version of C in 1989 which is now known as ANSI C. Then it was approved by the International Standards Organization (ISO) in 1990. The standard was updated in 1999.

            The increasing popularity of C is probably due to its many desirable qualities. It is a robust language whose rich set of built-in functions and operators can be used to write any complex programs. The C complier combines the capabilities of an assembly language with the features of a high-level language and therefore it is well suited for writing both system software and business packages. In fact, many of the C compliers available in the market are written in C. Programs written in C are efficient and fast. This is due to its variety of data types and powerful operators. It is many times faster than BASIC. For example, a program to increments a variable from 0 to 15000 takes about one second in C while it takes more than 50 seconds in an Interpreter BASIC.

            There are only 32 keywords and its strength lies in its built-in functions. Several standard functions are available which can be used for developments programs. C is highly portable. This means that C programs written for one computer can be run on another with little or no modification. Portability is important if we plan to use a new computer with a different operating system. C language is well suited for structured programming, thus requiring the user to think of a problem in terms of functions modules or blocks. A proper collection of these modules would make a complete program. This modular structure makes program debugging, testing and maintenance easier. Another important feature of C is its ability to extends itself. A C program is basically a collection of functions that are supported by the C library. We can continuously add our own functions to C library. With the availability of a large number of functions, the programming task becomes simple.

For example:

            Main()

            {

                        /* ……….Printing Begins…………*/

                        Printf(“ I see, I remember”);

                        /*…………Printing ends………..*/

            }

Write a program to add two numbers.

            Main()

            {

                        Int number;

                        Float amount;

                        Number = 100;

                        Amount = 30.75+75.35;

                        Printf(“ %d\n”, number);

                        Printf(“ %5.2f”, amount);

            }

Basic Structure of C Programs:  C program can be viewed as a group of building blocks called functions. A function is a subroutine that may include one or more statements designed to perform a specific task. To write a C program, we first create functions and then put them together. A C program may contain one or more sections.

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

            Documentation Section

            Link Section

            Definition Section

            Global Declaration Section

            Main() Function Section

            {

                        Declaration part

                        Executable part

            }

            Subprogram section

                        Function 1

                        Function 2

                        Function 3                                            (user-defined functions)

                        …………

                        …………

                        Function n

The documentation section consists of a set of comment lines giving the name of the program, the author and other details, which the programmer would like to use later. The link section provides instruction to the compiler to link functions from the system library. The definition section defines all symbolic constants. There are some variables that are used in more than one function. Such variables are called global variables and are declared in the global declaration section that is outside of all the functions. This section also declares all the user-defined functions. Every C program must have one main() function section. This section contains two parts, declaration part and executable part. The declaration part declares all the variables used in the executable part. There is at least one statement in the executable part. These two parts must appear between the opening and closing braces. All statements in the declaration and executable parts end with a semicolon. The subprogram section contains all the user-defined functions that are called in the main function. User-defined functions are generally placed immediately after the main function, although they may appear in any order. All sections, except the main() function section may be absent when they are not required.

C Tokens: In a passage of text, individual words and punctuation marks are called tokens. Similarly, in a C program the smallest individual units are known as C tokens. C has six types of tokens. C programs are written using these tokens and the syntax of the language.

  1. Keywords such as float, while
  2. Identifies such as main, amount
  3. Constants such as -15.5, 100
  4. Strings such as “ABC”, “Year”
  5. Special Symbols such as {}, []
  6. Operators such as +, -, *, /

Variables: A variable is a data name that may be used to store a data value. Unlike constant that remain unchanged during the execution of a program, a variable may take different values at different times during execution. A variable name can be chosen by the programmer in a meaningful way so as to reflect its function or nature in the program. For example

Average

Height

Total

Counter_1

Class_strength

As you know, variable names may consist of letters, digits, and the underscore (_) character, subject to the following conditions:

  1. They must begin with a letter. Some systems permit underscore as the first character.
  2. ANSI standard recognizes a length of 31 characters. However, length should not be normally more than eight characters, since only the first eight characters are treated as significant by many compilers.
  3. Uppercase and lowercase are significant. That is, the variable Total is not the same as total or TOTAL.
  4. It should not be a keyword.
  5. White space is not allowed.

For example: John, Value, T_raise, Delhi, x1, ph_value, mark, sum1, distance

Invalid Example: 123, (area), %, 25th

 

Expression – In C, an expression is anything that evaluates to a numeric value. C expressions come in all levels of complexity.

            The simplest C expression consists of a single item: a simple variable, literal constant, or symbolic constant. Here are four expressions:

 

Expression                                             Description

 

PI                                                 A symbolic constant (defined in the program)

20                                                 A literal constant

Rate                                               A variable

-1.25                                             Another literal constant

 

(A literal constant evaluates to its own value. A symbolic constant evaluates to the value it was given when you created it using the #define directive. A variable evaluates to the current value assigned to it by the program.)

            Complex expression consists of simpler expressions connected by operators. For example 2+8 is an expression consisting of the sub-expression 2 and 8 and the addition operator +. The expression 2+8 evaluates, as you know, to 10.

When an expression contains multiple operators, the evaluation of the expression depends on operator precedence.

C expression gets even more interesting.  X=a+10 this statement evaluates the expression a +10 and assign the result to x. In addition the entire statement x=a+10 is itself an expression that evaluates to the value of the variable on the left side of the equal sign.

A mathematical expression is any expression containing mathematical operators. For example +, -, *, /, %

An expression containing relational operators is known as a relational expression. For example >, >=, ==, <, <=, .

 

Identifiers – Identifiers are fundamental building blocks of a program and are used as the general terminology for the names given to different parts of the program viz. variables, functions, arrays etc.

            An identifier is a sequence of letters and digits. The first character must be a letter; the underscore _ counts as a letter. Upper and lower case are different. All characters are significant. For example

Myfile, DATE9_7_77, MYFILE, _DS,

The following are some invalid identifiers:

DATA-REC       contain special character –

29CLCT              starting with a digit

break                    reserved keyword

 

Keywords: Every C word is classified as either a keyword or an identifier. All keywords have fixed meaning and these meanings can not be changed. Keywords serve as basic building blocks for program statements. The list of all keywords of ANSI C are listed in table. All keywords must be written in lowercase.

Auto                            double                         int                                struct

Break                          else                              long                             switch

Case                            enum                           register                                    typedef

Char                            extern                          return                          union

Const                           float                            short                            unsigned

Continue                     for                               signed                         void

Default                                    goto                             sizeof                          volatile

Do                               if                                 static                           while

 

Data Types - A computer essentially is an input/output system where some data is fed, and some desirable output is provided after processing the data, as desired by the programmer. The way the data is stored and processed depends upon the type of data. For example, the integer number 15 and real number 15.00 are stored in different ways. The computer memory is measured in terms of bytes. Only two bytes are required for storing the integer number 15. But four bytes are required if the same number is stored as 15.00. That is why it is required to declare all the variables used in your program.

 

The Integer Type (Family)- Suppose a variable x can be assigned only an integer number. Such a variable can be declared as:

Int x;

The above declaration reserves two bytes of memory for storing the number. Such a variable can store a number lying between –32768 to 32767. In order to increase the range, you can add qualifiers to the declarations. The allowable qualifiers are unsigned and long. A variable can be declared as an unsigned integer, long integer or unsigned long integer. If a variable is declared as an unsigned integer, it can store a number lying between 0 to 65535. If a variable is declared as long integer the computer reserves four bytes of memory for its storage. It can store any number in the range –2,147,483,648 to 2,147,483,647. If a number is declared as an unsigned long, it can store any number in the range of 0 to 4,294,967,295. Unsigned integer, long integer and long unsigned integers can be declared as given below:

Unsigned int        var_name;

Long int               var_name;

Long                     var_name;

Long unsigned int var_name;

Where var_name is the name of the variable to be declared. The second and third declarations are equivalent. Either of them declares the variable to be long integer.

 

The Float Family – A real variable in C language is declared as float if it can store any variable within the range –3.4*1038 to 3.4*1038 . The stored variable will have accuracy up to eight places after the decimal point. If the variable is required to store values beyond this range it should be declared as double. A double variable can store any value in the range –1.08*10308 to 1.08*10308 . A float variable requires four bytes for it’s storage and a variable declared as double is assigned eight bytes of storage space. Syntax for declaration of float and double variables is as under:

Float    var_name;

Double var_name;

Where var_name is the name of the variable, which is to be declared.

 

The Character Family – A variable, which is required to store a single character as its value, can be declared as a character variable. A character variable can have any upper case letter, lower case letter, numeric character, punctuation character and some special character as its value. Each character has a number associated with it. This is known as the ASCII (American Standard Code of Information Interchange) number. For example, the ASCII number for ‘A’ is 65. For this reason, a variable storing a single character can also be declared as an integer. The syntax of declaring a character variable is given below:

Char variable_name;

Where variable_name is the name of the variable to be declared.

 

Constants: Constants in C refer to fixed values that do not change during the execution of a program. C supports several types of constants as illustrated in figure :

Constants

                       

           

                        Numeric Constants                                                     Character Constants

 

 


Integer Constants                    Real Constants                       

 

Single Character Constants                String Constants

 

Integer Constants: An integer constant refers to a sequence of digits. There are three types of integers, namely, decimal integer, octal integer and hexadecimal integer.

            Decimal integers consists of a set of digits, 0 through 9, preceded by an optional – or + sign. For example: 123            -321                 0                      654321                        +78

Embedded spaces, commas and non-digit characters are not permitted between digits. For example:

            15 750             20,000                         $1000 are illegal numbers.

            An octal integer constant consists of any combination of digits from the set 0 through 7, with a leading 0. For example:     037      0          0435                0551

            A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer. They may also include alphabets A through F or a through f. The letter A through F represent the numbers 10 through 15. For example: 0X2                  0x9F                0Xbcd             0x

We rarely use octal and hexadecimal numbers in programming.

            The largest integer value that can be stored in machine-dependent is 32767 on 16-bit machines and 2,147,483,647 on 32-bit machines. It is also possible to store larger integer constants on these machines by appending qualifiers such as U, L and UL to the constants. For example

            56789U           or         56789u            (unsigned integer)

            987612347UL             OR 987612347UL      (Unsigned long integer)

            9876543L        or 9876543l    (long integer)

For example: representation of integer constants on a 16-bit computer

 

Main()

{

            Printf(“Integer Values\n\n”);

            Printf(“%d %d %d\n”, 32767, 32767+1, 32767+10):

            Printf(“\n”);

            Printf(“Long Integer Values\n\n”);

            Printf(“%ld %ld %ld\n”, 32767L, 32767L+1L, 32767L+10L);

}

Output

Integer Values

32767              -32768             -32759

Long Integer Values

32767              32768              32777

 

Real Constants: Integer numbers are inadequate to represent quantities that vary continuously, such as distances, heights, temperatures, prices, and so on. These quantities are represented by numbers containing fractional parts like 17.548. Such numbers are called real (or floating point) constants. Further examples of real constants are:

            0.0083             -0.75                435.36             +247.0

These numbers are shown in decimal notation, having a whole number followed by a decimal point and the fractional part. A real numbers may also be expressed in exponential (or scientific) notation. For example, the value 215.65 may be written as 2.1565e2 in exponential notation. E2 means multiply by 102 . the general form is

                        Mantissa e exponent

The mantissa is either a real number expressed in decimal notation or an integer. The exponent is an integer number with a optional plus or minus sign. Since the exponent causes the decimal point to “float”, this notation is said to represent a real number in floating point form. For example

            0.65e4             12e-2               1.5e+5             3.18E3             -1.2E-1

            Exponential notation is useful for representing numbers that are either very large or very small in magnitude. For example, 7500000000 may be written as 7.5E9 or 75E8. Similarly, -0.0000000368 is equivalent to -3.68E-7.

            Floating point constants are normally represented as double-precision quantities. However, the suffixes f or F may be used to force single-precision and l or L to extend double precision further.

Single Character Constants: A single character constant (or simply character constant) contains a single character enclosed within a pair of single quote marks. For example:

            ‘5’                   ‘X’                  ‘;’                     

The last constant is a blank space.

            Character constants have integer values known as ASCII values. For example, the statement

                        Printf(“%d”, ‘a’);

Would print the number 97, the ASCII values of the letter a. Similarly, the statement

                        Printf(“%c”, ‘97’);

Would output the letter ‘a’.

String Constants: A string constants is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters and blank space. For example:

            “Hello”           “1987”            “WELL DONE”         “?....!”             “5+3”              “X”

Remember that a character constant (e. g., ‘X’) is not equivalent to the single character string constant ( e. g., “X”). Further, a single character string constant does not have an equivalent integer value while a character constant has an integer value.

Backslash Character Constants: C supports some special backslash character constants that are used in output functions. For example, the symbol ‘\n’ stands for newline character. A list of such backslash character constants is given in Table:

Constant

Meanings

‘\a’

Audible alert

‘\b’

Back space

‘\f’

Form feed

‘\n’

New line

‘\r’

Carriage return

‘\t’

Horizontal tab

‘\v’

Vertical tab

‘\’’

Single quote

‘\”’

Double quote

‘\?’

Question mark

‘\\’

Backslash

‘\0’

null

 

Operators – An operator is a symbol that instructs C to perform some operations, or action, on one or more operands. An operand is something that an operator acts on. In C, all operands are expressions. C operators fall into several categories:

  • The assignment operator
  • Mathematical operator
  • Relational operator
  • Logical operator

 

The Assignment Operator- The assignment operator is the equal sign. Its use in programming is somewhat different from its use in regular math. If you write

X=y;

In a C program, it does not mean, “x is equal to y”. Instead, it means, “assign the value of y to x”. In a C assignment statement, the right side can be any expression, and the left side must be a variable name. Thus, the form is follows:

Variable=expression;

 

The Mathematical Operators- C’s mathematical operators perform mathematical operations such as addition and subtraction. C has two unary mathematical operators and five binary mathematical operators.

The Unary Mathematical Operators- the unary mathematical operators are so named because they take a single operand. C has two unary mathematical operators, which are listed in table

Operator           Symbol              Action                                        Examples

Increment          ++                     Increments the operand by one    ++x, x++

Decrement         --                      Decrement the operand by one      --x, x—

 

The increment and decrement operators can be used only with variables, not with constants. The operations performed are to be adding one to or subtract one from the operand. In other words, the statements

++X;

--Y;

are the equivalent of these statements?

X = x+1;

y= y-1;

You should note from table that either unary operator could be placed before its operand (prefix mode) or after its operand (postfix mode). These two modes are not equivalent. They differ in terms of when the increment or decrement is performed:

  • When used in prefix mode, the increment and decrement operators modify their operand before it’s used.
  • When used in postfix mode, the increment and decrement operators modify their operand after it’s used.

 

For example

X = 10;

Y = x++;

After these statements are executed, x has the value 11, and y has the value 10. The value of x was assigned to y, and then x was incremented. In contrast, the following statements result in both y and x having the value 11. X is incremented, and then its value is assigned to y.

X=10;

Y=++x;

For example (Program)-

 

#include<stdio.h>

int a, b;

Main ()

{

a=b=5;

printf(“\n Post      Pre”);

printf(“\n %d        %d”, a--,  --b);

printf(“\n %d        %d”, a--,  --b);

printf(“\n %d        %d”, a--,  --b);

printf(“\n %d        %d”, a--,  --b);

printf(“\n %d        %d\n”, a--,  --b);

}

 

The Binary Mathematical Operator – C’s binary operators take two operands. The binary operators, which include the common mathematical operations found on a calculator, are listed

+, -, *, /, %

The first four operators listed should be familiar to you. The fifth operator, modulus, might be new. Modulus returns the remainder when the first operand is divided by the second operand. For example 11 modulus 4 equal 3.

The precedence of C’s mathematical operators.

Operators                                Relative Precedence

++    --                                     1

*  /  %                                     2

+    -                                        3

 

The Relational Operators – C’s relational operators are used to compare expressions, asking questions such as “ Is x greater than 100?” or “Is y equal to 0?” An expression containing a relational operator evaluates to either true or false. C’s six relational operators are listed in Table

 

Operator                                  Symbol                                   Example

Equal                                       = =                                           x = = y

Greater Than                           >                                              x > y

Less Than                               <                                              x < y

Greater Than or equal to         > =                                          x > = y

Less than or equal to               < =                                          x < = y

Not equal                                ! =                                           x ! = y

Relational operators are used mainly to construct the relational expressions used in if and while statements.

The Precedence of Relational Operators – Like the mathematical operators, the relational operators each have a precedence that determines the order in which they are performed in a multiple-operator expression.

Operators                                Relative Precedence

< <= > >=                                1

!=   = =                                    2

 

The Logical Operators – Sometimes you might need to ask more than one relational questions at once. For example “ If it’s 7:00 a.m. and a weekday and not my vacation, ring the alarm “. C’s logical operators let you combine two or more relational expression into a single expression that evaluates to either true or false. They are listed here

Operator                      Symbol                                   Example

AND                      &&                                  exp1 && exp2

OR                               | |                                             exp1 || exp2

NOT                            !                                               ! exp1

The Precedence of Operators – C’s logical operator also has a precedence order, both among themselves and in relation to other operators. The ! Operator has a precedence equal to the unary mathematical operators ++ and --. Thus ! has a higher precedence than all the relational operators and all the binary mathematical operators.

               In contrast, the && and || operators have much lower precedence, lower than all the mathematical and relational operators, although && has a higher precedence than ||.

 

The Conditional Operator – The conditional operator is C’s only ternary operator, meaning that it takes three operands. Its syntax is

Exp1 ? exp2 : exp3;

If exp1 evaluates to true, the entire expression evaluates to the value of exp2. If exp1 evaluates to false, the entire expression evaluates as the value of exp3. For example, the following statement assigns the value 1 to x if y is true and assigns 100 to x if y is false:

X = y ? 1 : 100;

Bitwise Operators – As you may know, the most basic unit of computer data storage is the bit. There are times when being able to manipulate individuals bits in your C program’s data is very useful.

            The C bitwise operators let you manipulate the individual bits of integer variables. Remember, a bit is the smallest possible unit of data storage, and it can have only one of two values: 0 or 1. The bitwise operators can be used only with integer types: char, int and long. The bitwise operators are most frequently used when your C program interacts directly with your system’s hardware.

The Shift Operators- Two shift operators shift the bits in an integer variable by a specified number of positions. The << operator shifts bits to the left, and the >> operator shifts bits to the right. The syntax for these binary operators is

X << n

And

X >> n

Each operator shifts the bits in x by n positions in the specified direction. For a right shift, zeros are placed in the n high order bits of the variables; for a left shift, zeros are placed in the n low-order bits of the variable. Here are a few examples:

Binary 00001100(decimal 12) right-shifted by 2 evaluates to binary 00000011(decimal 3)

Binary 00001100(decimal 12) left-shifted by 3 evaluates to binary 01100000(decimal 96)

The Bitwise Logical Operators – Three bitwise logical operators are used to manipulate individual bits in an integer data type, as shown in table

Operator                         Action

 &                                   AND

 |                                     Inclusive OR

 ^                                   Exclusive OR

These are all binary operators, setting bits in the result to 1 or 0 depending on the bits in the operands. They operate as follows:

  • Bitwise AND sets a bit in the result to 1 only if the corresponding bits in both operands are 1 ; otherwise, the bit is set to 0. The AND operator is used to turn off, or clear , one or more bits in a value.
  • Bitwise inclusive OR sets a bit in the result to 0 only if the corresponding bits in both operands are 0 ; otherwise the bit is set to 1. The OR operator is used to turn on, or set, one or more bits in a value.
  • Bitwise exclusive OR sets a bit in the result to 1 if the corresponding bits in the operands are different (if one is 1 and the other is 0); otherwise, the bit is set to 0.

The rules that decide the value of the resultant bit are shown below:

Bitwise AND operator:

            First bit                       Second bit                   Result(First bit & Second Bit)

            0                                  0                                  0

            0                                  1                                  0

            1                                  0                                  0

            1                                  1                                  1

Bitwise OR operator:

            First bit                       Second bit                   Result(First bit | Second bit)

            0                                  0                                  0

            0                                  1                                  1

            1                                  0                                  1

            1                                  1                                  1

Bitwise XOR operator:

            First bit                       Second bit                   Result(First bit ^ Second bit)

            0                                  0                                  0

            0                                  1                                  1

            1                                  0                                  1

            1                                  1                                  0

The Complement Operator- The final bitwise operator is the complement operator ~. This is a unary operator. Its action is to reverse every bit in its operand, changing all 0s to 1s and vice versa. For example, ~254(binary 11111110) evaluates to 1(binary 00000001).

 

Precedence and Associativity of Operators: 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. There are distinct level of precedence and an operator may belong to one of these levels. The operator 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. This is known as the associativity property of an operator. Table provides a complete list of operators, their precedence level and their rules of association. The groups are listed in the order of decreasing precedence. Rank 1 indicates the highest precedence level and 15 the lowest.

Operator

Description

Associativity left to right

Rank

( )

[ ]

Function Call

Array element reference

Left to right

1

+

-

++

--

!

~

*

 

&

Sizeof

(type)

Unary Plus

Unary Minus

Increment

Decrement

Logical negation

Ones complement

Pointer reference (indirection)

Address

Size of an object

Type cast (conversion)

Right to left

2

*

/

%

Multiplication

Divisions

Modules

Left to right

3

+

-

Addition

Subtraction

Left to right

4

<< 

>> 

Left shift

Right shift

Left to right

5

< 

<=

> 

>=

Less than

Less than or equal to

Greater than

Greater than or equal to

Left to right

6

= =

!=

Equality

Inequality

Left to right

7

&

Bitwise AND

Left to right

8

^

Bitwise XOR

Left to right

9

|

Bitwise OR

Left to right

10

&&

Logical AND

Left to right

11

||

Logical OR

Left to right

12

?:

Conditional expression

Right to left

13

=

*=  /=   %=

+=   -=   &=

^=   |=

<<=   >>=

Assignment operators

Right to left

14

,

Comma operator

Left to right

15

 

Type conversion in expression

Implicit Type Conversion:- C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without loosing any significance. This automatic conversion is known as implicit type conversion.

            During evaluation it adheres to very strict rules of type conversion. If the operands are of different types, the lower type is automatically converted to the higher type before the operation proceeds. The result is of the higher type. Given below is the sequence of rules that are applied while evaluating expressions.

            All short and char are automatically converted to int; then

  1. If one of the operands is long double, the other will be converted to long double and the result will be long double.
  2. Else, if one of the operands is double, the other will be converted to double and the result will be double.
  3. Else, if one of the operands is float, the other will be converted to float and the result will be float.
  4. Else, if one of the operands is unsigned long int, the other will be converted to unsigned long int and the result will be unsigned long int.
  5. Else, if one of the operands is long int and the other is unsigned int, then

·       If unsigned int can be converted to long int, the unsigned int operand will be converted as such and the result will be long int.

·       Else, both operands will be converted to unsigned long int and the result will be unsigned long int.

  1. Else, if one of the operands is long int, the other will be converted to long int and the result will be long int.
  2. Else, if one of the operands is unsigned int, the other will be converted to unsigned int and the result will be unsigned int.

 

Conversion hierarchy

Long double

                                                                                                                        Double

                                                                                                            Float

                                                                                                Unsigned long int

                                                                                    Long int

                                                                        Unsigned int

                                                            Int

                                                Short               char

 

Note that some version of C automatically converts all floating-point operands to double precision. The final result of an expression is converted to the type of the variable on the left of the assignment sign before assigning the value of it.

 

Explicit Conversion:- We know that C performs type conversion automatically. However, there are instances when we want to force a type conversion in a way that is different from the automatic conversion. For example, the calculation of ratio of females to males in a town.

                        Ratio= female_number/male_number

Since female_number and male_number are declared as integers in the program, the decimal part of the result of the division would be lost and ratio would represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as shown below:

                        Ratio = (float) female_number/male_number

The operator (float) converts the female_number to floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed in floating point mode, thus retaining the fractional part of result.

            The process of such as local conversion is known as explicit conversion or casting a value. The general form of a cast is:

            (type – name) expression

Where type-name is one of the standard C data types. The expression may be a constant, variable or an expression. Some examples of casts and their actions are shown in table

Example

Action

X= (int) 7.5

7.5 is converted to integer by truncation

A=(int) 21.3/(int) 4.5

Evaluated as 21/4 and the result would be 5

B=(double) sum/n

Division is done in the floating point mode.

Y=(int)(a+b)

The result of a+b is converted to integer

Z=(int) a+b

A is converted to integer and then added to b

P=cos((double)x)

Converts x to double before using it.

 

 

 

Basic input/output and library functions: Reading , processing and writing of data are the three essential functions of a computer program. Most program take some data as input and display the processed data, often known as information or results. Normally we use two methods of providing data to the program variables. One method is to assign values to variables through the assignment statements such as x=5; a=0; and so on. Another method is to use the input function scanf which can read data from a keyboard. For outputting results we used the function printf which sends results out to a terminal. All input/output operations are carried out through function calls such as printf and scanf. There exist several functions that have more or less become standard for input and output operations in C. These functions are collectively known as the standard I/O library.

            Each program that uses a standard input/output functions must contain the statement #include<stdio.h> at the beginning. The file name stdio.h is an abbreviation for standard input-output header file. The instruction #include<stdio.h> tells the complier to search for a file named stdio.h and place its contents at this point in the program. The contents of the header file become part of the source code when it is complied.

           

Single character input/output: The simplest of all input/output operations is reading a character from the standard input unit and writing it to the standard output unit.

Getch()

Getchar(): It is used to read a single character. The getchar takes the following form:

                        Variable_name = getchar();

Variable_name is a valid C name that has been declared as char type. Single getchar is used on the right-hand side of an assignment statement, the character value of getchar is in turn assigned to the variable name of the left. For example

                        Char name:

                        Name = getchar();

Will assign the character ‘H’ to the variable name when we press the key H on the keyboard.

For example program:

            #include<stdio.h>

            Main()

            {

                        Char answer;

                        Printf(“ Would you like to know my name?\n”);

                        Printf(“ Type Y for YES and N for NO:”);

                        Answer=getchar();     /* reading a character */

                        If(answer = = ‘Y’ || answer = = ‘y’)

                                    Printf(“\n\n My name is Busy Bee\n”);

                        Else

                                    Printf(“\n\n You are good for nothing\n”);

            }

 

 

Getche()

Putchar(): Like getchar, there is an analogous function putchar for writing characters one at a time to the terminal. It takes the form as shown below:

            Putchar(variable_name);

Where variable_name is a type char variable containing a character. This statement display the character contained in the variable_name at the terminal. For example,

            Answer = ‘Y’;

            Putchar(answer);

Will display the character Y on the screen.

For example program:

            #include<stdio.h>

            #include<ctype.h>

            Main()

            {

                        Char alphabet;

                        Printf(“ Enter an alphabet”);

                        Putchar(‘\n’);

                        Alphabet = getchar();

                        If(islower(alphabet))

                                    Putchar(toupper(alphabet));

                        Else

                                    Putchar(tolower(alphabet));

            }

           

Formatted input/ output

Printf(): The printf statement provides certain features that can be effectively exploited to control the alignment and spacing of print-outs on the terminals. The general form of printf statement is

            Printf(“control string”, arg1, arg2,….argn);

Control string consists of three types of items:

  1. Characters that will be printed on the screen as they appear.
  2. Format specifications that define the output format for display of each item.
  3. Escape sequence characters such as \n, \t, and \b.

The control string indicates how many arguments follow and what their types are. The arguments arg1, arg2,……argn are the variables whose values are formatted and printed according to the specifications of the control string. The arguments should match in number, order and type with the format specifications.

            A simple format specification has the following form:

             %w,p type specifier

Where w is an integer number that specifies the total number of columns for the output value and p is another integer number that specifies the number of digits to the right of the decimal point(of a real number) or the number of characters to be printed from a string. Both w and p are optional. Some examples of formatted printf statement are:

                        Printf(“Programming in C”);

                        Printf(“ “);

                        Printf(“\n”);

                        Printf(“%d”, x);

                        Printf(“a= %f\n b= %f”, a, b);

                        Printf(“sum = %d”, 1234);

                        Printf(“\n\n”);

            The format specification for printing an integer number is

            % w d

Where w specifies the minimum field width for the output. However, if a number is greater than the specified field width, it will be printed in full, overriding the minimum specification. d specifies that the value to be printed is an integer. The number is written right-justified in the given field width. Leading blanks will appear as necessary. For example

                        Format                                                 Output

                        Printf(“%d”, 9876);                            |9|8|7|6|

                        Printf(“%6d”, 9876);                          |  |  |9|8|7|6|

                        Printf(”%-6d”, 9876);                         |9|8|7|6|  |  |

                        Printf(“%06d”, 9876);                        |0|0|9|8|7|6|

            Long integers may be printed by specifying ld in the place of d in the format specification. Similarly, we may use hd for printing short integers.

The output of a real number may be displayed in decimal notation using the following format specification:

            %w.p f

The integer w indicates the minimum number of positions that are to be used for the display of the value and the integer p indicates the number of digits to be displayed after the decimal point. The value, when displayed, is rounded to p decimal places and printed right justified in the field of w columns. The default precision is 6 decimal places. The negative numbers will be printed with the minus sign. We can also display a real number in exponential notation by using the specification

            % w.p e

The following examples illustrate the output of the number y= 98.7654 under different format specifications:

                        Format                                                 Output

                        Printf(“%7.4f”,y)                               |9|8| . |7|6|5|4|

                        Printf(“%7.2f”,y)                               |  |  |9|8| . |7|7|

                        Printf(“%-7.2f”,y)                              |9|8| . |7|7|  |  |

                        Printf(“%f”,y)                                    |9|8| . |7|6|5|4|

                        Printf(“%10.2e”,y)                             |  |  |9| . |8|8|e|+|0|1|

A single character can be displayed in a desired position using the format

            %wc

The character will be displayed right-justified in the field of w columns. We can make the display left-justified by placing a minus sign before the integer w. The default value for w is 1.

The format specification for outputting strings is similar to that of real numbers. It is of the form

            %w.ps

Where w specifies the field width for display and p instructs that only the first p characters of the string are to be displayed. The display is right-justified.

For example

 

Specification                                      Output

%s

N

E

W

 

D

E

L

H

I

 

1

1

0

0

0

1

 

 

 

 

%20s

 

 

 

 

N

E

W

 

D

E

L

H

I

 

1

1

0

0

0

1

%20.10s

 

 

 

 

 

 

 

 

 

 

N

E

W

 

D

E

L

H

I

 

%.5s

N

E

W

 

D

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

%-20.10s

N

E

W

 

D

E

L

H

I

 

 

 

 

 

 

 

 

 

 

 

%5s

N

E

W

 

D

E

L

H

I

 

1

1

0

0

0

1

 

 

 

 

 

           

Scanf(): Formatted input refers to an input data that has been arranged in a particular format. For example, consider the following data:

                        15.75               123                  John

The first part of the data should be read into a variable float, the second into int, and the third part into char. This is possible in C using the scanf function. The general form of scanf is

            Scanf(“control string”, arg1,arg2,….argn);

The control string specifies the field format in which the data is to be entered and the arguments arg1, arg2,…..argn specify the address of location where the data is stored. Control string may include:

  • Field (or format) specifications, consisting of the conversion character %, a data type character (or type specifier), and an optional number, specifying the filed width.
  • Blanks, tabs, or newlines

Blanks, tabs and newlines are ignored. The data type character indicates the type of data that is to be assigned to the variable associated with the corresponding argument. The field width specifier is optional. The field specification for reading an integer number is:

                        % w d

The percent sign(%) indicates that a conversion specification follows, w is an integer number that specifies the field width of the number to be read and d, known as data type character, indicates that the number to be read is in integer mode. For example:

            Scanf (“%2d  %5d”, &num1, &num2);

Data line:                                50           31426

The value 50 is assigned to num1 and 31426 to num2.

Unlike integer numbers, the field width of real numbers is not to be specified and therefore scanf reads real numbers using the simple specification %f for both the notations, namely, decimal point notation and exponential notation. For example, the statement

            Scanf(“%f %f %f”, &x, &y, &z);

With the input data

            475.89             43.21E-1         678

If the number to be read is of double type, then the specification should be %lf instead of simple %f.

A single character can be read using the scanf function also. In addition, a scanf function can input strings containing more than one character. Following are the specifications for reading character strings:

            %ws                or                     %wc

However, %c may be used to read a single character when the argument is a pointer to a char variable.

 

Branching Constructs: You know that a C program is a set of statements which are normally executed sequentially in the order in which they appear. However, if you have a number of situations where you may have to change the order of execution of statements based on certain conditions, or repeat a group of statements until certain specified conditions are met. This involves a kind of decision making to see whether a particular condition has occurred or not and then direct the computer to execute certain statements accordingly.

C language have such decision-making capabilities by supporting the following statements:

  1. If statement
  2. Switch statement
  3. Conditional operator statement
  4. Goto statement

 

If-else: The if statement is a powerful decision-making statement and is used to control the flow of execution of statements. It is basically a two-way decision statement and is used in conjunction with an expression. It takes the following form:

            If(test expression)

It allows the computer to evaluate the expression first and then, depending on whether the value of the expression is true or false, it transfers the control to a particular statement. Some examples of decision-making, using if statements are:

  1. If (bank balance is zero)

Borrow money

  1. If (room is dark)

Put on lights

  1. If (code is 1)

Person is male

  1. If (age is more than 55)

Person is retired

            The if statement may have different forms depending on the condition to be tested. The different forms are:

  1. Simple if Statement
  2. If…….else statement
  3. Nested if……else statement
  4. Else if ladder

The general form of a simple if statement is

                        If(test expression)

                        {

                                    Statement-block;

                        }

                        Statement-x;

The statement block may be a single statement or a group of statements.

Program:- Write a program to reads four values a, b, c, and d from the terminal and evaluates the ratio of (a+b) to (c-d) and prints the result, if c-d is not equal to zero.

            Main()

            {

                        Int a, b, c, d;

                        Float ratio;

                        Printf(“Enter four integer values\n”);

                        Scanf(“ %d %d %d %d”, &a, &b, &c, &d);

                        If (c-d !=0)

                        {

                                    Ratio = (float)(a+b)/(float)(c-d);

                                    Printf(“Ratio = %f\n”, ratio);

                        }

            }

Program:- Write a program to counts the number of boys whose weight is less than 50 kg and height is grater than 170 cm.

            Main()

            {

                        Int count, f;

                        Float weight, height;

                        Count=0;

                        Printf(“Enter weight and height for 10 boys\n”);

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

                        {

                                    Scanf(“%f %f”, &weight, &height);

                                    If(weight<50 && height >170)

                                    Count= count+1;

                        }

                        Printf(“Number of boys with weight <50 kg\n);

                        Printf(“ and height>170 cm=%d\n”, count);

            }

The if …..else statement is an extension of the single if statement. The general form is

            If (test expression)

                        {

                        True-block statement(s)

                        }

            Else

                        {

                        False-block statement(s)

                        }

            Statements-x;

Program:

            Main()

            {

                        Int a, b, c, d;

                        Float ratio;

                        Printf(“Enter four integer values\n”);

                        Scanf(“ %d %d %d %d”, &a, &b, &c, &d);

                        If (c-d !=0)

                        {

                                    Ratio = (float)(a+b)/(float)(c-d);

                                    Printf(“Ratio = %f\n”, ratio);

                        }

                        Else

                        Printf(“c-d is zero\n”);

            }

 

When a series of decision are involved, we may have to use more than one if….else statement in nested form as shown below:

            If(test condition-1)

                        {

                        If (test condition-2)

                                    {

                                                Statement -1;

                                    }

                        Else

                                    {

                                                Statement-2;

                                    }

                        }

                        Else

                                    {

                                                Statement-3;

                                    }

                                                Statement-x;

Program:- Write a program to select and prints the largest of the three numbers using nested if……..else statements.

            Main()

            {

            Float A, B, C;

            Printf(“Enter three values\n”);

            Scanf(“%f %f %f”, &A, &B, &C);

            Printf(“\n Largest value is”);

            If (A>B)

            {

                        If (A>C)

                        Printf(“%f\n”, A);

                        Else

                        Printf(“%f\n”, C);

            }

            Else

            {

                        If (C>B)

                        Printf(“%f\n”, C);

                        Else

                        Printf(“%f\n”, B);

            }

            }

There is another way of putting ifs together when multipath decisions are involved. A multipath decision is a chain of ifs in which the statement associated with each else is an if. It takes the following form:

            If (condition 1)

                        Statement-1;

            Else if (condition 2)

                        Statement-2;

            Else if (condition 3)

                        Statement-3;

            Else if (condition n)

                        Statement -n;

                        Else

                        Default-statement;

            Statement-x;

This construct is known as the else if ladder.

Program:- An electric power distribution company charges its domestic consumers as follows:

            Consumption units                                         rate of charges

            0 – 200                                                            Rs. 0.50 per unit

            201-400                                                           Rs. 100 plus Rs. 0.65 per unit excess of 200

            401-600                                                           Rs. 230 plus Rs. 0.80 per unit excess of 400

            601 and above                                                 Rs. 390 plus Rs. 1 per unit excess of 600

Write a program to reads the customer number and power consumed and prints the amount to be paid by the customer.

            Main()

            {

                        Int units, custnum;     

                        Float charges;

                        Printf(“Enter Customer No. and Units Consumed\n”);

                        Scanf(“ %d %d”, &custnum, &units);

                        If (units<=200)

                        Charges = 0.5*units;

                        Else if (units<=400)

                                    Charges = 100+0.65*(units-200)

                                    Else if (units<=600)

                                                Charges= 230+0.8*(units-400)

                                                Else

                                                Charges= 390+(units-600)

                        Printf(“\n\n Customer No: %d: Charges = %.2f\n”, custnum, charges);

            }

 

Switch: - You know that when one of the many alternatives is to be selected, we can use an if statement to control the selection. However, the complexity of such a program increases dramatically when the number of alternatives increases. The program becomes difficult to read and follow. At times, it may confuse even the person who designed it. Fortunately, C has a built-in multiway decision statement known as a Switch. The switch statement tests the value of a given variable against of a case values and when a match is found, a block of statements associated with that case is executed. The general form of the switch statement is as shown below:

            Switch(expression)

            {

                        Case value-1;

                                    Block-1

                                    Break;

                        Case value-2;

                                    Block-2

                                    Break;

                        ……………….

                        ……………….

                        Default:

                                    Default-block

                                    Break;

            }

            Statement-x;

The break statement at the end of each block signals the end of a particular case and causes an exit from the switch statement, transferring the control to the statement-x following the switch.

The default is an optional case. When present, it will be executed if the value of the expression does not match with any of the case values. If not present, the control goes to the statement-x.

 

If statement: already discussed with If

If…….else statement: already discussed with If

 

Nesting of If …. Else statement: already discussed with If

 

Else if ladder: already discussed with If

 

The Conditional operator ( ? ,  : operator): The C language has an unusual operator, useful for making two-way decisions. This operator is a combination of ? and : and takes three operands. This operator is popularly known as the conditional operator. The general form of use of the conditional operator is as follows:

            Conditional expression ? expression1 : expression2

For example, the segment

            If(x<0)

                        Flag=0;

            Else

                        Flag=1;

Can be written as

            Flag = (x<0) ? 0 :1;

 

The Goto statement: Like many other languages, C supports the goto statement to branch unconditionally from one point to another in the program. Although it may not be essential to use the goto statement in a highly structured language like C, there may be occasions when the use of goto might be desirable.

            The goto requires a label in order to identify the place where the branch is to be made. A label is any valid variable name and must be followed by a colon. The label is placed immediately before the statement where the control is to be transferred. The general forms of goto and label statements are shown below:

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

            Goto label;                                                                                          label:

…………………………….                                                                           Statement;

…………………………….                                                                           ………………………….

………………………………                                                                        ………………………….

            Label:                                                                                                  ………………………….

            Statement;                                                                                          goto label;

 

The label can be anywhere in the program either before or after the goto label statement. A goto is often used at the end of a program to direct the control to go to the input statement, to read further data. For example:

            Main()

            {

                        Double x, y;

                        Read:

                        Scanf(“%f”, &x);

                        If (x<0) goto read;

                        Y= sqrt(x);

                        Printf(“%f %f\n”, x, y);

                        Goto read;

            }

 

                       

 

Loop Controls: In looping, a sequence of statements are executed until some conditions for termination of the loop are satisfied. A program loop therefore consists of two segments, one known as the body of the loop and the other known as the control statement. The control statement tests certain conditions and then directs the repeated execution of the statements contained in the body of the loop.

            Depending on the position of the control statement in the loop, a control structure may be classified either as the entry-controlled loop or as the exit-controlled loop. In the entry-controlled loop, the control conditions are tested before the start of the loop execution. If the conditions are not satisfied, then the body of the loop will not be executed. In the case of an exit-controlled loop, the test is performed at the end of the body of the loop and therefore the body is executed unconditionally for the first time. The entry-controlled and exit-controlled loops are also known as pre-test and post-test loops respectively.

            In general, a looping process would include the following four steps:

  1. Setting and initialization of a condition variable.
  2. Execution of the statements in the loop.
  3. Test for a specified value of the condition variable for execution of the loop.
  4. Incrementing or updating the condition variable.

The C language provides for three constructs for performing loop operations. They are:

  1. The while statement.
  2. The do-while statement.
  3. The for statement.

 

 

For: The for loop is another entry-controlled loop that provides a more concise loop control structure. The general form of the for loop is

            For( initialization; test-condition; increment)

            {

                        Body of the loop

            }

The execution of the for statement is as follows:

  1. Initialization of the control variables is done first, using assignment statements such as i=1 and count=0. The variable I and count are known as loop-control variables.
  2. The value of the control variables is tested using the test-condition. The test condition is a relational expressions, such as i<10 that determine when the loop will exit. If the condition is true, the body of the loop is executed; otherwise the loop is terminated and the execution continues with the statement that immediately follows the loop.
  3. When the body of the loop is executed, the control is transferred back to the for statement after evaluating the last statement in the loop. Now, the control variable is incremented using an assignment statement such as i=i+1 and the new value of the control variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied, the body of the loop is again executed. This process continues till the value of the control variable fails to satisfy the test condition.

For example:

            For(x=0; x<=9; x=x+1)

            {

                        Printf(“%d”, x);

            }

            Printf(“\n”);

Write a program to print the “powers of 2” table for the power 0 to 20, both positive and negative.

            Main()

            {

                        Long int p;

                        Int n;

                        Double q;

                        Printf(“-------------------------------------------------------------\n”);

                        Printf(“ 2 to power n               n                      2 to power -n\n”);

                        Printf(“--------------------------------------------------------------\n”);

                        P=1;

                        For(n=0; n<21; ++n)

                        {

                                    If (n = = 0)

                                                P=1;

                                    Else

                                                P=p*2;

                                    Q=1.0/(double)p;

                                    Printf(“%10ld %10d %20.12lf\n”;, p, n, q);

                        }

                        Printf(“------------------------------------------------------------------\n”);

            }

 

While: The simplest of all the looping structures in C is the while statement. The basic format of the while statement is

            While(test condition)

            {

                        Body of the loop

            }

The while is an entry-controlled loop statement. The test-condition is evaluated and if the condition is true, then the body of the loop is executed. The body of the loop may have one or more statements. The braces are needed only if the body contains two or more statements. For example:

            Sum=0;

            N=1;

            While(n<=10)

            {

                        Sum = sum + n*n;

                        N=n+1;

            }

            Printf(“sum = %d\n”, sum);

Write a program to evaluate the equation y=xn when n is a non-negative integer.

            Main()

            {

                        Int count, n;

                        Float x, y;

                        Printf(“ Enter the values of x and n :”);

                        Scanf(“%f %d”, &x, &n);

                        Y=1.0;

                        Count=1;

                        While(count <= n)

                        {

                                    Y=y*x;

                                    Count++;

                        }

                        Printf(“\n x = %f; n = %d; x to power n = %f\n”, x, n, y);

            }

 

Do-While Loops: The while loop construct makes a test of condition before the loop is executed. Therefore, the body of the loop may not be executed at all if the condition is not satisfied at the very first attempt. On some occasions it might be necessary to execute the body of the loop before the test is performed. Such situations can be handled with the help of the do statement. This takes the form:

            Do

            {

                        Body of the loop

            }

            While(test-condtion);

On reaching the do statement, the program proceeds to evaluate the body of the loop first. At the end of the loop, the test-condition in the while statement is evaluated. If the condition is true, the program continues to evaluate the body of the loop once again. This process continues as long as the condition is true. When the condition becomes false, the loop will be terminated and the control goes to the statement that appears immediately after the while statement. It is a exit-controlled loop. A simple example of a do…while loop is:

            Do

            {

                        Printf(“Input a number\n”);

                        Number = getnum();

            }

            While(number>0);

Jumps in loops:- Loops perform a set of operations repeatedly until the control variables 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.

Break: An early exiting from a loop can be accomplished by using the break statement or the goto statement. These statements can also be used within while, do or for loops.

            When a break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately following the loop. When the loops are nested, the break would only exit from the loop containing it. That is, the break will exit only a single loop.

            While(…….)

            {

                        ………………………………………..

                        ……………………………………….

                        If (condition)

                                    Break;

            }

Program:- Write a program to reads a list of positive values and calculates their average. The for loop is written to read 1000 values. However, if we want the program to calculate the average of any set of values less than 1000, then we must enter a negative number after the last value in the list, to mark the end of input.

            Main()

            {

                        Int m;

                        Float x, sum, average;

                        Printf(“ This program computes the average of a set of numbers\n);

                        Printf(“ Enter values one after another\n”);

                        Printf(“ Enter a negative number at the end.\n\n”);

                        Sum=0;

                        For(m=1; m<=1000; ++m)

                        {

                                    Scanf(“%f’”, &x);

                                    If(x<0)

                                    Break;

                                    Sum += x;

                        }

                        Average = sum/(float)(m-1);

                        Printf(“\n”);

                        Printf(“Number of values = %d\n”, m-1);

                        Printf(“ Sum                     = %f\n”, sum);

                        Printf(“Average                =%f\n”, average);

            }

 

 

Continue:- Like the break statement, C supports another similar statement called the continue statement. However, unlike the break which causes the loop to be terminated, the continue causes the loop to be continued with the next iteration after skipping any statements in between. The continue statement tells the compiler, “ Skip the following statements and continue with the next iteration”. The format of the continue statement is simply

            Continue;

In while and do loops, continue causes the control to go directly to the test-condition and then to continue the iteration process. In the case of for loop, the increment section of the loop is executed before the test condition is evaluated.

            While(test-condition)

            {

            …………………………

            If (……………………..)

            Continue;

            ………………………………

            ………………………………

            }

Program: Write a program to evaluates the square root of a series of numbers and prints the results. The process stops when the number 9999 is typed in.

            #include<math.h>

            Main()

            {

                        Int count, negative;

                        Double number, sqroot;

                        Printf(“Enter 9999 to Stop\n”);

                        Count = 0;

                        Negative = 0;

                        While(count<=100)

                        {

                                    Printf(“ Enter a number:”);

                                    Scanf(“%lf”, &number);

                                    If (number = = 9999)

                                    Break;

                                    If (number<0)

                                    {

                                    Printf(“Number is negative\n\n”);

                                    Negative++;

                                    Continue;

                                    }

                                    Sqroot= sqrt(number);

                                    Printf(“ Number     = %lf\n Square root = %lf\n\n”, number, sqroot);

                                    Count++;

                        }

                        Printf(“ Number of items done = %d\n”, count);

                        Printf(“\n\n Negative items = %d\n”, negative);

                        Printf(“End of Data\n”);

            }

No comments:

Post a Comment