21CSS101J Programming For Problem Solving

Download as pdf or txt
Download as pdf or txt
You are on page 1of 135

21CSS101J

PROGRAMMING FOR PROBLEM SOLVING

UNIT-1
2
Pseudocode &
History and Evolution of C
Writing Pseudo code

Pseudo – Imitation / False


Code - Instructions
Outline or a rough draft of the Program.
Simple English syntaxes.
Goal: To provide a high level description of the Algorithm
Benefit: Enables programmer to concentrate on Algorithm
• Similar to programming code .
• Explanation of the Algorithm .
• No specific Programming language symbolizations .
• Pseudo Code can be transformed into actual program code .
How to write a Pseudo-code?
Guidelines of Pseudo code
1. Sequence of operations need to be decided and arranged then should write the
pseudo code accordingly.
2. Start with statement that establishes the aim of the Program.
Example
The program checks the given number is Odd or Even.
3. Indent the statement , as it helps to understand the execution mechanism of any
decision control. The Pseudo code should ease the readability.
Example
if “yes”
Print response
“I am in”
if “No”
Print response
“I am not in”
4. Use proper Naming Conventions.
5. Use suitable sentence casings such
I. Camel Case –Methods.
II. Uppercase-Constants
III. Lowercase-Variables.
6. Don’t be abstract with the Pseudo code . Make the Pseudo code elaborate and
explanatory.
7. Use Structured programming such as i) if-then ii) for iii)while iv)case
8. Make sure the Pseudo code is very clear, understandable, finite and comprehend.
9. The pseducode should be understandable even for a layman or client. Don't make too
much of technical complex terms.
Do’s and Don’ts of Pseudo code

Do’s
1. Use Control Structures.
2. Use appropriate naming conventions.
3. Indentation and white spaces are the key.
4. Keep it simple
5. Keep it concise.
Don’ts
1. Don’t be too generalized.
2. Don’t make the pseudo code abstract.
Advantages

• The Pseudo code can be easily converted into programming.


• Easy to understand for even non-programmers
• Syntax errors are not so important.
• Changes in the requirement can be easily incorporated in the pseudo code.
• Implements Structured concepts
• No special symbols
• No specific platform required, it can be typed in MS Word.
Disadvantage

• No standard is followed
• Compilation and Execution of the program cannot
be done.
• It may be time consuming to produce result.
Examples of Pseudo code

1. Write a Pseudo code to add 2 numbers together


and then display the result
Line1: Start Program
Line 2: Enter two numbers, A, B
Line 3: Add the numbers together
Line 4: Print Sum
Line 5: End Program
2. Write a Pseudo code to compute the area of a
rectangle:
Line1 : Get the length, l, and width, w
Line2 : Compute the area = l*w
Line3: Display the area
Examples of Pseudo code Continues….

3. Compute the perimeter of a rectangle:


Line1 : Enter length, l
Line2 : Enter width, w
Line3 : Compute Perimeter = 2*l + 2*w
Line4 : Display Perimeter of a rectangle
Examples of Pseudo code Continues….

4.Input examination marks and award grades


Use Variables: mark of type integer
If mark >=80 DISPLAY “Distinction”
If mark >=60 and mark <80 DISPLAY “First Class”
If mark >=50 and mark <60 DISPLAY “Second Class”
If mark <50 DISPLAY “Fail”
End Program
Flowchart to add 2 numbers and display the result

Start

Enter
Number A
Line1: Start Program
Enter Line 2: Enter two numbers, A, B
Number B Line 3: Add the numbers together
Line 4: Print C
Line 5: End Program
A+B=C

Print C

End
History and Evolution of C

1. C – General Purpose Programming Language


2. Developed by Dennis Ritchie in 1972
3. Developed at Bell Laboratories
4. Developed to overcome the problems of previous languages such as B, BCPL, etc.
5. Structured Programming Language
6. C Program
❑ Collection of Functions
❑ Supported by C library
Father of C Programming : Dennis Ritchie

Born on September 09,1941


Born In Bronxville ,New York
Full name Dennis MacAlistair Ritchie
Nick name DMR
Nationality American
Graduate From Harvard University
Graduate In Physics and Applied Mathematics
Dead On October 12 2011
Evolution of C
Language Year Developed By

Algol 1960 International Group


BCPL 1967 Martin Richard
B 1970 Ken Thompson
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis
Ritchie
ANSI C 1989 ANSI Committee
ANSI/ISO C 1990 ISO Committee
C99 1999 Standardization Committee
Features of C Language
Features of C are
1. Simple
2. Machine Independent.
3. Mid-level programming language
4. Structured Programming language
5. Rich Library
6. Memory management
7. Speed
8. Pointer
9. Recursion
10. Extensible.
Advantages of C
1. Compiler based Language
2. Programming – Easy & Fast
3. Powerful and Efficient
4. Portable
5. Supports Graphics
6. Supports large number of Operators
7. Used to Implement Data structures
Disadvantages of C

1. Not a strongly typed Language


2. Use of Same operator for multiple purposes
3. Not Object Oriented
Input and Output Statements
standard input-output header file, named stdio.h

1. Input- To provide the data for the program


2. Output-To display the data on the screen
3. C programming language provides many built-in functions to read any given
input and to display data on screen when there is a need to output the result.
4. The Standard input-output file – Studio.h.
5. The input statement is called scanf()
6. The output statement is called printf().
Topic
Variables,Identifiers,Expressions,Single line
comments and Multiline comments
● Single line comment
● Multi line comment
● Variables
● Identifiers
● Expressions
USING COMMENTS
• It is a good programming practice to place some
comments in the code to help the reader understand the
code clearly.
• Comments are just a way of explaining what a program
does. It is merely an internal program documentation.
• The compiler ignores the comments when forming the
object file. This means that the comments are
non-executable statements.
Continued….

C supports two types of commenting:


• // is used to comment a single statement. This
is known as a line comment. A line comment
can be placed anywhere on the line and it does
not require to be specifically ended as the end
of the line automatically ends the line.
• /* is used to comment multiple statements. A
/* is ended with */ and all statements that lie
within these characters are commented.
EXAMPLE
// This is my first program in C

#include<stdio.h>
int main()
{
printf("\n Welcome to the world of C ");
/* the above statement prints the
statements given in double quotes*/
return 0;
}
IDENTIFIERS
• Identifiers are names given to program elements
such as variables, arrays and functions.
Rules for forming identifier name:
▪ it cannot include any special characters or
punctuation marks (like #, $, ^, ?, ., etc) except the
underscore"_".
▪ There cannot be two successive underscores
KEYWORDS
▪ Keywords cannot be used as identifiers
▪ The names are case sensitive. So, example,
“FIRST” is different from “first” and “First”.
▪ It must begin with an alphabet or an underscore.
▪ It can be of any reasonable length. Though it should
not contain more than 31 characters.
▪ Example: roll_number, marks, name, emp_number,
basic_pay, HRA, DA, dept_code
VARIABLES
• Can provide one value for variables initialized in one
statement:
◻ int x, y, z = 0;
• Each variable declared and then initialized with the
value
Variables

Numeric Variable Character Variables


VARIABLES
● Numeric variables can be used to store either
integer values or floating point values.
● While an integer value is a whole numbers
without a fraction part or decimal point, a floating
point number, can have a decimal point in them.
● Numeric values may also be associated with
modifiers like short, long, signed and unsigned
VARIABLES

• By default, C automatically a numeric variable


signed..
• Character variables can include any letter from
the alphabet or from the ASCII chart and
numbers 0 – 9 that are put between single
quotes.
Example
int emp_num;
float salary;
char grade;
double balance_amount;
unsigned short int acc_no;
EXPRESSION
◻ linked to each other by the use of operators to
compute a value. An operand can be a function
reference, a variable, an array element or a
constant.
Example:
◻ a-b;

◻ In the above expression, minus character (-) is

an operator, and a, and b are the two operands.


◻ There are four types of expressions exist in C:
• Arithmetic expressions Ex:12/8 +8 * 2
• Relational expressions Ex:a!=b
• Logical expressions Ex: x > 10 || y <11
• Conditional expressions
Syntax: exp1 ? exp2 : exp3
◻ Each type of expression takes certain types of
operands and uses a specific set of operators.
Evaluation of a particular expression produces a
specific value.
1. Keywords
2. Constants
3. Values, Names
4. Scope
5. Binding
Introduction

Keywords:
❑ Keywords – Conveys special meaning to Compiler
❑ Cannot be used as variable names
❑ The following are the 32 reserved C keywords:

61
Introduction

Constants:
❑ Definition :Value does not change during execution
❑ Can be a Number (or) a Letter
❑ Types
❑ Integer Constants
❑ Real Constants
❑ Character Constant
❑ Single Character Constants
❑ String Constants
Introduction

Constants condt:
Introduction

Values:
There are two kinds of expressions in C −

• lvalue − Expressions that refer to a memory location are called "lvalue" expressions. An
lvalue may appear as either the left-hand or right-hand side of an assignment.

• rvalue − The term rvalue refers to a data value that is stored at some address in
memory. An rvalue is an expression that cannot have a value assigned to it which
means an rvalue may appear on the right-hand side but not on the left-hand side of an
assignment.

• Variables are lvalues and so they may appear on the left-hand side of an assignment.
• Numeric literals are rvalues and so they may not be assigned and cannot appear on the
left-hand side. Take a look at the following valid and invalid statements −

int g = 20; // valid statement

10 = 20; // invalid statement; would generate compile-time error


Introduction

Names:
Function names and variable names are both identifiers in C.
• The following are all the characters you can use to make a valid variable name:
1. Characters A through Z and a through z.
2. Digit characters 0 through 9, which can be used in any position except the first
of a variable name.
3. The underscore character (_).
For instance, stop_sign, Loop3, and _pause are all valid variable names.
Now, let's see what you cannot use in variable naming:
• A variable name cannot contain any C arithmetic signs.
• A variable name cannot contain any dots (.).
• A variable name cannot contain any apostrophes (`).
• A variable name cannot contain any other special symbols such as *, @, #, ?, and
so on.
Some invalid variable names, for example, are, 4flags, sum-result, method*4, and
what_size?.
Introduction

Scope of Variable:
❑ Definition
❑ A scope in any programming is a region of the program where a
defined variable can have its existence and beyond that variable
it cannot be accessed

❑ Variable Scope is a region in a program where a variable is


declared and used

❑ The scope of a variable is the range of program statements that can


access that variable

❑ A variable is visible within its scope and invisible outside it


Introduction

Scope of Variable:

❑ There are three places where variables can be declared


a) Inside a function or a block which is called local variables
b) Outside of all functions which is called global variables
c) In the definition of function parameters which are

called formal parameters


Introduction

Scope of Variable:
a) Local Variables
❑ Variables that are declared inside a function or block are called

local variables

❑ They can be used only by statements that are inside that

function or block of code

❑ Local variables are created when the control reaches the block

or function containing the local variables and then they get

destroyed after that


Introduction

Scope of Variable:
/* Program for Demonstrating Local Variables*/
#include <stdio.h> int main ( )

{
/* local variable declaration */
int a, b; int c;

/* actual initialization */
a = 10; b = 20;
c = a + b;
printf ("value of a = %d, b = %d and c = %d\n", a, b, c); return 0;

}
Introduction

Scope of Variable:
b) Global Variables
❑ Defined outside a function, usually on top of the program
❑ Hold their values throughout the lifetime of the program
❑ Can be accessed inside any of the functions defined for the
program

❑ Can be accessed by any function


❑ That is, a global variable is available for use throughout the
entire program after its declaration
Introduction

Scope of Variable:
/* Program for Demonstrating Global Variables*/
#include <stdio.h>
/* global variable declaration */
int g;
int main ( )
{
/* local variable declaration */
int a, b;
/* actual initialization */
a = 10; b = 20;
g = a + b;
printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0;
}
Introduction

Binding:
❑ A Binding is an association between an entity and an attribute
❑ Between a variable and its type or value
❑ Between a function and its code
❑ Binding time is the point at which a binding takes place
❑ Types of Binding
a) Design Time
b) Compile Time
c) Link Time
d) Run Time
Introduction

Binding:
a) Design Time
❑ Binding decisions are made when a language is designed
❑ Example
❑ Binding of + to addition in C
b) Compile Time
❑ Bindings done while the program is compiled
❑ Binding variables to datatypes
❑ Example
❑ int a; float b; char c;
Introduction

Binding:
c) Link Time
❑ Compiled code is combined into a full program for C
❑ Example
❑ Global and Static variables are bound to addresses
d) Run Time
❑ Any binding that happens at run time is called Dynamic
❑ Any binding that happens before run time is called Static
❑ Values that are dynamically bound can change
Storage Classes
STORAGE CLASS

✔Storage Class

- Where to store
- Default Initial Value
- Scope
- Life

76
Four Types of Storage Class


Auto
• Every time new value

• Static Retains value between calls

• Extern
Variable is defined Outside

Value is Stored in CPU Register


Register
Auto-Example

{
int month;
auto int month;
}

.
Static-Example
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() { Output:
while(count--)
{
func(); i is 6 and count is 4
} i is 7 and count is 3
return 0;
} i is 8 and count is 2
/* function definition */ i is 9 and count is 1
void func( void )
{
i is 10 and count is 0
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
Extern-Example
First File: main.c
#include <stdio.h>
Output:
int count ;
extern void write_extern();
count is 5
main() {
count = 5;
write_extern();
}
Second File: support.c
#include <stdio.h>
extern int count;
void write_extern(void) {
printf("count is %d\n", count);
}
Register-Example

{
register int miles;
}
Numeric Data Types : Integers and Floating
Point
Numeric Data Types : Integers and Floating Point

• Numeric Data means numbers.


• Numbers come in a variety of different types

Just a normal integer, a whole number which


Integers
can be positive or negative
keyword:int

- Explicit signs allowed


- Commas, decimal points and special signs not allowed

- Example: 12
45
1274
100000000
-3
-5735
Numeric Data Types : Integers and Floating Point

Floating point It is used to store decimal numbers (numbers with floating


keyword:float point value) with single precision.

-Used for representing non-integer numbers


- fractional values
- “sign bit” for postive and negative numbers

Examples:

float pi, _run_rate, Average_score;


Non Numeric Data Types : char and string
Non Numeric Data Types: char and string
• Non Numeric:
-Only Words are Counted
-Cannot be manipulated mathematically using standard arithmetic
operators.

Non Numeric Character : ‘a’

String :
“ anything between
double quotes”
Numeric and Non-Numeric Data
Types-Example
Operators
Topics

• Increment and decrement operators


• Assignment operators
• Comma ,Arrow
• Bitwise operators and SizeOf Operators
Operators
- Symbols which take one or more operands
- Perform arithmetic or logical computations.
INCREMENT AND DECREMENT OPERATORS

▪ Increment and decrement operators

- Unary operator
- ++ (the increment operator)
- -- (the decrement operator)
- either a prefix or postfix
position with different results

91
INCREMENT AND DECREMENT OPERATORS

Prefix and Postfix

++ Post-increment. aNumber++

-- Post-decrement. aNumber--

++ Pre-increment. ++yourNumber

-- Pre-decrement. --yourNumber

92
; INCREMENT AND DECREMENT OPERATORS

Example:
#include <stdio.h> Output:
int main() ++a = 11
{ --b = 99
int a = 10, b = 100; ++c = 11.500000
float c = 10.5, d = 100.5; ++d = 99.500000
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}

93
ASSIGNMENT OPERATORS

▪ Assignment Operators
• Assign value to an variable and denoted by =
• Binary operator, operates on two operands
• Have Two Values – L-Value and R-Value.
• Also be used for logical operations
ASSIGNMENT OPERATORS

Operator Example Same as

= a=b a=b

+= a += b a = a+b

-= a -= b a = a-b

*= a *= b a = a*b

/= a /= b a = a/b

%= a %= b a = a%b
Comma
Comma (,) as Separator and Operator
• Separator -While declaration multiple variables and providing
multiple arguments in a function
• Operator-assign multiple values to a variable

Example: As a Separator Example: As a Operator


a = 10,20,30;
int a,b,c; b = (10,20,30);
(a, b, and c) are three different variables.
value of a will be 10
value of b will be 30
Arrow
Arrow Operator
• Accessing members of structure using pointer variable
• Access the structure members when we use pointer variable to
access it

struct student
{
char name[20],
int roll;
}*ptr
Bitwise Operator
Bitwise Operator
• Used in bit level programming
• Manipulate bits of an integer expression
• Logical, shift and complement are three types
Bitwise Operator
Example:
#include <stdio.h>
main()
{
unsigned int a = 60;
unsigned int b = 13;
int c = 0; Line 1 - Value of c is 12
c = a & b;
printf("Line 1 - Value of c is %d\n", c );
Line 2 –Value of c is 61
c = a | b; Line 3 - Value of c is 49
printf("Line 2 - Value of c is %d\n", c ); Line 4 - Value of c is -61
c = a ^ b; Line 5 - Value of c is 240
printf("Line 3 - Value of c is %d\n", c );
c = ~a; Line 6 - Value of c is 15
printf("Line 4 - Value of c is %d\n", c );
c = a << 2;
printf("Line 5 - Value of c is %d\n", c );
c = a >> 2;
printf("Line 6 - Value of c is %d\n", c );
}
Sizeof Operator
• calculate the size of data
type or variables.
• sizeof operator can be
nested.
• sizeof operator will return
the size in integer format.
#include <stdio.h>
int main()
{
int integerVar;
Output
printf("Size of char = %d\n", sizeof(char));
printf("Size of int = %d\n", sizeof(integerVar)); Size of char = 1
printf("Size of expression (3+2.5) = %d\n", Size of int = 4
sizeof(3 + 2.5)); s return 0; Size of expression
} (3+2.5) = 8
❖ Relational and Logical Operators
❖ Conditional Operators
❖ Operator Precedence
❖ Pre / Post increment operators
Relational Operators

❖ The relational operators are used to compare two values.


❖ An expression which consists of a relational operator is known
as a relational expression.
❖ The final result of a relational expression is either 0 or 1. ie, True
or False.

Operator Meaning
< 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

102
Relational Operators

❖ == and != relational operators are called equality operators.

❖ General form
expression1 relational-operator expression2

❖ Example1: x=1, y=2 and z=3

Expression Interpretation Value


1. x<y true 1
1<2 T
2. (x+y)>=z true 1
1+2>=3 T
3. (x+z)>(x+5) false 0
1+3>1+5 F

4. x!=1 false 0
5. z==3 true 1
103
Relational Operators

❖ Example 2: a=2, b=3.5, and c=‘z’

Expression Interpretation Value


1. a<4 true 1
2. (a+b)>=10 false 0
3. c!=’p’ true 1

❖ Example 3: a=20, b=10


if (a > b)
printf(“a is big”);
else
printf(“b is big”);
Output:
a is big
104
Logical Operators

❖ The logical operators are used to combine two or more


conditions to make decisions.

Operators Meaning
&& Logical AND
|| Logical OR
! Logical NOT

❖ Example:
x<y && z!=5
❖ An expression which combines two or more relational
expressions is called as a logical expression or a compound
relational expression.

105
Logical Operators

❖ The common truth table of logical &&, || and ! operators are


given below: (where 1-true and 0-false)

❖ &&-AND returns 1 when all


the conditions are true

❖ | |-OR returns 1 when one or


more conditions are true

❖ !-NOT 1 when condition is


false
106
Logical Operators

■ Example: x=1, y=2, and z=3.

Expression Interpretation Value


1. (x<=6) && (z == 3) true 1
(1<=6) && (3==3)
T && T

2. (y!=6) && ( z>=(x+4)) false 0


T && F

3. (x<=3) | | (z >= 4) true 1


T||F

107
Conditional Operators (Ternary operator)

❖ A ternary operator pair “? :” is available in C language.


❖ It can able to construct conditional expressions.
❖ The general form is

exp1 ? exp2 : exp3;

❖ Where exp1, exp2, and exp3 are expressions.


❖ First, exp1 is evaluated.
❖ If it is nonzero (true), then the expression exp2 is evaluated.
❖ Otherwise, exp1 will be false, exp3 is evaluated.
Conditional Operators (Ternary operator)

Example:
#include<stdio.h>
main()
{
int a,b,c;
printf(“\nGive two numbers:”);
scanf(“%d%d”,&a,&b); /*a=15, b=10*/
c = (a > b) ? a : b;
printf(“\nThe Biggest value: %d”,c);
}
Output:
The Biggest value: 15
Operator Precedence

❖ An expression is evaluated from left to right.


❖ In C language, each operator has a “precedence” or priority
associated with it.
❖ The operators at the higher level of priority are evaluated first.
❖ The operators of the same priority 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.

❖ Example:
( 3 * 5 ) + ( 4 / 2) – ( 1 * 2)
15 + 2 - 2
15
Operator Precedence
Pre / Post increment operator

• Increment and decrement operators are unary operators.


• They can add or subtract ‘1’ from the operand.
Eg: x = x +1 can be written as ++x
result : x=2

• C languages has two types (pre and post) of each


operator:
1. Operator placed before variable (Pre)
2. Operator placed after variable (Post)

• The increment/decrement operator is ++ and --.


Increment and Decrement Operators Contd…
• Types:
1. Pre Increment Operator
2. Post Increment Operator
3. Pre Decrement Operator
4. Post Decrement Operator

• Syntax:
(pre)++var_name; (pre)--var_name;
(Or)
var_name++ (post); var_name -- (Post);
• Examples:
++a, --total, a--, i--
Increment and Decrement Operators Contd…

S.
No Operator type Operator Description
Pre Value of x is incremented by 1 before assigning it
1 Increment ++x to variable x.

Post Value of x is incremented by 1 after assigning it to


2 Increment x++ variable x.
Pre Value of x is decremented by 1 before assigning it
3 Decrement --x to variable x.
Post Value of x is decremented by 1 after assigning it to
4 Decrement x -- variable x.
Increment and Decrement Operators Contd…
/* Program for Post Increment*/
#include<stdio.h>
#include<conio.h>
void main()
{
int x = 0;
while (x++<3)
{
printf(“%d,”, x);
}
getch ( );
}

Output
1, 2, 3,
Increment and Decrement Operators Contd…
Program execution:

❖ Step 1 : In the program, value of x “0” is compared with 3 in while statement.


❖ Step 2 : Then, value of “x” is incremented from 0 to 1 using post- increment
operator.

❖ Step3:Then,this incremented value“1” is assigned to the variable “x”.

❖ Above3 steps are continued until whilestatement becomes ‘ false ‘ and

output is displayed as “1, 2, 3”.


Increment and Decrement Operators Contd…
/* Program for Pre Increment*/
#include<stdio.h>
#include<conio.h>
void main()
{
int x = 0;
while (++x<3)
{
printf(“%d,”, x);
}
getch ( );
}

Output
1, 2,
Increment and Decrement Operators Contd…
Program execution:

❖ Step 1 : In the program, value of “x” is incremented from 0 to 1 using pre-


increment operator.
❖ Step 2 : Then, value of x “0” is compared with 3 in while statement.
❖ Step3:Then,this incremented value“1” is assigned to the variable “x”.

❖ Above3 steps are continued until whilestatement becomes ‘ false ‘ and

output is displayed as “1, 2”.


Conditional Operator
• C Programming Language provide ‘?’ As
Conditional operator
• These are called as ‘Ternary operator’
• It has three operands.
• Syntax :
Condition ? Expression1 : Expression2

1
1
9
• This equation is equal to :
if (condition)
expression 1
else
expression 2

1
2
0
• Working of Ternary Operator
The ternary operator is an operator that takes three arguments.
The first argument is a comparison argument, the second is the
result upon a true comparison, and the third is the result upon a
false comparison.
<expression-1> ? <expression-2> : <expression-3> ;
Expression-1 ⇨ Conditional statement
Expression-2 ⇨ It will execute if condition in Expression-1
evaluate as TRUE.
Expression-3 ⇨ It will execute if Condition in Expression-1
evaluate as FALSE.

1
2
1
Example :
max = (a>b) ? a : b ;
This is equivalent to,
if (a>b) max = a;
else max=b;
Note - Ternary operator is right associative.

1
2
2
Examples
#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output :
x value is 1
y value is 2

1
2
3
Example
#include<stdio.h>
int main( )
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even\n"):printf("Odd");
}
Output
Enter the Number : 10
Even
1
2
4
Example
#include<stdio.h>
int main( )
{
int age;
printf(" Please Enter your age here: \n ");
scanf(" %d ", &age);
(age >= 18) ? printf(" You are eligible to Vote ") : printf(" You are not eligible to
Vote ");
return 0;
}

Output
Please Enter your age here: 19
You are eligible to Vote

1
2
5
Examples
#include<stdio.h>
int main( )
{
int a, b, max;
printf("Enter a and b: ");
scanf("%d%d", &a, &b);
max = a > b ? a : b;
printf("Largest of the two numbers = %d\n", max);
return 0;
}
Output
Enter a and b: 10 20
Largest of the two numbers = 20 12
6
Assignment Operator
• Uses the assignment operator (=)
• General syntax: variable_name = expression
• Assignment Operator is binary operator which operates on two
operands
• Assignment Operator have Two Values – L-Value and R-Value
• Operator = copies R-Value into L-Value
• Left of = is called L-value, must be a modifiable variable
• Right of = is called R-value, can be any expression

12
7
12
8
• L-Value stands for left value
• L-Value of Expressions refer to a memory locations
• In any assignment statement L-Value of Expression
must be a container(i.e. must have ability to hold the
data)
• Variable is the only container in C programming
thus L Value must be any Variable.
• L Value cannot be a Constant, Function or any of
the available data type in C.

12
9
Diagram Showing L-Value of Expression :

13
0
L-Value and R-Value of Expression Contd...
#include<stdio.h>
int main( )
{
int num;

num=5;
return(0);
}
Example of L-Value Expression
#include<stdio.h>
int main( )
{
int num;

5 = num; //Error
return(0);
}
L-value cannot be a Constant
#include<stdio.h> int main( )
{
const num;

num = 20; //Error


return(0);
}
L-value cannot be a Constant Variable

13
1
#include<stdio.h>
#define MAX 20
int main( )
{
MAX = 20; //Error
return(0);
}
L-value cannot be a MACRO
#include<stdio.h>
enum {JAN,FEB,MARCH};
int main( )
{

JAN = 20; //Error


return(0);
}
L-value cannot be a Enum Constant
13
2
• R Value stands for Right value of the expression
• In any Assignment statement R-Value of Expression must be anything
which is capable of returning Constant Expression or Constant Value

13
3
Examples of R-Value of Expression
Variable Constant
Function Macro
Enum Constant Any other data type

R value may be a Constant or Constant Expression


R value may be a MACRO
R Value may be a variable

13
4
References

• Maureen Sprankle, “Problem Solving and Programming Concepts”,


Pearson,7th Edition, 2011
• E.Balagurusamy,“Programming in ANSI C”, Tata McGrawHill, 5thEdition,
2011.
• Y.P. Kanetkar, “Let us C”, BPB Publications, 8th Edition, 2008.
• Steve Oualline, “ Practical C Programming”, O’Reilly Publishers, 2011.
• Byron Gottfried, “Programming with C”, Schaum’s Outline Series, 2nd
Edition, 2000.

You might also like