0% found this document useful (0 votes)
38 views

PPS

Uploaded by

vishvakrajan009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

PPS

Uploaded by

vishvakrajan009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 220

21CSS101J – Programming for Problem Solving

Unit I
UNIT I (TOPICS
COVERED)
Evolution of Programming & Languages - Problem Solving
through Programming - Creating Algorithms - Writing
Pseudocode - Evolution of C language, its usage history - Input
and output functions: Printf and scanf - Variables and
identifiers – Expressions - Single line and multiline comments
- Constants, Keywords - Values, Names, Scope, Binding, Storage
Classes - Numeric Data types: integer -
UNIT I (TOPICS
COVERED)
floating point - Non-Numeric Data types: char and string -
Increment and decrement operator - Comma, Arrow and
Assignment operator - Bitwise and Sizeof operator Arithmetic,
Relational and logical Operators, Condition Operator, Operator
Precedence - Expressions with pre / post increment operator
Evolution of Programming & Languages

❑ A Computer needs to be given instructions in a programming


language that it understands

❑ Programming Language
❑ Artificial language that controls the behavior of computer
❑ Defined through the use of syntactic and semantic rules
❑ Used to facilitate communication about the task of organizing
and manipulating information

❑ Used to express algorithms precisely


Evolution of Programming & Languages Contd…

Period Programming Langugaes


1950’s Creation of high-level languages
1960’s Forth. Simula I. Lisp, Cobol
1970’s Pascal, C language
1980’s ML. Smalltalk, C++
1990’s Java, Perl, Python languages
2000 Internet Programming
2010 Concurrency and asynchronicity. JavaScript and Go language
Problem Solving through Programming

❑ Problem - Defined as any question, something involving doubt,


uncertainty, difficulty, situation whose solution is not
immediately obvious
❑ Problem Solving- Problem solving is the systematic approach to
define the problem and creating number of solutions.
-The problem solving process starts with the
problem specifications and ends with a Correct program.
❑ Computer Problem Solving –Things to be done
❑ Understand and apply logic
❑ Success in solving any problem is only possible after we
have made the effort to understand the problem at hand
❑ Extract from the problem statement a set of precisely
defined tasks
Problem Solving through Programming Contd…
i. Creative Thinking
❑ Proven method for approaching a challenge or opportunity in
an imaginative way
❑ Process for innovation that helps explore and reframe the
problems faced, come up with new, innovative responses and
solutions and then take action

❑ It is generative, nonjudgmental and expansive


❑ Thinking creatively, a lists of new ideas are generated
Problem Solving through Programming Contd…
ii. Critical Thinking
❑ Engages a diverse range of intellectual skills and activities that
are concerned with evaluating information, our assumptions
and our thinking processes in a disciplined way so that we can
think and assess information more comprehensively
❑ It is Analytical, Judgmental and Selective
❑ Thinking critically allows a programmer in making choices
Problem Solving through Programming Contd…
Problem Solving through Programming Contd…

❑ Program - Set of instructions that instructs the computer to do a


task

❑ Programming Process
a) Defining the Problem
b) Planning the Solution
c) Coding the Program
d) Testing the Program
e) Documenting the Program
Problem Solving through Programming Contd…
Problem Solving through Programming Contd…
❑ A typical programming task can be divided into two phases:
i. Problem solving phase
❑ Produce an ordered sequence of steps that describe solution
of problem.
ii. Implementation phase
❑ Implement the program in some programming language
Problem Solving through Programming Contd

❑ Problem solving techniques


-Problem solving technique is a set of techniques that helps in
providing logic for solving a problem.

❑ Problem Solving Techniques/Program Design Tools


-Problem solving can be expressed in the form of

1. Algorithms.
2. Flowcharts. Programs
3. Pseudo codes.

❑ General Features
Problem Solving through Programming Contd…
❑ Steps in Problem Solving
a) Produce a general algorithm (or pseudocode)
b) Refine the algorithm successively to get step by step detailed
algorithm that is very close to a computer language
Creating Algorithms
❑ An informal definition of an algorithm is:

Algorithm: a step-by-step method for solving a


problem or doing a task.
Creating Algorithms Contd…
❑ What are Algorithms for?
❑ A way to communicate about your problem/solution with
others

❑ A possible way to solve a given problem


❑ A "formalization" of a method, that will be proved
❑ A mandatory first step before implementing a solution
❑ Algorithm Definition - “A finite sequence of unambiguous,
executable steps or instructions, which, if followed would
ultimately terminate and give the solution of the problem”
Creating Algorithms
❑ Notations
❑ Starting point
❑ Step Numbers – Positions in Algorithm
❑Incoming Information - Input
❑ Control Flow – Order of evaluating Instructions
❑ Statements
❑ Outgoing Information - Output
❑ Ending Point
Creating Algorithms Contd…
❑ Properties of an algorithm
❑ Finite: The algorithm must eventually terminate
❑ Complete: Always give a solution when one exists
❑ Correct (sound): Always give a correct solution
❑ Rules of Writing an Algorithm
❑ Be consistent
❑ Have well Defined input and output
❑ Do not use any syntax of any specific programming language
Creating Algorithms Contd…
❑ Characteristics of algorithm

• Should be written in simple English


• Each and every instruction should be precise and
unambiguous.
• Instructions in an algorithm should not be repeated
infinitely.
• Algorithm should conclude after a finite number of
steps.
• Should have an end point
• Derived results should be obtained only after the
algorithm terminates.
Creating Algorithms Contd…

❑ Qualities of a good algorithm

Time - Lesser time required.

Memory - Less memory required.

Accuracy - Suitable or correct solution obtained.

Sequence - Must be sequence and some instruction may be


repeated in number of times or until particular condition is met.

Generability - Designed to handle a range of input data.


Creating Algorithms Contd…
❑ Algorithm development process consists of five major steps
❑ Step 1: Obtain a description of the problem
❑ Step 2: Analyze the problem
❑ Step 3: Develop a high-level algorithm
❑ Step 4: Refine the algorithm by adding more detail
❑ Step 5: Review the algorithm
Creating Algorithms Contd…

❑ Building blocks of algorithms

Statements: Statement is a single action in a computer.


In a computer statements might include some of the following actions
• input data-information given to the program
• process data-perform operation on a given input
• output data-processed result
State: Transition from one process to another process under specified
condition with in a time is called state.
Control flow: The process of executing the individual statements in a
given order is called control flow.
The control can be executed in three ways
1. sequence
2. selection
3. iteration
4. Function
Creating Algorithms Contd…

❑ Sequence:
All the instructions are executed one after another is called
sequence execution.

Example:
Add two numbers:

Step 1: Start
Step 2: Get/Read a,b
Step 3: calculate c=a+b
Step 4: Display/Print c
Step 5: Stop
Creating Algorithms Contd…

❑ Selection: A selection statement causes the program control to be


transferred to a specific part of the program based upon the
condition.
-If the conditional test is true, one part of the program will be
executed, otherwise it will execute the other part of the program.

Example:

Write an algorithm to check whether he is eligible to vote?


Step 1: Start
Step 2: Get age
Step 3: if age is greater than and equal to 18 then print “Eligible to
vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop
Creating Algorithms Contd…

❑ Iteration: In some programs, certain set of statements are


executed again and again based upon conditional test.
-i.e. executed more than one time.
-This type of execution is called looping or repetition or iteration.

Example

Write an algorithm to print all natural numbers up to n

Step 1: Start
Step 2: get n value.
Step 3: initialize i as 1
Step 4: if i less than or equal to n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop
Creating Algorithms Contd…

❑ Function: Function is a sub program which consists of block of


code(set of instructions) that performs a particular task.
- For complex problems, the problem is been divided into
smaller and simpler tasks during algorithm design

❑ Benefits of Using Functions

➢ Reduction in line of code


➢ code reuse
➢ Better readability
➢ Easy to debug and test
➢ Improved maintainability
Creating Algorithms Contd…

Example:
Algorithm for addition of two numbers using function

Main function()
Step 1: Start
Step 2: Call the function add()
Step 3: Stop

sub function add()


Step 1: Function start
Step 2: Get a, b Values
Step 3: add c=a+b
Step 4: Print c
Step 5: Return
Creating Algorithms Contd…
Example
❑ Problem
a) Develop an algorithm for finding the largest integer among a
list of positive integers
b) The algorithm should find the largest integer among a list of

any values
c) The algorithm should be general and not depend on the
number of integers
Creating Algorithms Contd…
❑ Solution
a) To solve this problem, we need an intuitive approach
b) First use a small number of integers (for example, five), then

extend the solution to any number of integers


c) The algorithm receives a list of five integers as input and
gives the largest integer as output
Creating Algorithms Contd…
Example 2: Print 1 to 20
❑ Step 1: Start

❑ Step 2: Initialize X as 0,

❑ Step 3: Increment X by 1,

❑ Step 4: Print X,

❑ Step 5: If X is less than 20 then go back to step 2.

❑ Step 6: Stop
Creating Algorithms Contd…
Example 3
Convert Temperature from Fahrenheit (℉)to Celsius (℃)
❑ Step 1: Start

❑ Step 2: Read temperature in Fahrenheit

❑ Step 3: Calculate temperature with formula C=5/9*(F-32)

❑ Step 4: Print C

❑ Step 5: Stop
Creating Algorithms Contd…
Example 4
Algorithm to Add Two Numbers Entered by User
❑ Step 1: Start

❑ Step2: Declare variables num1, num2 and sum.

❑ Step 3: Read values num1 and num2.


❑ Step 4: Add num1 and num2 and assign the result to sum.
sum←num1+num2

❑ Step 5: Display sum Step 6: Stop


Creating Algorithms Contd…
❑ Write an Algorithm to:

1) Find the Largest among three different numbers

2) Find the roots of a Quadratic Equation

3) Find the Factorial of a Number

4) Check whether a number entered is Prime or not

5) Find the Fibonacci Series


Drawing flowchart Contd…

❑ FLOW CHART
➢ Flow chart is defined as graphical or diagrammatic
representation of the logic for problem solving.

➢ The purpose of flowchart is making the logic of the


program clear in a visual representation.

➢ A flowchart is a picture of the separate steps of a


process in sequential order
Drawing flowchart Contd…
Drawing flowchart Contd…

❑ Rules for drawing a flowchart


1. The flowchart should be clear, neat and easy to follow.
2. The flowchart must have a logical start and finish.
3. Only one flow line should come out from a process
symbol.
4. Only one flow line should enter a decision symbol.
However, two or three flow lines may leave the decision
symbol
5. Only one flow line is used with a terminal symbol
6. Within standard symbols, write briefly and precisely.
7. Intersection of flow lines should be avoided.
Drawing flowchart Contd…
Drawing flowchart Contd…

Example - sequence
Find the area of a circle of radius r
Drawing flowchart Contd…

Example- Selection
Flowchart Problem 1: Draw the flowchart to find the largest number
between A and B
Drawing flowchart Contd…

Example - Iteration
Flowchart for the problem of printing even numbers between 0 and 99
Drawing flowchart Contd…

Example
Drawing flowchart Contd…

Draw a Flowchart to:

1. Flowchart for an algorithm which gets two numbers and prints sum of their
value.
2. Convert temperature Fahrenheit to Celsius
3. Draw the flowchart to show whether the given number is even or odd
4. Flowchart for n natural numbers
Writing Pseudocode
❑ Pseudo – Imitation / False

❑ Code – Instructions

❑ Goal: To provide a high level description of the Algorithm

❑ Benefit: Enables programmer to concentrate on Algorithm

❑ Similar to programming code

❑ Description of the Algorithm

❑ No specific Programming language notations

❑ Pseudo Code transformed into actual program code


Writing Pseudocode Contd…
a) Guidelines for Writing Pseudo Code

❑ Write only one Statement per line

❑ Example – Pseudo Code for calculating Salary


1. READ name, hourly rate, hours worked, deduction rate
2. Gross pay = hourly rate * hours worked
3. deduction = gross pay * deduction rate
4. net pay = gross pay – deduction
5. WRITE name, gross, deduction, net pay
Writing Pseudocode Contd…
b) Capitalize Initial Keyword

❑ Keywords to be written in capital letters


❑ Examples: READ, WRITE, IF, ELSE, WHILE, REPEAT, PRINT
c) Indent to show Hierarchy
❑ Indentation shows the structure boundaries
❑ Sequence
❑ Selection
❑ Looping
Writing Pseudocode Contd…
d) End Multiline structures

❑ Each structure must end properly


❑ Example: IF statement must end with ENDIF
e) Keep Statements Language independent
❑ Resist the urge to write Pseudo Code in any
programming language
Writing Pseudocode Contd…
❑ Advantages
❑ Easily typed in a Word document
❑ Easily modified
❑ Simple to Use and understand
❑ Implements Structured Concepts
❑ No special symbols are used
❑ No specific syntax is used
❑ Easy to translate into Program
Writing Pseudocode Contd…
❑ Disadvantages
❑ No accepted Standard
❑ Cannot be compiled and executed
❑ Common keywords used in pseudocode
The following gives common keywords used in pseudocodes.
1. //: This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end is the last
statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the
given expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and
initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the
program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented
tested automatically.
Writing Pseudocode Contd…

Example:

Addition of two numbers:

BEGIN
GET a,b
ADD c=a+b
PRINT c
END
Example
Writing Pseudocode Contd…
❑ Write an Pseudo Code to:

1) Add three numbers and Display the result

2) Calculate Sum and product of two numbers


3) Input examination marks and award grades according to the
following criteria:
a) > = 80 Distinction
b) > = 60 First Class

c) > = 50 Second Class


d) < 40 Fail
Writing Pseudocode Contd…
1. Pseudo Code to Add Three Numbers
⚫ BEGIN
⚫ Use Variables: sum, num1, num2, num3 of type integer
⚫ ACCEPT num1,num2,num3
⚫ COMPUTE Sum = num1+num2+num3
⚫ PRINT sum
⚫ END
Writing Pseudocode Contd…
2. Calculate Sum and product of two numbers
⚫ BEGIN
⚫ Use Variables: sum, product, num1, num2 of type real
⚫ DISPLAY “Input two Numbers”
⚫ ACCEPT num1,num2
⚫ CALCULATE Sum = num1+num2
⚫ PRINT “The sum is”, sum
⚫ CALCULATE product = num1*num2
⚫ PRINT “The product is”, product
⚫ END
Writing Pseudocode Contd…
3. Input examination marks and award grades
⚫ BEGIN
⚫ Use Variables: mark of type integer
⚫ IF mark >=80 DISPLAY “Distinction”
⚫ ELSE IF mark >=60 and mark <80 DISPLAY “First
Class”
⚫ ELSE IF mark >=50 and mark <60 DISPLAY “Second
Class”
⚫ ELSE DISPLAY “Fail” ENDIF
⚫ END
Writing Pseudocode Contd…

4. Calculate the factorial of the given numbers

• BEGIN
• GET n
• INITIALIZE i=1,fact=1
• WHILE(i<=n) DO
• fact=fact*i
• i=i+1
• ENDWHILE
• PRINT fact
• END
Writing Pseudocode Contd…

Write the Pseudocode for the following

• To calculate Simple Interest


• To check whether the given year is “LEAP” year
or not
• To check whether given number is +ve, -ve or
zero
• To print N odd numbers
• To print squares of N numbers
C - Language
History & Evolution of C
❑ C – General Purpose Programming Language
❑ Developed by Dennis Ritchie in 1972
❑ Developed at Bell Laboratories
❑ Structured Programming Language
❑ C Program
❑ Collection of Functions
❑ Supported by C library
History & Evolution of C Cont…
Father of C Programming : Dennis Ritchie

Born On September 9 1941


Born in Bronxville – New York
Full Name Dennis MacAlistair Ritchie
Nickname DMR
Nationality American
Graduate From Harvard University
Graduate In Physics and Applied Mathematics
Webpage http://cm.bell-labs.com/who/dmr/
Dead On October 12 2011
History & Evolution of C Cont…

1960
1967
1970
1972
1978
1989
1990
1999

Evolution of C
History & Evolution of C Cont…
❑ Why the Name “C” was given ?
❑ Many of C’s principles and ideas were derived from the earlier
language B
❑ BCPL and CPL are the earlier ancestors of B Language (CPL is
common Programming Language)
❑ In 1967, BCPL Language ( Basic CPL ) was created as a scaled
down version of CPL
❑ As many of the features were derived from “B” Language
the new language was named as “C”.
History & Evolution of C Cont…
❑ Characteristics of ‘C’
❑ Low Level Language Support
❑ Structured Programming
❑ Extensive use of Functions
❑ Efficient use of Pointers
❑ Compactness
❑ Program Portability
❑ Loose Typing
History & Evolution of C Cont…
❑ Advantages of C
❑ Compiler based Language
❑ Programming – Easy & Fast
❑ Powerful and Efficient
❑ Portable
❑ Supports Graphics
❑ Supports large number of Operators
❑ Used to Implement Datastructures
History & Evolution of C Cont…
❑ Disadvantages of C
❑ Not a strongly typed Language
❑ Use of Same operator for multiple purposes
❑ Not Object Oriented
Single Line and Multiline Comments
❑ Comment – Definition

❑ Used to provide information about lines of code


❑ Provide clarity to the C source code
❑ Allows others to better understand what the code was
intended to

❑ Helps in debugging the code


❑ Important in large projects containing
hundreds or
thousands of lines of source code

❑ Types – Single line and multiline comment


Single Line and Multiline Comments Contd…
a) Single Line Comment
❑ Represented by double slash \\

#include<stdio.h>
int main( ){
//printing information
printf("Hello C");

return 0;
}
Single Line and Multiline Comments Contd…
b) Multi-Line Comment
❑ Represented by slash asterisk \* ... *\

#include<stdio.h>
int main( ){
/*printing information
Multi Line Comment*/
printf("Hello C");

return 0;
}
Multi-Line Comments Single-Line Comment

Starts with /* and ends with */ Starts with //

All Words and Statements written Statements after the symbol //


between /* and */ are ignored upto the end of line are ignored

Comment Ends whenever


Comment ends when */ Occures ENTER is Pressed and New Line
Starts

e.g /* using for loop print e.g // Program for Fibonacci


welcome to pps class for 10 time
*/
Structure of ‘C’ Program
❑ Structure based on Set of rules defined by the Compiler
❑ Sections

1) Documentation 5) Local Declaration


2) Preprocessor 6) Program Statements
3) Global Declaration
4) main( ) function
Structure of ‘C’ Program Contd…
❑ Rules for Writing a C Program
a) All statements should be written in lower case
b) All statements should end with a semicolon
c) Upper case letters are used for symbolic constants
d) Blank spaces can be inserted between words
e) No blank space while declaring a variable, keyword, constant
f) Can write one or more statement in same line separated by
comma
g) Opening and closing of braces should be balanced
Structure of ‘C’ Program Contd…
Structure of ‘C’ Program Contd…

/* Program to Find Area of Circle */ Comment


#include <stdio.h>
#include <conio.h>
Preprocessor Directives

const float pi = 3.14; Global Declaration


void main( ) main Function
{
float area; Local Declaration &Initialization
int r;
printf(“Enter the Radius of the Circle”);
scanf(“%d”, &r); Execution
area = pi * r * r;
printf(“The area of the Circle is %f”, area);
getch( );
}
Structure of ‘C’ Program Contd…
1) Documentation Section
❑ Used for providing Comments
❑ Comment treated as a single white space by Compiler
❑ Ignored at time of Execution: Not Executable
❑ Comment: Sequence of Characters given between /* and */
❑ Example: Program Name, Statement description
/* Program to Find Area of a Circle*/
Structure of ‘C’ Program Contd…
2) Preprocessor Section
❑ Also called as Preprocessor Directive
❑ Also called as Header Files
❑ Not a part of Compiler
❑ Separate step in Compilation Process
❑ Instructs Compiler to do required Preprocessing
❑ Begins with # symbol
❑ Preprocessor written within < >
Structure of ‘C’ Program Contd…
❑ Examples
❑ #include <stdio.h>
❑ #include <conio.h>
❑ #include <math.h>
❑ #include <stdlib.h>
❑ #define PI 3.1412
Structure of ‘C’ Program Contd…

Directive Description

#define Substitutes a preprocessor macro.


#include Inserts a particular header from another file.
#undef Undefines a preprocessor macro.
#ifdef Returns true if this macro is defined.
#ifndef Returns true if this macro is not defined.
#if Tests if a compile time condition is true.
#else The alternative for #if.
#elif #else and #if in one statement.
#endif Ends preprocessor conditional.

Macro - a piece of code defined with the help of the #define directive.
-useful at multiple places to replace the piece of code with a single value of the macro.
Structure of ‘C’ Program Contd…

Directive Description

#error Prints error message on stderr.


Issues special commands to the compiler, using a standardized
#pragma
method.
Structure of ‘C’ Program Contd…
2. #include Directive

• The #include directive loads specified file (Header file) in the


current program. The macros and functions of loaded file can be
called in the current program.

• The included file also gets complied with the current program.

• The syntax is as given below:


(a) # include “filename” , #include<filename>
(b) # is a symbol used with directives

EXAMPLE
#include<stdio.h>
3. #Ifdef
- Returns true if this macro is defined.
4. #undef
- Undefines a preprocessor macro.

Output:
5. #Ifndef
- Returns true if this macro is not defined.

# define T 8
void main()
{
clrscr();
#ifndef T
printf(“\n Macro is not defined.”);
#else
printf(“\n Macro is defined.”);
#endif
getche();
}

OUTPUT:
Macro is defined.
6. Error directive

- The #error is used to display the user-defined


message during the compilation of the program.

- The syntax is as follows:

#ifndef identifier
# error <ERROR MESSAGE>
#endif
The Value of INT_MAX
(for 32 bit integers) =
2^31-1 =
2147483647

The Value of
MILLISECONDS(12) =
378432000000

Output
Structure of ‘C’ Program Contd…
3) Global Declaration Section
❑ Used to Declare Global variable (or) Public variable
❑ Variables are declared outside all functions
❑ Variables can be accessed by all functions in the program
❑ Same variable used my more than one function
Structure of ‘C’ Program Contd…
4) main( ) Section
❑ main( ) written in all small letters (No Capital Letters)
❑ Execution starts with a Opening Brace : {
❑ Divided into two sections: Declaration & Execution
❑ Declaration : Declare Variables
❑ Executable: Statements within the Braces
❑ Execution ends with a Closing Brace : }
❑ Note: main( ) does not end with a semicolon
Structure of ‘C’ Program Contd…
5) Local Declaration Section
❑ Variables declared within the main( ) program
❑ These variables are called Local Variables
❑ Variables initialized with basic data types
Input and Output Functions
❑ Ability to Communicate with Users during execution
❑ Input Operation
❑ Feeding data into program
❑ Data Transfer from Input device to Memory
❑ Output Operation
❑ Getting result from Program
❑ Data Transfer from Memory to Output device
❑ Header File : #include<stdio.h>
Input and Output Functions Contd…
❑ Input / Output Function Types
a) Formatted Input / Output Statements - used to take
various inputs from the user and display multiple
outputs to the user.
- we can use format specifiers in these functions and
hence, we can format these functions according to our
needs.
b) Unformatted Input / Output Statements - used to read
single input from the user at the console and it allows to
display the value at the console.
-We cannot use format specifiers in these functions
and hence, cannot format these functions according to our
needs.
Input and Output Functions Contd…
a) Formatted Input / Output Statements
❑ Reads and writes all types of data values
❑ Arranges data in particular format
❑ Requires Format Specifier to identify Data type
❑ Basic Format Specifiers
❑ %d – Integer
❑ %f – Float
❑ %c – Character
❑ %s - String
Input and Output Functions Contd…
i. The scanf ( ) Function
❑ Reads all types of input data
❑ Assignment of value to variable during Runtime
❑ Syntax

scanf(“Control String/Format Specifier”, &arg1, &arg2,… &argn)

❑ Control String / Format Specifier


❑ arg1, arg2.,,, arg n – Arguments (Variables)
❑ & - Address
Input and Output Functions Contd…

/* Giving Direct Input in /*Getting Input using scanf ( )


Program */ function */

#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int a; int a;
a=10; scanf(“%d”, &a);
} }
Input and Output Functions Contd…

/* Getting Multiple Input using /* Getting Multiple Different Inputs


scanf ( ) function */ using scanf ( ) function */
#include<stdio.h> #include<stdio.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int a, b, c; int a, b;
scanf(“%d%d%d”,&a,&b,&c); float c;
} scanf(“%d%d%f”,&a,&b,&c);

}
Input and Output Functions Contd…
/* Getting Multiple Input using scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b;
float c;
scanf(“%d %d”, &a, &b);
scanf(“%f ”, &c);
}
Input and Output Functions Contd…
ii. The printf ( ) Function
❑ To print Instructions / Output onto the Screen
❑ Requires Format Specifiers & Variable names to print
data

❑ Syntax

printf(“Control String/Format Specifier”,arg1,arg2,… argn)

❑ Control String / Format Specifier


❑ arg1, arg2.,,, arg n – Arguments (Variables)
Input and Output Functions Contd…
/* Example 1 – Using printf ( ) & scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
printf(“Enter the Value of a”);
scanf(“%d”, &a);
printf(“Value of a is %d”, a);
getch( );
}
Input and Output Functions Contd…
/* Example 2 – Using printf ( ) & scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, c;
printf(“Enter the Value of a, b & c”);
scanf(“%d %d %d”, &a, &b, &c);
printf(“Value of a, b & c is %d%d%d”, a, b, c);
getch ( );
}
/* Example 3 – Using printf ( ) & scanf ( ) function */
#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b, c;
printf(“Enter the Value of a & b”);
scanf(“%d %d”, &a, &b);
c=a+b;
printf(“Value of a, b is %d%d”, a, b);
printf(“Value of c is %d”, c);
getch ( );
}
Input and Output Functions Contd…

/* Example 4 – Using printf ( ) & scanf ( ) function */


#include<stdio.h>
#include<conio.h>
void main( )
{
int a, b;
float c;
printf(“Enter the Value of a, b & c”);
scanf(“%d %d%f”, &a, &b, &c);
printf(“Value of a, b & c is %d%d%f”, a, b, c);
getch ( );
}
Input and Output Functions Contd…
❑ Try it Out Yourself ! Write a C program to:
1) Add five numbers
2) To Multiply two floating point numbers
3) To compute Quotient and Remainder

4) To Swap two numbers


Input and Output Functions Contd…
b) Unformatted Input / Output Statements
❑ Works only with Character Data type
❑ No need of Format Specifier
❑ Unformatted Input Statements
i. getch ( ) – Reads alphanumeric characters from
Keyboard
ii. getchar ( ) – Reads one character at a time till enter key
is pressed
Input and Output Functions Contd…
iii. gets ( ) – Accepts any string from Keyboard until Enter Key
is pressed

❑ Unformatted Output Statements


i. putch ( ) – Writes alphanumeric characters to Monitor
(Output Device)
ii. putchar ( ) – Prints one character at a time
iii. puts ( ) – Prints a String to Monitor (Output Device)
Formatted I/O vs Unformatted I/O

Formatted I/O Unformatted I/O


S No.
functions functions
These functions allow us to These functions do not allow to
1 take input or display output in take input or display output in user
the user’s desired format. desired format.
These functions support format These functions do not support
2
specifiers. format specifiers.
These are used for storing data These functions are not more user-
3
more user friendly friendly.
Here, we can use only character
4 Here, we can use all data types.
and string data types.
printf(), scanf, sprintf() and getch(), getche(), gets() and puts(),
5 sscanf() are examples of these are some examples of these
functions. functions.
Unformatted Functions -Example

getchar(): Reads a
character from the
standard input
device.
putchar(): Writes a
character to the
standard output
device
Unformatted Functions -Example

gets() reads a string from the standard input device. It accepts


the name of a string as a parameter input from the keyboard.
puts() writes a string to the standard output device. It accepts the
name of a string and displays the accepted string on the screen.
C Programming Fundamentals
C Programming Fundamentals Contd…
C Programming Fundamentals Contd…
❑C Token - Smallest
individual unit of a C
program
❑C program broken into
many C tokens
❑Building Blocks of C
program
Keywords
❑ Keywords – Conveys special meaning to Compiler
❑ Cannot be used as variable names
Constants
❑ Definition : The constants in C are the read-only
variables whose values cannot be modified once they
are declared in the program i.e)Value does not change
during execution
❑ The const keyword is used to define the constants
❑ initialize the constant variables at declaration.
❑ We can also define a constant in C using #define
preprocessor. These constants are not handled by the
compiler, they are handled by the preprocessor.
❑ Syntax
❑ const data_type var_name = value;
Constants Cont…
Properties of Constant in C

1. Initialization with Declaration


We can only initialize the constant variable in C at the time of its
declaration. Otherwise, it will store the garbage value.

2. Immutability
The constant variables in c are immutable after its definition.
i.e., they can be initialized only once in the whole program. After
that, we cannot modify the value stored inside that variable.
Example
#include <stdio.h>

int main()
{
// defining integer constant using const keyword
const int int_const = 25;

// defining character constant using const keyword


const char char_const = 'A';

// defining float constant using const keyword


const float float_const = 15.66;

printf("Printing value of Integer Constant: %d\n",int_const);


printf("Printing value of Character Constant: %c\n",char_const);
printf("Printing value of Float Constant: %f",float_const);
return 0;
}

Output
Printing value of Integer Constant: 25
Printing value of Character Constant: A
Printing value of Float Constant: 15.660000
Constants Cont…

❑ Types
❑ Integer Constants & floating pointer
❑ Real Constants
❑ Character Constant
❑ Single Character Constants
❑ String Constants
Constants Contd…
Variables & Identifiers
❑ Identifier
❑ A string of alphanumeric characters that begins with an
alphabetic character or an underscore character
❑ There are 63 alphanumeric characters, i.e., 53 alphabetic
characters and 10 digits (i.e., 0-9)
❑ Used to represent various programming elements such as
variables, functions, arrays, structures, unions
❑ The underscore character is considered as a letter in
identifiers (Usually used in the middle of an identifier)
Identifier
Variables & Identifiers Contd…
❑ Rules for Identifers
❑ Combination of alphabets, digits (or) underscore
❑ First character should be a Alphabet
❑ No special characters other than underscore can be used
❑ Keywords cannot be represented as an identifier.
❑ The length of the identifiers should not be more than 31
characters.
❑ No comma / spaces allowed within variable name
❑ A variable name cannot be a keyword
❑ Variable names are case sensitive
❑ Variable Definition :Value changes during execution
❑ Identifier for a memory location where data is stored
Variables & Identifiers Contd…
❑ A variable can have alphabets, digits, and underscore.
❑ A variable name can start with the alphabet, and underscore only. It
can't start with a digit.
❑ No whitespace is allowed within the variable name.
❑ A variable name must not be any reserved word or keyword(int,
float, etc. )

❑ Examples: AVERAGE, height, a, b, sum, mark_1, gross_pay

❑ Variable Declaration
❑ A variable must be declared before it is used
❑ Declaration consists of a data type followed by one or
more variable names separated by commas.
❑ Syntax
datatype variablename;
Variables & Identifiers Contd…
❑ Examples
int a, b, c, sum;
float avg;

char name;
❑ Variable Initialization
❑ Assigning a value to the declared variable
❑ Values assigned during declaration / after declaration
Variables & Identifiers Contd…
❑ Examples
i. int a, b, c;
a=10, b=20, c=30;
ii. int a=10 ,b=10, c=10;
❑ Scope of Variables
❑ Local Variables
❑ Global Variables
Scope of Variables
❑ 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


Scope of Variables Contd…
❑ 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
Scope of Variables Contd…
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
❑ Local variables are not known to functions outside their own
/* 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;
}
Scope of Variables Contd…
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
/* 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;
}
Scope of Variables Contd…
❑ Note: A program can have same name for local and global
variables but the value of local variable inside a function will
take preference
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
Binding Contd…
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;
Binding Contd…
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 in C
❑ What is a Variable?
❑ Storage Class Specifiers tells the Compiler about the following:
❑ Where to Store a Variable
❑ What is the Initial value of the Variable
❑ What is the Lifetime of a Variable
❑Variable Scope: Area or block where the variables can be
accessed

a) Automatic Variables b) External Variables


c) Static Variables d) Register variables
Storage Classes in C Contd…
a) Automatic Variable (Or) Auto Variable (Or) Local Variable
❑ Default Storage class
❑ Defined inside a Function
❑ Scope of the Variable: Local to the function block where the
variable is defined

❑ Lifetime of the variable’s content vanishes after execution


❑ Keyword Auto used to Erase content of the variable
/* Program to Demonstrate Automatic (Or) Local Variables*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int n = 10; // auto int n = 10;

block1( );
block2( );
printf(“In Main Block n=%d”, n);
getch( );
}
block1( )
{
int n = 20;
printf(“In Block 1 n=%d”, n);
}
block2( )
{
int n = 30;
printf(“In Block 2 n=%d”, n);
}

Output
In Block 1 n=20

In Block 2 n= 30

In Main Block n=10


Storage Classes in C Contd…
b) External Variable (Or) Global Variable
❑ Available to all the Functions
❑ Defined outside the Function
❑ We can share a variable in multiple C source files by using an
external variable.
❑ To declare an external variable, you need to use extern
keyword.

❑ Scope of the Variable: Global to all the function blocks


❑ Lifetime of the variable’s content vanishes after the entre
program is executed
/* Program to Demonstrate External / Global Variables*/
#include<stdio.h>
#include<conio.h>
int n = 10;
void main( )
{
block1( );
block2( );
clrscr( );
printf(“In Main Block n=%d”, n);
getch( );
}
block1( )
{
printf(“In Block 1 n=%d”, n);
return;
}
block2( )
{
printf(“In Block 2 n=%d”, n);
return;
}

Output
In Block 1 n=10

In Block 2 n= 10

In Main Block n=10


Storage Classes in C Contd…
c) Static Variables
❑ Keyword Static is used to define the variable (Compulsory)
❑ Variable declared as static is initialized to NULL
❑ Value of the Static variable remains the same throughout the
program
❑ Scope of the Variable: Local or Global depending on where
it is declared

❑ Static Global: Defined outside the Function


❑ Static Local: Defined inside the Function
/* Program to Demonstrate Static Variables*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int x;
static int y;
clrscr( );
printf(“x=%dy=%d”, x, y);
getch( );
}

Output

x = 28722

y=0
Storage Classes in C Contd…
d) Register Variables
❑ Variables stored in the CPU registers instead of Memory
❑ Keyword Register is used to define the variable
❑ Scope of the Variable: Local
❑ Advantages
❑ CPU register access is faster than memory access
❑ Disadvantages
❑ Number of CPU registers is less
❑ Less Number of variables can be stored in CPU registers
/* Program to Demonstrate Register Variables*/
#include<stdio.h>
#include<conio.h>
void main( )
{
register int n=1;
clrscr( );
for(n=1; n<=10; n++)
printf(“%d”, n);
getch( );
}

Output

1 2 3 4 5 6 7 8 9 10
Summarize: Storage class
Constants

❑ The value certain variable to remain same or unchanged


during the program execution.

❑ Example: Const int m=10;

❑ But using pointer the value can be changed.


Datatypes
❑ Defines a variable before use
❑ Specifies the type of data to be stored in variables
❑ Basic Data Types – 4 Classes
a) int – Signed or unsigned number
b) float – Signed or unsigned number having Decimal Point
c) double – Double Precision Floating point number
d) char – A Character in the character Set
❑ Qualifiers
Datatypes Contd…
Datatypes Contd…
a) Integer Data Type
❑ Whole numbers with a range
❑ No fractional parts
❑ Integer variable holds integer values only
❑ Keyword: int
❑ Memory: 2 Bytes (16 bits) or 4 Bytes (32 bits)
❑ Qualifiers: Signed, unsigned, short, long
❑ Examples: 34012, 0, -2457
Datatypes Contd…
a) Integer Data Type
#include<stdio.h>

int main()

{
int a;
scanf(“%d”,&a);
printf(“%d”,a);

return 0;

}
Datatypes Contd…
b) Floating Point Data Type
❑ Numbers having Fractional part
❑ Float provides precision of 6 digits
❑ Integer variable holds integer values only
❑ Keyword: float
❑ Memory: 4 Bytes (32 bits)
❑ Examples: 5.6, 0.375, 3.14756
Datatypes Contd…

b) Floating Point Data Type


#include<stdio.h>
int main()
{
float g;
scanf(“%f”,&g);
printf(“%f ”,g);
return 0;

}
Datatypes Contd…
c) Double Data Type
❑ Also handles floating point numbers
❑ Double provides precision of 14 digits
❑ Integer variable holds integer values only
❑ Keyword: double
❑ Memory: 8 Bytes (64 bits) or 10 Bytes (80 bits)
Datatypes Contd…
c) Double Data Type
#include<stdio.h>
int main()

{
double g;
scanf(“%ld”,&g);
printf(“%ld”,g);
return 0;

}
Datatypes Contd…
d) Character Data Type
❑ handles one character at a time
❑ Keyword: char
❑ Memory: 1 Byte (8 bits)
Datatypes Contd…
d) Character Data Type
#include<stdio.h>
int main()
{
char g;
scanf(“%c”,&g);
printf(“%c”,g);
return 0;

}
L-Value and R-Value of Expression
a) 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
L-Value and R-Value of Expression Contd…
❑ Diagram Showing L-Value of Expression :
L-Value and R-Value of Expression Contd…

#include<stdio.h> #include<stdio.h> #include<stdio.h>


int main( ) int main( ) int main( )
{ { {
int num; int num; const num;
num = 5; 5 = num; //Error num = 20; //Error
return(0); return(0); return(0);
} } }

Example of L- L-value cannot be L-value cannot be


Value Expression a Constant a Constant
Variable
L-Value and R-Value of Expression Contd…

#include<stdio.h> #include<stdio.h>
#define MAX 20 enum {JAN,FEB,MARCH};
int main( ) int main( )
{ {
MAX = 20; //Error JAN = 20; //Error
return(0); return(0);
} }

L-value cannot be L-value cannot be


a MACRO a Enum Constant
L-Value and R-Value of Expression Contd…
b) 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
L-Value and R-Value of Expression Contd…

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
Expressions
❑ Expression : An Expression is a collection of operators and
operands that represents a specific value
❑ Operator : A symbol which performs tasks like arithmetic
operations, logical operations and conditional operations

❑ Operands : The values on which the operators perform the task


❑ Expression Types in C
a) Infix Expression
b) Postfix Expression
c) Prefix Expression
Expressions Contd…
a) Infix Expression
❑ The operator is used between operands
❑ General Structure : Operand1 Operator Operand2
❑ Example : a + b
b) Postfix Expression
❑ Operator is used after operands
❑ General Structure : Operand1 Operand2 Operator
❑ Example : ab+
Expressions Contd…
c) Prefix Expression
❑ Operator is used before operands
❑ General Structure : Operator Operand1 Operand2
❑ Example : +ab
Expressions Contd…
Operators in C
❑ C supports rich set of built in Operators
❑ Used to manipulate Constants (Data) & Variables
❑ Part of Mathematical (or) Logical expressions
❑ Operators vs Operands
❑ Operator – Definition
❑ Symbol (or) Special character that instructs the compiler
to perform mathematical (or) Logical operations
Operators in C Contd…
❑ Classification of Operators
a) Increment & Decrement Operators
b) Comma Operator
c) Arrow Operator
d) Assignment Operators
e) Bitwise Operators
f) Sizeof Operator
Operators in C Contd…
a) Increment and Decrement Operators
❑ Increment and decrement operators are unary operators that
add or subtract one from their operand
❑ C languages feature two versions (pre- and post-) of each
operator
❑ Operator placed before variable (Pre)
❑ Operator placed before variable (Post)
❑ T he increment operator is written as ++ and the decrement
operator is written as --
Operators in C Contd…
a) Increment and Decrement Operators Contd…
❑ Classification
❑ Pre Increment Operator
❑ Post Increment Operator
❑ Pre Decrement Operator
❑ Post Decrement Operator
Operators in C Contd…
a) Increment and Decrement Operators Contd…
❑ Syntax

(pre)++variable_name; (pre)- -variable_name;


(Or)
variable_name++ (post); variable_name – (Post);

❑ Examples
❑ ++count, ++a, ++i, ++count
❑ Count++, a++, i++, count++
Operators in C Contd…
a) Increment and Decrement Operators Contd…
S. No Operator type Operator Description
Value of i is incremented before
1 Pre Increment ++i
assigning it to variable i.
Value of i is incremented after
2 Post Increment i++
assigning it to variable i.
Value of i is decremented before
3 Pre Decrement -- i
assigning it to variable i.
Post Value of i is decremented after
4 i --
Decrement assigning it to variable i.
/* Program for Post Increment*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int i = 1;
while (i++< 5)
{
printf(“%d”, i);
} }
getch ( );
}

Output
1234
Operators in C Contd…
a) Increment and Decrement Operators Contd…
❑ Step 1 : In this program, value of i “0” is compared with 5 in while
expression.
❑ Step 2 : Then, value of “i” is incremented from 0 to 1 using post-
increment operator.
❑ Step 3 : Then, this incremented value “1” is assigned to the
variable “i”.
❑ Above 3 steps are continued until while expression becomes
false and output is displayed as “1 2 3 4 5”.
/* Program for Pre Increment*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int i = 1;
while (++i<5)
{
printf(“%d”, i );
} }
getch ( );
}

Output
234
Operators in C Contd…
a) Increment and Decrement Operators Contd…
❑ Step 1 : In above program, value of “i” is incremented from 0 to 1
using pre-increment operator.
❑ Step 2 : This incremented value “1” is compared with 5 in while
expression.
❑ Step 3 : Then, this incremented value “1” is assigned to the
variable “i”.
❑ Above 3 steps are continued until while expression becomes false
and output is displayed as “1 2 3 4”.
/* Program for Post Decrement*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int i = 10;
while (i--< 5)
{
printf(“%d”, i );
} }
getch ( );
}

Output
10 9 8 7 6
Operators in C Contd…
a) Increment and Decrement Operators Contd…
❑ Step 1 : In this program, value of i “10” is compared with 5 in
while expression.
❑ Step 2 : Then, value of “i” is decremented from 10 to 9 using post-
decrement operator.
❑ Step 3 : Then, this decremented value “9” is assigned to the
variable “i”.
❑ Above 3 steps are continued until while expression becomes
false and output is displayed as “9 8 7 6 5”.
/* Program for Pre Decrement*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int i = 10;
while (--i<5)
{
printf(“%d”, i);
} }
getch ( );
}

Output
9876
Operators in C Contd…
a) Increment and Decrement Operators Contd…
❑ Step 1 : In above program, value of “i” is decremented from 10 to
9 using pre-decrement operator.
❑ Step 2 : This decremented value “9” is compared with 5 in while
expression.
❑ Step 3 : Then, this decremented value “9” is assigned to the
variable “i”.
❑ Above 3 steps are continued until while expression becomes false
and output is displayed as “9 8 7 6”.
Operators in C Contd…
b) Comma Operator
❑ Special operator which separates the declaration of multiple
variables
❑ Has Lowest Precedence i.e it is having lowest priority so it is
evaluated at last
❑ Returns the value of the rightmost operand when multiple
comma operators are used inside an expression
❑ Acts as Operator in an Expression and as a Separator while
Declaring Variables
Operators in C Contd…
b) Comma Operator Contd…
#include<stdio.h>
int main( )
{
int i, j;
i=(j=10, j+20);
printf(“i = %d\n j = %d\n” , i,j );
return 0;

}
Operators in C Contd…
c) Arrow Operator (->)
❑ Arrow operator is used to access the structure members
when we use pointer variable to access it
❑ When pointer to a structure is used then arrow operator is
used
c) Arrow Operator (->)
#include <stdio.h>

#include<stdlib.h>

struct abc {

int a;};

int main(){

struct abc * g; g=(struct abc *)malloc(sizeof(struct abc));

g->a=19;

printf("%d",g->a);

return 0;}
Operators in C Contd…
d) Assignment Operators
❑ Assigns result of expression to a variable
❑ Performs Arithmetic and Assignment operations
❑ Commonly used Assignment operator: =
❑ Syntax variable = expression;
❑ Examples
❑ num = 25; age = 18; pi = 31.4; area = 3.14 * r * r;
Operators in C Contd…
❑ Shorthand Assignment Operators
Simple Assignment
Shorthand Operator
Operator
a=a+1 a+=1
a=a–1 a-=1
a=a*2 a*=2
a=a/b a/=b
a=a%b a%=b
c = c * (a + b) c *= (a + b)
b = b / (a + b) b /=(a + b)
/* Program for Assignment Operations*/
#include<stdio.h>
#include<conio.h>
void main( )
{
int a;
a = 11;
a+ = 4;
printf(“Value of A is %d\n”,a);
a = 11;
a- = 4;
printf(“Value of A is %d\n”,a);
a = 11;
a* = 4;
printf(“Value of A is %d\n”,a);
a = 11; a/ = 4;
printf(“Value of A is %d\n”,a);
a = 11;
a% = 4;
printf(“Value of A is %d\n”,a);
getch ( );
}

Output
Value of A is 15
Value of A is 7
Value of A is 44
Value of A is 2
Value of A is 3
Operators in C Contd…
e) Bitwise Operators
❑ In arithmetic-logic unit, mathematical operations like:
addition, subtraction, multiplication and division are done in
bit-level
❑ To perform bit-level operations in C programming, bitwise
operators are used
❑ Bit wise operators in C language are & (bitwise AND), |
(bitwise OR), ~ (bitwise NOT), ^ (XOR), << (left shift) and >>
(right shift)
Operators in C Contd…
e) Bitwise Operators Contd…
Operator Description Example

BinaryAND Operator copies a bit to the result if it (A &B) = 12, i.e., 0000
& exists in both operands. 1100

Binary OR Operator copies a bit if it exists in either (A | B) = 61, i.e., 0011


|
operand. 1101
Binary XOR Operator copies the bit if it is set in one (A ^ B) = 49, i.e., 0011
^ operand but not both. 0001

Binary Ones Complement Operator is unary and has (~A ) = -60, i.e,. 1100 0100
~ in 2's complement form.
the effect of 'flipping' bits.

Binary Left Shift Operator.The left operands value is


<< moved left by the number of bits specified by the A << 2 = 240 i.e., 1111
right operand. 0000

Binary Right Shift Operator.The left operands value


>> is moved right by the number of bits specified by the A >> 2 = 15 i.e., 0000 1111
right operand.
PROGRAM TO DEMONSTRATE BITWISE OPERATIONS

# include <stdio.h>
int main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0; c = a & b; /* 12 = 0000 1100 */
printf("Line 1 - Value of c is %d\n", c ); c = a | b; /* 61 = 0011 1101 */
printf("Line 2 - Value of c is %d\n", c ); c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 - Value of c is %d\n", c ); c = ~a; /*-61 = 1100 0011 */
printf("Line 4 - Value of c is %d\n", c ); c = a < < 2; /* 240 = 1111 0000 */
printf("Line 5 - Value of c is %d\n", c ); c = a > > 2; /* 15 = 0000 1111 */
printf("Line 6 - Value of c is %d\ n", c );
return 0;
}
Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Operators in C Contd…
f) Sizeof Operators
❑ This operator returns the size of its operand in bytes
❑ The sizeof operator always precedes its operand
❑ Used to calculate the size of data type or variables
❑ Can be nested
❑ Returns the size in integer format
❑ Syntax looks more like a function but it is considered as an
operator in c programming
/* Program for Sizeof Operators*/
#include<stdio.h>
int main( )
{
int a;
float b;
double c;
char d;
printf(“Size of Integer :%d\n\n”,sizeof(a));
printf(“Size of Floating Point :%d\n\n”,sizeof(b));
printf(“Size of Double :%d\n\n”,sizeof(c));
printf(“Size of Charcter :%d\n\n”,sizeof(d));
return 0;
}
Output
Size of Integer :2
Size of Floating Point :4
Size of Double :8
Size of Character :1
Operators in C
a) Relational Operators
b) Logical Operators
c) Conditional Operators
Operators in C Contd…
a) Relational Operators
❑ Binary Operators (or) Boolean Operators
❑ Produces an integer result
❑ Condition True : Integer value is 1
❑ Condition False : Integer value is 0
❑ Compares
❑ Values between two variables
❑ Values between variables and constants
Operators in C Contd…
a) Relational Operators Contd…
❑ Relational Expression / Boolean Expression : An
expression containing a relational operator
Operators in C Contd…
a) Relational Operators Contd…
❑ Consider a = 10 and b =4. The relational expression returns
the following integer values

Relational Expression Result Return Values


a<b False 0
a>b True 1
a<=b False 0
a>=b True 1
a==b False 0
a!=b True 1
/* Program for Relational Operations*/

#include<stdio.h>
int main( )
{
int a,b;
printf("Enter the two Values\n");
scanf("%d%d", &a, &b);
printf(“a>b is %d\n“, (a>b));
printf(“a<b is %d\n“, (a<b));
printf(“a>=b is %d\n“, (a>=b));
printf(“a<=b is %d\n“, (a<=b));
printf(“a==b is %d\n“, (a==b));
printf(“a!=b is %d\n“, (a!=b));
return 0;
}
Output
4
2
a > b is 1
a < b is 0
a > = b is 1
a < = b is 0
a = = b is 0
a ! = b is 1
Operators in C Contd…
b) Logical Operators
❑ Combines two or more relations
❑ Used for testing one or more conditions
Operators in C Contd…
b) Logical Operators Contd…
❑ Logical Expression / Compound Relational Expression :
An expression which combines two or more relational
expression

Op1 Op2 Op1 && Op2 Op1 || Op2


F (0) F (0) F (0) F (0)
F (0) T (1) F (0) T (1)
T (1) F (0) F (0) T (1)
T (1) T (1) T (1) T (1)
Operators in C Contd…
b) Logical Operators Contd…
❑ Consider a = 10 and b =4. The Logical expression returns the
following integer values

Relational Expression Result Return Values


a < 5 && b > 2 True 1
a < 5 && b < 2 False 0
a >5 && b < 2 False 0
a >5 || b < 2 True 1
a <5 || b < 2 False 0
a > 5 || b < 2 True 1
/* Program for Logical Operations*/

#include<stdio.h>
int main( )
{
int age,height;
printf("Enter Age of Candidate:\n");
scanf("%d", &age);
printf(“Enter Height of Candidate:\n“);
scanf("%d", &height);
if ((age>=18) && (height>=5))
printf(“The Candidate is Selected”);
else
printf(“Sorry, Candidate not Selected”);
return 0;
}
Output 1
Enter Age of Candidate: 18
Enter Height of Candidate: 6
The Candidate is Selected

Output 2
Enter Age of Candidate: 19
Enter Height of Candidate: 4
Sorry, Candidate not Selected
Operators in C Contd…
c) Conditional Operators
❑ ? and are the Conditional Operators
❑ Also called as Ternary Operators
❑ Shorter form of if-then-else statement
❑ Syntax
Expression 1 ? Expression 2 : expression 3
❑ If expression 1 is true then the value returned will be
expression 2

❑ Otherwise the value returned will be expression 3


#include<stdio.h>
#include<stdio.h> int main( )
int main( ) {
{ int x, y;
int x, y; scanf("%d", &x);
if(x >5)
scanf("%d", &x);
y=(x > 5 ? 3 : 4); y=3;
printf(“%d”, y); else
return 0; y=4;
} printf(“%d”, y);
return 0;
}
THANK YOU

You might also like