Tuesday, February 1, 2011

Computer Programming Unit II (JNTU I YEAR)




Introduction to  c  language
a)      History of C Language
b)      Simple C Program
c)      Identifiers.
d)      Basic Data Types.
e)      Variables.
f)       Constants.
g)      Input/Output
h)      Operators.
i)        Expressions.
j)        Precedence and Associtivity.
k)      Expression Evaluation.
l)        Type Conversions.
m)    Bitwise Operators .
n)      Statements.
o)      Simple C Programming Exmples.
p)      Control Statements






            History  of  c  language :
The C programming language was developed in the early 1970s as a system implementation language for the nascent UNIX operating system. Derived from the type BCPL, it evolved a type structure; created on a tiny machine as a tool to improve insufficient programming environment, it has become one of the dominant languages of today.
C has often been termed as a "Pseudo high level language" or a "Middle level language" by many programmers. C is often called a middle-level language because it combines the best elements of low-level or machine language with high-level languages. This is not because of its lack of programming power but because of its capability to access the system's low level functions. In fact C was invented specifically to implement UNIX. C instructions are compiled to assembly code, therefore, depending on the complexity of the code and on the compiler optimization capabilities, C code may run as fast as assembly.
Ken Thompson created the B language in 1969 from Martin Richard's BCPL (Basic Combined Programming Language). He used assembly language and B to produce the initial versions of the UNIX operating system. BCPL and B were type less languages in which variables were simply words in memory. Dennis Ritchie of Bell Laboratories later converted B into C by retaining most of B's syntax in 1972 and wrote the first compiler. This was implemented on DEC's PDP 11 and it was first used as the system's language for rewriting the UNIX operating system. Later on, UNIX, its tools and C grew simultaneously. In 1978, Kernighan and Ritchie wrote a book entitled 'The C Programming Language' that became the language definition for almost a decade. Beginning in 1983, the ANSI X3J11 committee was asked to standardize the C language. The result was ANSI C, a standard which was adopted in 1988. It is not forced upon any programmer, but since it is so widely accepted, it would be economically unwise for any systems programmer or compiler writer not to conform to the standard.

Uses of C

C's wide acceptance and efficiency is the reason why libraries of several other applications are often implemented in C. Some of the applications using C in its kernels are: ; ,
Uses of C are many in addition to Systems programming. Some of which are as follows :;
·         Language compilers and interpreters
·         Device drivers
·         Telecom applications
·         Network programming
·         Digital Signal processing applications
·         Database applications
·         Text editors

Compilers available

Most flavors of UNIX operating system have a C compiler. So if a student has access to an UNIX system, he or she can straight away start coding and compiling C sample programs and exercises given in this course. With respect to personal computers , Microsoft C for IBM PC's and compatibles or Borland C are the two most commonly used programming environments. There are a number of free C compilers available on the web for installation on the PC, one can use them as well.

Future of C

The current popularity of C++ may seem to have displaced C's position in the programming world. But C is here to stay for a very long time. One main factor is that C++ has inherited most of its syntax from C but has incorporated several new concepts which form the basis of Object Oriented programming. It is better to know C in order to learn C++ though there are many who advocate the theory that one has to unlearn procedural programming habits in order to learn Object Oriented programming. GUI based C++ programming environments are more popular, and use lot of disk space and extended memory. They use complex class libraries and are not well suited for developing small programs that run on smaller systems. C is a better option when it comes to programming device drivers, embedded applications and utility programs.
Simple C program :

C program consists of one or more functions . Each function is a group or sequence of C statements that are executed together. Each C program starts with a Pre-Defined function called main( ).
The general Structure of a C program is




 Writing your first C program 

                The following is a simple C program that prints a message ‘Hello, world’ on the screen.
#include<stdio.h>
main( )
{
       printf(“Hello, world”);
}
The steps given below are used to type and run the program given above: 
1.      Go to the directory where you have installed Turbo C.
2.      Double click on TC application.
3.      In the edit window that opens, type the mentioned program above.
4.      Save the program as hello.c by pressing F2 or Alt + ‘S’.
5.      Press Alt + ‘C’ or Alt + F9 to compile the program.
6.      Press Alt + ‘R’ or Ctrl + F9 to execute the program.
7.      Press Alt + F5 to see the output.
Note: C is a case-sensitive language. It makes a distinction between letters written in lower and upper case. For example, ‘A’ and ‘a’ would be taken to mean different things. Also, remember that all C language keywords should be typed in lower case.

Understanding the program

In the program you saw above, the information enclosed between ‘/* */’ is called a ‘comment’ and may appear anywhere in a C program. Comments are optional and are used to increase the readability of the program.
 
The ‘#include’ in the first line of the program is called a preprocessor directive. A preprocessor is a program that processes the C program before the compiler. All the lines in the C program beginning with a hash (#) sign are processed by the preprocessor. 
‘stdio.h’ refers to a file supplied along with the C compiler. It contains ordinary C statements. These statements give information about many other functions that perform input-output roles. 
Thus, the statement ‘#include<stdio.h>’ effectively inserts the file ‘stdio.h’ into the file hello.c making functions contained in the ‘stdio.h’ file available to the programmer. For example, one of the statements in the file ‘stdio.h’ provides the information that a function printf() exists, and can accept a string (a set of characters enclosed within the double quotes). 

The next statement is the main() function. As you already know, this is the place where the execution of the C program begins. Without this function, your C program cannot execute. 
Next comes the opening brace ‘{’, which indicates the beginning of the function. The closing brace ‘}’ indicates the end of the function. 

The statement printf() enclosed within the braces‘{}’ informs the compiler to print (on the screen) the message enclosed between the pair of double quotes. In this case, ‘Hello, world’ is printed. As mentioned earlier, the statement printf() is a built-in function shipped along with the C compiler. Many other built-in functions are available that perform specific tasks. The power of C lies in these functions.

Be cautious about errors! 

Errors/bugs are very common while developing a program. If you don't detect them and correct them, they cause a program to produce wrong results. There are three types of errors — syntax, logical, and run-time errors. Let us look at them: 
1.       Syntax errors: These errors occur because of wrongly typed statements, which are not according to the syntax or grammatical rules of the language. For example, in C, if you don’t place a semi-colon after the statement (as shown below), it results in a syntax error.
printf(“Hello,world”) – error in syntax (semicolon missing)
printf("Hello,world"); - This statement is syntactically correct. 
2.       Logical errors: These errors occur because of logically incorrect instructions in the program. Let us assume that in a 1000 line program, if there should be an instruction, which multiplies two numbers and is wrongly written to perform addition. This logically incorrect instruction may produce wrong results. Detecting such errors are difficult.
3.       Runtime errors: These errors occur during the execution of the programs though the program is free from syntax and logical errors. Some of the most common reasons for these errors are
    1. when you instruct your computer to divide a number by zero.
    2. when you instruct your computer to find logarithm of a negative number.
    3. when you instruct your computer to find the square root of a negative integer.
Unless you run the program, there is no chance of detecting such errors.
Character set:

Characters used in C language can be classified as fallows.
Letters: A to Z, a to z.
Digits: 0 to 9.
Special characters: {, . , }, “, =, -, +,.etc.
White spaces:  Blank space, Carriage return, New line, Form feed.


Data Types:
Are the pre-defined words which are meant for a specific representation or nature of the variable to be used in the program.
Eg : int a;
       Char b;
       Char a[10] ; [ used to define string ]




Type
Typical Size in Bits
Minimal Range
char
8
–127 to 127
unsigned char
8
0 to 255
signed char
8
–127 to 127
int
16
–32,767 to 32,767
unsigned int
16
0 to 65,535
signed int
16
0 to 65,535
short int
16
–32,767 to 32,767
unsigned short int
16
0 to 65,535
signed short int
16
0 to 65,535
long int
32
–2,147,483,647 to 2,147,483,647
long long int
64
–(263) to 263 – 1
signed long int
32
–2,147,483,647 to 2,147,483,647
unsigned long int
32
0 to 4,294,967,295
unsigned long long int
64
264 – 1
float
32
3.4e-38 to 3.4e+38
double
64
1.7e-308 to 1.7e+308
long double
80
3.4e-4932 to 1.1e+4932
void
--
data type that not return any value

Conversion Specifiers:

Code
Format
%a
Hexa decimal output in the form of 0xh.hhhhp+d(
%s
String of characters (until null zero is reached )
%c
Character
%d
Decimal integer
%f
Floating-point numbers
%e
Exponential notation floating-point numbers
%g
Use the shorter of %f or %e
%u
Unsigned integer
%o
Octal integer
%x
Hexadecimal integer
%i
Signed decimal integer
%p
Display a pointer
%n
The associated argument must be a pointer to integer,
 This sepecifier causes the number of characters written in to be stored in that integer
%hd
short integer
%ld
long integer
%lf
long double
%%
Prints a percent sign (%)




Tokens :

Token is a sequence of one or more characters that have a uniform meaning. A token may be defined as the smallest  individual unit in a program. In c there are six classes of tokens:
     
1.     Keywords.
2.     Identifiers.
3.     Constants.
4.     Operators.
5.     Strings (string literals).
6.     Special symbols.

1.     Keywords: -

Keywords are the words, which has fixed meaning. All the keywords must be written in lower case letters and cannot be used as an identifier.

The standard key words are :



2.     Identifier:

Identifiers refer to the names of variables functions and arrays. These are user - defined names and consist of sequence of letters and digits with a letter as a first character both upper case and lower case letters are commonly used. The under score( _ ) character is also counted as a letter.

3.     Constants:

Constants in C language refer to fixed values that don’t change during the execution of a program. Variables, on the other hand, store data that may vary during program execution.

In programming, each variable actually refers to a memory location where a constant is stored. Every variable has a name. You should note the following rules before naming a variable: 

1.      Only alphabets, numerals, and underscores (_) are permitted (spaces and special symbols are not allowed).
2.      The name cannot start with a digit.
3.      Upper case and lower case letters are treated as different.
4.      A variable cannot be a C language keyword.

There are four character constant
 

·         Integer constants.
·         Decimal integer constants
·         Octal integer constants
·         Hexadecimal integer constants
·         Real Constants.
·         character constants.
·         Single character constant.
·         String character constant.
·         Back slash character constant.





Integer constants:

An integer constant refers to a sequence of digits. There are three types of integer constants.
·         Decimal integer constants
·         Octal integer constants
·         Hexadecimal integer constants



·         Decimal integer constants:
These integer constants consist of a set of digits 0 to 9 preceded by an optional sign.
E.g.: - 768, - 89, +30 etc.,

·         Octal integer constants:
Octal integer constants consist of any combination of digits from the set 0 through 7 with a leading 0.
E.g.: - 0123, 045, 0121 etc.,
Now consider an example :

main( )
{
int a;
a = 0121;
clrscr( );
printf("Integer  representation of %o = % d " , a , a ) ;
getch( );
}
Output :
Integer representation of 0121 : 81


    •  Hexadecimal integer constants:
A sequence of digits 0 to 9 proceeded by 0x or 0X is considered as hexadecimal i nteger constant we may also include alphabets a to f or A to F.

main( )
{
int a;
a = 0x 4c4;       
clrscr( );
printf("Integer  representation of %x = % d " , a , a ) ;
getch( );
}

Output :
Integer representation of  0x4c4 : 1220

Real Constants :

Numbers containing fractional parts are like 17.584 are called real ( or floating point ) constants.
E.g.: - 0.00083, +24.72, etc.,
These numbers are shown in decimal notation, having a whole number followed  by a decimal point and the fractional part. It is possible to omit digits before the decimal point or digits after the decimal point.
I.e. 25.
.98
.75
A real number may also be expressed in exponential (or scientific) notation.
Note: - It is used if the value of the constant is either too large or too small. The general form is

mantissa E e xponent

The mantissa is either a real number expressed in decimal notation or an integer the exponent is an integer number with an optional plus or minus sign. The letter e separating the mantissa and the exponent can be written in either
lower case or upper case.

E.g.: - 0.65e4, 12e-2, -1.2E - 1.

character constants :

An character constant refers to a sequence of characters. There are two types of character constants.
·         Single character constant.
·         String character constants.
·         Back slash character constant.


Single character constants:
A single character constant consist a single character enclosed with in a pair of single quote marks.
E.g.: - ‘a’, ‘*’, ‘”’, ‘ : ’ , ’ ; ’ , e t c . ,

String character constants :
A String character constant consist a Set of characters  enclosed with in a pair of double quote marks.
E.g : “ mukesh “ , “ INFORMATION TECHNOLOGY “ etc.,

Back slash character constant: -
C supports some special back slash character constants each one of them represents one character, although they consists of more than one character enclosed with in a pair of single quote marks.
E.g.: - ‘\ a ’ , ‘\ n’, ‘ \t ’ ,
Here is the sample program.

main( )
{
char c1 = '\ 101';
char c2 = '\x42';
clrscr( );
printf("\n c1 = %c",c1);
printf("\n c2 = %c",c2);
getch( );
}

4.     Operators :

An operator, in general, is a symbol that operat es on a certain datatype.
E.g.: - The operator + is the addition operator it can op erate on integer,
character, and real numbers.

Expression: -
An expression is a combination of variables, constants, and operators written according to the syntax of the language.
In c every expression evaluates to a value. i.e. many expressions results in some value of a certain type that can be
assigned to a variable.

Operands: -
The data items that operation acts upon are called operands.

There are 8 operators which are basically used in C language .
·         Arithmetic operators.
·         Relational operators.
·         Logical operators.
·         Assignement operators.
·         Increment and Decrement operators.
·         Conditional operators.
·         Bitwise operators.
·         Special operators

Arithmetic Operators:

C has the following five basic arithmetic operators.

Operator
Operation
+
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulo division

The percent operator produces the remainder of an integer division. The percent operator can not be used with floating point data.

Integer arithmetic: -
When both operands in arithmetic expression are integers then the expression is called integer arithmetic. Integer arithmetic always yields an integer value.
E.g.: - suppose a = 5, b=2 then
 a+b =7
 a-b=3,
 a*b=10,
 a/b=2,
 a%b=1.

Real arithmetic: -
An arithmetic expression involving only real operands is called real arithmetic. A real arithmetic always yields a real value.
E.g.: - a=5.o, b=2.o then
a+b=7.0
a/b=2.5.

Mixed mode arithmetic: -
When one of the operands is real and the other is i nteger, then the expression is called a mixed mode arithmetic expression. If either operand is of the real type then only the real operation is performed and the result is always
a real number.
E.g.: - 15/10.0=1.5.

Relational operators:

In C comparisons can be done with the help of relational operators. An expr ession containing relational operators is termed as a relational expression. C has the fol lowing relational operators.

Operator
Operation
Is less than
<=
Is less than or equal to
Is greater than
>=
Is greater than or equal to
==
Is equal to
     !=
Is not equal to

           
E.g.: - a<b, a>c etc.,
The value of the relational expression is either 1 or 0. It is one if the specified relation is true and zero if the relation is false.


Logical operators:

In C these operators are used to combine two or more relational expressions.Combining two or more relational expressions is termed as a logical expression.

Operator
Operation
&&
Logical AND
| |
Logical OR
!
Logical NOT

A logical expression also yields a value of one or zero.
E.g.: - a>b && a> c, !(a>b) etc.,


Assignment operator:

Assignment operators are used to assign the result of an expression to a variable. The assignment operator (=) eval uates the expression on the right and assigns the resulting value to the variable on the left. The general form of an assignment expression is
Variable=expression;
E.g.: - a+=5 ;  which is equal to a= a+5 ;
C also has a set of short hand assignment operators of the form.
V op = exp;
Where V is a variable name, exp is an expression and op is a ‘c’ binary
arithmetic or bit wise operator.
The op= is known as the short hand assignment operator.

Increment and decrement operators:

C has two very useful increment and dec rement operators ( ++ ), and ( --.)  The operator ++ adds 1 to the operand while – subtracts 1. Both are unary operators.
These operators can be used before the variable (++n) or after the variable (n++). If the operator is used before the operator is called prefix operator. If the operator is after the variable such operator is called postfix operator.
In both cases, the effect is to increment n but the expression ++n increment n before its value is used while n++ increments n after its value has been used. Consider the following example.
E.g.: -  If x=5;m=++x;   after execution m=6,x=6.
If x=5; m=x++; after execution m=5,x=6.

           
Conditional operator:

A ternary operator pair (?:) is available in c language to construct conditional expression of the following form.

Exp1 ? Exp2: Exp3;

In this expression the expression Exp1 is evaluated first, if it is nonzero (true) then the expression Exp2 is evaluated and its value becomes the value of the total expression; otherwise Exp3 is evaluated and its value bec omes the value
of the total expression.
E.g.:  Z=x>y? x* 2: y/ 2;   Suppose x=10,y=25 then z=x*2 ie 20.

Bit wise Operators:

Bit wise operators are used for manipulating the data at bit level these operators are used for testing the bits or shift ing them right or left.The bit wise operators can be divided into three general categories:


·         The logical bit wise operators.
·         The shift operators
·         The one’s complement operators.


·         Bit wise logical operators:
These are 3 logical bit wise operators. They are:

·         Bit wise AND(&)
·         Bit wise OR(|)
·         Bit wise exclusive OR(^). (XOR operator)
These are binary operators and require two integer type operands. These operators work as their operands bit by bit starting from the least significant ( i . e. the right most bit), setting each bit in the result as shown in the following
table. Result of Logical Bit wise operators.

A
B
A&B
A|B
A^B
1
1
1
1
0
1
0
0
1
1
0
1
0
1
1
0
0
0
0
0

           
·         Bit wise AND:
The bit wise AND operator is represented by a single ampersand (&) and is surrounded on both sides by integer expressions. The result of anding operation is 1 if the both the bits have a value of 1; other wise it is 0.

Suppose x=13, y=25, z=x&y.
X à 0000 0000 0000 1101
Y à 0000 0000 0001 1001
- - - - - - - - - - - - - - - - - - - - - - -
Z à 0000 0000 0000 1001
- - - - - - - - - - - - - - - - - - - - - - -
Note: - Bit wise AND is often used to test whether a particular bit is 1 or 0.The bit wise AND is often used to set a particular bit to 0(zero ).

E.g.: - The following program tests whether the fourth bit of the variable flag is 1 or 0.

main( )
{
int flag,test=8;
flag=69;
if( (flag & test) != 0 )
printf(“Fourth bit is 1”);
else
printf(“Fourth bit is 0”);
}

Another Program to test whether a given number is even or odd by using bit wise and operator.

main( )
{
int test=1;
int number;
printf(“Enter a number:”);
scanf(“%d”,&number);
if( number & test )
printf(“Number is odd”);
else
printf(“Number is even”);
}




·         Bit wise OR::
The bit wise OR is represented by the symbol | (vertical bar) and is surrounded by tow integer operands. The result of OR operation is 1 if at least one of the bits has a value of 1; otherwise it is zero.

E.g.: -
Suppose x=13, y=25, z=x|y.
X à 0000 00 00 0000 1101
Y à 0000 0000 0001 1001
 - - - - - - - - - - - - - - - - - - - - - - -
Z à 0000 0000 0001 1101
 - - - - - - - - - - - - - - - - - - - - - - -
Note: - The bit wise OR operation is often used to set a particular bit to 1.
E.g.: -
main( )
{
int flag,set=8;
flag=4;
flag=flag|set;
if( ( flag & set ) ! = 0 )
printf(“Fourth bit of flag is 1”);
else
printf(“Fourth bit of flag is 0”);
}

In the above program the statement flag=flag|set sets the fourth bit of flag to 1 if the fouth bit of flag to if it is 0 and does not change it if it is already 1.


·         Bit wise Exclusive OR:
The bit wise exclusive of is represented by the symbol ^. The result of exclusive OR is 1 if only one of the bits is 1; otherwise it is 0.Consider the following example

E.g.: -
Suppose x=13, y=25, z=x^y.
X à 0000 0000 0000 1101
Y à 0000 0000 0001 1001
 - - - - - - - - - - - - - - - - - - - - - -
Z à 0000 0000 0001 0100
 - - - - - - - - - - - - - - - - - - - - - -
Note: - It is used t o set a particular bit of a variable to 1 if it is 0 and to 0 if it is 1.
Eg:
main( )
{
int flag=31,set=8;
printf(“Before XOR operation the status of 4t h bit of flag is:”);
if( (flag & set) != 0 )
printf(“1”);
else
printf(“0”);
flag=flag^set;
printf(“After XOR operation the status of 4th bit of flag is:”);
if( (flag & set) != 0 )
printf(“1”);
else
printf(“0”);
}


    •  Bitwise Shift operators:

The sift operators are used to move bit patterns either to the left or to the right. The shift operators are represented by the symbols << and >> are used in the following form.

Left Shift: op << b
Right Shift: op >> b

Op is the integer expression that is to be shifted and b the number of bit positions to be shifted.

·         Left Shift : The left shift operation causes all the bits in the operand op to be shifted to the left by n positions. The left most n bits in the original bit pattern will be lost and the right most n bit positions that are vacated will be filled with 0’s.
·         Right Shift:  The right shift operation causes all the bits in the operand op to be shifted to the right by n positions. The right most n bits will be lost. The left most n bit positions that are vacated will be filled with zeros if the op is an
unsigned integer if the variable to be shifted is signed then the operation is machine dependent.

Note:
Both operands op and b can be constants or variables. There are tow restrictions on the value of b It may not be negative. It may not exceed the number of bits used to represent the left operand op.


  •  The ones Complement operator (~):
It is a unary operator that causes the bits of its operand to be inverted (i.e. reversed) so that 1s becomes 0s and 0s becomes 1s. This operator always precedes its operand.


X
~X
1
0
0
1

(The operand must be an integer type quantity (including integer, long, short, unsigned, or char)).

E.g.: - If x contain the following bit pattern
x à 1001 0110 1100 1011
~xà 0110 1001 0011 0100

This operator is often combined with the bit wise AND operator is to turn off a particular bit:

E.g.: - The statements
x=8; /* 0000 0000 0000 1000 */
flag=flag&(~x);
Would turn off the fourth bit in the variable flag.

Variable:

A variable is a named location in memory that is used to hold a value that may be modified by the program. Variable names may consist of letters, digits and underscore character subject to the following conditions: They must begin with a letter ANSI standard recognizes a length of 31 characters. Variable name should not be a keyword White spaces are not allowed

Declaration of variables:
The declaration of variable must be done at the beginning of the compound statement means just below the opening braces and above all other executable statements. The syntax for declaration of a variable is
<type> var1,var2,var3, … varn;

Where var1,var2,var3, … varn are names of variables separated by comas. The declaration statement must be end with semicolon.
E.g.:
main( )
{
int a, b;
printf("Enter values for a and b:");
scanf("%d%d",&a,&b);
if(a<b)
{
int x,y,z;
x = 2;
y = 3;
z = x + y;
}
}

Reading a character:
Reading a single character can be done by using the function getchar() as show in the follwing code.
E.g.:
char ch;
ch = getchar();

Writing a character:
putchar() is used for writing a character one at a time to the screen the general format of this statement is
putchar( variable name );
Here variable name is character variable containing a single character. We can also use a character constant instead of a variable name (To print a particular character).
E.g :
char ch=’a’;
putchar(ch);

By using scanf we can read single character with %c format specifier see the code below.

char c;
Scnaf(“%c”,&c);

Control statements:
Control statements are used to alter the flow of execution of the programs. They are:
  • Selective statements (or) Conditional Statements .
  • Iterative statements (or) Looping statements .
  • Jump statements (or) unconditional Statements


Including these control structures ‘C’ also has 3 statements they are label,expression, block statements.

Selective statements (or) Conditional Statements :
C supports two types of selection statements, ‘ If ‘ and ‘ switch ‘. In a ddition, the ? : Operator is an alternative to ‘ if ‘ in certain circumstances.

  • If statement:
The if-statement may be implemented depending on the complexity of conditions to be tested. The implemetation can be done in four types they are

·         simple if statement
·         if…else statement
·         nested if…else statement
·         else if ladder.

simple if statement :
If the exp is true, the statement gets executed; otherwise the statement will be skipped and the execution will jump to the statement-x. Remember when the condition is true both the statement and statement-x are executed in sequence.

The syntax of a simple if statement is:
if( condition )
<statement>;
<statement-x>;

The Flowchart of a simple if statment is :



/* Write a program to check a citizen is eligible for voting */
#include<conio.h>
#include<stdio.h>
int main()
{
    int age;
    clrscr();
    printf(“Enter the age : ”);
    scanf(“%d”,&age);
    if(age >= 18)
       printf(“Eligible for voting…”);
    getch();
}


The if…else statement:
If the test expression is true, then the true-block statement(s) gets executed; otherwise, the false-block statements are executed. In both the cases, the control is transferred statement-x.

Syntax:
if( condition )
{
true block statement ;
}
else
{
false block statement ;
}
Statement-x;

           
The Flowchart of a if....else statment is



/*Write a C Program to find largest number between two numbers.*/

#include<stdio.h>
main()
{
int i, j, larger;
printf(“Enter two numbers:”);
scanf(“%d%d”, &i, &j);
if( i > j )
larger = i;
else
larger = j;
printf(“largest = %d”, larger);
}

/* Write a C program to print a number is even or odd */
#include<stdio.h>
int main()
{
     int number;
     printf(“Enter a number : “);
     scanf(“%d”, &number);
     if((number %2) == 0)
{
         printf(“%d is even number.”,number);
}
     else
{
         printf(“%d is odd number.”,number);
}
}          

Nested if…else statements:
When a series of decisions are involved we may have to use more than one if…else statement in nested
If the condition-1 is false, the statement-3 will be executed; other wise it continues to perform the second test. If the condition-2 is true, the statement-1 will be executed; other wise statement-2 will be executed and then the control is transferred to the statement-x.

Syntax:
if ( test condition1 )
{
if( test condition2 )
{
statement-1;
}
else
{
statement-2;
}}
else
{
statement-3;
}
statement x;

            The Flowchart of a Nested if....else statment is



/*Write a C Program to find largest number among three numbers
#include<stdio.h>
main()
{
int a, b, c, lar;
printf(“Enter three Numbers:”);
scanf(“%d%d%d”, &a, &b, &c);
if( a > b )
{
if( a > c )
lar = a;
else
lar = c;
}
else
{
if( b > c )
lar = b;
else
lar=c;
}
}

/* Write a C Program to check whether a year is leap year or not */
#include<conio.h>
#include<stdio.h>
int main(  )
 {
int year;
printf("Enter the year ?");
scanf("%d",&year);
if((year %100) == 0)
{
if((year % 400) == 0)
printf("%d is leap year.",year);
else
printf("%d is not leap year.",year);
}
else
{
if((year % 4) == 0)
printf("%d is leap year.",year);
else
printf("%d is not leap year.",year);
}
getch();
}

Else..,if lader:
A multi path decision is a chain of ifs in which the statement associated with each else is an if. There is another way of putting ifs together when multi path decisions are involved.

The conditions are evaluated from the top (of the ladder), down words. As soon as a true condition is found, the statement associated with it is executed and the control is transferred to the statement-x   (skipping the rest of the ladder). When all the n conditions become false, the final else containing the defaultstatement will be executed.

Syntax:
if( exp1 )
statement 1;
else if ( exp2 )
statement 2;
else if( exp3 )
statement 3;
- - - - - - - -
- - - - - - - -
- - - - - - - -
else if ( exp-n )
statement n;
else
default-statement;
Statement x;
This construct is known as else if ladder.

The Flowchart of a else..if ladder statment is

/* Write a C program to print the grade of student */
#include<stdio.h>
#include<conio.h>
int main( )
 {
int marks;
clrscr( );
printf("Enter marks ? ");
scanf("%d", &marks);
if(marks >= 75)
printf("Distinction");
else if(marks >= 60)
printf("First class");
else if(marks >= 50)
printf("Second class");
else if(marks >= 35)
printf("Third class");
else
printf("Failed");
getch(  );
}

/* Write a CProgram to find grade of a particular student */
#include<stdio.h>
main( )
{
int rno;
float marks;
printf(“Enter roll Numbers:”);
scanf(“%d”,&rno);
printf(“Enter Avarage Marks:”);
scanf(“%f”,&marks);
if( marks > 79 )
printf(“Honours”);
else
if( marks > 59 )
printf(“First Division”);
else
if( marks > 49 )
printf(“Second Division”);
else
if( marks > 39 )
printf(“ 3 rd Division”);
else
printf(“Fail”);
}

  • The switch statement:
The switch statement is multi way decision that tests whether an expression matches one of a number of constant integer values and branches accordingly.
Each case is labeled by one or more integer-valued constants or constant expressions. If a case matches the expression value, execution starts at that case. All case expressions must be different. A default is optional; if it is not there and if none of the cases match, no action at all takes place. Cases and default clause can occur in any order.The break statement causes an immediate exit form the switch. Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape.
Syntax:
switch( expression )
{
case const-expr1:
statements;
break;
case const-expr2:
statements;
break;
--------
--------
--------
case const-exprn:
statements;
break;
default:
statements;
}





The Flowchart of Switch statment is



           
            /*Write a C  program to simulate a simple calculator */
#include<stdio.h>
int main() {
    float a,b;
    char opr;
    printf("Enter number1 operator number2 : ");
    scanf("%f %c %f",&a,&opr,&b);   
    switch(opr)
    {
        case '+':
             printf("Sum : %f",(a + b));
             break;
        case '-':
             printf("Difference : %f",(a - b));
             break;
        case '*':
             printf("Product : %f",(a * b));
             break;
        case '/':
             printf("Quotient : %f",(a / b));
             break;
        default:
             printf("Invalid Operation!");
    }
}

Iterative statements (or) Looping statements
Iteration statements allow a set of instructions to be executed repeatedly until a certain condition is reached. Loop constructs (Iteration statements) used in ‘c’ language are:
·         While
·         For
·         do…while

While 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. After the execution of the body, the test condition is once again evaluated and if it is true, the body is executed once again. This process of repeated execution of the body continues until the test-condition finally becomes false and the control is transferred out of the loop. On exit, the program continues with the statement immediately after the while loop.

Syntax:
while( condition )
{
body of loop ;
}

The Flowchart of While Loop statment is :


/* write a C program to sum of 1 to 10 numbers using While loop*/
#include<stdio.h>
int main() {
    int i = 1,sum = 0;
    while(i<=10){
         sum = sum + i;
         i = i + 1;
    } 
    printf(“Total : %d “,sum);
}   

/* Write a C program to find Largest Number among N Numbers using While Loop */
#include<stdio.h>
main()
{
int n, x, i, lar=0;
printf(“enter n:”);
scanf(“%d”,&n);
i=0;
printf(“Enter n values:”);
while( i<n )
{
scanf(“%d”,&x);
if( i==0 || x>lar)
lar = x;
i++;
}
printf(“Largest Number=%d”,lar);
}

For loop:
It is another entry-controlled loop and provides a more concise loop control structure.
When exp1 (expression1) is used to initialize some parameter that controls looping operation. exp2 (expression2) represents a condition that must be satisfied for the loop to continue the operation and exp3 (expression3) is used to change the value of parameter initially assigned by exp1. When for statement is executed, first exp1 is evaluated, exp2 is tested before each pass through the loop. exp3 is evaluated at the end of each pass.

Syntax:
for( initialization ; condition ; increment(or)decrement )
{
body of loop ;
}

The Flowchart of For Loop statment is :



/*Write a C Program to Find Factorial of a given number using For Loop */
#include<stdio.h>
main()
{
int n, fact, i;
clrscr();
printf(“Enter a Number:”);
scanf(“%d”,&n);
fact=1;
for(i=1;i<n; i++)
{
fact = fact * i;
}
printf(“Factorial = %d”,fact);
}

Do…while loop:
It is an exit-controlled loop statement.
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.

Syntax :
do
{
body of loop
}while( test-condition);

Note: The statements with in do…while loop are executed at least once. Since test for repetition does not occur until the end of first pass through the loop.

The Flowchart of Do...While Loop statment is :



/*Write a  program to find the G.C.D of the given 2 number using do-while loop. */
#include<stdio.h>
main()
{
int m, n, v;
printf(“\n Enter two Numbers:”);
scanf(“%d%d”, &n, &v);
do
{
m=n%v;
n=v;
v=m;
}while( m!= 0);
printf(“Gcd=%d”,m);
}

/* Write a C Program to find average of 5 natural numbers using do while */
#include<stdio.h>
int main() {
int count = 1;
float x,  sum = 0;
do {
printf(“x = “);
scanf(“%f”,&x);
sum += x;
++ count;
}  while(count <= 5);
printf(“Average = %f “, (sum/5))
}

Jump statements (or) unconditional Statements
C has four statements that perform an unconditional branch:
·         goto
·         break
·         continue
·         return

Goto statement:
C supports the goto statement to branch unconditionally form 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.

Syntax:
goto label;

Where the label may be any valid c-variable name.The label statement can be written in the following form:

label: statement;
or
label:
statement;

Because of goto statement the control flow is transferred to the statement having the specified label.

Break statement:
The break statement is used to terminate loops (or) to exit from switch statement this statement can be used with in a while, do…while, for, or a switch statement. When the keyword break is encountered inside a loop then the control automatically passes to the first statement after the loop. Break is usually associated with an if statement.
           
Syntax :

break;

/*Write a C program to find wheterher a given number is prime or not.using Break Statment */
#include<stdio.h>
#include<conio.h>
Void main( )
{
int n, c, flag=1;
clrscr();
printf(“Enter Number:”);
scanf(“%d”,&n);
c=2;
while( c <= n/2 )
{
if( n%c = = 0)
{
flag = 0;
break;
}
c ++;
}
if( flag = = 1 )
printf(“Prime Number”);
else
printf(“Not Prime Number”);
}

Continue statement: -
Like the break statement c supports another similar statement called continue statement. However, unlike the break which causes the loop to be terminated, the continue, as the name implies, 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”.
Syntax:

continue;

Note: It is used in while, do…while, and for loops.In while and do…while loops, continue causes the control to go directly to the iteration process. In the case of for loop, the increment section (exp3) of the loop is executed before the test-condition is evaluated.

/*Write a C program to print odd number <= 10 using continue statement.*/
#include<stdio.h>
#include<conio.h>
main()
{
int i;
clrscr();
printf(“Odd Numbers <=10:”);
i=0;
while(i < 10)
{
i++;
if(I%2 == 1)
continue;
printf(“ %d”,i);
}
}

Return statement:
The return statement is used to return form a function. It is categorized as a jump statement because if causes execution to return (jump back) to the point at which the call to the function was made.
Syntax:

return;
return (exp);

The first return does not return any value it acts as closing braces of the function. When return is encountered the control is immediately transferred back to the calling function. The second form of return with an expression returns the value of the expression.
A function may have more than one return statement.

 


Precedence and Associativity of Operators:

Precdence Group    
Operators
Associativity
(Highest to Lowest ) (param) subscript etc.,
( ), [ ] , –> ,.    
L à R
Unary operators
- , + , ! ,~ ,++ , – – .  (type) , & , sizeof
R à L
Multiplicative
* , / , %
L à R
Additive         
+ , –
L à R
Bitwise shift
<<  , >>          
L à R
Relational
<,<=,>,>=
L à R
Equality        
= =, !=
L à R
Bitwise AND
&
L à R
Bitwise exclusive OR
^
L à R
Bitwise OR
|
L à R
Logical AND
&&
L à R
Logical OR
| |
L à R
Conditional
?:
R à L
Assignment
=,+=.–=,*=,/=,%=,&=,^=,|=,<<=, >>=
R à L
Comma         
,
L à R


Important Functions in math.h :

·         abs(x)            absolute value of integer x
·         ceil(x)             rounds up and returns the smallest integer greater than or equal to x
·         floor(x)           rounds down and returns the largest integer less than or equal to x
·         log(x)             returns natural logarithm
·         pow(x,y)        returns the value of xy
·         sqrt(x)            returns square root of x
·         exp(x)                        returns natural anti logarithm
·         sin(x)              returns sine value where x in radians
·         cos(x)                        returns cosine value where x in radians
·         tan(x)             returns tangent values where x in radians
·         fmod(x,y)      calculate x modulo y, where x and y are double
·         hypot(x,y)     calculate hypotenuse of right angle where x,y are sides.
·         log10(x)         returns logarithm base 10

No comments:

Post a Comment