SlideShare a Scribd company logo
Chapter 2: Introduction to Language
Semantics & Program Flow
By Mr. Samwel Tarus
Overview
Introduction to Character set
C Tokens
Management of Input and output in C language
Character set
• Collection of letters, digits, white spaces and special characters that are used to
form instructions in a program / used to represent information.
• The characters that can be used to form words, numbers and expressions depend
upon the computer on which the program is run. E.g
• LOWERCASE LETTERS a-z
• UPPER CASE LETTERS A-Z
• DIGITS 0, 1, 2, …. 9
• WHITE SPACES (Blank spaces)
• SPECIAL CHARACTERS
+ - * / = % & # ! ? ^
“ ‘ ~  | < > ( ) [ ]
{ } : ; . , _
C Tokens
Basic element recognized by the compiler.
Source-program text that the compiler does not break down into
component elements.
The smallest individual units that acts as basic building blocks in
program development.
E.g: Keywords, Identifiers (Variables), Constants, Operators
Cont’d…
Keywords
Reserved words whose meaning is understood by the compiler.
Predefined words that serve as basic building blocks in program development.
 They have standard, fixed, predefined meanings in C. These meanings cannot be
changed.
It cannot be used as an identifier.
All the keywords are written in lower case
The standard keywords are
Int, float, auto, break, continue, return, else, if, long, switch, default, do, whiule,
static, short, void, goto, sizeof, volatile, for char
Variable/Identifiers
Anything that changes in the execution of the program.
Named location in the memory that has a value.
Identifiers refer to the names of variables, functions and arrays.
These are user-defined names and consist of a sequence of letters and digits.
x = 3
x can hold different values at different times x is known as a variable
Variables are user-defined data types:
Rules regarding variable formation:
Variable names must not be keywords
Variable names must not have a white space in between
Variable names are case sensitive
Variable names can start or be separated with an underscore
Variable names must not begin with a digit
Constants
• Values that do not change during the execution of a program.
• C supports several types of constants: eg
Primary constants
Constants Explained
Integer constants:
sequence of digits (whole numbers) eg, 2, 78,45,0, 1,
Occupy 2 bytes in memory
Given by keyword int
Management of i/o is %d
Float Constants:
Sequence of digits with decimal points eg, 12.5, 0.003, 34.890
numbers that contain fractional part are called real or floating-point constants.
Occupies 4 bytes of memory
Given by the keyword float
Management of i/o is %f
Cont’d …
Character Constant:
Any single character enclosed in single quotes eg, ‘a’, ‘5’, ‘ ‘ ‘$’
Occupies 1 byte of memory
Given by the keyword char
Management of i/o is %c
String constant:
A string constant is a sequence of characters enclosed in double quotes.
The characters may be letters, numbers, special characters, blank space.
Ex: “KSR” “College of Arts and Science”
Occupies total number of characters + 1
 Given by the keyword char
 Management of i/o is %s
Escape Sequence / Charcters
Character combinations consisting of a backslash () followed by a letter or by
a combination of digits.
Used to format o/p
Examples:
 a Alert
 n New Line
 t Tab
 r Carriage Return
 b Backspace
 o Null
Data types
C supports four classes of data types namely
1. Primary or fundamental data types
2. User-defined data types
3. Derived data types
4. Empty data set
Primary data types
All C compilers support four fundamental data types namely;
 integer (int),
character (char),
floating point (float) and
double precision floating point (double).
Operators and Expressions
• Operator: Symbol which helps the user to command the computer to do a
certain mathematical or logical manipulations.
• Sign or symbol that is used to manipulate two or more variables, constants,
expressions etc.
• Operators are used in C language program to operate on data and variables.
C has a rich set of operators.
• Expresion:
• Collection of variables, constants operators and must evaluate to a value
• E.g x = (y+2) < 9
Operators (Cont’d …)
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Comma operator
9. Special Operators
Arithmetic Operators
+ Addition
- subtraction
* Multiplication
/ Division
% Modulus
Relational Operators
• Used to compare two or more variables, constants, and expressions in the
program: eg
• Used in making decisions, Always evaluate to either true or false:
Logical Operators
Combine or evaluate logical and relational expressions.
Logical AND (&&)
Logical OR (||)
Logical NOT (!)
Nb: logical operators evaluate to either true of false
Assignment Operator
(=), is used to assign the result of an expression to a variable.
C has a set of ‘shorthand’ assignment operators of the form
Var = value;
Var oper=value;
The Assignment Operator evaluates an expression on the right of the expression
and substitutes it to the variable on the left of the expression.
Example 1:
x = a + b
Here the value of a + b is evaluated and substituted to the variable x.
Example 2:
x + = 1 is same as x = x + 1
Increment and Decrement Operators
Use to increase or decrease the value of the variable by some value eg; ++ , --
The operator ++ adds 1 to the operand while -- subtracts 1.
Both are unary operators and can appear before the variable called prefix and
after the variable called postfix.
++a and --a (Prefix Increment / Decrement Operator)
a++ and a-- (Postfix Increment / Decrement Operator)
++a is equivalent to a = a + 1 or a += 1
 --a is equivalent to a = a – 1 or a – = 1
Conditional Operators
Called ternary operator is denoted as ? :
Used to evaluate the value of an expression.
Syntax: res = (expression) ? True : false;
Eg; res = (x < y) ? 3 : 7;
Bitwise Operators
To manipulation data / values at bit level.
Eg:
& Bitwise And
| Bitwise Or
! Bitwise Not
<< Bitwise Shift left
>> Bitwise Shift Right
~ Ones Complement
Comma operator
Used to separate variables, constants, expressions in a
program.
Eg, int a,b,c;
{2,4,6,1,8,4}
Special Operators
& -Ampersand
- Address of operator
- Returns the address where the variable is residing in the memory
* -Asterik /Star
-Value at address operator
-Returns value contained in the address
Sizeof() - sizeof function operator
- Return the number of bytes occupied by a variable, constant in memory
Eg. x=sizeof(2);
Program examples (Objective is mgt of I/O)
1. A program to find the perimeter of a rectangle
2. A program to compute simple Interest for the sum invested for any number
of years.
3. A program that reads the name of a student and find the total marks of four
subjects.
4. A program that checks the size of memory occupied variables in a program.
Read on operator precedence and associativity
Control Structures / Statements
Directs the flow of execution in a program.
C language control statement are divided into three categories:
1. Decision control structures
2. Looping control structures
3. Jumping control structures
Branching: The process of taking the alternative course of action against the
other.
Looping: The process of repeating / iterating a block of statements any number of
times.
Jumping: Moving to a specified location / point in a program
Decision Control Structures
Facilitate the action of branching
Examples of structures / statements;
i. if statement
ii. if ... else statement
iii. nested if … else statement
iv. switch case statement
Looping Control structures
Facilitate the action of repetition / iteration
Examples:
i. for loop
ii. do … while loop
iii. while loop
Jumping Control Structures
Facilitate the action of jumping to some other point in the program:
Examples:
i. break statement
ii. continue statement
iii. goto statement
If control structure
Control structure that considers only the true part of the condition;
Syntax:
Example 1;
if(condition)
Statement;
Example 2
if(condition)
{
Statement;
Statement;
Statement;
}
Cont’d …
Program example (for if control statement)
a. Write a program to check if any input number is a an even number.
b. Write a program to check if any input number is less than zero.
c. Nb: also draw a flowchart of the same
If … else
Syntax:
if(condition)
{
Statement;
Statement;
}
else
{
statement;
Statement;
}
Cont’d …
Program demo for if .. else
a. Program to check if any input number is either odd or even number
b. Program to check if any input number is divisible by 5
Nb: also draw a flowchart for the same
Nested if … else
if(cond)
statement
else if(cond)
statement
else if(cond)
statement;
else
statement;
Cont’d …
Program demo for nested if … else
Write a program that reads the name and the marks scored by a
student, and to display the corresponding grade:
Use the given grading system:
< 0 marks Invalid marks
Between 0 and 39 grade = E, Fail
Between 40 and 49 Grade = D
Between 50 and 59 Grade = C
Between 60 and 69 Grade = B
Between 70 and 100 Grade = A
> 100 marks beyond the range
Switch case
switch(exp)
{
case 1:
statement;
statement;
break;
case 2:
statement;
statement;
break;
case n:
statement;
statement;
break;
default:
statement;
statement;
break;
}
Switch case: Explanation
An expression must evaluate to a value. The value of the expression is
compared upon several cases in the switch case control structure.
The case that matches the value of an expression, is executed.
The break statement in each of the cases transfers the control of execution
outside the switch control structure.
The default option handles any mismatch in the control structure.
Program demo for switch case:
• Write a menu driven program to preform the following:
• Compute the perimeter of a rectangle
• Compute the sum of two numbers
Ie:
Main menu
1. perimeter
2. sum
Enter your choice
comp 122 Chapter 2.pptx,language semantics

More Related Content

Similar to comp 122 Chapter 2.pptx,language semantics

C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)sachindane
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2Don Dooley
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniquesvalarpink
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III TermAndrew Raj
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptxAnisZahirahAzman
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdfHome
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 FocJAYA
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C ProgrammingMOHAMAD NOH AHMAD
 
C programming language
C programming languageC programming language
C programming languageAbin Rimal
 
unit 1 cpds.pptx
unit 1 cpds.pptxunit 1 cpds.pptx
unit 1 cpds.pptxmadhurij54
 

Similar to comp 122 Chapter 2.pptx,language semantics (20)

C Language (All Concept)
C Language (All Concept)C Language (All Concept)
C Language (All Concept)
 
2 EPT 162 Lecture 2
2 EPT 162 Lecture 22 EPT 162 Lecture 2
2 EPT 162 Lecture 2
 
Introduction%20C.pptx
Introduction%20C.pptxIntroduction%20C.pptx
Introduction%20C.pptx
 
PSPC--UNIT-2.pdf
PSPC--UNIT-2.pdfPSPC--UNIT-2.pdf
PSPC--UNIT-2.pdf
 
Problem Solving Techniques
Problem Solving TechniquesProblem Solving Techniques
Problem Solving Techniques
 
C programming | Class 8 | III Term
C programming  | Class 8  | III TermC programming  | Class 8  | III Term
C programming | Class 8 | III Term
 
component of c language.pptx
component of c language.pptxcomponent of c language.pptx
component of c language.pptx
 
Basics of c
Basics of cBasics of c
Basics of c
 
C intro
C introC intro
C intro
 
C material
C materialC material
C material
 
c_programming.pdf
c_programming.pdfc_programming.pdf
c_programming.pdf
 
Unit 4 Foc
Unit 4 FocUnit 4 Foc
Unit 4 Foc
 
Introduction to C Programming
Introduction to C ProgrammingIntroduction to C Programming
Introduction to C Programming
 
C programming language
C programming languageC programming language
C programming language
 
C programming
C programmingC programming
C programming
 
unit 1 cpds.pptx
unit 1 cpds.pptxunit 1 cpds.pptx
unit 1 cpds.pptx
 
c programming session 1.pptx
c programming session 1.pptxc programming session 1.pptx
c programming session 1.pptx
 
Pc module1
Pc module1Pc module1
Pc module1
 
Basics of C.ppt
Basics of C.pptBasics of C.ppt
Basics of C.ppt
 
c-programming
c-programmingc-programming
c-programming
 

More from floraaluoch3

Functions.pptx, programming language in c
Functions.pptx, programming language in cFunctions.pptx, programming language in c
Functions.pptx, programming language in cfloraaluoch3
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cfloraaluoch3
 
901470_Chap1.ppt.artificial intelligence
901470_Chap1.ppt.artificial intelligence901470_Chap1.ppt.artificial intelligence
901470_Chap1.ppt.artificial intelligencefloraaluoch3
 
lecture-2-3_Memory.pdf,describing memory
lecture-2-3_Memory.pdf,describing memorylecture-2-3_Memory.pdf,describing memory
lecture-2-3_Memory.pdf,describing memoryfloraaluoch3
 
lect11-12_parallel.pdf,describing parallelism
lect11-12_parallel.pdf,describing parallelismlect11-12_parallel.pdf,describing parallelism
lect11-12_parallel.pdf,describing parallelismfloraaluoch3
 
Computational models,vonneuman model,turing model
Computational models,vonneuman model,turing modelComputational models,vonneuman model,turing model
Computational models,vonneuman model,turing modelfloraaluoch3
 

More from floraaluoch3 (6)

Functions.pptx, programming language in c
Functions.pptx, programming language in cFunctions.pptx, programming language in c
Functions.pptx, programming language in c
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in c
 
901470_Chap1.ppt.artificial intelligence
901470_Chap1.ppt.artificial intelligence901470_Chap1.ppt.artificial intelligence
901470_Chap1.ppt.artificial intelligence
 
lecture-2-3_Memory.pdf,describing memory
lecture-2-3_Memory.pdf,describing memorylecture-2-3_Memory.pdf,describing memory
lecture-2-3_Memory.pdf,describing memory
 
lect11-12_parallel.pdf,describing parallelism
lect11-12_parallel.pdf,describing parallelismlect11-12_parallel.pdf,describing parallelism
lect11-12_parallel.pdf,describing parallelism
 
Computational models,vonneuman model,turing model
Computational models,vonneuman model,turing modelComputational models,vonneuman model,turing model
Computational models,vonneuman model,turing model
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaCzechDreamin
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...Product School
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupCatarinaPereira64715
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Julian Hyde
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
Measures in SQL (a talk at SF Distributed Systems meetup, 2024-05-22)
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 

comp 122 Chapter 2.pptx,language semantics

  • 1. Chapter 2: Introduction to Language Semantics & Program Flow By Mr. Samwel Tarus
  • 2. Overview Introduction to Character set C Tokens Management of Input and output in C language
  • 3. Character set • Collection of letters, digits, white spaces and special characters that are used to form instructions in a program / used to represent information. • The characters that can be used to form words, numbers and expressions depend upon the computer on which the program is run. E.g • LOWERCASE LETTERS a-z • UPPER CASE LETTERS A-Z • DIGITS 0, 1, 2, …. 9 • WHITE SPACES (Blank spaces) • SPECIAL CHARACTERS + - * / = % & # ! ? ^ “ ‘ ~ | < > ( ) [ ] { } : ; . , _
  • 4. C Tokens Basic element recognized by the compiler. Source-program text that the compiler does not break down into component elements. The smallest individual units that acts as basic building blocks in program development. E.g: Keywords, Identifiers (Variables), Constants, Operators
  • 6. Keywords Reserved words whose meaning is understood by the compiler. Predefined words that serve as basic building blocks in program development.  They have standard, fixed, predefined meanings in C. These meanings cannot be changed. It cannot be used as an identifier. All the keywords are written in lower case The standard keywords are Int, float, auto, break, continue, return, else, if, long, switch, default, do, whiule, static, short, void, goto, sizeof, volatile, for char
  • 7. Variable/Identifiers Anything that changes in the execution of the program. Named location in the memory that has a value. Identifiers refer to the names of variables, functions and arrays. These are user-defined names and consist of a sequence of letters and digits. x = 3 x can hold different values at different times x is known as a variable Variables are user-defined data types:
  • 8. Rules regarding variable formation: Variable names must not be keywords Variable names must not have a white space in between Variable names are case sensitive Variable names can start or be separated with an underscore Variable names must not begin with a digit
  • 9. Constants • Values that do not change during the execution of a program. • C supports several types of constants: eg
  • 11. Constants Explained Integer constants: sequence of digits (whole numbers) eg, 2, 78,45,0, 1, Occupy 2 bytes in memory Given by keyword int Management of i/o is %d Float Constants: Sequence of digits with decimal points eg, 12.5, 0.003, 34.890 numbers that contain fractional part are called real or floating-point constants. Occupies 4 bytes of memory Given by the keyword float Management of i/o is %f
  • 12. Cont’d … Character Constant: Any single character enclosed in single quotes eg, ‘a’, ‘5’, ‘ ‘ ‘$’ Occupies 1 byte of memory Given by the keyword char Management of i/o is %c String constant: A string constant is a sequence of characters enclosed in double quotes. The characters may be letters, numbers, special characters, blank space. Ex: “KSR” “College of Arts and Science” Occupies total number of characters + 1  Given by the keyword char  Management of i/o is %s
  • 13. Escape Sequence / Charcters Character combinations consisting of a backslash () followed by a letter or by a combination of digits. Used to format o/p Examples:  a Alert  n New Line  t Tab  r Carriage Return  b Backspace  o Null
  • 14. Data types C supports four classes of data types namely 1. Primary or fundamental data types 2. User-defined data types 3. Derived data types 4. Empty data set
  • 15. Primary data types All C compilers support four fundamental data types namely;  integer (int), character (char), floating point (float) and double precision floating point (double).
  • 16. Operators and Expressions • Operator: Symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. • Sign or symbol that is used to manipulate two or more variables, constants, expressions etc. • Operators are used in C language program to operate on data and variables. C has a rich set of operators. • Expresion: • Collection of variables, constants operators and must evaluate to a value • E.g x = (y+2) < 9
  • 17. Operators (Cont’d …) 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Assignment Operators 5. Increment and Decrement Operators 6. Conditional Operators 7. Bitwise Operators 8. Comma operator 9. Special Operators
  • 18. Arithmetic Operators + Addition - subtraction * Multiplication / Division % Modulus
  • 19. Relational Operators • Used to compare two or more variables, constants, and expressions in the program: eg • Used in making decisions, Always evaluate to either true or false:
  • 20. Logical Operators Combine or evaluate logical and relational expressions. Logical AND (&&) Logical OR (||) Logical NOT (!) Nb: logical operators evaluate to either true of false
  • 21. Assignment Operator (=), is used to assign the result of an expression to a variable. C has a set of ‘shorthand’ assignment operators of the form Var = value; Var oper=value; The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the variable on the left of the expression. Example 1: x = a + b Here the value of a + b is evaluated and substituted to the variable x. Example 2: x + = 1 is same as x = x + 1
  • 22. Increment and Decrement Operators Use to increase or decrease the value of the variable by some value eg; ++ , -- The operator ++ adds 1 to the operand while -- subtracts 1. Both are unary operators and can appear before the variable called prefix and after the variable called postfix. ++a and --a (Prefix Increment / Decrement Operator) a++ and a-- (Postfix Increment / Decrement Operator) ++a is equivalent to a = a + 1 or a += 1  --a is equivalent to a = a – 1 or a – = 1
  • 23. Conditional Operators Called ternary operator is denoted as ? : Used to evaluate the value of an expression. Syntax: res = (expression) ? True : false; Eg; res = (x < y) ? 3 : 7;
  • 24. Bitwise Operators To manipulation data / values at bit level. Eg: & Bitwise And | Bitwise Or ! Bitwise Not << Bitwise Shift left >> Bitwise Shift Right ~ Ones Complement
  • 25. Comma operator Used to separate variables, constants, expressions in a program. Eg, int a,b,c; {2,4,6,1,8,4}
  • 26. Special Operators & -Ampersand - Address of operator - Returns the address where the variable is residing in the memory * -Asterik /Star -Value at address operator -Returns value contained in the address Sizeof() - sizeof function operator - Return the number of bytes occupied by a variable, constant in memory Eg. x=sizeof(2);
  • 27. Program examples (Objective is mgt of I/O) 1. A program to find the perimeter of a rectangle 2. A program to compute simple Interest for the sum invested for any number of years. 3. A program that reads the name of a student and find the total marks of four subjects. 4. A program that checks the size of memory occupied variables in a program. Read on operator precedence and associativity
  • 28. Control Structures / Statements Directs the flow of execution in a program. C language control statement are divided into three categories: 1. Decision control structures 2. Looping control structures 3. Jumping control structures Branching: The process of taking the alternative course of action against the other. Looping: The process of repeating / iterating a block of statements any number of times. Jumping: Moving to a specified location / point in a program
  • 29. Decision Control Structures Facilitate the action of branching Examples of structures / statements; i. if statement ii. if ... else statement iii. nested if … else statement iv. switch case statement
  • 30. Looping Control structures Facilitate the action of repetition / iteration Examples: i. for loop ii. do … while loop iii. while loop
  • 31. Jumping Control Structures Facilitate the action of jumping to some other point in the program: Examples: i. break statement ii. continue statement iii. goto statement
  • 32. If control structure Control structure that considers only the true part of the condition; Syntax: Example 1; if(condition) Statement; Example 2 if(condition) { Statement; Statement; Statement; }
  • 34. Program example (for if control statement) a. Write a program to check if any input number is a an even number. b. Write a program to check if any input number is less than zero. c. Nb: also draw a flowchart of the same
  • 37. Program demo for if .. else a. Program to check if any input number is either odd or even number b. Program to check if any input number is divisible by 5 Nb: also draw a flowchart for the same
  • 38. Nested if … else if(cond) statement else if(cond) statement else if(cond) statement; else statement;
  • 40. Program demo for nested if … else Write a program that reads the name and the marks scored by a student, and to display the corresponding grade: Use the given grading system: < 0 marks Invalid marks Between 0 and 39 grade = E, Fail Between 40 and 49 Grade = D Between 50 and 59 Grade = C Between 60 and 69 Grade = B Between 70 and 100 Grade = A > 100 marks beyond the range
  • 41. Switch case switch(exp) { case 1: statement; statement; break; case 2: statement; statement; break; case n: statement; statement; break; default: statement; statement; break; }
  • 42.
  • 43. Switch case: Explanation An expression must evaluate to a value. The value of the expression is compared upon several cases in the switch case control structure. The case that matches the value of an expression, is executed. The break statement in each of the cases transfers the control of execution outside the switch control structure. The default option handles any mismatch in the control structure.
  • 44. Program demo for switch case: • Write a menu driven program to preform the following: • Compute the perimeter of a rectangle • Compute the sum of two numbers Ie: Main menu 1. perimeter 2. sum Enter your choice