Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Computer Programming Using C Unit IV Objectives

The document discusses various operators and control structures in C programming like unary operators, arithmetic operators, logical operators, bitwise operators, assignment operators, conditional expressions, if-else statements, switch case, loops like for, while and do-while. It also covers operator precedence and order of evaluation.

Uploaded by

vikas__cc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Computer Programming Using C Unit IV Objectives

The document discusses various operators and control structures in C programming like unary operators, arithmetic operators, logical operators, bitwise operators, assignment operators, conditional expressions, if-else statements, switch case, loops like for, while and do-while. It also covers operator precedence and order of evaluation.

Uploaded by

vikas__cc
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Master of Science (Information Technology)

Computer Programming Using C


Unit - IV
Objectives
Introduction
Operators: Unary operators, arithmetic & logical operators
Bit wise operators
Assignment operators and expressions
Conditional expressions
Precedence and order of evaluation
Control statements: If-else, switch, break, continue, the comma operator, goto statement.
Loops: For, while, do-while.
Summary
Keywords
Self assessment
Review questions
Objectives
 Discuss Operators: Unary operators, Arithmetic & logical operators
 Explain Bit wise operators
 Discuss Assignment operators and expressions
 Understand Conditional expressions
 Discuss Precedence and order of evaluation
 Discuss Control statements: if-else, switch, for, while, do-while, break, continue
Introduction
A combination of constants, variables and operators that confirm to the grammatical rules of
the language C and evaluate to some valid value is called an expression. The effect that
1
operators bring about on their operands is called operation. An expression that confirms to the
rules of grammar of C language is referred to as valid or wellformedexpression. A valid or
well expression always evaluates to a single value of a valid C data type.
Operators: Unary operators, Arithmetic & logical operators
Arithmetic operator:
These are used for performing arithmetic calculation e.g +, - , * , / ,%. Arithmetic
operators work on integer, floating point and character data. % operator is used to find the
remainder of a division.
Relational operators:
These are used for making comparisons between two values and return true/false. All
relational operators can work on integers, floats and characters.
The various relational operator provided by C are >, <,>=, <=, == and <>. The operator == is
use for comparing equality, but this cannot be used for floating numbers.
Logical operators:
Logical operators are used to apply logical conditions which includes && stands for
logical and, || which stands for logical or. The output of logical operator is true of false.
Logical operator are used to make logical expression
E.g a>b&&a>c is a logical expression.
Increment and decrement operator:
Increment and decrement operator are used to increment and decrement the value of a variable
by 1. The symbol for increment operator is ++ and for decrement operator is --.
The increment and decrement operator are used in 2 form.
pre increment : ++x;
post increment : x++;
Examples of Increment and decrement operator:
Pre:
Int x=5;

2
Int y=++x;
Printf (“%d %d”, x, y);
The output of the above code is 6 6
Here the value of x is first incremented and then assigned to y.
Post:
Int x=5;
Int y=x++;
Printf (“%d %d”, x, y);
The output of the above code is 6 5
Here the value of x is assigned to y and then incremented.
The effects are same for decrement operator which is also used in both the forms.
More examples:
In the postfix notation, the value of the operand is used first and then the operation of
increment or decrement takes place, e.g. consider the statements below:

Int a,b;
a = 10;
b = a++;
Printf (“%d\n”, a);
Printf (“%d\n”, b);

Program Output

10
11

3
Prefix notation

In the prefix notation, the operation of increment or decrement takes place first after which the
new value of the variable is used.

Int a, b;
a = 10;
b = ++a;
Printf (“%d\n” , a);
Printf (“%d\n” , b);
Program Output

11
11

Bit wise operators


These are the operators which work on the binary values. e.g & known as bit wise works as
follows:
Int a=5, b=3;
c=a&b;
Printf (“%d”,c);
The output is 1.
Explanation The binary of 5 is 101
The binary of 3 is 011

bit wise & is 001


Which is binary of 1?
Example:

4
72 & 184 = 8
01001000 &
10111000 =
-----------------
00001000
72 | 184 = 248
01001000 |
10111000 =
------------------
11111000
Special operator:
There are two special operators in C. This include sizeof opearator and comma operator.
Sizeof ():
Sizeof operator is used to find the size of any type.
E.g sizeof (int) gives us sizeof int.
#include <stdio.h>
Int main (void){
Int b = 5;
Printf (“%d”, sizeof (b);
Return 0;
}
Output is 2
#include <stdio.h>
Int main (void) {

5
Int b = 5;
Printf (“%d”, sizeof (b++);
Return 0;
}
Error because sizeof () does not work on expressions.
Assignment operators and expressions
The assignment operator assigns the value on its right hand side to the variable on its right
hand side. The left has side has to be a variable and cannot be an expression.
E.g int x=8;
In the above example 8 is assigned to x.
Conditional expressions
This operator which is also known as ternary operator is used to apply condition. The syntax
is:
Condition? True: false
Explanation: if the coniditon is true then true part will execute otherwise false part will
execute. This can be an alternate to if statement.
Example:
a>b? ++a: ++b;
If a is greater than b then a is incremented otherwise b is incremented.
Average = (n > 0)? Sum / n: 0
It can be used in place of if
If (n > 0)
Average = sum / n;
Else
Average = 0;

6
Precedence and order of evaluation
The Following table shows C operators in order of precedence (highest to lowest). Their
associatively indicates in what order operators of equal precedence in an expression are
applied.

Operator Description Associativity

() Parentheses (function call) (see Note 1) left-to-right


[] Brackets (array subscript)
. Member selection via object name
-> Member selection via pointer
++ -- Postfix increment/decrement (see Note 2)

++ -- Prefix increment/decrement right-to-left


+ - Unary plus/minus
! ~ Logical negation/bitwise complement
(type) Cast (change type)
* Dereference
& Address
sizeof Determine size in bytes

* / % Multiplication/division/modulus left-to-right

+ - Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to left-to-right


> >= Relational greater than/greater than or equal to

== != Relational is equal to/is not equal to left-to-right

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

7
&& Logical AND left-to-right

|| Logical OR left-to-right

?: Ternary conditional right-to-left

= Assignment right-to-left
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment
%= &= Modulus/bitwise AND assignment
^= |= Bitwise exclusive/inclusive OR assignment
<<= >>= Bitwise shift left/right assignment

, Comma (separate expressions) left-to-right

Control statements: if-else, switch, for, while, do-while, break, continue


If Statement
1) if statement: if statement can be applied in different formats
Simple if statement:
Syntax: if (condition)
Statement;
Explanation: The statement will execute if the condition is true.
If….Else Statement
Syntax: if (condition)
{
Statement 1;
Statement 2;
}
Else
{

8
Statement 3;
Statement 4;
}
Explanation:
If the condition is true then statement1 and statement2 will execute, and if it is false then
statement3 and statement 4 will execute.
Example:
Program to check if a given number is even or odd.
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int num;
Printf (“enter the number”);
Scanf (“%d”, & num);
If (num%2==0)
{
Printf (“number is even”);
}
Else
{
Printf (“number is odd”);
}
}

9
If…..Else If…. Statement
When there are further conditions to be checked under else part of if, the following syntax is
used:
Syntax:
If (condition1)
{
True 1
….
….
}
Else
If (condition2)
{
true2
……
}
Else
{
False 2…….
…….
}
Explanation:
If condition1 is true then true1 part will execute, otherwise condition 2 is checked, and if it
true then true2 will execute otherwise false 2 will execute.
Example: Program to find discount on a bill with the following conditions.

10
1) 10 % for the amount >=10000
2) 5% for the amount >=5000 and amount <10000
3) 2% for the amount <5000
#include<stdio.h>
#include<conio.h>
Void main ()
{
Float billamount, discount;
Printf (“enter the bill amount”);
Scanf (“%f”, & billamount);
If (billamount>=10000)
Discount=.1*billamount;
Else
If (billamount>=5000)
Discount=.05*billamount;
Else
Discount=.02*billamount;
Printf (“the discount is %f”, discount);
}
More examples of if statements:
Simple if:
#include <stdio.h>
void main()
{
int number = 0;
printf("\nEnter an integer between 1 and 10: ");
11
scanf("%d",&number);
if (number > 7)
printf("You entered %d which is greater than 7\n", number);
if (number < 3)
printf("You entered %d which is less than 3\n", number);
}
If –else
main()
{
float cost,tax,luxury,total;
luxury=0.0;
printf("Enter the cost of the item: ");
scanf("%f", &cost);
tax=cost*0.06;
if(cost >40000)
{
luxury=cost*0.005;
printf("The luxury tax is %.2f",luxury);
}
else
{
puts("There is no luxury tax for the items");
luxury=0.0;
}
}
Switch statement:
Switch statement is another conditional statement which is applied when any variable or
expression is compared with multiple values. The syntax of applying switch is:
Switch (variable/expression)
{
Case 1…

12
……..
……..
Break;

Case 2…
……..
……..
Break;

Case 3…
……..
……..
Break;
Case 4…
……..
……..
Break;
Default…
……..
……..
Break;
}
Explanation: The variable/expression given with in the brackets is compared with 1,2,3,4 and
the corresponding case will execute and if none of the above case is true then the default case
will execute.

13
Example:
Program to perform addition, subtraction, multiplication and division of two numbers with in
the same program.
#include<stdio.h>
#include<conio.h>
Void main()
{
Int choice, a, b, c;
Printf (“1. Addition\n”);
Printf (“2. Subtraction\n”);
Printf (“3. Multiplication\n”);
Printf (“4. Division\n”);
Printf (“enter your choice”);
Scanf (“%d”, &choice);
Printf (“enter the two numbers”);
Scanf (“%d%d”, &a, &b);
Switch (choice)
{
Case 1: c=a+b;
Printf (“Addition is %d\n”, c);
Break;
Case 2: c=a-b;
Printf (“Subtration is %d\n”, c);
Break;
Case 3: c=a*b;
14
Printf (“Multiplication is %d\n”, c);
Break;

Case 4: c=a/b;
Printf (“Division is %d\n”, c);
Break;

Default: printf (“wrong choice”);


}
}
Example of switch:
#include <stdio.h>
#include <stdlib.h>
Intmain ()
{
Intinput;
Printf (“1. Play game\n”);
Printf (“2. Load game\n”);
Printf (“3. Play multiplayer\n”);
Printf (“4. Exit\n”);
Printf (“Selection: " );
Scanf (“%d", &input);
Switch (input)
{

15
Case 1: /* Note the colon, not a semicolon */
Printf ("Playing the game\n");
Break;
Case 2:
Printf ("Loading the game\n");
Break;
Case 3:
Printf ("Playing multiplayer\n");
Break;
Case 4:
Printf ("Thanks for playing! \n");
Break;
Default:
Printf ("Bad input! \n");
Break;
}
}
Nesting of switch
Nested-Switch statements refer to Switch statements inside of another Switch Statements.
Syntax:
Switch (n)
{
// code to be executed if n = 1;
Case 1:

16
// nested switch
Switch (num)
{
// code to be executed if num = 10
Case 10:
Statement 1;
Break;
// code to be executed if num = 20
Case 20:
Statement 2;
Break;
// code to be executed if num = 30
Case 30:
Statement 3;
Break;
// code to be executed if n
// doesn't match any cases
Default:
}
Break;
// code to be executed if n = 2;
Case 2:
Statement 2;
Break;

17
// code to be executed if n = 3;
Case 3:
Statement 3;
Break;
// code to be executed if n doesn't match any cases
Default:
}
To print 2 digits number to words
#include <stdio.h> // include stdio.h library
Intmain (void)
{
Int, num, num1, num2;
Printf ("Enter a two-digit number: ");
Scanf ("%1d%1d", & num);
num2=num%10;
num1=num/10;
Printf ("You have entered: ");
// print word for the first digit
Switch (num1)
{
case1:
// special case for numbers between 11-19
Switch (num2)
{

18
case0:
Printf ("ten");
return0;
case1:
Printf ("eleven");
return0;
case2:
Printf ("twelve");
return0;
case3:
Printf ("thirteen");
return0;
case4:
Printf ("fourteen");
return0;
case5:
Printf ("fifteen");
return0;
case6:
Printf ("sixteen");
return0;
case7:
Printf ("seventeen");
return0;

19
case8:
Printf ("eigthteen");
return0;
case9:
Printf ("nineteen");
return0;
}
case2:
Printf ("twenty");
Break;
case3:
Printf ("thirty");
Break;
case4:
Printf ("forty");
Break;
case5:
Printf ("fifty");
Break;
case6:
Printf ("sixty");
Break;
case7:
Printf ("seventy");

20
Break;
case8:
Printf ("eighty");
Break;
case9:
Printf ("ninety");
Break;
}

// print word for the second digit


Switch (num2)
{
case1:
Printf ("-one");
Break;
case2:
Printf ("-two");
Break;
case3:
Printf ("-three");
Break;
case4:
Printf ("-four");
Break;

21
case5:
Printf ("-five");
Break;
case6:
Printf ("-six");
Break;
case7:
Printf ("-seven");
Break;
case8:
Printf ("-eight");
Break;
case9:
Printf ("-nine");
Break;
}
return0;
}
While
While loop: The syntax of using while loop is:

While (condition)
{
statements1;

22
statements2;
statements3;
statements4;
….
….
….
}

Explanation: The statements within the { } brakets will execute till the condition is true.
Example: Program to print table of n.
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int n, count=1;
Printf (“enter the number”);
Scanf (“%d”, &n);
While (count<=10)
{
Printf (“%d\n”, count*n);
Count++;
}
Example: Program to print sum of digits of a number.
#include<stdio.h>

23
#include<conio.h>
Void main ()
{
Int num, sum=0, r;
Printf (“enter the number”);
Scanf (“%d”, & num);
While (num! =0)
{
r=num%10;
Sum=sum+r;
Num=num/10;
}
Printf (“sum of digits is %d”, sum);
}
Program to reverse a number:
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int num, rnum=0,r;
Printf (“enter the number”);
Scanf (“%d”, & num);
While (num! =0)
{

24
r=num%10;
Rnum=rnum*10+r;
Num=num/10;
}
Printf (“reverse of number is %d”, rnum);
}
Do….While Statement
It is a kind of loop in which the condition is applied at the end of the loop. This is a kind of
loop in the statements are executed at least once.
Syntax of do-while loop is:
Do
{
……
……
……
……
……
}
While (condition);
Example:
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int choice, a, b, c;
25
Do
{
Printf (“1. Addition\n”);
Printf (“2.Subtraction\n”);
Printf (“3. Multiplication\n”);
Printf (“4. Division\n”);
Printf (“5. Exit\n”);
Printf (“enter your choice”);
Scanf (“%d”, &choice);
Printf (“enter the two numbers”);
Scanf (“%d%d”, &a, &b);
Switch (choice)
{
Case 1: c=a+b;
Printf (“Addition is %d\n”, c);
Break;
Case 2: c=a-b;
Printf (“Subtration is %d\n”,c);
Break;
Case 3: c=a*b;
Printf (“Multiplication is %d\n”, c);
Break;
Case 4: c=a/b;
Printf (“Division is %d\n”, c);

26
Break;
Case 5: exit (0);
Break;
Default: printf (“wrong choice”);
}
}
While (1);
}
This program will perform addition, subtraction, multiplication and division on repeated basic
and will terminated only will user go for exit option.
For Statement
For loop:
The syntax of using for loop is:
For (initialization; condition; increment/decrement)
{
Statements……
………….
}
Explanation: In for statement initialization is done first ,then condition is checked and if the
condition is true then the statements are executed. After the execution of statements the
increment or decrement takes place.
Example:
Program to print sum of 10 natural numbers
#include<stdio.h>
#include<conio.h>

27
Void main ()
{
Int sum=0, count;
For (count=1; count<=10; count++)
{
Sum=sum+count;
}
Printf (“the sum of 10 natural numbers is %d”, sum)
}
Example:
To print factorial of a number
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int fact=1, num, count;
Printf (“enter the number”);
Scanf (“%d”, &num);
For (count=1; count<=num; count++)
Fact=fact*count;
Printf (“the factorial is %d”, fact);
}
Program to find m raise to power n
#include<stdio.h>

28
#include<conio.h>
Void main()
{
Int m, n, p=1;
Printf (“enter the base”);
Scanf (“%d”, &m);
Printf (“enter the power”);
Scanf (“%d”, &n);
For (count=1; count<=n; count++)
p=p*m;
printf (“the power is %d”,p);
}
Nested Control Statement
Nesting of loops:
When a loop is applied within another loop then it is termed a nested of loop. Nesting of loop
forms two types of loops, outer and inner. The execution of inner loop is based on outer loop.
For each execution of outer loop, the inner completes its work.
e.g
For (i=1;i<=10;i++)
{
For (j=1;j<=10;j++)
{
…….
…….
}

29
}
For each value of i for outer loop, the inner loop of j will execute 10 times. So the inner loop
will execute 100 times in total.
Examples:
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int i,j;
For (i=1; i<=5; i++)
{
For (j=1; j<=i;j++)
{
Printf (“%d”,j);
}
Printf (“\n”);
}
}
The output of the above program is
1
12
123
1234
12345
The problems related to pattern printing can be solved using nesting of loop.
30
Break
Break statement is used to interrupt the loop in between. This is used when a loop has to be
terminated in between because of some condition. It can be used with while, do-while or for
loop.
Example:
Program to find sum of 10 numbers entered by user but if user enter some negative number
the loop should break
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int sum=0, n, count=1;
For (count=1; count<=10; count++)
{
Printf (“enter the number”);
Scanf (“%d”, & n);
If (n<0)
Break;
Sum=sum+n; }
Printf (“sum of number entered is %d”, sum); }

Continue
Continue statement is used to take the loop back to starting point.
Example:
Program to find sum of 10 numbers entered by user but if user enter some negative number
the next number is entered
31
#include<stdio.h>
#include<conio.h>
Void main ()
{
Int sum=0, n, count=1;
For (count=1; count<=10; count++)
{
Printf (“enter the number”);
Scanf (“%d”, &n);
If (n<0)
Continue;
Sum=sum+n;
}
Printf (“sum of number entered is %d”, sum);
}
More Examples:
// continue example
#include <stdio.h>
Void main ()
{
// declare storage for input, an array and counter variable
Char buffer [81];
Int ctr;
// input and read a line of text using

32
// puts () and gets () are pre defined functions in stdio.h
Puts ("Enter a line of text and press Enter key,");
Puts ("all the vowels will be discarded! \ N");
Gets (buffer);
// go through the string, displaying only those
// characters that are not lowercase vowels
For (ctr=0; buffer [ctr] != '\0'; ctr++)
{
// if the character is a lowercase vowel, loop back without displaying it
if((buffer[ctr]=='a')||(buffer[ctr]=='e')|| (buffer[ctr]=='i')||(buffer[ctr]=='o')||(buffer[ctr]=='u'))
Continue;
// if not a vowel, display it
Putchar (buffer [ctr]);
}
Printf ("\n");
}
// another do…while statement example
#include <stdio.h>
Int get_menu_choice (void);

Void main ()
{
Int choice;
Choice = get_menu_choice ();

33
Printf ("You have chosen Menu #%d\n", choice);
Printf ("\n");
}
Int get_menu_choice (void)
{
Int selection = 0;
Do
{
Printf ("1 - Add a record");
Printf ("\n2 - Change a record");
Printf ("\n3 - Delete a record");
Printf ("\n4 - Quit");
Printf ("\nEnter a selection: ");
Scanf ("%d", & selection );
} while ((selection < 1) || (selection > 4));
Return selection;
}
Goto Statement.
Goto statement is used to transfer the control of execution of a program to a particular point
within the program.

The syntax is:


Goto label1;
Where label1 is defined within the program.
Example:
34
#include <stdio.h>
#include <conio.h>
int main() {
int n = 0;
loop: ;

printf("\n%d", n);
n++;
if (n<10) {
goto loop;
}
getch();
return 0;
}
// demonstrates the goto statement
#include <stdio.h>
Void main ()
{
Int n;
Start: ;
Puts ("Enter a number between 0 and 10: ");
Scanf ("%d", &n);
If ((n < 0) || (n > 10))
goto start;
Else if (n == 0)
Goto location0;
Else if (n == 1)
Goto location1;

35
Else
Goto location2;
location0:
{
Puts ("You entered 0.");
}
Goto end;
location1:
{
Puts ("You entered 1.");
}
Goto end;
location2:
{
Puts ("You entered something between 2 and 10.");
}
End:
}

36
Summary
C is a programming language developed at AT & T’s Bell Laboratories of USA in 1972..It
was designed and written by a man named Dennis Ritchie.In the late seventies C began to
replace the more familiar languages of that time like
PL/I, ALGOL, etc. No one pushed C.It wasn’t made the ‘official’ Bell Labs language. Thus,
without any advertisement C’s reputation spread and its pool of users grew. Ritchie seems to
have been rather surprised that so many programmers preferred C to older languages like
FORTRAN or PL/I, or the newer ones like Pascal and APL. But, that’s what happened.
This unit tells us the basic terminology related to programming and the various terms required
for making of a program. Also we are able to understand the concept of datatype and variable
which is base of making program. This unit explains the technicals of variable and data types
This unit explained the different operators and their functionalities. It also explains how
different operator is applied and are useful for applying the logic of the problem. It also tells
about the precedence of operator. The unit also explains about expressions, evaluation of
expression

Keywords
1. AT & T Bell Laboratories
2. Dennis Ritchie
3. Structure of c program
4. Character set
5. Tokens
6. Identifiers
7. Constants
8. Variable
9. Data types
10. Arithmetic operator
11. Relational operator
12. Logical operator
13. Assignment operator, increment and decrement operator
14. Bit wise operator
15. Arithmetic expression
16. Evaluation of expression
37
17. operator precedence

Self assessment questions


Choose the appropriate answers:
1. What are the entities whose values can be changed called?
a) Constants
b) Variables
c) Modules
d) Tokens
2. Which of the following is not a basic data type in C language?
a) Float
b) int
c) real
d) char
3. Which one is not a operator?
(a) Bitwise operator
(b) Comma operator
(c) Local operator
(d) Assignment operators
4. Relational operator generally used for
(a) Compare two operands
(b) Addition two operands
(c) Multiplication two operands
(d) None of the above
5. Symbol used to represent increment operator
(a) +-
(b) ++
(c) - -

38
(d) **
6. Conditional operator represented by
(a):?
(b):_
(c):*
(d) :%
7. Array expression represented by
(a) []
(b) ()
(c) ++ - -
(d) //++
8. Which one is not a relational operator?
(a) = =
(b) ! +
(c) >
(d) > =
Fill in the blanks:
9. ................... are used to store the result of an expression to a variable.
10. Bitwise operators are used ................... of data at bit level.
11. An expression may contain more than ................... operator.
12. ................... operators work on numeric type of operands.
Review questions
1. What are the different classes of operators available in C language?
2. Define the term “Expression”. Explain the various types of expression in C.
3. What are the various logical and relational operators supported by C. Explain them with

39
4. Proper examples.
5. Draw a table that will provide a complete list of operators, their precedence level and
their
6. Rules of association.
7. List down the advantages and limitations of using conditional operator in a C program.
8. Write short notes on:
9. Shorthand assignment operators
10. Bitwise operators
11. Write a program addition of 1-10 numbers with the help of arithmetic operator.
12. Ramesh’s basic salary is input through the keyboard. His dearness allowance is 40% of
basic salary, and house rent allowance is 20% of basic salary. Write a program to
calculate his gross salary.
13. Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a
program to convert this temperature into Centigrade degrees.

Answers: Self Assessment


1. A 2.C 3. C 4. A 5. B 6. A
7. A 8. B 9. Assignment operators 10. For manipulation
11. One 12. Arithmetic

****

40

You might also like