All Lecture Notes For CS111 & COM101 (Intro. To CS Fall 2024)
All Lecture Notes For CS111 & COM101 (Intro. To CS Fall 2024)
to Computer Science
Computer Science Dept.
Helwan University
FALL 2024
Contents
0: Course Introduction & Plan
1: Computational Thinking – Part 1
(Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2
(Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3
(Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & relational Operators, and Precedence
6: Control Structures – Selection (Decisions / Choice)
7: Control Structures – Repetition (Loops / Iterations)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & the Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference vs. Call-by-Value
12: Solved Examples (2nd Set)
2
Recorded Lectures | Announcements | Additional
Resources | Contacts
Recorded Lectures:
• https://www.youtube.com/AmrSGhoneim
• https://www.youtube.com/playlist?list=PLsnvpvHuTUbDQZEakmW9YzwGxHTO9VlUR
• https://www.linkedin.com/in/amrghoneim/
3
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 0
Course Introduction
& Plan
▪ Course Details & Course Instructor (Short Bio)
▪ Dependent Courses (CS111 as a Prerequisite)
▪ Tentative Topics & Learning Objectives
▪ Course Logistics & Grading Policy
▪ Previous Course Statistics Faculty of
▪ Be an Effective Learner ..? Computing &
Artificial Intelligence
▪ Classroom Code of Conduct
▪ Academic Agenda FALL 2024
Course Details
2
Tentative Topics
& Learning Objectives
.. of this course
3
Learning Objectives of this Course [ ] أهداف المقرر
ماذا ستتعلم؟
فهم واسع وقوي لعلوم الحاسوب ومجاالته ،والتفكير الحسابي ،والبرمجة.
معرفة المكونات الرئيسية لنظام الحاسوب (األجهزة ،البرامج،
البيانات/المعلومات).
التعرف على كيفية عمل الحواسيب من خالل مقدمة في أنظمة األرقام والتمثيل
الثنائي.
كيفية التفكير بشكل خوارزمي (منهجي) لحل مشكالت البرمجة األساسية بكفاءة،
وكيفية تمثيل الخوارزميات.
اإللمام بمفاهيم مثل التجريد ،والخوارزميات ،وهياكل البيانات ،وهندسة
البرمجيات.
اإللمام بمفاهيم البرمجة األساسية.
اإللمام بلغة البرمجة .C
5
Learning Objectives of this Course [ ] أهداف المقرر
.. Continued..
As well, Students by the end of this course should be able to:
Think more methodically (logically / systematically);
Program procedurally;
Represent & process information;
Solve basic problems efficiently;
Recognize patterns among problems;
Decompose problems into parts;
Operate at multiple levels of abstraction;
Separate design from implementation details;
Assess the correctness, design, and style of code;
Teach themselves new languages;
6
] أهداف المقرر [ Learning Objectives of this Course
.. Continued..
بحلول نهاية هذا المقرر ،يجب أن يكون الطالب قادرين على:
التفكير بشكل أكثر منهجية (منطقيًا /بشكل منظم).
البرمجة بطريقة إجرائية.
تمثيل ومعالجة المعلومات.
حل المشكالت األساسية بكفاءة.
التعرف على األنماط بين المشكالت.
تقسيم المشكالت إلى أجزاء.
العمل على مستويات متعددة من التجريد.
فصل التصميم عن تفاصيل التنفيذ.
تقييم صحة التصميم وأسلوب كتابة الشيفرة.
تعليم أنفسهم لغات برمجة جديدة.
7
Learning Objectives of this Course [ ] أهداف المقرر
.. Continued..
سا قويًا
ً يوفر هذا المقرر للطالب أسا.. – كأي مقرر تمهيدي لعلوم الحاسوب
لمواصلة دراستهم في مجال علوم الحاسوب ويمنحهم القدرة على تطبيق علوم
.الحاسوب لحل المشكالت في مجاالت أخرى
8
Topics Covered [ Tentative ]
The main contents of the course are:
▪ What is a Computer? What is Computer Science?
▪ Computer terminology, and Hardware versus Software.
▪ Algorithms, Pseudocode, Flowcharts, and Programming Languages.
▪ Generations of Computers, & Computers’ classification.
▪ Problem solving concepts & an Introduction to C programming.
▪ Comments in C, Pre-processor Directives, & the Main Function.
▪ Statements, Variables, Data Types, and C Built-in Functions.
▪ Tracing a Program & Memory Concepts.
▪ C operators (arithmetic, equality, relational, logical, and bitwise), &
Operators Precedence.
▪ Counter / Sentinel controlled repetition, & Break / Continue statements.
▪ User-Defined Functions, Functions Overloading, & Recursive
Functions.
▪ Binary Data Representation.
▪ Important Number Systems for Computers & Conversions between
Number Systems.
▪ Binary Arithmetic & Logic, and Negative Numbers & Complements.
9
Course Logistics
• Announcements & Course Materials
• Additional Resources (per section)
• Assessment Summary (Grading Policy)
• Exercises .. What have we learned?
• Be an Effective Learner ..?
• Classroom Code of Conduct
• Academic Integrity & Plagiarism
10
Announcements & Course Materials
Video Lessons:
All recorded lectures are on the following:
11
Announcements & Course Materials
12
Announcements & Course Materials
Required Resources:
The prescribed textbook for the course is:
- Deitel and Deitel, "C How to Program", 8th Edition, Pearson Education Inc.
The Assessment for this subject consists of six components with the
following weightings (grading breakdown):
15
Exercises
What have we learned?
At the end of each section, there will be a set
review activities (exercises), that would help
you see the progress you've made in this
lesson.
The exercises would help you:
▪ Highlight what you have learned today &
emphasize key information.
▪ Correct misunderstandings.
▪ Summarize, review, & demonstrate your
understanding of major points.
▪ Transfer ideas to new situations.
Be an Effective Learner ..
o Have the desire to seek knowledge and acquire new skills (be
inquisitive / curious).
o Ask questions.
o Be an avid (keen & passionate) reader.
o Be an attentive / focused listener.
o Find your preferred learning style .. & .. Learn in multiple ways.
o Do NOT memorize.
o Embrace Discomfort.
o Practice, practice, practice (you must gain practical experience).
o Teach what you’ve learned to another person.
o Use testing to boost / improve learning.
o Avoid multitasking.
o Make use of Memory Improvement Basics.
o Draw up a schedule.
o Examine your lifestyle.
o Create a study station. 17
Classroom Code of Conduct
Be punctual & prepared to study:
- Attend all classes including online and face-to-face classes.
- Arrive to all classes on time.
- Keep all handouts & work in a folder and make sure they are well organised.
- Prepare yourself for your classes.
Participate in the classroom:
- Participate in class.
- Respect yourself, your teachers, and your classmates.
- Turn mobile phones off or put them on silent mode before entering the classroom.
- Adopt a professional attitude - no eating, side-talk, etc.
Study independently:
- Study outside the classroom as part of your student effort (about 6 to 8 hours per week).
- Complete all homework assignments and hand them in on time.
- Use the University/Faculty facilities (e.g., the library) and online resources.
Respect University regulations:
- Follow (University, Faculty, Department, and Programme) regulations.
- Know the due date of all assessments, submit them by that date & in the required format.
- Understand what you need to successfully progress.
- Maintain academic honesty (academic integrity & plagiarism). 18
Academic Integrity & Plagiarism
19
Previous Course Statistics .. & ..
Dependent Courses
.. a list of the Courses requiring
CS111 as a Prerequisite ..
20
The Grading / GPA System
Per Course
21
The Overall Grading / GPA System
22
[CS–111 HELWAN UNIVERSITY]
Natural Language
Understanding
AI460
AI360
Natural
Spoken language
Language
Processing
Processing AI435
Human Computer
Interaction AI380
Intelligent
Information
Systems IS441
Bioinformatics
AI490
Knowledge
Representation
Artificial Intelligence AI310
AI457
Algorithms CS316
Advanced
Algorithms
CS416
Compilers
CS419
Parallel Processing &
High-Performance
Computing CS471
-
-
-
-
CS241
Operating
Systems 1
Operating
Systems 2 CS342
Software
Engineering 2
CS352
Graduation Project
1 CS251
Software
Engineering
Programming Programming
Languages 2 Languages 3
CS213 CS313
Virtual Reality
IT431
Computer
Graphics 2 IT332
3D Modeling &
IT331
Animation IT456
Computer
Graphics 1
Game
Development
IT457
Artificial Intelligence Dept.
Computer Science Dept.
Concepts of
Programming
Information Systems Dept.
24
Languages CS410
Mainstream Programme
Multimedia
IT433
Real-time
Software &
Systems
Prog.
(IS425)
Languages 2
(CS213) Machine
Learning
(CS317)
Programme
Operating
Systems 1
(CS241)
Artificial
Intelligence
Medical Informatics
(CS361)
Data
Structures &
Algorithms
(CS316)
Graduation
Project
Software (MI416)
(CS111)
Engineering
1 (CS251) Software
Databases Engineering
Programming Languages 1 (CS112)
for 2 (CS352)
Healthcare
System Evidence-
Based
(IS211) Medicine
(IS313)
Large-Scale
Data-Handling
in Biology
(IS422)
Introduction to Computer Science
Mathematics for
25
Computer Science
(MA101)
[CS–111 HELWAN UNIVERSITY]
[CS–111 HELWAN UNIVERSITY]
Software Engineering
Programme
Data Structures
Algorithms
Systems 1 Languages 2 Intelligence Graphics 1
(CS316)
(CS241) (CS213) (CS361) (IT331)
27
Week: Starts: Tentative Academic Agenda (Topics)
Course Introduction & Plan + Computational Thinking – Part 1 (Computers,
Wk. 1 Sept. 28
Computer Science, & Binary Representation)
Wk. 1 Oct. 05 Computational Thinking – Part 2 (Algorithms & Programming Languages)
Wk. 2 Oct. 12 Computational Thinking – Part 3 (Basics of Programs & Compilation)
Wk. 3 Oct. 19 Variables, Constants, & Data Types in C
Wk. 4 Oct. 26 Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
Wk. 5 Nov. 02 Control Structures – Selection (Decisions)
Wk. 6 Nov. 09 Control Structures – Repetition (Loops)
Wk. 7 Nov. 16 Midterm Written Exams (20%) – Schedule TBA by the Faculty
Wk. 8 Nov. 23 C Built-In Functions & Solved Examples (1st Set) – Part 1
Self-study C Built-In Functions & Solved Examples (1st Set) – Part 2
Wk. 9 Nov. 30 User–Defined Functions & Scope of Variables
Wk. 10 Dec. 07 Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
Wk. 11 Dec. 14 Number Systems, Binary Arithmetic, & the Complements Representation
Self-study Solved Examples (2nd Set)
Quizzes (Practical & Written), Assignments & Sheets (20%) – Deadlines TBA online
Final Practical Exams (10%) + Final Written Exams (50%) – Schedule TBA by the Faculty 28
Up Next ..
Welcome to Lecture 1
CS111 | COM101
an Introduction to
Computer Science
Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 1
Computational
Thinking – Part 1
1.1 Computers & Computer Science
▪ What is a Computer? – The Evolution of
Computers. – Computer Science? – Informatics?
1.2 Binary versus Decimal Numeral System
1.3 Representation Faculty of
▪ ASCII & UNICODE – RGB, Pixels, Videos, & Audio Computing &
– Computer Graphics / Vision, Image & Signal Artificial Intelligence
Processing. FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
▪ Computer Science?
▪ Informatics?
1.3 Representation
▪ ASCII & UNICODE
4
The Evolution of Computers
George Boole; Invented
Ismail al-Jazari; Ada Lovelace;
Boolean logic, the basis of
Invented the first Writer of the world's modern digital computer
programmable first computer program. logic.
humanoid robots
in 1206.
6
Computer Science?
o Data; Raw, unorganized facts (can be in the form of text,
graphics, audio, or video).
o Information; Data that has been processed into a meaningful
form.
o Information Processing; Converting data into information
Information
Processing
data → → information
(data + meaning)
7
Computer Science?
Its fields can be divided into various theoretical and practical disciplines.
Programming
Computer Concepts & Data Structures Algorithms Databases
Languages
Science Data/Digital
Parallel &
Operating Computer Communication
Distributed
Systems Architecture & Computer
Computation
Networks
Artificial
Computer Computer Intelligence &
Robotics
Graphics Vision Machine
Learning
Health Informatics
Biomedical Medical Clinical
Bioinformatics
Informatics Informatics Informatics
11
Exercises
What have we learned?
▪ Computer Science?
▪ Informatics?
1.3 Representation
▪ ASCII & UNICODE
15
Decimal Vs. Binary
Number Systems
16
When we first learned to count, we might have used
one finger to represent one thing. That system is
called unary.
0123456789
17
Digital devices understand only two different states:
ON and OFF ..
01
18
Why does the following represent
one hundred and twenty-three?
123
19
1
The 3 is in the ones column.
123
10
The 2 is in the tens column.
123
100
And ..
The 1 is in the hundreds column.
123
20
Each place for a digit represents a power of ten, since
there are ten possible digits for each place.
100 10 1
123
100 × 1 + 10 × 2 + 1×3
21
100 10 1 100 10 1
000 006
001 007
002 008
003 009
004 ….?
005 22
100 10 1 100 10 1
000 006
001 007
002 008
003 009
004 010
005 23
In binary, with just two digits, we have powers of two
for each place value:
4 2 1
000
24
So, Decimal (powers of 10) ..
000
.. versus Binary (powers of 2).
22 21 20
000 25
Counting in Binary ..
4 2 1
000
26
Counting in Binary ..
4 2 1
001
27
Counting in Binary ..
4 2 1
010
28
Counting in Binary ..
4 2 1
011
29
Counting in Binary ..
4 2 1
100
30
Counting in Binary ..
4 2 1
101
31
Counting in Binary ..
4 2 1
110
32
Counting in Binary ..
4 2 1
111
33
How can we represent 8 in binary?
34
Binary makes sense for computers because we power them
with electricity, which can be either on or off, so each bit
only needs to be on or off.
bit
In a computer, there are millions, or billions of switches
called transistors that can store electricity and represent a
bit by being “on” or “off”.
35
With enough bits, or binary digits, computers can count to
any number.
36
What is the value of the following byte?
37
Binary Data Representation:
Computer memory is normally represented in terms of Kilobytes or
Megabytes. In the Metric System, one Kilo represents 1000 grams,
that is 103. In the Binary System, one Kilobytes represent 1024 bytes,
that is 210.
The following table shows the representation of various memory
sizes: Name Abbreviation Size (in bytes)
Kilo K 210
Mega M 220
Giga G 230
Tera T 240
Petta P 250
Exa E 260
Zetta Z 270
Yotta Y 280
Exercises
What have we learned?
▪ Computer Science?
▪ Informatics?
1.3 Representation
▪ ASCII & UNICODE
42
- ASCII & UNICODE
To represent letters, all we need to do is decide how
numbers map to letters. Some humans, many years ago,
collectively decided on a standard mapping called ASCII
(stands for American Standard Code for Information
Interchange). It's a 7-bit character code where every single
code represents a unique character.
A
The letter “A”, for example, is the number 65, and “B” is 66,
and so on.
44
A
ASCII 65
1000001
45
... A B C D E F G H I ...
ASCII
... 65 66 67 68 69 70 71 72 73 ...
46
The mapping includes upper and lowercase Latin alphabet,
the numbers 0-9, and some extra characters (punctuation
and other symbols).
47
The first thirty-two codes (0 to 31) in ASCII are reserved for control
codes that control computer equipment (such as printers). For example,
code 10 represents the "line feed" function (which causes a printer to
advance its paper). Table 1 shows the printable characters with the
ASCII.
48
So, if you received the following
message, what does it mean?
49
So, if you received the following
message, what does it mean?
G o o d D a y !
50
How is the following message sent?
65
51
How is the following message sent?
6 5
54 53
110110 110101
52
Other characters, like letters with
accent marks, and emoji, are part
of a standard called Unicode that
use more bits than ASCII to
accommodate all these
characters.
53
Unicode
Unicode – Egyptian Hieroglyphs
Examples:
54
Unicode – Arabic
Unicode
55
- Pixels, & the RGB System
- Image, Video, and Audio Files
An image, too, is comprised of many smaller square dots, or pixels,
each of which can be represented in binary with a system called
RGB:
.. with values for red, green, and blue light in each pixel.
By mixing different amounts of each color, we can represent
millions of colors. 57
We can see this in an emoji if we zoom in far enough:
58
Pixels; Picture Elements
59
What does the following numbers mean
in the context of images (pixels)?
72 73 33
60
What does the following numbers mean
in the context of images (pixels)?
RGB: 72 73 33
61
The red, green, and blue values are
combined to get a light-yellow color:
RGB: 72 73 33 ➔
62
An RGB Example ..
63
Videos are just many, many images
displayed one after another, at some number
of frames per second.
64
65
66
67
68
Sub-fields of CS dealing
with images?
Computer vision; deals with how
computers can gain high-level
understanding from digital images
or videos. It seeks to understand
and automate tasks that the
human visual system can do.
Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 2
Computational
Thinking – Part 2
2.1 Computer Hardware
▪ Central Processing Unit, & Storage – Input, Output, &
Communication Devices – Digital Design & Computer Architecture
2.2 Algorithms
▪ What is an algorithm? – The four essential properties of an algorithm
– An Algorithms’ Complexity – Advancement in Algorithms: AI
2.3 Pseudocodes & Flow-Charts Faculty of
2.4 Programming Languages Computing &
Artificial Intelligence
▪ What is a Programming Language? – Programming Languages vs.
Natural Languages – Which Language to Learn? FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )
RAM
ROM
Ports;
A port is a channel through which data is transferred between
input/output devices and the processor. E.g., Universal Serial
Bus (USB), Network Port, etc.
9
Exercises
What have we learned?
2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )
input →
? → output
13
Recap:
Computer science is fundamentally problem-solving; taking
some input (details about our problem) & generating some
output (the solution to our problem). Information Processing
is converting data (raw, unorganized facts) into information
(data processed into a meaningful form).
Computer
Science (Problem → Output
Input (problem
Solving, (problem’s
definition, data) Information solution,
→ Processing) information)
.. via ..? 14
The black box earlier will contain algorithms, step-by-step
instructions for solving a problem:
Algorithms
18
We could start by flipping through the book, one page at a time,
until we find Mike Smith or reach the end of the book.
1024
1023
1022
1021
1020
1019
1018
1017
1016
1015
1014
... 19
We could also flip two pages at a time, but if we go too far, we’ll
have to know to go back a page.
1024
1022
1020
1018
1016
1014
1012
1010
1008
1006
1004
... 20
But an even more efficient way would be opening the phone
book to the middle, decide whether Mike will be in the left half
or right half of the book (because the book is alphabetized), and
immediately throw away half of the problem.
1024
512
We can repeat this, 256
dividing the problem in
128
half each time. With 1024
pages to start, we would 64
only need 10 steps of 32
dividing in half before we 16
have just one page 8
remaining to check. 4
2
1 21
In fact, we can represent the efficiency of each of those
algorithms with a chart:
22
Our first solution, one page at a time, is like the red line: our
time to solve increases linearly as the size of the problem
increases.
23
The second solution, two pages at a time, is like the yellow line:
our slope is less steep, but still linear.
24
The second solution, two pages at a time, is like the yellow line:
our slope is less steep, but still linear.
x pages
25
The second solution, two pages at a time, is like the yellow line:
our slope is less steep, but still linear.
x pages
26
Our first solution, one page at a time, is like the red line:
Steeper when compared to the yellow line.
x pages
27
Our first solution, one page at a time, is like the red line:
Steeper when compared to the yellow line.
x pages
28
Our final solution, is like the green line: logarithmic, since our
time to solve rises more & more slowly as the size of the
problem increases.
In other words, if the phone book
went from 1000 to 2000 pages, we
would need one more step to find
Mike. If the size doubled again from
2000 to 4000 pages, we would still
only need one more step.
x pages
29
Advanced Algorithms?
→ Artificial Intelligence .. ?
"The exciting new effort to make computers think .. machines
with minds, in the full and literal sense." (Haugeland, 1985)
30
Advanced (Intelligent) Systems in your everyday life
o Post Office
- Automatic address recognition, and automatic sorting of mail
o Banks
- Automatic check readers, signature verification systems
- Automated loan application classification
o Customer Service
- Automatic voice recognition, speech recognition, & language recognition
o The Web
- Identifying your age, gender, location, from your Web surfing
o Digital Cameras
- Automated face detection and recognition
o Computer Games
- Intelligent characters/agents
o Hospitals & Medical Centers
- Automatic Cancer Detection, Automatic Prediction & Grading of Diseases,
Mass Screening Systems, etc.
31
Algorithms .. How are they represented?
1. Pseudocode
2. Flowcharts
32
Exercises
What have we learned?
▪ Define an Algorithm.
2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )
Pseudocode
It is a mixture of:
• English statements (or any other language).
• Some mathematical notations.
• Selected keywords from programming language.
• And there is no standard convention for writing pseudo-
codes, as long as clarity is ensured. 36
Pseudocode for our algorithm:
Flowcharts
1 2 3
4 5 6 42
Flowcharts
Flowcharts consist basically of the following 6 symbols:
44
Start
later in NO
Book?
C
YES
Open to middle of
right half of book
B
46
We can write programs with the building blocks
we just discovered:
- Functions
- Conditions / Decisions
- Boolean Expressions
- Loops / Repetitions
47
Exercises
What have we learned?
▪ Discuss the relation between algorithms, pseudocodes, and flowcharts.
▪ Write down an algorithm using pseudocode, & represent it graphically
using a flowchart, to:
1. Convert a temperature in Celsius to Fahrenheit according to the
formula: F = 1.8 * C + 32.
2. Divide two numbers given by a user, & if the second number is 0 print
the result as unknown.
3. Find the greatest number within 3 numbers given by the user.
4. Identify whether water is in a solid form (ice), in a liquid form, or a
gaseous form (vapor), based on a temperature value given by the user.
5. Read a positive integer N and determine whether N is even or odd.
6. Read two positive integers, determine which has a greater value, and
then print this value only if it is even.
Up Next ..
Additional Section 2.4
Resources
▪ Pseudo code & flow chart (in Arabic):
https://www.youtube.com/watch?v=xyyOOBv2G7E
▪ OCR GCSE 2.1 How to produce algorithms using
pseudocode and flow diagrams:
https://www.youtube.com/watch?v=wvAblqsEj54
▪ 5 Minutes to Code: Programming Basics "Pseudocode":
https://www.youtube.com/watch?v=HhBrkpTqzqg
▪ Algorithms in pseudocode and flow diagrams:
https://www.youtube.com/watch?v=XDWw4Ltfy5w
▪ Algorithm using Flowchart & Pseudo code Level 1
Flowchart:
https://www.youtube.com/watch?v=vOEN65nm4YU
Lecture 2: Computational Thinking – Part 2
2.1 Computer Hardware
▪ Central Processing Unit & Storage
2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )
51
Natural Languages Programming Languages
.. Consists of?
- Vocabulary/Words - Keywords
.. What for?
- Sentences - Instructions
.. How?
- Grammar - Syntax
.. Has a meaning?
- Meaningful sentences - Correct Semantic
.. Different Languages?
- Arabic, English, Spanish, .. etc. - C/C++, Java, Python, R, .. etc.
52
Exercises
What have we learned?
Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 3
Computational
Thinking – Part 3
3.1 Computer Software
▪ Programs versus Software – Software Engineering – Types of Software
– Classification of Computer Systems – Generations of Computers
3.2 Your First C Program
▪ Why C? – Code::Blocks IDE – MAIN Function – Statements – PRINTF
Function – Strings – Escape Sequences – Preprocessor Directives –
Header Files – RETURN Statements – MAIN returning a 0? – Faculty of
Comments – Blank-lines/Spaces/Tabs Computing &
3.3 Compilation Artificial Intelligence
▪ Preprocessor – Compiler – Assembler – Linker – Types of Errors –
Critical & Real-time Systems FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
#include <stdio.h>
int main(void)
{
printf( "Hello, World!\n" );
return 0;
} 4
Programs Vs. Software ..
.. in simple terms:
o Program; is a set of instructions telling a computer what to do.
Programming is the process of creating a set of instructions
that tell a computer how to perform a task.
o Software; is the computer program(s) and the associated
documentation. Software products may be developed for a
particular customer or may be developed for a general market.
5
Programs Vs. Software ..
6
How to solve a problem?
Software Engineering ..
1. Define the problem.
2. Analyze the problem (i.e. specifying the requirements).
3. Develop an algorithm (a method) for solving a problem
(i.e. design; designing the solution).
4. Write a computer program corresponding to the
algorithm (i.e. implementation).
5. Test and debug the program (i.e. testing).
6. Document everything about the program (write an
explanation of how the program is designed, how it
works, how it was tested, and how to use it). 7
Types of Software ..
The 2 basic categories of Software are:
System Software: Mainly, Operating systems that allow
computers to operate;
o Boots the computer and launches programs at the
user’s direction.
o Mostly uses a GUI “Graphical User Interface” to
interact with the user via windows, icons, menus,
buttons, .. etc.
o E.g. Windows, Mac OS, Linux, android, etc.
Application Software: Software which allows computers to
carry out specific tasks related to the users;
o E.g. Payroll processing, inventory control, word
processing, .. etc.
8
Types of
Software
9
Types of
Software
Software designed to help
analyze, configure, optimize, or
maintain a computer (primarily
used to support the computer
infrastructure), e.g.: Anti-virus,
System Monitors, etc.
10
Types of
Software
11
Types of
Software
12
Types of Software ..
16
1st Generation 1940–1956
A vacuum-tube circuit storing 1 byte
2nd Generation
1956–1963: Transistors
Generations of Computers?
3rd Generation 1964–1971:
Integrated Circuits (ICs)
Artificial Intelligence!
18
Exercises
What have we learned?
Keywords, Functions,
.. & ..
Syntax Rules
22
Why C?
o C is a general-purpose, procedural computer programming language.
o C has become one of the most widely used programming languages.
o C has lasting use in applications previously coded in assembly
language (e.g. Operating Systems).
o Many later languages have borrowed directly or indirectly from C,
including C++, C#, D (Dlang), Go, Java, JavaScript, Perl, PHP, Python, &
many more. [C++ is an extension of C, or "C with Classes"]
o C is widely used for systems programming in implementing operating
systems and embedded system applications.
o A consequence of C's wide availability and efficiency is that compilers/
interpreters, and libraries of other programming languages are often
implemented in C (e.g., the reference implementations of Python,
Perl, and PHP are written in C).
o C enables programmers to create efficient implementations of
algorithms and data structures, an important criterion for
computationally intensive programs (e.g., programs such as
Mathematica, MATLAB, and many others are completely or partially
23
written in C).
Why C?
The TIOBE index graph, showing a comparison of the popularity of various
programming languages.
Check: https://www.tiobe.com/tiobe-index/
24
So .. Your very first program!
25
Algorithm; Pseudocode & Flowchart
1 Start Start
2 Display Hello, World!
3 End
Write Hello, World!
End
26
Your first C program ..
#include <stdio.h>
int main(void)
{
printf( "Hello, World!\n" );
return 0;
}
27
An IDE is a software application that provides
comprehensive facilities to computer programmers
Code::Blocks for software development (consisting of a source-
code editor, build automation tools, debugger, and
the necessary compiler.).
Code::Blocks is a free C, C++ and Fortran IDE (Integrated
Development Environment).
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
o A string in C (also known as C string) is an array
of characters, followed by a NULL character.
To represent a string, a set of characters are
enclosed within double quotes (“ “). 33
Escape Sequences
o An escape sequence is a sequence of characters that does not
represent itself when used inside a character or string literal but
is translated into another character or a sequence of characters.
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
o In C, all escape sequences consist of two or more characters, the
first of which is the backslash, \ (called the "Escape character");
the remaining characters determine the interpretation of the
escape sequence. For example, \n is an escape sequence that 34
denotes a newline character.
Escape Sequences
Escape Sequence Description
\n New Line
Example: printf ( "Welcome\n to\n C!\n");
Output: Welcome
to
C!
\t Tab
Example: printf ( "Welcome\t to C!\n" );
Output: Welcome to C!
\a Alert Sound
\\ Backslash
\” Double Quotation
Example: printf( "My name is \"Ahmed \" / Mohamed \\" );
Output: My name is "Ahmed" / Mohamed \ 35
35
Preprocessor Directives
Lines starting with a # are:
o Directives to the C preprocessor.
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
o They are processed before the program is compiled.
o They are NOT instructions.
o #include tells the preprocessor to include the contents of
the <stdio.h> into the program. 36
Header File
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
o <stdio.h> is a header file that contains information used
by the compiler when compiling calls to library functions
(built-in functions) such as printf.
o <stdio.h> stands for STandarD Input/Output.Header 37
The RETURN Statement
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
o At the end of every MAIN function.
o The keyword return is used to exit a function.
38
Why does the MAIN function return a 0?
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
39
Comments
o Don’t cause the computer to perform any action when the
program is running. Thus, comments do nothing, they’re
NOT instructions.
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
o They’re used to improve a program’s readability, & to help
others read & understand your program. There’re 2 forms:
a) /* .. .. */ for multiple-lined comments.
b) // .. .. for single-lined comments. 40
Blank-lines, Spaces, Tabs, .. etc.
o N.B. Blank-lines, Spaces, Tabs are also ignored by the
compiler.
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
#include <stdio.h>
int main(void){printf("Hello, World!\n");return 0;}
#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */
▪ What is a C String?
Compilation
47
We learned to write our first program in C. We learned the syntax
for the main function in our program, the printf function for
printing to the terminal, how to create strings with double
quotes, and how to include stdio.h for the printf function.
Source Code →
hello.c
48
We write our source code in C, but need to compile it to machine
code, in binary, before our computers can run it.
49
Any computer can directly understand only its own machine
language (machine code); consists only of binary digits (0’s and 1’s).
a) preprocessing
b) compiling
c) assembling
d) linking
52
“Compiling” source code into machine code is made up of smaller
steps:
53
So, our source code will be preprocessed into .. :
#include <stdio.h>
preprocessing int printf(const char *format, ...);
compiling
int main(void)
assembling {
linking printf( "Hello, World!\n" );
return 0;
}
54
“Compiling” source code into machine code is made up of smaller
steps:
preprocessing
Compiling takes our source code, in C,
compiling and converts it to assembly code,
which looks like this .. (see next slide)
assembling
linking
55
main:
sub rsp,28h
ret
__local_stdio_printf_options:
lea rax,[?_OptionsStorage@?1??__local_stdio_printf_options@@9@9]
ret
_vfprintf_l:
mov qword ptr [rsp+20h],r9
sub rsp,38h
call __local_stdio_printf_options
call __stdio_common_vfprintf
add rsp,38h
These instructions are
ret
lower-level and is closer to
printf: the binary instructions that
mov qword ptr [rsp+8],rcx a computer’s CPU can
call __acrt_iob_func directly understand.
mov r9,qword ptr [rsp+28h]
They generally operate on
call _vfprintf_l
mov dword ptr [rsp+20h],eax bytes themselves, as
mov eax,dword ptr [rsp+20h] opposed to abstractions like
ret variable names.
56
“Compiling” source code into machine code is made up of smaller
steps:
preprocessing
The next step is to take the assembly
compiling code and translate it to instructions in
binary by assembling it. The
assembling
instructions in binary are called
linking machine code, which a computer’s CPU
can run directly.
57
01111111010001010100110001000110
00000010000000010000000100000000
00000000000000000000000000000000
00000000000000000000000000000000
00000001000000000011111000000000
00000001000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
10100000000000100000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
01000000000000000000000000000000
00000000000000000100000000000000
00001010000000000000000100000000
01010101010010001000100111100101
01001000100000111110110000010000
00110001110000001000100111000111
01001000101111100000000000000000
00000000000000000000000000000000
00000000000000001011000000000000
11101000000000000000000000000000
00000000010010001011111100000000
00000000000000000000000000000000
00000000000000000000000001001000
58
...
“Compiling” source code into machine code is made up of smaller
steps:
preprocessing
compiling The last step is linking, where the contents of
previously compiled libraries that we want to link,
assembling
like printf.c, are combined with the binary of our
linking program. So we end up with one binary file,
“hello.exe”, that is the compiled version of hello.c,
and printf.c.
59
hello.c
60
hello.c stdio.c
61
hello.c printf.c
62
01111111010001010100110001000110
00000010000000010000000100000000
00000000000000000000000000000000
00000000000000000000000000000000
00000001000000000011111000000000
00000001000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
10100000000000100000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
01000000000000000000000000000000 printf.c
00000000000000000100000000000000
00001010000000000000000100000000
01010101010010001000100111100101
01001000100000111110110000010000
00110001110000001000100111000111
01001000101111100000000000000000
00000000000000000000000000000000
00000000000000001011000000000000
11101000000000000000000000000000
00000000010010001011111100000000
00000000000000000000000000000000
00000000000000000000000001001000
63
...
01111111010001010100110001000110 00101111011011000110100101100010
00000010000000010000000100000000 01100011001011100111001101101111
00000000000000000000000000000000 00101110001101100010000000101111
00000000000000000000000000000000 01110101011100110111001000101111
00000001000000000011111000000000 01101100011010010110001000101111
00000001000000000000000000000000 01111000001110000011011001011111
00000000000000000000000000000000 00110110001101000010110101101100
00000000000000000000000000000000 01101001011011100111010101111000
00000000000000000000000000000000 00101101011001110110111001110101
00000000000000000000000000000000 00101111011011000110100101100010
10100000000000100000000000000000 01100011010111110110111001101111
00000000000000000000000000000000 01101110011100110110100001100001
00000000000000000000000000000000 01110010011001010110010000101110
01000000000000000000000000000000 01100001001000000010000001000001
00000000000000000100000000000000 01010011010111110100111001000101
00001010000000000000000100000000 01000101010001000100010101000100
01010101010010001000100111100101 00100000001010000010000000101111
01001000100000111110110000010000 01101100011010010110001000101111
00110001110000001000100111000111 01111000001110000011011001011111
01001000101111100000000000000000 00110110001101000010110101101100
00000000000000000000000000000000 01101001011011100111010101111000
00000000000000001011000000000000 00101101011001110110111001110101
11101000000000000000000000000000 00101111011011000110010000101101
00000000010010001011111100000000 01101100011010010110111001110101
00000000000000000000000000000000 01111000001011010111100000111000
00000000000000000000000001001000 00110110001011010011011000110100
64
... ...
01111111010001010100110001000110000000100000000100000001000000000000000000000
00000000000000000000000000000000000000000000000000000000001000000000011111000
00000000000001000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000010100000000000100000000000000000000000000000000000000000000000000
00000000000000000000000000000000100000000000000000000000000000000000000000000
00010000000000000000001010000000000000000100000000010101010100100010001001111
00101010010001000001111101100000100000011000111000000100010011100011101001000
10111110000000000000000000000000000000000000000000000000000000000000000010110
00000000000111010000000000000000000000000000000000001001000101111110000000000
00000000000000000000000000000000000000000000000000000001001000......001011110
11011000110100101100010011000110010111001110011011011110010111000110110001000
00001011110111010101110011011100100010111101101100011010010110001000101111011
11000001110000011011001011111001101100011010000101101011011000110100101101110
01110101011110000010110101100111011011100111010100101111011011000110100101100
01001100011010111110110111001101111011011100111001101101000011000010111001001
10010101100100001011100110000100100000001000000100000101010011010111110100111
00100010101000101010001000100010101000100001000000010100000100000001011110110
11000110100101100010001011110111100000111000001101100101111100110110001101000
01011010110110001101001011011100111010101111000001011010110011101101110011101
01001011110110110001100100001011010110110001101001011011100111010101111000001
01101011110000011100000110110001011010011011000110100...
65
Types of Errors ..
1) Syntax error is a violation of the C grammar rules,
detected during program compilation.
o E.g., a missing semicolon, an unclosed comment,
spelling mistakes, .. etc.
2) Run-time error is an attempt to perform an invalid
operation, detected during program execution.
o E.g., Divide by zero, .. etc.
3) Semantic error is an error caused by following an
incorrect algorithm.
o Not the required output. 66
The most expensive typo in history ever!
Why is Syntax IMPORTANT ?!
o Mariner 1 was the first spacecraft of the
American Mariner program, designed for a
planetary flyby of Venus.
o It cost $18.5 million in 1962 ($150 million in
2017), It was launched on July 22.
o Shortly after take-off (294.5 seconds after
launch) the rocket responded improperly to
commands from the guidance systems on
the ground (manoeuvring in a way that it
shouldn’t have), setting the stage for an
apparent software-related guidance system
failure (which put it on a path to crash,
possibly into inhabited areas), and therefore
it was destroyed on command.
68
Why designing & optimizing software is important?
Real-time Systems .. ?
o Multiple categorizations do exist (based on size,
computational power, technology/generation, intended
usage, etc.).
o If we choose the speed of response as the main criterion,
three general groups emerge:
– Batch Systems: I don’t mind when the computer results
arrive. The time taken may be hours or even days in
such systems.
– Interactive Online Systems: I would like the results with
a fairly short time, typically a few seconds.
– Real-time Systems: I need the results within definite
time scales, otherwise the system just won’t work
properly.
69
Exercises
What have we learned?
▪ What are the three different Types of Errors? .. Give an
example for each.
Lecture 4
Variables, Constants,
& Data Types in C
4.1 Variables & Data-Types (Part A)
▪ Solved Example: Convert Feet to Centimetres – C Data
Types & their sizes – Prompt Messages – Identifiers in C
4.2 Variables & Data-Types (Part B)
▪ The Assignment Statement – Basic Arithmetic Operations
in C – Conversion / Format Specifiers in C – The printf
function with a Format Control String – The scanf function Faculty of
Computing &
4.3 Constants
Artificial Intelligence
▪ Constant Variables (Constants / Read-Only Variables)
▪ #define Preprocessor Directive (Symbolic Constants) FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
4.3 Constants
▪ Constant Variables (Constants / Read-Only Variables) and their advantages
▪ #define Preprocessor Directive (Symbolic Constants) and their advantages
Example 4.1: Convert Feet to Centimetres
Write a program that converts a length in feet, to a length in
centimeters. The program should prompt the user (through)
a message to input a number representing the length in feet,
then display the equivalent value in centimeters.
o How many cm in 1 feet? The answer is 30.48.
Pseudocode:
End 5
Example 4.1: Convert Feet to Centimetres
So, .. your program should behave like this:
bool 1 byte
char 1 byte
int 4 bytes
float 4 bytes
long 8 bytes
double 8 bytes
string ? bytes
..
13
In C, when we create a variable of type char, which will be sized
one byte, it will physically be stored in one of those boxes in
RAM. For instance:
char c1 = 'H';
char c2 = 'I';
char c3 = '!';
14
Inside our computers, we have chips called RAM, random-
access memory, that stores data for short-term use.
15
We can think of bytes, stored in RAM, as though they were in a grid:
16
In reality, there are millions or billions of bytes per chip.
17
In reality, there are millions or billions of bytes per chip.
18
Let's zoom in!
19
char c1 = 'H';
H
c1
20
char c2 = 'I';
H I
c1 c2
21
char c3 = '!';
H I !
c1 c2 c3
22
72 73 33
c1 c2 c3
23
01001000 01001001 00100001
c1 c2 c3
24
Data Types in C/C++ .. their Sizes ..
25
Once more .. Let's zoom in!
26
int score1 = 72;
72
score1
27
int score2 = 73;
72 73
score1 score2
28
int score3 = 33;
72 73
score1 score2
33
score3
29
00000000000000000000000001001000 00000000000000000000000001001001
score1 score2
00000000000000000000000000100001
score3
30
Data Types in C/C++ .. Examples ..
31
Exercises
What have we learned?
4.3 Constants
▪ Constant Variables (Constants / Read-Only Variables) and their advantages
▪ #define Preprocessor Directive (Symbolic Constants) and their advantages
#include <stdio.h>
// The main function, execution starts here
int main()
Declarations of more than one variable
{
could be combined in a single line only
// Variables Declarations when having the same type.
float length_cm, length_ft; E.g., int x; int y; OR int x, y;
// Prompt messages E.g., double a; float b;
printf("Hello!\n");
printf("This program converts a length in feet into centimeters\n");
printf("Please enter the length in feet ..\n");
scanf("%f", &length_ft); // Reads length in feet
length_cm = length_ft * 30.48; // Converts feet to centimetres
// Displays the length in centimetres
printf("The equivalent length in centimeters is %f \n", length_cm);
printf("Thank you!\n");
return 0; // Program ended successfully
35
}
The scanf function is a built-in function that
reads from the standard input (keyboard).
#include <stdio.h>
// The main function, execution starts here Memory
int main()
{ length_ft 2.0
// Variables Declarations
float length_cm, length_ft; length_cm
// Prompt messages
printf("Hello!\n");
printf("This program converts a length in feet into centimeters\n");
printf("Please enter the length in feet ..\n");
scanf("%f", &length_ft); // Reads length in feet
length_cm = length_ft * 30.48; // Converts feet to centimetres
// Displays the length in centimetres
printf("The equivalent length in centimeters is %f \n", length_cm);
printf("Thank you!\n");
return 0; // Program ended successfully
36
}
#include <stdio.h>
// The main function, execution starts here
int main() The scanf function contains:
{ - A Format Control String (E.g., "%f").
// Variables Declarations - The Address Operator: an Ampersand (&).
float length_cm, length_ft; - A Variable name(s) (E.g., length_ft).
// Prompt messages
printf("Hello!\n");
printf("This program converts a length in feet into centimeters\n");
printf("Please enter the length in feet ..\n");
scanf("%f", &length_ft); // Reads length in feet
length_cm = length_ft * 30.48; // Converts feet to centimetres
// Displays the length in centimetres
printf("The equivalent length in centimeters is %f \n", length_cm);
printf("Thank you!\n");
return 0; // Program ended successfully
37
}
#include <stdio.h>
// The main function, execution starts here
int main() Conversion / Format Specifiers
{ for a variable of the type float.
// Variables Declarations
float length_cm, length_ft;
// Prompt messages
printf("Hello!\n");
printf("This program converts a length in feet into centimeters\n");
printf("Please enter the length in feet ..\n");
scanf("%f", &length_ft); // Reads length in feet
length_cm = length_ft * 30.48; // Converts feet to centimetres
// Displays the length in centimetres
printf("The equivalent length in centimeters is %f \n", length_cm);
printf("Thank you!\n");
return 0; // Program ended successfully
38
}
Conversion / Format Specifiers in C ..
A format specifier is a sequence formed by an
initial percentage sign (%), which is used to
specify the type & format of the data to be
retrieved and stored into locations pointed by
the additional arguments (i.e., it tells us what
data to read, store, and print).
%c chars
%f floats
%lf doubles
%d ints
%li longs
%s strings 39
The "Address Of" Operator denoted
by the ampersand character (&)
#include <stdio.h>
returns the address of a variable.
// The main function, execution starts here
int main()
{
// Variables Declarations
float length_cm, length_ft; &length_ft, tells scanf the location (or
// Prompt messages address) in memory of length_ft, then
printf("Hello!\n"); stores the value at that location.
printf("This program converts a length in feet into centimeters\n");
printf("Please enter the length in feet ..\n");
scanf("%f", &length_ft); // Reads length in feet
length_cm = length_ft * 30.48; // Converts feet to centimetres
// Displays the length in centimetres
printf("The equivalent length in centimeters is %f \n", length_cm);
printf("Thank you!\n");
return 0; // Program ended successfully
40
}
#include <stdio.h>
You can assign (give) a value to a
// The main function, execution starts here
variable by using the assignment
int main() operator = .. For example:
{ middleInitial = 'R';
// Variables Declarations age = 12;
float length_cm, length_ft; tax = 3.7;
// Prompt messages x = ( 7 - 10 ) * ( 5 % 3 ) * 4 + 9;
printf("Hello!\n");
printf("This program converts a length in feet into centimeters\n");
printf("Please enter the length in feet ..\n");
scanf("%f", &length_ft); // Reads length in feet
length_cm = length_ft * 30.48; // Converts feet to centimetres
// Displays the length in centimetres
printf("The equivalent length in centimeters is %f \n", length_cm);
printf("Thank you!\n");
return 0; // Program ended successfully
41
}
The Assignment Statement ..
length_cm 60.96
42
Basic Arithmetic Operations in C ..
+ addition
- subtraction
* multiplication
/ division
% remainder
Arithmetic operators are all binary operators; each has 2
operands. E.g., The expression x + y contains the binary
operator (+) and the operands x and y.
47
Exercises
What have we learned?
▪ What is a Conversion/Format Specifier?
▪ Write down an algorithm using pseudocode, represent it graphically
using a flowchart, and finally write the corresponding C program that:
1) Converts a temperature in Celsius to Fahrenheit according to the
formula: F = 1.8 * C + 32.
2) Prompts the user for 5 integers. The program should then print:
▪ The sum of these integers.
▪ The average of these integers.
▪ The sum of the squares of these integers.
▪ The sum of the cubes of these integers.
Up Next ..
Additional Section 4.3
Resources
▪ C Data Types:
https://www.programiz.com/c-programming/c-data-types
4.3 Constants
▪ Constant Variables (Constants / Read-Only Variables) and their advantages
▪ #define Preprocessor Directive (Symbolic Constants) and their advantages
This is a C program that calculates the average of an
arbitrary number of grades.
You DON’T have to understand this code now, but do you
notice the repeating numeric values?
#include <stdio.h>
int main() {
int grades[5]; //declare the array
for ( int i = 0; i < 5; i++ ) {
printf("\nEnter garde %d: ", i);
scanf("%d", &grades[i]);
}
float avg; int sum = 0;
for ( int i = 0; i < 5; i++ ) {
sum = sum + grades[ i ];
}
avg = (float) sum / 5;
printf("The average is: %f", avg);
}
How can we solve this issue?
using Constant Variables or Symbolic Constants
#include <stdio.h>
int main() {
const int x = 5;
int grades[x]; //declare the array
for ( int i = 0; i < x; i++ ) {
printf("\nEnter garde %d: ", i);
scanf("%d", &grades[i]);
}
float avg; int sum = 0;
for ( int i = 0; i < x; i++ ) {
sum = sum + grades[ i ];
}
avg = (float) sum / x;
printf("The average is: %f", avg);
}
Constant Variables Example
a.k.a Constants or Read-Only Variables
#include <stdio.h>
const float pi = 3.14;
int main(void) // The main function, execution starts here
{
float area, radius; // Variables Declarations
// Prompt messages
printf( "This program calculates the area of a circle.\n" );
printf( "Please enter the radius of the circle:\n" );
scanf("%f", &radius); // Reads the Radius
area = pi * radius * radius; // Calculates the Area
// Displays the Area
printf( "The area of the circle is: %f\n", area );
return 0; // Program ended successfully
}
Constant Variables
a.k.a Constants or Read-Only Variables
o A constant variable must be initialized when it’s declared and
cannot be modified thereafter.
o Attempting to modify a constant after it’s initialized, results in the
following error (from the GNU C++ compiler):
error: assignment of read-only variable ‘x’
o Assigning a value to a constant variable in a separate statement
from its declaration is a compilation error.
o Not initializing a constant variable when it’s declared is a
compilation error in some compilers (not an error any more in
others).
Constant Variables Advantages
a.k.a Constants or Read-Only Variables
o Defining some variables as constant variables instead of literal
constants makes programs clearer and easier to update;
o This technique eliminates so-called magic numbers (numeric
values that are not explained). Using a constant variable allows
you to provide a name for a literal constant and can help explain
the purpose of the value in the program.
#define Preprocessor Directive
Symbolic Constants / Macro Definition Example
#include <stdio.h>
#define PI 3.14
int main(void) // The main function, execution starts here
{
float area, radius; // Variables Declarations
// Prompt messages
printf( "This program calculates the area of a circle.\n" );
printf( "Please enter the radius of the circle:\n" );
scanf("%f", &radius); // Reads the Radius
area = PI * radius * radius; // Calculates the Area
// Displays the Area
printf( "The area of the circle is: %f\n", area );
return 0; // Program ended successfully
}
#define Preprocessor Directive
Symbolic Constants / Macro Definition
o The #define preprocessing directive creates symbolic constants
(constants represented as symbols) and macros (operations
defined as symbols).
o The #define preprocessing directive format is:
#define identifier replacement-text
o When this line appears in a file, all subsequent occurrences
(except those inside a string) of identifier in that file will be
replaced by replacement-text before the program is compiled. For
example: #define PI 3.14159 replaces all subsequent occurrences
of the symbolic constant PI with the numeric constant 3.14159.
#define Preprocessor Directive
Symbolic Constants / Macro Definition Advantages
o Symbolic constants enable you to create a name for a constant
and use the name throughout the program.
o Later, if the constant needs to be modified throughout the
program, it can be modified once in the #define preprocessing
directive — and when the program is recompiled, all occurrences
of the constant in the program will be modified.
o Note: Do NOT put a semicolon character at the end of #define
statements. This is a common mistake.
o Note: Do NOT use the assignment operator. This is a common
mistake.
Exercises
What have we learned?
Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 5
C Operators: Arithmetic, Bitwise,
Logical, Relational, & Equality
5.1 Arithmetic Expressions & Operators
▪ C / C++ Operators – Assignment Operators – Compound
Assignment Operators – Increment / Decrement Operators
5.2 Equality, Relational, & Logical Operators
▪ Equality Operators & Expressions – Relational Operators &
Expressions – Logical Operators & Expressions – Operators’
Faculty of
Precedence – Short-Circuit Evaluation
Computing &
5.3 Bitwise Operators & Expressions Artificial Intelligence
▪ bitwise AND – bitwise inclusive OR – bitwise exclusive OR
– left shift – right shift – the one's complement FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
length_cm 60.96
5
Recap
Basic Arithmetic Operations in C ..
+ addition
- subtraction
* multiplication
/ division
% remainder
Arithmetic operators are all binary operators; each has 2
operands. E.g., The expression x + y contains the binary
operator (+) and the operands x and y.
7
Assignment Operator ..
8
Trace the following code segment ..
What are the values of variables a & b after each step?
In the Memory
a b
int a, b;
a = 5;
b = 7;
b = a + 10;
a = b – 1;
b = 3;
printf(“a = %d, b = %d”, a, b); Output Screen
a = 14, b = 3
10
Compound Assignment Operators ..
Examples:
Assignment Expression (An Explanation: Assigns:
Operator: Example):
Assume: int c = 3, d = 5, e = 4, f = 6, g = 12;
+= c += 7 c=c+7 10 to c
-= d -=4 d=d–4 1 to d
*= e *= 5 e=e*5 20 to e
/= f /= 3 f=f/3 2 to f
%= g %= 9 g=g%9 3 to g
11
Increment / Decrement Operators ..
C also provides:
• the unary increment operator, ++, and ..
• the unary decrement operator, --.
.. has only one operand.
For example:
c++; ≡ c = c + 1; ≡ c += 1;
c--; ≡ c = c - 1; ≡ c -= 1;
/* demonstrates post-increment */
c = 5; /* assigns 5 to c */
printf( "%d\n", c ); /* prints 5 */
printf( "%d\n", c++ ); /* prints 5, then increments */
printf( "%d\n", c ); /* prints 6 */
/* demonstrates pre-increment */
c = 5; /* assigns 5 to c */
printf( " %d\n", c ); /* prints 5 */
printf( "%d\n", ++c ); /* increments, then prints 6 */
printf( "%d\n", c ); /* prints 6 */ 13
Increment / Decrement Operators ..
An Example ..
int x; /* defines the variable */
14
Exercises
What have we learned?
▪ Assignment Operator in C:
https://overiq.com/c-programming-101/assignment-operator-in-c/
Lecture 5: C Operators: Arithmetic, Bitwise, Logical,
Relational, & Equality
5.1 Arithmetic Expressions & Operators
▪ C / C++ Operators, Assignment Operators, & Compound Assignment Operators
▪ Increment / Decrement Operators
Selection Repetition
Sequence
(Decisions) (Loops)
Step-by-Step Choose a path Repeat a sequence
sequentially in from multiple of statements ..
order .. options ..
Conditions ..
Operators Precedence
Parentheses ()
Unary Postfix ++ --
Unary Prefix + Logical Operator (Negation) ++ -- !
* / %
Arithmetic Operators
+ -
Relational Operators >= <= < >
Equality Operators == !=
Logical Operator (AND) &&
Logical Operator (OR) ||
Conditional Operator ?:
Assignment Operators = += -= *= /= %=
Evaluate the following Expression ..
7 * 10 - 5 % 3 * 4 + 9
7 * 10 - 5 % 3 * 4 + 9
70 - 5 % 3 * 4 + 9
70 - 5 % 3 * 4 + 9
70 - 2 * 4 + 9
70 - 2 * 4 + 9
70 - 8 + 9
70 - 8 + 9
62 + 9
71
25
Evaluate the following Expression ..
Parentheses (Brackets)
o Parentheses can be used to change the usual order.
o Thus, the parts in ( ) are evaluated first.
o E.g., evaluate:
( 7 * (10 - 5) % 3) * 4 + 9
(7 * 5 % 3 ) * 4 + 9
( 35 % 3 ) * 4 + 9
2 * 4 + 9
8 + 9
17
26
What’re the values of the following
expressions?
EXPRESSION VALUE___
EXPRESSION
EXPRESSION
EXPRESSION
• Age is 21 or 22
(age == 21) || (age == 22)
▪ Bitwise Operators in C:
https://www.tutorialspoint.com/cprogramming/c_bitwise_o
perators.htm
Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 6
Control Structures: Selection
the If .. Else & Switch .. Case
6.1 Control Structures & Single-Selection Statements (If .. Then)
▪ Control Structures – Sequence Control Structure – Selection Control
Structure (Decisions) – Types of Selection Statements – Single-
Selection Statements – If .. Then Statements
6.2 Double-Selection Statements (If .. Else) & the Conditional Operator
▪ Double-Selection Statements – If .. Else Statements – Compound
Faculty of
Statement (Block) – Conditional Operator ( ? : )
Computing &
6.3 Multiple Selection Statements (Nested if & Switch Case) Artificial Intelligence
▪ Multiple Selection / Cases Statements – Nested if Statements –
Switch–Case Statements FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
Control
Structures
Selection Repetition
Sequence
(Decisions) (Loops)
Pseudocode:
Power ← xy
Output Power
End 6
Example 6.1: Calculate the Power of two
numbers ..
So, .. your program should behave like this:
7
Example 6.1: Calculate the Power of two
numbers ..
#include <stdio.h> // The header file including the printf & scanf
#include <math.h> // The header file including the pow function
int main() // The main function, execution starts here
{
float x, y; // Variables Declarations
// Prompt message to read the 2 numbers
printf( "Please enter 2 integers x & y to calculate the power x^y\n" );
scanf( "%f %f", &x, &y ); // Reads the 2 numbers
printf( "%f to the power of %f equals %f\n", x, y, pow(x, y) );
return 0; // Program ended successfully
}
8
Control Structures ..
Control
Structures
Selection Repetition
Sequence
(Decisions) (Loops)
YES Statement(s)
Condition
NO Statement(s)
NO YES
A < B?
Types of Selection Statements
o Single-Selection Statement:
o if statements, when the condition is:
o true performs an action;
o false the action is skipped.
o Double-Selection Statement:
o if .. else statements, when the condition is:
o true performs an action;
o false performs another action.
o Multiple-Selection Statement:
o Nested if .. else statements
o switch .. case statements
11
Types of Selection Statements ..
Single-Selection Statements ..
if (condition)
- a null statement, or
Statement(s); - a single statement, or
- a block of statements:
{
statement1;
statement2;…
}
true
condition
12
false
12
Example 6.2: Determine Passed Students
Write a program that reads a student’s grade and displays
“Passed” if his/her grade is greater than or equal to 60. The
program should prompt the user through a message to input
a grade, then displays Passed if that grade was greater than
or equal to 60.
Pseudocode:
Start
Read Grade
Print Grade
“Passed” Yes >= 60
No
End
14
Example 6.2: Determine Passed Students
15
Example 6.2: Determine Passed Students
#include <stdio.h> // The header file including the printf & scanf
int main() // The main function, execution starts here
{
int grade; // Variable Declaration
// Prompt message to read a grade
printf("Please enter a student's grade (from 0 to 100)\n");
scanf("%d", &grade); // Reads a grade
if (grade >= 60) // Decision (Selection) Indentation is a good
printf("Passed\n"); programming practice.
return 0; // Program ended successfully
}
16
Up Next ..
Exercises Section 6.2
What have we learned?
▪ Write down an algorithm using pseudocode,
represent it graphically using a flowchart, and
finally write the corresponding C program that:
1) Reads a positive integer N and determines
whether N is even or odd.
2) Reads two positive integers, determines which
has a greater value, and then prints this value
only if it is even.
▪ Write a C program that calculates the cube of an
integer number. The program should be
implemented by using two methods:
1) without using the “pow()” function, and ..
2) using the “pow()” function.
Lecture 6: Control Structures: Selection
the If .. Else & Switch .. Case Statements
6.1 Control Structures & Single-Selection Statements (If .. Then)
▪ Control Structures & the Sequence Control Structure
▪ Selection Control Structure (Decisions) & the Types of Selection Statements
▪ Single-Selection Statements: the If .. Then Statements
Pseudocode:
Step 1: Input a set of 4 marks (M1, M2, M3, & M4)
Step 2: Calculate their average by summing & dividing by 4
Step 3: If average is below 50
Step 4: Print “Fail”
Step 5: Else
Step 6: Print “Pass” 20
Example 6.3: Determine Final Grade
Flowchart:
START
Input M1, M2, M3, M4
GRADE ( M1 + M2 + M3 + M4 ) / 4
is
GRADE < 50
No Yes
PRINT “PASS” PRINT “FAIL”
END 21
Example 6.3: Determine Final Grade
22
Example 6.3: Determine Final Grade
#include <stdio.h> // The header file including the printf & scanf
int main() // The main function, execution starts here
{
// Variables Declaration
int mark_1, mark_2, mark_3, mark_4; float average;
// Prompt message to read the 4 marks
printf("Please enter the student’s 4 marks (each from 0 to 100)\n");
// Read the marks
scanf("%d %d %d %d", &mark_1, &mark_2, &mark_3, &mark_4);
average = (mark_1 + mark_2 + mark_3 + mark_4) / 4.0;
if (average < 50) // Decision (Selection)
printf("Fail\n");
else
printf("Pass\n");
return 0; // Program ended successfully
23
}
Compound Statement (Block) ..
if ( grade >= 60 ) {
printf("Passed.\n");
} // end if
else {
printf ("Failed.\n");
printf ("You must take this course again.\n");
} // end else
Yes Grade No
>=85
Print “A” Yes Grade No
>=75
Print “B” Yes Grade No
>=65
Print “C” Yes Grade No
>=50
Print “D” Print “F”
End
Example 6.4: A Multiple Cases Example
if ( grade >= 85 ) { Nested if Statements ..
printf("A.\n");
} // end if
else {
if ( grade >= 75 ) {
printf("B.\n");
} // end if
else {
if ( grade >= 65 ) { Only a single statement
printf("C.\n");
} // end if will be executed ..
else {
if ( grade >= 50) {
printf("D.\n");
} // end if
else { printf("F.\n");
} // end else
} // end else
} //end else
} // end else
Multiple Cases Statements ..
Switch – Case Statements ..
Yes menuNo No
== 1
result =
num1 + num2 Yes No
menuNo
== 2
result =
break; num1 - num2 display
illegal choice
break;
a third Solution ..
Exercises
What have we learned?
▪ C - switch statement:
https://www.tutorialspoint.com/cprogramming/switch_statement
_in_c.htm
Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 7
Control Structures: Loops
the For .. While .. Do – While
7.1 Counter–Controlled Loops
▪ Repetition Control-Structure (Loops / Iterations) –
Counter–Controlled Loops – General Forms of Repetition
Statements – for Statements – while Statements – do ..
while Statements – Block of Statements
7.2 Notes & Examples on Counter–Controlled Loops
Faculty of
7.3 Sentinel–Controlled Loops & Break/Continue Statements
Computing &
▪ Break Statement – Continue Statement – Sentinel– Artificial Intelligence
Controlled Repetitions
FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
Selection Repetition
Sequence
(Decisions) (Loops)
Step-by-Step Choose a path Repeat a sequence
sequentially in from multiple of statements ..
order .. options ..
Loops (Repetitions / Iterations)
False
...
Condition
True
Statement(s)
Loops (Repetitions / Iterations)
A loop is a repetition control structure. It causes a single
statement or block of statements to be executed repeatedly.
For example:
If we wish to read 100 numbers and compute the average.
Repetition statements in C:
• for statement Counter–Controlled Repetition
(Counter–Based Repetition)
• while statement .. or ..
• do .. while statement Sentinel–Controlled Repetition
Counter–Controlled Repetition
Defined repetition: Number of repetitions is known in advance.
Enter loop
Initial value
Control variable
k = 1
(Initialization)
(loop counter)
Loop-continuation
No Exit
k<=10 loop
Condition
Yes true→ loop
Instructions to false→ exist
be repeated
k=k + 1 Increment
An Iteration = 1 repetition
General Forms of Repetition Statements
Expression 1 Initialization: ( k = 1 )
We need: Expression 2 Continuation condition: ( k <= 10 )
Expression 3 Increment: ( k = k + 1 )
for ( expression 1 ; expression 2 ; expression 3 )
{
statement;
}
expression1 ; expression1 ;
while (expression 2) do
{ {
statement; statement;
expression 3; expression 3;8 8
} } while (expression 2) ;
Repetition Statements
(the For Loop)
Repetition Statements
(Block of Statements?)
Repetition Statements
(While vs. Do-While Loops)
Exercises
What have we learned?
int grade;
int counter; // control variable
counter = 1; // initialization
while ( counter <= 20 )
{
printf(“Enter the grade of student No. %d”, counter);
scanf(“%d”, &grade);
if ( grade >= 60 )
{
printf( "Passed\n" );
} // end if
counter++; // increment
}
do .. while Statement .. an Example
int grade;
int counter; // control variable
counter = 1; // initialization
do {
printf(“Enter the grade of student No. %d”, counter);
scanf(“%d”, &grade);
if ( grade >= 60 )
{
printf( "Passed\n" );
} // end if
counter++; // increment
} while ( counter <= 20 );
lecture 1
Expressions can contain arithmetic expressions:
For example, If x = 2 and y = 10 ..
for ( j = x + y; j <= 4 * x* y ; j += y / x)
lecture 1
• count++;
Thus, are all equivalent.
19
Notes about the Expressions ..
for Statements ..
Both expression 1 and expression 3 are comma-separated lists:
for ( x = 0 , y = 0 ; x <= 10 ; x++ , y += 2 )
lecture 1
The commas as used here are comma operators ..
lecture 1
for ( i = 1; i <= 100; i++ )
Vary the control variable from 7 to 77 in steps of 7.
for ( i = 7; i <= 77; i += 7 )
Vary the control variable from 20 to 2 in steps of -2.
for ( i = 20; i >= 2; i -= 2 )
Vary the control variable over the following sequence of values:
2, 5, 8, 11, 14, 17.
for ( j = 2; j <= 17; j += 3 )
21
Trace this code segment ..
int count ;
count = 2;
int count ;
count = 2;
Output:
count
Trace this code segment ..
2
int count ;
count = 2;
Output:
count
Trace this code segment ..
2
int count ;
count = 2;
Output:
count
Trace this code segment ..
2
int count ;
count = 2;
Output:
count
Trace this code segment ..
2
1
int count ;
count = 2;
Output:
count
Trace this code segment ..
2
1
int count ;
count = 2;
Output:
count
Trace this code segment ..
2
1
int count ;
count = 2;
Output:
count
Trace this code segment ..
2
1
int count ;
0
count = 2;
Output:
count
Trace this code segment ..
2
1
int count ;
0
count = 2;
Output:
count
Trace this code segment ..
2
1
int count ;
0
count = 2;
int sum = 0;
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0
int sum = 0;
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
int sum = 0;
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
int sum = 0;
int i; True!
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
1
int sum = 0;
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
1 2
int sum = 0;
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
1 2
int sum = 0;
int i; True!
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
1 2
int sum = 0; 3
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
1 2
int sum = 0; 3 3
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
1 2
int sum = 0; 3 3
int i; False!
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
printf (“The sum is %d”, sum);
Output:
sum i
Trace this code segment ..
0 1
1 2
int sum = 0; 3 3
int i;
for ( i = 1; i <= 2 ; i++)
{
sum = sum + i;
}
The sum is 3
printf (“The sum is %d”, sum);
Output:
for Statement .. an Example
The Sum of Even Values using a for Statement
.. Sum the Even values from 2 to 100 ..
#include <stdio.h>
int main ( void )
{
int sum = 0;
int number;
▪ do-while Loop
https://www.youtube.com/watch?v=TjkJQly2YCw
Lecture 7: Control Structures – Loops (Repetition)
the For .. While .. & Do – While Statements
7.1 Counter–Controlled Loops
▪ Repetition Control-Structure (Loops / Iterations)
▪ Counter–Controlled Loops
▪ General Forms of Repetition Statements
▪ for Statements, while Statements, & do .. while Statements
▪ Block of Statements
advance.
• read number
• while ( not end-of-data )
• increment count by 1
• total = total + number
• read number
• display average
while Statement .. an Example
Class Average by a Sentinel–Controlled Repetition
#include <stdio.h>
int main ( void ) {
int counter = 0; int total = 0; int grade; float average;
printf( “Enter grade, -1 to end: \n” ); scanf( “%d”, &grade );
while ( grade != -1 ) {
total += grade; counter++;
printf( “Enter grade, -1 to end: \n” ); scanf( “%d”, &grade );
}
if ( counter != 0 ) {
average = (float) total / counter;
printf( “Class average is %.2f\n” , average );
}
else
{ printf( “No grades were entered” ); }
}
Exercises
What have we learned?
▪ Write a C program that allows a user to enter integers until s(he)
enters a negative number or a zero. Use while and break in your
program.
▪ Write a C program that prints all odd numbers from 1 to 20. Use for
and continue in your program.
3) Simplify and optimize your steps; (1) Look for patterns and
see if there’s anything you can generalize, (2) See if you can
reduce any steps, or (3) See if you are repeating any steps.
Generic Steps when Solving a
Programming Problem:
4) Evaluate your algorithm(s); Work through the problem
manually with at least varying sets of sample data; Take out a
piece of paper and work through the problem manually.
programs).
Pseudocode .. ?
▪ The prefix pseudo- (from Greek; for "lying, false") is used to mark something that
superficially appears to be (or behaves like) one thing, but is something else (i.e.,
not actually but having the appearance of, pretended, false, imitation, sham).
Examples: pseudoscience, pseudoscientist, pseudopregnancy, .. etc.
Please pause the video and try to answer the question on your own!
Memory Concepts
Destructive versus Non-Destructive Operations
/* This is an Addition Program */
#include <stdio.h>
int main (void) Memory
{ Destructive integer1
int integer1, integer2, sum;
printf(“Enter the First Integer \n”); // Prompt 45
integer2
scanf(“%d”, &integer1); // Read an Integer
72
printf(“Enter the Second Integer \n”); // Prompt
scanf(“%d”, &integer2); // Read an Integer sum
sum = integer1 + integer2; // Assign total to Sum 117
printf(“Sum is: %d \n”, sum); // Print Sum
return 0;
} Non-destructive
Recap on some C Data-Types concepts
Boolean in C
Must include the header file stdbool.h
#include <stdio.h>
#include <stdbool.h>
- A boolean is a data type in
int main()
the C Standard Library which
{
can store true or false. Every
bool x = false;
non-zero value corresponds
if(x)
to true while 0 corresponds
{
to false.
printf("x is true.");
- The boolean works as it does
}
in C++. However, if you
else
don’t include the header
{
file stdbool.h, the program
printf("x is false.");
will not compile.
}
}
Recap on some C Data-Types concepts
o Here, we have to write a program in C that will print the ASCII table.
In this program, we are printing ASCII codes from 32 to 254 along
with their character values. To print the values, we are using a for
loop, where counter will start from 32 and stop at 254.
o Reference: https://en.wikipedia.org/wiki/ASCII
Please pause the video and try to answer the question on your own!
- For example,
unsigned int x;
int y;
Here, the variable x can hold only zero and positive values
because we have used the unsigned modifier.
#include <stdio.h>
int main()
{
int a, cube;
printf("Enter any integer number: ");
scanf("%d", &a);
cube = (a*a*a); //calculating cube
printf("CUBE is: %d\n", cube);
return 0;
}
8.14: Write a C program to calculate the CUBE of an
integer number using two different methods.
[ an example of the C built-in functions in Math.h ]
#include <stdio.h>
#include <math.h>
int main()
{
int a, cube;
printf("Enter any integer number: ");
scanf("%d", &a);
cube = pow(a,3); //calculating cube
printf("CUBE is: %d\n", cube);
return 0;
}
Please pause the video and try to answer the question on your own!
o This program will print the Square, Cube, and Square Root of all
the numbers from 1 to N, using a loop.
o Here, we are reading a value of N (limit) and will the calculate and
print the square, cube, and square root of all the numbers from 1
to N.
o To find the square; we are using (i*i), the cube; we are using
(i*i*i), and the square root, we are using the built-in function
sqrt(i).
o Here, i is the loop counter, and sqrt() is a function of the math.h,
which returns the square root of a number.
Please pause the video and try to answer the question on your own!
#include <stdio.h>
#include <math.h>
int main ()
{
double x;
// finding log(2.7); The natural logarithm (i.e., to the base e)
x = 2.7;
printf("log( %lf ) = %lf \n", x, log( x ));
int main()
{
char ch;
printf("Do you want to shutdown your pc now (y/n)?");
scanf("%c", &ch);
if( ch == 'y'|| ch == 'Y‘ )
{
/* /s is used to order the compiler to shutdown the PC */
system("C:\\WINDOWS\\System32\\shutdown /s");
}
return 0;
}
8.19: Write a C Program that prints n random numbers.
[ an example of the C built-in functions in Stdlib.h & Time.h ]
#include <stdio.h>
#include <stdlib.h>
#include <time.h> /* This header file contains definitions of functions to get and
manipulate date and time information. */
int main ( )
{
int n = 5;
// srand() initializes the random number generator
/* time() gets the current time; The value returned generally represents
the number of seconds since 00:00 hours, Jan 1, 1970 UTC "Coordinated
Universal Time.“ */
srand( time( NULL ) );
/* Print 5 random numbers from 0 to 49 */
for( int i = 0 ; i < n ; i++ )
{
printf( "%d\n", rand( ) );
}
}
Always Up Next ..
Section 8.4
Remember
Write useful Comments;
▪ WHY .. ? You may not always remember what every single
line meant a month later, and someone else working on
your code may not know either. That’s why it’s important
to write useful comments to avoid problems and save time
later if you need to come back to it.
▪ HOW .. ? Try to write brief, high-level comments that help
you understand what’s going on if it is not obvious. This
comes in handy when you are working on more complex
problems. It helps understand what a particular function is
doing and why.
▪ WHATELSE CAN HELP.. ? By using (1) clear variable names,
(2) clear function names, and (3) comments, you (and
others) should be able to understand:
▪ What is this code for?
▪ What is it doing?
Lecture 8: C Built-In Functions, & Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts
Arithmetic Operations
Division .. & .. Mixed–Type Expressions
o If both operands of a division operation are integers,
the result is an integer value.
o E.g., 6 / 4 = 1 .. & .. 18 / 5 = 3
Arithmetic Operations
Division .. & .. Mixed–Type Expressions
int m, n;
double p, x, y;
m=3;
n=2; m n p x y
p = 2.0 ; 3 2 2.0 ? ?
?
x=m/p;
y=m/n;
m = m / p; Remember ..
The expression is evaluated before
the assignment is made.
Recap on some Arithmetic Concepts
Arithmetic Operations
Division .. & .. Mixed–Type Expressions
int m, n;
double p, x, y;
m=3;
n=2; m n p x y
p = 2.0 ; 3 2 2.0 1.5 1.0
1
x=m/p;
y=m/n;
m = m / p;
Recap on some Arithmetic Concepts
Arithmetic Operations
The Remainder Operator ( % )
o It is an integer operator (i.e., only integer operands)
E.g., 7 % 4 = 3
E.g., 17 % 5 = 2
Arithmetic Operations
Evaluating Expressions
Arithmetic Operations
Algebraic Expressions versus C Expressions
m= (a + b + c + d + e)/5
m= a + b + c + d + e/5
Please pause the video and try to answer the question on your own!
o In this C program, we will read 2 numbers; the dividend and the divisor, and
E.g., if the dividend is 10 and the divisor is 3, then the quotient will be 3.
E.g., if the dividend is 10 and the divisor is 3, then the remainder will be 1.
Please pause the video and try to answer the question on your own!
o This program will read the value of N and print all the Leap Years
from 1 to N.
Non-Century years).
Please pause the video and try to answer the question on your own!
if ( i << 1 )
{
printf("Hola! \n" );
}
if ( i <<= 1 )
{
printf("Hey! \n" );
}
return 0;
}
8.25: What is the output of the following C program?
Only Hola! will get printed .. Why?
#include <stdio.h>
int main() In C, a char is an integer type used to store character data,
{ typically 1 byte (8 bits).
unsigned char i = 128;
#include <stdio.h>
int main()
{
int length, width, height;
length = 25;
width = 60;
if (length == 50)
height = 4;
else
height = 8;
printf ("%d %d %d", length, width, height);
}
8.26: What is the output of the following C program?
Results: 25 60 8
#include <stdio.h>
int main()
{
int length, width, height;
length = 25;
width = 60;
if (length == 50)
height = 4;
else
height = 8;
printf ("%d %d %d", length, width, height);
}
Please pause the video and try to answer the question on your own!
#include <stdio.h> a) 5 10 15 20
int main() b) 7 12 17 22
{ c) Syntax Error
for( int i = 0; i < 20; i++ ) d) 16 21
{
switch(i)
{
case 0: i += 5;
case 1: i += 2;
case 5: i += 5;
default: i +=4;
}
printf("%d", i);
}
}
8.27: What is the output of the following C program?
#include <stdio.h> a) 5 10 15 20
int main() b) 7 12 17 22
{ c) Syntax Error
for( int i = 0; i < 20; i++ ) d) 16 21
{ In the first iteration of the loop, i
switch(i) equals 0, and there are no breaks,
{ thus all the cases (0, 1, 5, & default)
case 0: i += 5; will be carried out (performed)
case 1: i += 2; resulting in i equals to 16.
case 5: i += 5;
default: i +=4; The for statement will then
increment the value of i by 1.
}
printf("%d", i); In the second iteration, the default
} case only will be executed, resulting
} in i equals to 21.
Please pause the video and try to answer the question on your own!
#include<stdio.h>
int main()
{
int age;
//input age
printf("Enter the age of the person: ");
scanf("%d", &age);
//check voting eligibility
if ( age >= 18 )
{ printf("Eligible for voting"); }
else
{ printf("Not eligible for voting\n"); }
return 0;
}
Please pause the video and try to answer the question on your own!
This program will read two integer numbers and an operator like +, -,
operations.
Please pause the video and try to answer the question on your own!
Enter a character: E
E is a VOWEL.
Enter a character: X
X is a CONSONANT.
Enter a character: +
+ is not an alphabet letter.
/*C program to check whether a character is a VOWEL or a CONSONANT*/
#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
scanf("%c", &ch);
//condition to check whether the character is alphabet letter or not
if ( ( ch >= 'A' && ch <= 'Z' ) || ( ch >= 'a' && ch <= 'z' ) )
{ //check for VOWEL or CONSONANT
switch(ch) {
case 'A': case 'E': case 'I': case 'O': case 'U':
case 'a': case 'e': case 'i': case 'o': case 'u':
printf("%c is a VOWEL.\n",ch);
break;
default: printf("%c is a CONSONANT.\n", ch);
} // switch ends here
} // if statement ends here
else { printf("%c is not an alphabet letter.\n",ch); }
return 0; }
Please pause the video and try to answer the question on your own!
#include <stdio.h>
int main()
{
int w = 1, x = 0, y, z;
y = z = 5;
if ( w && x || y++ )
printf("The 1st if statement is True. \n");
printf("The value of y is %d. \n", y);
#include <stdio.h>
int main()
{
unsigned char i;
for ( i = 5; i >= 0; i--)
{
printf("%d\n", i);
getchar();
}
return 0;
}
8.36: What is the output of the following C program?
5
#include <stdio.h> 4
int main() 3
{ 2
unsigned char i; 1
for ( i = 5; i >= 0; i--) // The condition will always be true 0
{ 255
254
printf("%d\n", i);
253
getchar();
252
} 251
return 0; 250
} 249
..
..
..
Please pause the video and try to answer the question on your own!
#include <stdio.h>
int main()
{
int i = 0;
for( printf("one\n"); i < 3 && printf(""); i++ )
{
printf("Hello!\n");
}
return 0;
}
8.39: What is the output of the following C program?
The output displayed:
#include <stdio.h> one
int main()
{
int i = 0;
for( printf("one\n"); i < 3 && printf(""); i++ )
{
printf("Hello!\n"); The printf() function returns the
number of characters that are
}
printed. If there is some error, then
return 0; it returns a negative value.
}
Please pause the video and try to answer the question on your own!
#include <stdio.h>
int main()
{
int i = 500;
while( i++ != 0 );
printf("%d\n", i);
return;
}
a) Infinite Loop
b) 0
c) 1
d) Syntax Error
8.40: What is the output of the following C program?
• 1st iteration: True, then i is post-incremented to 501
• 2nd iteration: True, then i is post-incremented to 502
• .. .. ..
#include <stdio.h> • Iteration in which i is equal to 2,147,483,647 .. True,
int main() and the i++ results in i equals to 0
{ • The following iteration, the condition is False, and
int i = 500; then i is post-incremented to 1
while( i++ != 0 );
printf("%d\n", i); // Statement not in the loop
return;
}
a) Infinite Loop
b) 0
c) 1 (Note: wait for a couple of seconds for the output to be printed)
d) Syntax Error
Please pause the video and try to answer the question on your own!
For Example:
o The Factorial of 5 is:
5! = 120 [ That is equivalent to 5*4*3*2*1 = 120 .. ]
Bye Bye!!! 45
8.43: Write a C program to check whether A NUMBER IS
POSITIVE, NEGATIVE, OR ZERO, until the user quits.
#include <stdio.h>
int main() { int num; char choice;
do {
printf("Enter an integer number :"); scanf("%d", &num);
if( num == 0 )
printf("Number is ZERO.");
else if( num > 0 )
printf("Number is POSITIVE.");
else
printf("Number is NEGATIVE.");
printf("\n\nWant to check again (press Y/y for 'yes') :");
scanf(" %c", &choice); /*Here is a space before %c*/
} while( choice == 'Y' || choice == 'y' );
printf("\nBye Bye!!!");
return 0;
}
Please pause the video and try to answer the question on your own!
using nested looping. There are two loops; a parent loop that
runs from 1 to 20, and a child loop that runs from 1 to 10 (to
Lecture 9
User-Defined Functions ..
& .. the Scope of Variables
9.1 An Introduction to Functions
▪ Why Functions? – Copy-Paste Coding! – An Overview of
Functions – User-Defined vs. Built-in Functions
9.2 Functions’ Declarations (Definitions) & Functions’ Prototypes
9.3 Returning Values and Arguments’ Types
9.4 How Functions Work? Function Calls, Returns, & Local Variables Faculty of
▪ Function Calls – The Return Statement – Returning Void – Computing &
Parameters versus Arguments – Local Variable(s) Artificial Intelligence
9.5 Variables’ Scope & Global Variables FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
Instead ..
#include <stdio.h>
with a
/ * Some code which raises an a r b i t r a r y
function in t e ge r t o an a r b i t r a r y power */
i n t main()
{
i n t threePowerFour = raiseToPower( 3, 4 ) ;
printf( "3^4 i s % d " , threePowerFour );
i n t sixPowerFive = raiseToPower( 6, 5 ) ;
printf( “6^5 i s % d " , sixPowerFive );
i n t twelvePowerTen = raiseToPower( 12, 1 0 ) ;
printf( “12^10 i s % d " , twelvePowerTen );
r e t u rn 0 ;
}
Functions .. An Overview
Functions are reusable sections of code that
serve a particular purpose.
Functions
Think of a function as a black box with a set of inputs and a single
(optional) output.
Inputs Output
The rest of the program does not need to know what goes on
inside the function, but the program can call the function, provide
it with inputs, and use the output.
(x, y) Pow xy
Functions (math.h)
You've probably used plenty of C functions already
like printf() from the stdio library or pow() from the math
library.
Hello
(“Hello”) Printf
(stdio.h)
But now we'll learn how to write our own functions and
incorporate them into our code. Basically, the point of
functions in C is to help you to partition your code into
manageable pieces.
Built-in vs. User-Defined Functions
Structured Programming
Function name
Return Type
Parameter 1
Parameter 2
Signature
( function i n t raiseToPower( i n t base, i n t power )
header ) {
i n t result = 1;
f o r ( i n t i = 0; i < power; i = i+ 1 )
{
result = result * base;
}
r e t u r n result;
}
Function Definition Syntax; An Example
For example:
i n t foo()
{
r e t u rn b a r ( ) * 2 ; / / ERROR; bar hasn’t been declared yet
}
i n t bar()
{
r e t u rn 3 ;
}
Function Definition
• Function definitions need to occur before
invocations.
• Solution 1: reorder function definitions.
For example:
i n t bar()
{
r e t u rn 3 ;
}
i n t foo()
{
r e t u rn b a r ( ) * 2 ; / / Ok
}
Function Definition
• Function definitions need to occur before
invocations.
• Solution 1: reorder function definitions.
• Solution 2: use a function prototype; it informs
the compiler that you w ill implement it later.
For example:
i n t b a r ( ) ; Function Prototype
i n t foo()
{
r e t u rn b a r ( ) * 2 ; / / Ok
}
i n t bar()
{
r e t u rn 3 ;
}
Function Prototype (Declaration)
• Function prototypes should match the
signature of the method, though argument
names don’t matter.
For example:
▪ Function Definition in C
https://www.youtube.com/watch?v=gF7wjwM9Jjs
▪ Function Declaration in C
https://www.youtube.com/watch?v=5wAf9nzX2R8
For example:
i n t foo()
{
r e t u r n "hello"; // error
}
i n t foo()
{
r e t u r n 2; // ok
}
Returning a Value
• Up to one value may be returned; it must be
the same type as the return type.
• If no values are returned, give the function a
void return type.
For example:
v o i d printNumber( i n t num )
{
printf( “The number is %d ", num );
}
i n t main()
{
printNumber( 4 ); // The number is 4
r e t u r n 0;
}
Returning a Value
• Up to one value may be returned; it must be
the same type as the return type.
• If no values are returned, give the function a
void return type.
• Note that you cannot declare a variable of
type void.
For example:
i n t main()
{
void x ; / / ERROR
r e t u rn 0 ;
}
Returning a Value
• Return statements don’t necessarily need to be
at the end.
• Function returns as soon as a return statement
is executed.
For example:
v o i d printNumberIfEven( i n t num ) {
i f ( num % 2 == 1) {
printf("Odd number");
return; }
printf("Even number; the number is %d", num); }
i n t main() {
i n t x = 4; i n t y = 5;
printNumberIfEven( x ); // PRINTS: Even number;
the number is 4
printNumberIfEven( y ); // PRINTS: Odd number
}
Argument Type Matters?
v o i d printOnNewLine( i n t x )
{
printf( "%d" , x );
}
• printOnNewLine( 3 ) works
• printOnNewLine("hello") will not compile
Argument Type Matters?
v o i d printOnNewLine( i n t x )
{
printf( "%d" , x );
}
v o i d printOnNewLine( c h a r x )
{
printf( "%c" , x );
}
v o i d printOnNewLine( c h a r x )
{
printf( "%c" , x );
}
• printOnNewLine( 3 ) works
• printOnNewLine('A') also works
Up Next ..
Additional Section 9.4
Resources
▪ C Programming Basics - Functions - Function with
arguments - return values
https://www.youtube.com/watch?v=G9QoX51IDzI
main()'s parameters
This program attempts to swap the
#include <stdio.h> values of x and y. Let's think through the
logic of that swap function:
void swap(int a, int b);
• Take the value of a and store it in a
temporary variable tmp.
int main(void) • Store the value of b in a.
{ • Store the value of tmp in b.
int x = 1; Seems perfectly reasonable, right?
int y = 2;
swap(x, y);
printf("x is %d\n", x);
printf("y is %d\n", y);
}
int main(void)
{
int x = 1;
int y = 2;
swap(x, y);
}
Caller 1
6
Caller Called fn.
2
5
Called fn. 4
3
funct1 ( ) {
//perform a task
funct2( );
…
}
funct2 ( ) {
…
//perform another task
…
}
Trace the following program:
#include <stdio.h>
float average( int a , int b , int c )
{ Parameters
float s = (a + b + c ) / 3.0 ;
return s ;
} Local Variable(s)
int main()
{ float a; Function Call
int x = 5 , y = 7 , z = 2 ;
printf ("x = %d , y = %d , z = %d \n", x , y , z );
a = average( x , 3 , z );
printf ("a = %f \n", a );
a = average ( z , y , x + z ); Arguments
printf ("a = %f \n", a );
return 0;
}
Consider a function “square” to calculate and print the square of an
integer. Then call it from main().
#include <stdio.h>
// “square” function doesn’t return a value
void square( int y ) {
void square( int y ) {
int Z = y * y; printf("the square is %d", y * y(;
printf ("the square is %d", Z); return; // can be omitted
} // end function }
#include <stdio.h>
int Square( int ); //declares these functions
int Cube( int );
int main( )
{
int num = 3;
int sq, cb;
sq = Square(num); Function call (invocation)..
printf("The square of 3 is %d \n", sq);
cb = Cube(num);
printf("The cube of 3 is %d \n", cb);
return 0;
}
.. a program with Three Functions
.. the Square & Cube Functions
#include <stdio.h>
int square( int ); /* function prototype */
int main (void)
{
int x, sq;
/ * loop 10 times and calculate the square of x each time */
for ( x = 1 ; x <= 10 ; x++)
{
sq = square (x) ; // function square is invoked or called
printf( "%d", sq);
} //end for
return 0;
}
int square( int y ) Can function Square have a variable x?
{
return y * y;
} /* end function square */
Up Next ..
Additional Section 9.5
Resources
▪ C Programming Tutorial 89 - Function Arguments,
Parameters, Return Statement
https://www.youtube.com/watch?v=ylPG6x1rDxY
void f oo( ) {
++numCalls;
}
i n t main() {
foo(); foo(); foo();
printf("%d", numCalls); / / 3
}
int numCalls = 0;
Scope:
i n t r a i s e To P o w e r ( int b a s e , i n t e x p o n e n t )
Global Variables {
numCalls = numCalls + 1;
int result = 1;
Scope; where a variable was for ( int i = 0; i < exponent; i++ )
declared, determines where {
it can be accessed from .. result = result * base;
}
r e tu rn r e s u l t ;
}
i n t m a x ( int n u m 1 , i n t n u m 2 )
{
numCalls = numCalls + 1;
int result;
if ( num1 > num2 ) { result = num1; }
else { r e s u l t = n u m 2 ; }
r e tu rn r e s u l t ;
}
int numCalls = 0;
Scope:
i n t r a i s e To P o w e r ( int b a s e , i n t e x p o n e n t )
Global Variables {
numCalls = numCalls + 1;
int result = 1;
Scope; where a variable was for ( int i = 0; i < exponent; i++ )
declared, determines where {
it can be accessed from .. result = result * base;
}
• numCalls has global r e tu rn r e s u l t ;
scope – can be }
accessed from any
function i n t m a x ( int n u m 1 , i n t n u m 2 )
{
numCalls = numCalls + 1;
int result;
if ( num1 > num2 ) { result = num1; }
else { r e s u l t = n u m 2 ; }
r e tu rn r e s u l t ;
}
int numCalls = 0;
Scope:
i n t r a i s e To P o w e r ( int b a s e , i n t e x p o n e n t )
Global Variables {
numCalls = numCalls + 1;
int result = 1;
Scope; where a variable was for ( int i = 0; i < exponent; i++ )
declared, determines where {
it can be accessed from .. result = result * base;
}
• numCalls has global r e tu rn r e s u l t ;
scope – can be }
accessed from any
function i n t m a x ( int n u m 1 , i n t n u m 2 )
• result has a function {
scope – each function numCalls = numCalls + 1;
can have its own int result;
separate variable if ( num1 > num2 ) { result = num1; }
named result else { r e s u l t = n u m 2 ; }
r e tu rn r e s u l t ;
}
int numCalls = 0;
i n t r a i s e To P o w e r ( int b a s e , i n t e x p o n e n t ) Scope
{
numCalls = numCalls + 1;
int result = 1;
for ( int i = 0; i < exponent; i++ )
{
result = result * base;
}
return r e s u l t ;
}
i n t m a x ( int n u m 1 , i n t n u m 2 )
{ Global Scope
numCalls = numCalls + 1;
int result; int
if ( num1 > num2 ) { result = num1; } numCalls
else { r e s u l t = n u m 2 ; }
return r e s u l t ;
}
raiseToPower function scope max function scope
double double
newHigh newLow
Scope
double squareRoot( double num ) { Cannot access variables that are out of scope.
double low = 1.0;
double high = num;
for ( int i = 0; i < 30; i = i + 1)
{
squareRoot function scope
double estimate = (high + low) / 2;
if ( estimate * estimate > num ) { double double
double newHigh = estimate; num double high
high = newHigh; low A
}
else {
double newLow = estimate; for loop scope
low = newLow; double
} int i estimate
} // A
return estimate; // ERROR
}
If statement scope else statement scope
double double
newHigh newLow
Scope
double squareRoot( double num ) { Cannot access variables that are out of scope.
double low = 1.0; Solution 1: move the code.
double high = num;
for ( int i = 0; i < 30; i = i + 1)
{
squareRoot function scope
double estimate = (high + low) / 2;
if ( estimate * estimate > num ) { double double
double newHigh = estimate; num double high
high = newHigh; low A
}
else {
double newLow = estimate; for loop scope
low = newLow; double
} int i estimate
B
if ( i == 29 ) {
return estimate; // B
}
} // A If statement scope else statement scope
} double double
newHigh newLow
Scope
double squareRoot( double num ) { Cannot access variables that are out of scope.
double low = 1.0; Solution 2: declare the variable in a higher
double high = num; scope.
double estimate;
for ( int i = 0; i < 30; i = i + 1)
squareRoot function scope
{
estimate = (high + low) / 2; double double double
if ( estimate * estimate > num ) { num double high estimate
double newHigh = estimate; low A
high = newHigh;
}
else { for loop scope
double newLow = estimate;
low = newLow; int i
}
} // A
return estimate;
} If statement scope else statement scope
double double
newHigh newLow
Scope
Exercises
What have we learned?
1) Write a C function that will output the multiplication
table as shown below:
1*1 = 1 2*1 = 2 3*1 = 3 .. 9*1 = 9
1*2 = 2 2*2 = 4 3*2 = 6 .. 9*2 = 18
.. .. .. .. ..
1*9 = 9 2*8 = 18 3*9 = 27 .. 9*9 = 81
Number Systems,
Binary Arithmetic, .. & ..
the Complements
10.1 Decimal & Binary Notations
▪ Binary Data Representation – Converting Binary to Decimal (& vice versa)
10.2 Useful Number Systems (in CS) & Number Systems Conversions
▪ Numbers with different bases; Octal & Hexadecimal Systems – Number
Systems Conversions
10.3 Binary Arithmetic & Binary Logic (Truth Tables)
▪ Addition, Multiplication, & Subtraction – Truth Tables of Logical Operations Faculty of
Computing &
10.4 The Complements Representation for Negative Numbers
Artificial Intelligence
▪ Why do we study Complements? Subtraction with Complements?
▪ r's [Radix] complement & (r - 1)'s [Diminished Radix] complement FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
If we have only two numbers, it's very easy to represent them in the
physical world using electricity. You can think of each binary digit as a
switch or a light bulb that can be either on or off, whereby convention
0 is thought of as "off" and 1 is "on".
Let's think more carefully about decimal notation.
We are used to Decimal Notation:
1 6 3
102 101 100
You get 163 when you multiply these digits by their respective
powers of 10 and sum them.
= 7000 + 300 + 20 + 9
= 7*103 + 3*102 + 2*101 + 9*100
Coefficient Base Weight
0-9 or
Radix
n 2 1 0 -1 -m
an r +….+ a2 r + a1r + a0r + a-1 r +… +a-m r
Computers Store & Process Data via
Binary Notation:
To represent this same number in binary, you'll need a 1 in the 1s
place (20), a 1 in the 2s place (21), a 1 in the 32s place (25), and a 1 in
the 128s place (27).
1 0 1 0 0 0 1 1
27 26 25 24 23 22 21 20
You get 163 when you multiply these digits by their respective
powers of 2 and sum them.
Bit;
• Smallest unit of information.
• Yes / No .. On / Off .. High / Low .. 1 / 0 .. 5V / 0V
Byte;
• Group of 8 bits → 2^8 = 256 different states.
Word;
• A group of two bytes is called a word.
• Bits 0 through 7 form the low-order byte, and bits 8 through 15
form the high-order byte.
• The word size in any given computer is fixed, for example: 16-bit
word .. Thus, every word holds a 16-bit pattern, with each being
bit either 0 or 1.
Binary Data Representation:
Computer memory is normally represented in terms of Kilobytes or
Megabytes. In the Metric System, one Kilo represents 1000 grams,
that is 103. In the Binary System, one Kilobytes represent 1024 bytes,
that is 210.
The following table shows the representation of various memory
sizes: Name Abbreviation Size (in bytes)
Kilo K 210
Mega M 220
Giga G 230
Tera T 240
Petta P 250
Exa E 260
Zetta Z 270
Yotta Y 280
Let's count to 8 in binary! Note how we can multiply the binary digits by their
respective powers of two and sum them to convert to a decimal value.
Converting Binary to Decimal (& vice versa)
0000 = 0*20 = 0
1 bit, 2 possibilities.
0001 = 1*20 = 1
2 bits, 4 possibilities.
0010 = 1*21 + 0*20 = 2
0011 = 1*21 + 1*20 = 3
3 bits, 8 possibilities.
0100 = 1*22 + 0*21 + 0*20 = 4
Total Number of
0101 = 1*22 + 0*21 + 1*20 =5 Possibilities = 2n ,
where n is the
0110 = 1*22 + 1*21 + 0*20 = 6
number of bits.
0111 = 1*22 + 1*21 + 1*20 = 7
4 bits, ? possibilities.
1000 = 1*23 + 0*22 + 0*21 + 0*20 =8
Exercises
What have we learned?
00 0000 00 0
01 0001 01 1
02 0010 02 2
03 0011 03 3
04 0100 04 4
05 0101 05 5
06 0110 06 6
07 0111 07 7
08 1000 10 8
09 1001 11 9
10 1010 12 A
11 1011 13 B
12 1100 14 C
13 1101 15 D
14 1110 16 E
15 1111 17 F
Number
Systems
.. & ..
Conversions
NUMBER BASE CONVERSION
BASE-R → DECIMAL
1 ×20 = 1
0 ×21 = 0
0 ×22 = 0
1 ×23 = 8
1 ×24 = 16
19
2510
110012 = 2510
CONVERSION: Octal to Decimal
• Base or Radix is 8 (“octo” in Latin ► eight)
• Digits: 0, 1, 2, 3, 4, 5, 6, 7
• Example:
1758
5 ×80 = 5
7 ×81 = 56
1 ×82 = 64
125
1758 = 12510
CONVERSION: Hexadecimal to Decimal
Base or Radix is 16 (“hexa” in Greek ► six .. & .. “decem”
in Latin ► ten)
Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
• A ► 10
• B ► 11
• C ► 12
• D ► 13
• E ► 14
• F ► 15
1 0
Example: 1216 = 1 × 16 + 2 ×16
= 16 + 2 = 1810
CONVERSION: Additional Examples
2 1 0
1012 = 1 × 2 + 0 × 2 + 1 × 2
= 4 + 0 + 1 = 510
2 1 0
1238 = 1 × 8 + 2 × 8 + 3 × 8
= 64 + 16 + 3 = 8310
2 1 0
1C216 = 1 × 16 + 12 × 16 + 2 × 16
= 256 + 192 + 2 = 45010
NUMBER BASE CONVERSION
DECIMAL → BASE-R
2 25 remainder
2 12 1
2 6 0
2 3 0
2 1 1
0 1
2510 = 110012
CONVERSION: Decimal to Octal (Integer Part)
• Conversion of 12510 to octal
8 125 remainder
8 15 5
8 1 7
0 1
12510 = 1758
CONVERSION: Decimal to Hexadecimal (Integer Part)
• Conversion of 45010 to hexadecimal
16 450 remainder
16 28 2
16 1 12
0 1
45010 = 1C216
CONVERSION: Decimal to Binary (Fraction Part)
Example 1: Decimal → Binary
0.812510 = ?2
= 0.11012
0.1457910 = ?2 .14579
x 2
0.29158
x 2
0.58316
x 2
1.16632
x 2
0.33264
x 2
0.66528
x 2
1.33056
= 0.001001...
etc.
Example:
41.687510 = 101001.10112
153.51310 = 231.4065178
CONVERSION: between Number Systems
Decimal Octal
Binary Hexadecimal
CONVERSION: between Number Systems
Example 1: Binary → Octal
10110001101011.1111000001102 = ?8
2 6 1 5 3 7 4 0 6
= 26153.74068
CONVERSION: between Number Systems
Example 2: Binary → Hexadecimal
10110001101011.111100102 = ?16
2 C 6 B F 2
= 2C6B.F216
CONVERSION: between Number Systems
Example 3: Octal → Binary
7058 = ?2
7 0 5
= 1110001012
CONVERSION: between Number Systems
Example 4: Hexadecimal → Binary
10AF16 = ?2
1 0 A F
= 00010000101011112
CONVERSION: between Number Systems
Example 5
CONVERSION: between Number Systems
Example 6: Octal → Hexadecimal
10768 = ?16
1 0 7 6
2 3 E
= 23E16
CONVERSION: between Number Systems
Example 7: Hexadecimal → Octal
1F0C16 = ?8
1 F 0 C
1 7 4 1 4
= 174148
Exercises
What have we learned?
1) Convert the following decimal numbers to binary:
a) 164
b) 255
c) 94
d) 68.5625
e) 43.625
2) Redo question 1 but convert the decimal numbers to hexadecimal.
3) Redo question 1 but convert the decimal numbers to octal.
4) Convert the following binary numbers to decimal:
a) 110111.110
b) 10010101.111
Exercises
What have we learned?
5) Convert the following binary numbers to octal:
a) 10110101
b) 110011111
c) 10101001101
d) 1110110.101
e) 01101011100.01100
6) Redo question 5 but convert the binary numbers to hexadecimal.
7) Convert the following Hexadecimal numbers to octal:
a) 4E8
b) 2F1
c) D78
d) 5C0
e) 5BCA
Up Next ..
Additional Section 10.3
Resources
▪ How To Convert Binary To Decimal:
https://www.youtube.com/watch?v=VLflTjd3lWA
1011
101
-------------
1011
+ 00000
+ 101100
-------------
110111
Binary Arithmetic..
the Subtraction
Binary Arithmetic..
the Subtraction
Addition & Subtraction
(Don’t forget to carry / borrow your 1s)
Addition and subtraction in binary works the same way as in decimal.
Start on the right and carry / borrow the 1s as needed.
1 0 1 01 11 1 1 1 10 010 0
+ 010 0 0 1 - 0 0 0 1 0
1111 0 0 1 1 0 10
Binary Arithmetic..
What about the division .. ?
Multiple Subtractions;
• One way to solve division problems – in any base – is to keep
subtracting the divisor from the dividend, then the remainder,
while tallying up the number of times you can do so before
getting a negative number.
▪ Binary Division:
https://www.youtube.com/watch?v=VKemv9u40gc
Lecture 10: Number Systems, Binary Arithmetic, .. &
the Complements Representation
10.1 Decimal & Binary Notations
▪ Binary Data Representation and Converting Binary to Decimal (& vice versa)
10.2 Useful Number Systems (in CS) & the Number Systems Conversions
▪ Numbers with different bases; Octal System & Hexadecimal System
▪ Number Systems Conversions
10.3 Binary Arithmetic & Binary Logic (Truth Tables)
▪ Binary Addition, Multiplication, & Subtraction
▪ Truth Tables, & Truth Tables of Logical Operations
10.4 The Complements Representation for Negative Numbers
▪ Why do we study Complements? Subtraction with Complements?
▪ The Complements Representation for Negative Numbers
▪ r's [Radix] complement & (r - 1)'s [Diminished Radix] complement
Recap:
Binary Arithmetic..
the Concept of Borrow in Decimal Subtraction
Recap:
Binary Arithmetic..
the Subtraction
the
Complements
Representation
for Negative
Numbers ..
Why do we study Complements?
hardware.
50 – 5 = 45 5
61
But .. What does the complements
approach do? Why it works?!
o Let’s try an example, 5010 – 510 = 4510
o Using 10’s complement:
o 10’s complement of 5 is: 99 – 5 + 1 = 95 (i.e., ≡ 100 – 5)
o 50 + (100 – 5 ) = 50 + 95 = 145 ..
o Discard the carry 145 ..
o The answer is: 45
But .. What does the complements
approach do? Why it works?!
o Let’s try an example, 5010 – 510 = 4510
o Using 10’s complement: to calculate the 10’s complement for
2 digits, you should subtract from .. ?
100
63
But .. What does the complements
approach do? Why it works?!
o Let’s try an example, 5010 – 510 = 4510
o Using 10’s complement: 50 + (100 – 5 ) = 145
50 + 95 ( = 100 – 5) 5 =
Discard the
carry: 145 =
50 100 95 45
A - B = A + (-B "using 1's Complement")
Binary Subtraction using 1's Complement
Step 0: Both numbers should have the same number of bits/digits.
Step 1: Convert number to be subtracted to its 1's Complement form.
Step 2: Perform the addition.
Step 3: If the final carry is 1, then add it to the result obtained in Step 2. If
final carry is 0, result obtained in step 2 is negative and in the 1's
complement form.
Example 1:
A = 1100 (4 bits) .. & .. B = 0101 (4 bits)
A – B = 1100 (12) – 0101 (5)
1111 – 0101 (5) = 1010 (–5) “using 1's Complement”
1100 + 1010 = 10110 ► (add the final carry) ► 0111 (7)
Example 2:
A = 0101 (4 bits) .. & .. B = 1100 (4 bits)
A – B = 0101 (5) – 1100 (12)
1111 – 1100 (12) = 0011 (–12) “using 1's Complement”
0101 + 0011 = 1000 ► (no final carry, thus it’s a negative number “a 1's
complement”) ► [1111 – 1000 = 0111] ► –0111 (–7) 65
A - B = A + (-B "using 2's Complement")
Binary Subtraction using 2's Complement
Step 0: Both numbers should have the same number of bits/digits.
Step 1: Convert number to be subtracted to its 2's Complement form.
Step 2: Perform the addition.
Step 3: If a final carry is generated then the result is positive and in its true form.
If a final carry is not produced, then the result obtained in step 2 is negative and
in its 2's complement form. Please note that the final carry is always neglected.
Example 1:
A = 1001 (4 bits) .. & .. B = 0100 (4 bits)
A – B = 1001 (9) – 0100 (4)
1111 – 0100 = 1011 + 1 = 1100 (–4) “using 2's Complement”
1001 + 1100 = 10101 ► Neglect the final Carry, the result is positive ► 0101 (+5)
Example 2:
A = 0110 (4 bits) .. & .. B = 1011 (4 bits)
A – B = 0110 (6) – 1011 (11)
1111 – 1011 = 0100 + 1 = 0101 (–11) “using 2's Complement”
0110 + 0101 = 1011 ► (no final carry, thus it’s a negative number “a 2's
complement”) ► 1111 – 1011 = 0100 + 1 = –0101 (–5) 66
Exercises
What have we learned?
1) Find the 1’s and 2’s complement of the following:
a) 1011 1011
b) 0101 1000
c) 0110 1101 0111
d) 1011 0110 1101
e) 0001 0110 1010
2) How are negative numbers represented in binary?
Why? Write a program that reads an integer (a
positive or a negative integer) and then prints the
binary representation of that integer.
Up Next ..
Additional Lecture 11
Resources
▪ Binary Addition and Subtraction With Negative Numbers,
2's Complements & Signed Magnitude:
https://www.youtube.com/watch?v=sJXTo3EZoxM
Function Overloading,
Recursion & Pass-by-Value
versus Pass-by-Reference
11.1 An Introduction to Recursion
▪ Recursion – Base Case (Recursion without a Base Case?) –
Recursive Functions – Factorial: An Example
11.2 More Examples on Recursion
▪ The Fibonnaci Series – The Euclidean Algorithm (Computing
the Greatest Common Divisor 'GCD')
11.3 Function Overloading & Pass-by-Reference versus Pass-by- Faculty of
Value Computing &
▪ Function Overloading – Passing Arguments – Pass (Call) by- Artificial Intelligence
Value – Pass (Call) by-Reference – Returning Multiple Values
FALL 2024
Where are we now .. ?!
0: Course Introduction & Plan
1: Computational Thinking – Part 1 (Computers, Computer Science, & Binary Representation)
2: Computational Thinking – Part 2 (Types of Hardware, Algorithms, & Programming Languages)
3: Computational Thinking – Part 3 (Types of Software, Basics of Programs, & Compilation)
4: Variables, Constants, & Data Types in C
5: Arithmetic & Bitwise Operations, Logical & Relational Operators, and Precedence
6: Control Structures – Selection (Decisions)
7: Control Structures – Repetition (Loops)
8: C Built-In Functions & Solved Examples (1st Set)
9: User–Defined Functions & Scope of Variables
10: Number Systems, Binary Arithmetic, & the Complements Representation
11: Recursion, Function Overloading, & Call-by-Reference versus Call-by-Value
12: Solved Examples (2nd Set)
Input Output
function.
Factorial
For our next example, let’s think about the factorial operation.
The factorial operation is a perfect candidate for recursion
because it is a problem that can easily be broken up into similar
smaller problems!
n! = n * (n - 1) * (n - 2) * … * 1
5! = 5 * 4 * 3 * 2 * 1
So, if we want to calculate the factorial of 5, we can think of it as
multiplying 5 by the factorial of 4:
5! = 5 * 4!
Similarly, to calculate the factorial of 4, we multiply 4 by the
factorial of 3:
4! = 4 * 3!
And so on ..
Let’s implement a factorial function in C!
This recursive function calculates the factorial of its integer argument,
and unlike the last function we saw, this one has a base case!
Think through what happens when you pass this function an argument
of 3:
factorial(3) = 3 * factorial(2)
2 * factorial(1)
heap
factorial ( 3 )
stack main ( )
Every function call results in a new frame being created. These frames are arranged on
top of each other in the stack, with the frame for the most recently called function
(the active frame) at the top.
• main() calls factorial(3)
• factorial(3) calls factorial(2)
heap
factorial ( 2 )
factorial ( 3 )
stack main ( )
heap
factorial ( 1 )
factorial ( 2 )
factorial ( 3 )
stack main ( )
heap
factorial(1) returns 1
to factorial(2). Its
frame is destroyed, and the
one for the function below
(in this case
1 factorial(2)) becomes
active again.
factorial ( 2 )
factorial ( 3 )
stack main ( )
heap
factorial(2) returns 2
to factorial(2). Its
frame is destroyed, and the
one for the function below
(in this case
factorial(3)) becomes
active again.
2
factorial ( 3 )
stack main ( )
heap
factorial(3) returns 6
to main(). Its frame is
destroyed, and the one for
the function below (in this
case main()) becomes
active again.
▪ Recursion:
https://www.youtube.com/watch?v=mz6tAJMVmfM
How?
Fibonacci Numbers/Sequence
Fibonacci Numbers/Sequence
#include <stdio.h>
int fib( int n ) {
if( ( n == 1 )||( n == 0 ) ) { return n; }
else { return( fib( n - 2 ) + fib( n - 1 ) ); }
}
int main() {
int x, i = 0;
printf("Enter the number of terms in the series : ");
scanf("%d", &x);
printf("\n The Fibonnaci Series : ");
while( i < x ) {
printf(" %d", fib( i ) );
i++;
}
return 0;
}
Euclidean Algorithm
Computing the Greatest Common Divisor 'GCD'
In mathematics, the Euclidean algorithm, is an efficient method for
computing the greatest common divisor (GCD) of two integers
(numbers), the largest number that divides them both without a
remainder.
o It is named after the ancient mathematician who first described it
Euclid of Alexandria (Ptolemaic Egypt - c. 300 BC).
o It is one of the oldest algorithms in common use.
o Synonyms for the GCD include the greatest common factor (GCF),
the highest common factor (HCF), the highest common divisor
(HCD), and the greatest common measure (GCM).
Euclidean Algorithm
Computing the Greatest Common Divisor 'GCD'
Different implementations of the algorithm may be expressed by the
following pseudocodes:
a) a = 100, & b = 20
b) a = 11, & b = 77
/ / pass-by-value
void i n cremen t( i n t a )
{
a = a + 1;
printf( "a i n increment: %d" , a );
}
i n t main()
{
i n t q = 3;
increment( q );
printf( "q i n main: %d" , q );
}
The C language is pass-by-value without exception.
/ / pass-by-value
void i n cremen t( i n t a )
{
a = a + 1; Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 3
i n t main()
{
i n t q = 3;
increment( q ); / / does nothing
printf( "q i n main: %d" , q );
}
The C language is pass-by-value without exception.
q=3
/ / pass-by-value
void i n cremen t( i n t a )
{
a = a + 1;
Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 3
i n t main()
{
i n t q = 3 ; / / HERE
increment( q ); / / does nothing
printf( "q i n main: %d" , q );
}
The C language is pass-by-value without exception.
q=3 a=3
/ / pass-by-value
void i n cremen t( i n t a ) / / HERE
{
a = a + 1;
Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 3
i n t main()
{
i n t q = 3;
increment( q ); / / does nothing
printf( "q i n main: %d" , q );
}
The C language is pass-by-value without exception.
q=3 a=4
/ / pass-by-value
void i n cremen t( i n t a )
{
a = a + 1 ; / / HERE
Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 3
i n t main()
{
i n t q = 3;
increment( q ); / / does nothing
printf( "q i n main: %d" , q );
}
This is pass-by-reference in C++ (won't work in C).
/ / pass-by-reference
void i n cremen t( i n t & a )
{
a = a + 1;
printf( "a i n increment: %d" , a );
}
i n t main()
{
i n t q = 3;
increment( q );
printf( "q i n main: %d" , q );
}
This is pass-by-reference in C++ (won't work in C).
/ / pass-by-reference
void i n cremen t( i n t & a )
{
a = a + 1; Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 4
i n t main()
{
i n t q = 3;
increment( q ); / / works
printf( "q i n main: %d" , q );
}
This is pass-by-reference in C++ (won't work in C).
q=3
/ / pass-by-reference
void i n cremen t( i n t & a )
{
a = a + 1;
Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 4
i n t main()
{
i n t q = 3 ; / / HERE
increment( q ); / / works
printf( "q i n main: %d" , q );
}
This is pass-by-reference in C++ (won't work in C).
q=3 a
/ / pass-by-reference
void i n cremen t( i n t & a ) / / HERE
{
a = a + 1;
Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 4
i n t main()
{
i n t q = 3;
increment( q ); / / works
printf( "q i n main: %d" , q );
}
This is pass-by-reference in C++ (won't work in C).
q=4 a
/ / pass-by-reference
void i n cremen t( i n t & a )
{
a = a + 1 ; / / HERE
Output
printf( "a i n increment: %d" , a ); a in increment: 4
} q in main: 4
i n t main()
{
i n t q = 3;
increment( q ); / / works
printf( "q i n main: %d" , q );
}
This is pass-by-reference in C++ (won't work in C).
int main()
{
int q = 3;
int r = 5;
swap( q, r );
printf( "q %d", q ); // q 5
printf( "r %d", r ); // r 3
}
This is pass-by-reference in C++ (won't work in C).
int main()
{
int q = 3;
int r = 5; / / HERE
swap( q, r );
printf( "q %d", q ); // q 5
printf( "r %d", r ); // r 3
}
This is pass-by-reference in C++ (won't work in C).
i n t d i v i d e ( i n t n u m e r a t o r, i n t d e n o m i n a t o r, i n t & r e m a i n d e r ) {
remainder = numerator % denominator;
return numerator / denominator;
}
int main() {
int num = 14;
int den = 4;
int rem;
int result = divide( num, den, rem ); // 3 * 4 + 2 = 14
printf( "%d * %d + %d = %d", result, den, rem, num );
}
Note:
Pass-by-address / C Style Pass-by-reference
12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.
5
/*EMI Calculator (C program to calculate EMI).*/
#include <stdio.h>
#include <math.h>
int main() {
float principal, rate, time, emi;
printf("Enter principal: "); scanf( "%f", &principal );
printf("Enter rate: "); scanf( "%f", &rate);
printf("Enter time in year: "); scanf( "%f", &time);
rate = rate / ( 12 * 100 ); /*one month interest*/
time = time * 12; /*one month period*/
emi = calculate_emi( principal, rate, time );
printf("Monthly EMI is = %f\n", emi );
return 0;
6
}
Please pause the video and try to answer the question on your own!
7
Please pause the video and try to answer the question on your own!
First run:
Enter an integer number: 12321
12321 is a palindrome.
Second run:
Enter an integer number: 1234
1234 is not a palindrome.
8
/* C program to check whether a number is palindrome or not */
#include <stdio.h>
/*function to check Palindrome Number*/
int isPalindrome( int num ) {
int tempNumber = num; int dig, revNumber;
/*getting reverse number*/
revNumber = 0;
while(num > 0) {
dig = num % 10;
revNumber = ( revNumber * 10 ) + dig;
num/=10; }
if( revNumber == tempNumber )
return 1; /*Palindrome Number*/
else
return 0; /*Not a Palindrome Number*/
}
int main() {
int number;
printf("Enter an integer number: "); scanf("%d", &number);
if( isPalindrome( number ) ) printf("%d is a palindrome.", number);
else printf("%d is not a palindrome.", number);
9
return 0; }
Please pause the video and try to answer the question on your own!
o This program will read an integer number and count the total
number of digits in that number. For example, the total number of
digits in the integer 1234 is 4.
10
/* C program to count digits in a number.*/
#include <stdio.h>
/*function to count digits*/
int countDigits( int num ) {
int count = 0;
while( num > 0 ) {
count++;
num/=10;
}
return count;
}
int main() {
int num, cnt;
printf("Enter a number: ");
scanf("%d", &num);
cnt = countDigits( num );
printf("Total numbers of digits are: %d in the number: %d.", cnt, num);
return 0;
11
}
Lecture 12: Solved Examples [ 2nd Set ]
Solved Examples on:
12.1 Functions [ Part A ]; Function Declaration (Definition), Function Prototype,
Function Call, Parameters versus Arguments, Returning Values (Return Type &
the Return Statement), Local Variables (Variables’ Scope), & Pass-by-Value
versus Pass-by-Reference.
12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.
o For example, if the user entered the number 12311, in which (s)he
wants to find the occurrence of the digit 1, the occurrence of 1 will
be 3 in the given number (12311).
13
/*C program to print occurrence of a particular digit in a number.*/
#include <stdio.h>
/*function to get occurrence of a digit in a number*/
int findOccurrence( int num, int dig ) {
int rem, cnt; cnt = 0;
while( num > 0) {
rem = num%10;
if( rem == dig )
cnt++;
num/=10;
}
return cnt;
}
int main() {
int num, digit, cnt;
printf("Enter a number: "); scanf("%d", &num);
printf("Enter a digit to search: "); scanf("%d", &digit);
cnt = findOccurrence( num, digit);
printf("Total occurrence of the digit is: %d in number: %d.", cnt, num);
14
}
Please pause the video and try to answer the question on your own!
First run:
Enter an integer number: 153
153 is an Armstrong number.
Second run:
Enter an integer number: 167
167 is not an Armstrong number.
16
/* C program to check whether a number is armstrong or not */
#include <stdio.h>
/*function to check Armstrong Number*/
int isArmstrong( int num ) {
int tempNumber = num; int rem; int sum = 0; /*sum of digit's cube*/
while( tempNumber != 0) {
rem = tempNumber % 10;
sum = sum + ( rem * rem * rem );
tempNumber /= 10;
}
if( sum == num) return 1; /*Armstrong Number*/
else return 0; /*Not an Armstrong Number*/
}
int main() {
int number;
printf("Enter an integer number: "); scanf("%d", &number);
if( isArmstrong( number ) )
printf("%d is an Armstrong number.", number);
17
else printf("%d is not an Armstrong number.", number);
return 0; }
Please pause the video and try to answer the question on your own!
This result of 12 sets is the calculation of nPr( 4, 2), the total number
of permutations of 4 objects taking 2 at a time. We can confirm that
the formula produces 12:
nP ( 4, 2) = 4! / ( 4 − 2 )! = ( 4 ∗ 3 ∗ 2 ∗ 1 ) / ( 2 ∗ 1 ) = 24 / 2 = 12
r
Please pause the video and try to answer the question on your own!
12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.
int main() {
int no = 5;
fun1( no );
return 0; }
24
12.7: What is the output of the following code
segment?
What will be the output of the program?
#include <stdio.h>
int fun1( int no ) {
if( no == 0 )
return 0;
else
printf("%d,", no );
fun1( no-- ); }
int main() {
int no = 5;
fun1( no );
return 0; }
Infinite loop. 5, 5, 5, 5, ……
25
Please pause the video and try to answer the question on your own!
int main() {
int no = 5;
fun1( no );
return 0; }
26
12.8: What is the output of the following code
segment?
What will be the output of the program?
#include <stdio.h>
int fun1( int no ) {
if( no == 0 )
return 0;
else
printf("%d,", no );
fun1( --no ); }
int main() {
int no = 5;
fun1( no );
return 0; }
Print 5, 4, 3, 2, 1.
27
Please pause the video and try to answer the question on your own!
int main()
{
int num, prime;
printf("Enter a positive number to check if it's a Prime Number: ");
scanf("%d", &num);
prime = isPrime( num, num / 2 );
if( prime == 1 )
{ printf("\n%d is a Prime Number.\n", num); }
else
{ printf("\n%d is a Composite Number.\n", num); }
return 0;
}
12.3 Recursion, Base Cases (and Recursion without a Base Case), & Recursive
Functions.
o Write a program in C to
convert a decimal number into
binary.
31
Please pause the video and try to answer the question on your own!
For Example:
32
#include <stdio.h>
void main()
{
int n, i, j, binno = 0, dn;
printf("\n\nConvert Decimal to Binary:\n ");
printf("-------------------------\n");
printf("Enter a number to convert : ");
scanf("%d", &n);
dn = n;
i = 1;
for( j = n; j > 0; j = j / 2)
{
binno = binno + ( n % 2 ) * i;
i = i * 10;
n = n / 2;
}
printf("\nThe Binary of %d is %d.\n\n", dn, binno);
} 33
Please pause the video and try to answer the question on your own!
o Write a program in
C to convert a
binary number into
a decimal number.
34
Please pause the video and try to answer the question on your own!
35
#include <stdio.h>
void main() {
int n1, n, p = 1;
int dec = 0, i = 1, j, d;
printf("\n\n Convert Binary to Decimal:\n ");
printf("-------------------------\n");
printf("Input a binary number :");
scanf("%d", &n);
n1 = n;
for ( j = n; j > 0; j = j / 10) {
d = j % 10;
if( i == 1 )
p = p * 1;
else
p = p * 2;
dec = dec + ( d * p );
i++;
}
printf("\nThe equivalent Decimal Number : %d \n\n", dec); 36
}
Please pause the video and try to answer the question on your own!
an Introduction to
Computer Science
Thank you!