0% found this document useful (0 votes)
289 views802 pages

All Lecture Notes For CS111 & COM101 (Intro. To CS Fall 2024)

Uploaded by

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

All Lecture Notes For CS111 & COM101 (Intro. To CS Fall 2024)

Uploaded by

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

CS111 | COM101 Intro.

to Computer Science
Computer Science Dept.
Helwan University

A Compilation of the Lecture Notes /


Slides, & Exercises for the Module:
.. an Introduction to Computer
Science and Programming by
C & C++ Examples
Faculty of
Computing &
Artificial Intelligence

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

Announcements and Additional Resources:


• https://www.facebook.com/amr.s.ghoneim/

Contacts and Additional Resources:


• https://linktr.ee/AmrGhoneim

• 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

Course Code CS111 [or COM101 at Helwan National Uni.]

Course Name Introduction to Computer Science

Coordinating Unit Department of Computer Science,


Faculty of Computing & Artificial ..
.. Intelligence, Helwan University

Term Semester 1 [Fall]

Level Undergraduate – Level 1

2
Tentative Topics
& Learning Objectives
.. of this course

3
Learning Objectives of this Course [ ‫] أهداف المقرر‬

What you'll learn?


 A broad and robust understanding of computer science & its
fields, computational thinking, and programming.
 Know the key components of a computer system (hardware,
software, data/information).
 Be familiar with how computers work through an introduction
to number systems & binary representation.
 How to think algorithmically, to solve basic programming
problems efficiently, and how to represent algorithms.
 Familiarity with concepts like abstraction, algorithms, data
structures, and software engineering.
 Familiarity with basic programming concepts.
 Familiarity with the C programming language.
4
‫] أهداف المقرر [ ‪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..

Eventually .. & as any entry-level course to Computer


Science .. this course provides students with a foundation
for further studies in computer science and empowers
them to apply computer science to problems in other
domains.

‫سا قويًا‬
ً ‫ يوفر هذا المقرر للطالب أسا‬.. ‫– كأي مقرر تمهيدي لعلوم الحاسوب‬
‫لمواصلة دراستهم في مجال علوم الحاسوب ويمنحهم القدرة على تطبيق علوم‬
.‫الحاسوب لحل المشكالت في مجاالت أخرى‬
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:

Amr S. Ghoneim YouTube Channel :


https://www.youtube.com/AmrSGhoneim/

CS111 Introduction to Computer Science YouTube Playlist :


https://www.youtube.com/playlist?list=PLsnvpvHuTUbDQZEakmW9
YzwGxHTO9VlUR

11
Announcements & Course Materials

Downloads, Homework, & Announcements:


All course material (lecture notes “slides", assignments, any supplemental notes
or documentation), will be made available “posted” online on weekly basis, on:
CS111 & COM101 Introduction to Computer Science Google Drive Folder:
https://drive.google.com/drive/folders/1RTakuNor6594Z289NWygz1lmd-jjHHQ-
?usp=sharing

All announcements will be made available “posted” online, on:


Amr S. Ghoneim Facebook Page : https://www.facebook.com/amr.s.ghoneim/

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.

Course & Lectures are based on their counterparts in the


following:
- Harvard University's CS50; An introduction to the intellectual enterprises of
computer science and the art of programming, Harvard School of Engineering
and Applied Sciences.
- UNSW's CS1: Higher Computing, by Richard Buckland – The University of
New South Wales.
- MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++
(2011), and 6.S096 Introduction to C and C++ (2013), MIT (Massachusetts
Institute of Technology) OpenCourseWare.
13
Additional
Resources
▪ At the end of each section, there will be a
short list of additional resources.
▪ The list will include articles, YouTube videos,
online courses, books, .. etc. (in both Arabic
and English).
▪ These resources will provide more details on
some of the topics discussed during the
lectures.
Tentative Assessment Summary [ Grading Policy ]

The Assessment for this subject consists of six components with the
following weightings (grading breakdown):

1) Final Written Exam: 50%


2) Midterm Written Exam: 20%
3) Quizzes (written, practical, and/or online): 20%
4) Final Practical Exam: 10%
5) Attendance and Participation during the Labs. (Sections) are
obligatory.
6) Take-home Assignments/Sheets (about 7 to 8 Sheets): 0% to -16%
(Students will lose 2 marks for every sheet not delivered on time
or found to be copied).

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

o You can discuss ideas and methodology for the homework


(assignments / sheets) with other students in the course, but
you must write your solutions completely independently.

o We will be code-checking to assess similar submissions or


submissions that use code from other sources.

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]

Previous Course Statistics [ Averaged; Multiple


Academic Years & Different Programs ]
Grade Percentage
A+ ≈1.5%
A ≈2.5%
B+ ≈6.0%
B ≈10.0%
C+ ≈13.0%
C ≈17.0%
D+ ≈17.0%
D ≈25.0%
F ≈8.0%
23
Computational
Intelligence AI430

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

Data Structures CS214


Computer
Vision IT444
[CS–111 HELWAN UNIVERSITY]

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

CS498 & AI498

Programming Programming
Languages 2 Languages 3
CS213 CS313
Virtual Reality
IT431

Computer
Graphics 2 IT332

3D Modeling &
IT331

Programming Languages 1 CS112

Animation IT456
Computer
Graphics 1

Game
Development
IT457
Artificial Intelligence Dept.
Computer Science Dept.

Introduction to Computer Science CS111

Concepts of
Programming
Information Systems Dept.

24

Languages CS410
Mainstream Programme

Information Technology Dept.

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

Operating Programming Artificial Computer


(CS214)

Algorithms
Systems 1 Languages 2 Intelligence Graphics 1
(CS316)
(CS241) (CS213) (CS361) (IT331)

Programming Languages 1 (CS112)

Introduction to Computer Science


(CS111) 26
Academic
Agenda

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
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
▪ ASCII & UNICODE

▪ RGB, Pixels, Videos, & Audio

▪ Computer Graphics, Computer Vision, Image & Signal Processing


What is a Computer?
▪ The term computer is derived from the word compute; that
is, to calculate.
▪ A computer is .. a programmable, electronic device that
accepts data (input), performs operations on that data
(processing), and stores the data (storage) or results (output)
as needed. Thus, these are a computers basic operations.
▪ Computers follow instructions, called programs, which
determine the tasks the computer will perform.

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.

Alan Turing; Father of


theoretical computer
science and artificial
5
intelligence.
Computer Science?
- Computer science is the study of computation and information.
- Computer science is fundamentally problem-solving.
- We can think of problem-solving as the process of taking some
input (details about our problem) and generate some output (the
solution to our problem). The “black box” in the middle is
computer science.
Computer
Science
input → → output

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

Computer Human– Digital Signal &


Software
Security & Computer Image
Engineering
Cryptography Interaction Processing

Artificial
Computer Computer Intelligence &
Robotics
Graphics Vision Machine
Learning

Statistics Linear Algebra Discrete Math ..


8
Informatics?
o " .. Scientific progress increasingly depends on our ability to
harness and apply tools and techniques from the computer
and information sciences."
o " .. This application of methods from the computer and
information sciences in other fields of science is not just a
happy accident; it is also a field in its own right — one
commonly referred to as informatics."
o " .. Prefix that term with – usually – a Greek root or two and
you get terms like bioinformatics, neuro-informatics, psycho-
informatics, and ecoinformatics, all are well-established
subfields responsible for many of the most exciting recent
discoveries in their parent disciplines."
Psychoinformatics: New Horizons at the Interface of the Psychological and Computing Sciences - Tal Yarkoni - Current Directions in
Psychological Science 2012 21: 391 - DOI: 10.1177/0963721412457362 9
Informatics?
Examples:
o Psycho-informatics; "an emerging [research] discipline that uses tools and
techniques from the computer and information sciences to improve the
acquisition, organization, and synthesis of psychological data."
o Ecoinformatics (a.k.a. ecological informatics); the application of
computer/information science in Ecology and Environmental science.
o Business Informatics (BI); a discipline combining economics, business
administration, information technology, and concepts of computer science.
o Geographic Information Science (GIScience / GISc); a discipline that studies the
techniques to capture, represent, process, and analyze geographic information
(using Geographic Information Systems "GIS", which are software tools).
o Engineering Informatics; the study of use of information and the design of
information structures that facilitate the practice of engineering.
o Astroinformatics; a field of study involving the combination of astronomy, data
science, machine learning, informatics, and communications technologies.
o Disaster Informatics (a.k.a. Crisis informatics); the study of the use of
information & technology in the preparation, mitigation, response, and
10
recovery phases of disasters and other emergencies.
Informatics?
More Examples:
o Health informatics; is a field that concerns the generation, processing, storage,
and use of health-related data, information, and knowledge. There is a great
diversity in the sub-disciplines of health informatics, including:

Health Informatics
Biomedical Medical Clinical
Bioinformatics
Informatics Informatics Informatics

Nursing Pharmacy Public Health


..
Informatics Informatics Informatics

11
Exercises
What have we learned?

▪ What is a computer? And what


is Computer Science?
▪ What’s the difference between
data and information?
▪ Mention 5 computer science
disciplines (fields).
▪ Define informatics.
Up Next ..
Additional Section 1.2
Resources
▪ What is Computer Science (in Arabic):
https://ar.wikipedia.org/wiki/‫علم_الحاسوب‬

▪ Lecture 1 | MIT 6.00 Introduction to Computer


Science and Programming, Fall 2008 (in English):
https://www.youtube.com/watch?v=k6U-
i4gXkLM
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
▪ ASCII & UNICODE

▪ RGB, Pixels, Videos, & Audio

▪ Computer Graphics, Computer Vision, Image & Signal Processing


Why the Binary Representation?

We need a way to represent inputs and


outputs, such that we can store, work-with,
& display information in a standard way.

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.

When we learned to write numbers with the digits 0


through 9, we learned to use decimals (Arabic numeral
system):

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) ..

102 101 100

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.

bit bit bit bit bit bit bit bit


byte
8 bits make up one byte.

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?

▪ Define the Decimal and Binary number systems, and


the differences between them.
▪ How can we represent the following decimal values
in binary: 2, 3, 7, 8, 50, 60, 100, 127, 128, 255, 256.
Up Next ..
Additional Section 1.3
Resources
▪ What is a binary number (in Arabic):
https://ar.wikipedia.org/wiki/‫نظام_عد_ثنائي‬

▪ Why Do Computers Use 1s and 0s? Binary and Transistors


Explained (in English):
https://www.youtube.com/watch?v=Xpk67YzOn5w

▪ How exactly does binary code work? [TED-Ed]


(in English):
https://www.youtube.com/watch?v=wgbV6DLVezo
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
▪ ASCII & UNICODE

▪ RGB, Pixels, Videos, & Audio

▪ Computer Graphics, Computer Vision, Image & Signal Processing


Once more .. Why the Binary Representation?

We need a way to represent inputs and outputs,


such that we can store, work-with, & display
information in a standard way.

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?

71 111 111 100 32 68 97 121 33

49
So, if you received the following
message, what does it mean?

71 111 111 100 32 68 97 121 33

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:

Unicode currently defines 154 separate


scripts, including 91 modern scripts
and 63 ancient or historic scripts.

54
Unicode – Arabic
Unicode

When we receive an emoji, our computer is just receiving a


decimal number that it then maps to the image of the emoji.

Face with tears of joy➔

E.g., Unicode: 128514 .. 11111011000000010 in binary.

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 ➔

N.B., Computer programs know, based on the context of its


code, whether the binary numbers should be interpreted as
numbers, or letters, or pixels.

62
An RGB Example ..

63
Videos are just many, many images
displayed one after another, at some number
of frames per second.

(Move back & forth quickly between the next 2


sides .. What did you notice?)

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.

Digital Image Processing; is the


use of a digital computer to
process digital images through
algorithms.

Computer Graphics; studies


methods for digitally creating and
69
manipulating visual content.
What about Audio
(Sound)?

A microphone converts sound waves into voltage changes. If a microphone


is plugged into a sound card, then the voltage can be sampled at regular
intervals (the sample rate) and each value converted into a binary number,
and the series of binary numbers can be stored as a sound file.
Digital Signal Processing (DSP); is the use of digital processing, such as by
computer, to perform a wide variety of signal processing operations.
Exercises
What have we learned?

▪ What is the difference between ASCII code & Unicode?


▪ Convert the following ASCII numbers to text:
072 105 033 032 073 032 108 111 118 101 032 067 083 033
▪ Discuss how images are represented in a computer
system, and the relationship between videos and
images.
▪ What are the differences between computer graphics,
computer vision, and image processing?
▪ Watch the first additional resource (video), then define
what is an image resolution?
Up Next ..
Additional Lecture 2
Resources
▪ Images, Pixels and RGB (in English):
https://www.youtube.com/watch?v=15aqFQQVBWU

▪ Understanding ASCII and Unicode - GCSE (in English):


https://www.youtube.com/watch?v=5aJKKgSEUnY

▪ Representing Sound (GCSE) (in English):


https://www.youtube.com/watch?v=1ZV_TxtLd_c

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 2: Computational Thinking – Part 2
2.1 Computer Hardware
▪ Central Processing Unit & Storage

▪ Input / Output / Communication Devices

▪ Digital Design and Computer Architecture

2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )

2.3 Pseudocodes & Flow-Charts

2.4 Programming Languages


▪ What is a Programming Language?

▪ Programming Languages vs. Natural Languages


Recap: In sections 1.2 & 1.3, we presented different
ways to represent inputs & outputs, so that we can
store, work-with, & display information in a
standard way ..

What were they? .. the Binary Number System,


the ASCII Code & Unicode, the RGB System, ..
etc.

So .. How can we input & output data?


How do we store & process information?
4
Computer hardware
includes the physical
(tangible) parts or
components of a
computer, ..

RAM
ROM

.. Such as the , central processing unit, monitor, keyboard, computer


data storage, graphics card, sound card, speakers & motherboard. 5
Input Devices;
Are hardware components that gather raw data from the user for
processing. Keyboard, mouse, touchscreen, microphone, scanner,
camera, joystick, & light pen are the examples of input devices.

Output Devices; Peripheral Devices


Used to send the processed (useful) information out of the computer.
The computer monitor (display) is a common example. There are 2
main types of output components – temporary (monitors, speakers
and projectors) and permanent (printers and plotters) output devices.

Storage devices (Secondary Storage);


Used for storing all the data which is not in current usage. The hard
disk drive is the perfect example of this type of memory. You can store
large volume of data on this type of storage volumes. There are two
main types of secondary storage solutions – Internal Storage (hard
disk drives & solid-state drives “SSD”) and External Storage (external
hard disk drives and SSDs, flash memory sticks, CD-ROMs, & DVDs).
6
Communications Devices;
Allow users to communicate with others and to electronically
access information. E.g., Modems, network adapters, etc.

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.

Central Processing Unit (CPU);


As the name suggests, the CPU processes all functions within a
computer. It will have control over the functions of the various
components. It will process all the data and perform calculations.
It will also control the data transfer between the primary and
secondary memory, and between memory and itself.
It is the processor where all the basic computation takes place.
Other parts will contribute to the processing task by performing
other essential functions like storing or transferring data to and
7
from the CPU.
Main Memory (Primary Storage);
Main memory is the location where instructions and data are stored.
Memory is principally made up of RAM chips but may include one or
more ROM chips.

- Read-Only Memory (ROM);


ROM chips provide fast-access to non-volatile information. It tends to
be used to store the instructions required to load the computer
system.

- Random Access Memory (RAM);


Random Access Memory or RAM is used for temporarily storing
information which is being currently used for processing. The RAM
stores most of the currently processed data because the CPU doesn’t
have enough memory. While the processor holds only a tiny amount
of data and instructions, RAM will hold complete data sets and
programs which are in current use. It is volatile memory and the data
and instructions will be deleted when the system is switched off or
when the current program is stopped. 8
Digital Design .. & ..
Computer Architecture?

.. is a set of rules and methods that


describe the functionality, organization,
and implementation of computer systems.

9
Exercises
What have we learned?

▪ What are the Peripheral Devices? Give some examples.

▪ Write in detail about the different types of Primary


Storage (Search the internet to include more
information & details).

▪ Draw a suitable block diagram of basic organization of a


computer system and describe them in brief.

▪ What is the difference between the Control Unit “CU”


& the Arithmetic & Logic Unit “ALU”.
Up Next ..
Additional Section 2.2
Resources
▪ How Computers Work: CPU, Memory, Input, & Output:
https://www.youtube.com/watch?v=DKGZlaPlVLY

▪ Inside your computer:


https://www.youtube.com/watch?v=AkFi90lZmXA

▪ Computer Basics: Inside a Computer:


https://www.youtube.com/watch?v=HB4I2CgkcCo

▪ How computer memory works:


https://www.youtube.com/watch?v=p3q5zWCw8J4

▪ Computer System Hardware:


https://www.youtube.com/watch?v=w0vwVDjeq78
Lecture 2: Computational Thinking – Part 2
2.1 Computer Hardware
▪ Central Processing Unit & Storage

▪ Input / Output / Communication Devices

▪ Digital Design and Computer Architecture

2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )

2.3 Pseudocodes & Flow-Charts

2.4 Programming Languages


▪ What is a Programming Language?

▪ Programming Languages vs. Natural Languages


Recap:
So now we can represent inputs and outputs, and we input
data, and display the results (outputs).

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

The four essential properties of an algorithm:


1. Each step of an algorithm must be exact.
2. An algorithm must terminate.
3. An algorithm must be effective.
15
4. An algorithm must be general.
Algorithms .. their essential properties?
The four essential properties of an algorithm:
i. Exact: Precisely and unambiguously described, so that
there remains no uncertainty.
ii. Terminate: The ultimate purpose of an algorithm is to
solve a problem.
iii. Effective: Must give the correct answer.
iv. General: Must solve every instance of the problem.
E.g., a program that computes the area of a rectangle,
within the limits of the programming language and the
machine. 16
Algorithms .. Origin & More Definitions
An Algorithm is a procedure or
formula for solving a problem,
based on conducting a
sequence of specified actions.
Mostly used in Computer
Science & Mathematics, it’s a
finite sequence of well-defined
(unambiguous), computer
implementable instructions, to
solve a class of problems or to
perform a computation.

Muhammad ibn Musa al-Khwarizmi


Polymath (mathematics, astronomy, geography)
Founder of Algebra (al-jabr, i.e. “rejoining”)
17
c. 780 – c. 850
Let’s say we wanted to find a friend,
“Mike Smith”, in a phone book ..
Searching by his last name, Smith ..

What might be the step-by-step


instructions to solve this problem?

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)

"The art of creating machines that perform functions that


require intelligence when performed by people." (Kurzweil,
1990)

"The study of the computations that make it possible to


perceive, reason, and act." (Winston, 1992)

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?

Two commonly used tools to represent algorithms:

1. Pseudocode

2. Flowcharts

32
Exercises
What have we learned?

▪ Define an Algorithm.

▪ Define an Algorithm’s Complexity.

▪ What are the Essential Properties of an


algorithm?

▪ Define the concept of Artificial Intelligence


and mention some of its applications in
everyday life.
Up Next ..
Additional Section 2.3
Resources
▪ How we teach computers to understand pictures [TED talk by Fei
Fei Li on AI, Computer Vision, & Machine Learning]:
https://www.youtube.com/watch?v=40riCqvRoMs
▪ Why is 'x' the unknown? | TED talk by Terry Moore
https://www.youtube.com/watch?v=YX_OxBfsvbk
▪ What exactly is an algorithm? Algorithms explained | BBC Ideas
https://www.youtube.com/watch?v=ZnBF2GeAKbo
▪ Intro to Algorithms: Crash Course Computer Science #13
https://www.youtube.com/watch?v=rL8X2mlNHPM
▪ Why algorithms are called algorithms | BBC Ideas
https://www.youtube.com/watch?v=oRkNaF0QvnI
▪ What's an algorithm? - David J. Malan
https://www.youtube.com/watch?v=6hfOvs8pY1k
Lecture 2: Computational Thinking – Part 2
2.1 Computer Hardware
▪ Central Processing Unit & Storage

▪ Input / Output / Communication Devices

▪ Digital Design and Computer Architecture

2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )

2.3 Pseudocodes & Flow-Charts

2.4 Programming Languages


▪ What is a Programming Language?

▪ Programming Languages vs. Natural Languages


We can write pseudocode, an artificial informal syntax that is
just a more specific version of English (or other human
language) that represents our algorithm.

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:

1 Pick up phone book


2 Open to middle of phone book
3 Look at page
4 If Smith is on page
5 Call Mike
6 Else if Smith is earlier in book
7 Open to middle of left half of book
8 Go back to line 3
9 Else if Smith is later in book
10 Open to middle of right half of book
11 Go back to line 3
12 Else
13 Quit
37
Some of these lines start with verbs, or actions.
We’ll start calling these functions:

1 Pick up phone book


2 Open to middle of phone book
3 Look at page
4 If Smith is on page
5 Call Mike
6 Else if Smith is earlier in book
7 Open to middle of left half of book
8 Go back to line 3
9 Else if Smith is later in book
10 Open to middle of right half of book
11 Go back to line 3
12 Else
13 Quit
38
We also have branches that lead to different paths,
like forks in the road, which we’ll call conditions:

1 Pick up phone book


2 Open to middle of phone book
3 Look at page
4 If Smith is on page
5 Call Mike
6 Else if Smith is earlier in book
7 Open to middle of left half of book
8 Go back to line 3
9 Else if Smith is later in book
10 Open to middle of right half of book
11 Go back to line 3
12 Else
13 Quit
39
Questions that decide where we go are called
Boolean expressions, which eventually result to a
value of true or false:
1 Pick up phone book
2 Open to middle of phone book
3 Look at page
4 If Smith is on page
5 Call Mike
6 Else if Smith is earlier in book
7 Open to middle of left half of book
8 Go back to line 3
9 Else if Smith is later in book
10 Open to middle of right half of book
11 Go back to line 3
12 Else
13 Quit
40
Finally, we have words that lead to cycles, where
we can repeat parts of our program, called loops:

1 Pick up phone book


2 Open to middle of phone book
3 Look at page
4 If Smith is on page
5 Call Mike
6 Else if Smith is earlier in book
7 Open to middle of left half of book
8 Go back to line 3
9 Else if Smith is later in book
10 Open to middle of right half of book
11 Go back to line 3
12 Else
13 Quit
41
We can also draw a Flowchart; a diagram that uses standard
symbols to solve the problem (to represent our Algorithm
graphically).

Flowcharts consist basically of the following 6 symbols:

Flowcharts

1 2 3
4 5 6 42
Flowcharts
Flowcharts consist basically of the following 6 symbols:

1) Terminal (Start/End Points) Symbol; used to represent the start,


end of the algorithm's logic/steps.
2) Data (Input/Output) Symbol; used to represent data input or
output.
3) Process Symbol; indicates any processing function, thus used to
represent the calculations, data movements, initialization
operations, etc.
4) Decision (Choice) Symbol; used to denote a decision (between
2 paths) to be made at that point.
5) Flow-Direction (Flow of Control) line; used to connect the
symbols.
6) Connector (On/Off Page Reference); used to create a cross-
reference from process to another (on the same page, or on
another page). 43
The Flowchart for our Algorithm ..

44
Start

Pick up phone book

Open to middle of phone book


Open to middle of
Look at page B
left half of book
YES
NO Smith on
YES
NO earlier in Call Smith
Page?
Book?
C
A
End 45
A

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

▪ Input / Output / Communication Devices

▪ Digital Design and Computer Architecture

2.2 Algorithms
▪ What is an algorithm? .. & The four essential properties of an algorithm
▪ An Algorithms’ Complexity .. & Advancement in Algorithms ( Artificial Intelligence )

2.3 Pseudocodes & Flow-Charts

2.4 Programming Languages


▪ What is a Programming Language?

▪ Programming Languages vs. Natural Languages


Programming Languages ..?

o A Programming Language is a formal language


comprising a set of instructions that produce various
kinds of output.

o Programming languages are used in computer


programming to implement algorithms.

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?

▪ Define a Programming Language.

▪ What are the differences between Natural Languages


and Programming Languages?

▪ What’s the difference between the syntax and the


semantics?
Up Next ..
Additional Lecture 3
Resources
▪ Computer Science Basics: Programming Languages:
https://www.youtube.com/watch?v=Y_9t3eQFmU4

▪ Top 10 Programming Languages In 2020 | Best


Programming Languages To Learn In 2020:
https://www.youtube.com/watch?v=mUxS-35qO44

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 3: Computational Thinking – Part 3
3.1 Computer Software 3.2 Your First C Program
▪ Programs versus Software ▪ Why C?
▪ Software Engineering ▪ Code::Blocks IDE
▪ Types of Software ▪ MAIN Function
▪ Classification of Computer Systems ▪ Statements
▪ Generations of Computers ▪ PRINTF Function
▪ Strings
▪ Escape Sequences
▪ Preprocessor Directives
3.3 Compilation ▪ Header Files
▪ Preprocessor ▪ RETURN Statements
▪ Compiler ▪ MAIN returning a 0?
▪ Assembler ▪ Comments
▪ Linker ▪ Blank-lines / Spaces / Tabs
▪ Types of Errors
▪ Critical & Real-time Systems
If you would like to print (display) on the console
window the phrase “Hello, World!” .. This is how your
C language program should look like:

#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 ..

.. Thus, in software development there is more than just writing


code (programming) .. for example:
o Software Engineering; a branch of computer science which
includes the development and building of computer systems
software and applications software.
o Human-Computer Interaction “HCI”; studies the design and use
of computer technology, focused on the interfaces between
people (users) and computers (or Robots, thus Human-Robot
Interaction “HRI”).

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

Also known as Software Library; A collection of


standard programs, subroutines, or packages
that are stored and made available for
immediate common use within some
environment. A basic example would be
packages for mathematical operations.

11
Types of
Software

Also known as Custom or Tailored


Software; A software application
developed for a specific user (specifically
to their custom requirements) and is
particularly used when there is no ‘off-
the-shelf’ alternative available.

12
Types of Software ..

The Software also varies based on the type/category of


the computer.
The Six basic categories of computers are:
1) Embedded Computers.
2) Mobile Devices.
3) Personal Computers (Microcomputers).
4) Midrange Servers (Minicomputers).
5) Mainframe Computers (High-end Servers).
6) Supercomputers (Supercomputing Cluster).
13
Types of Software ..
Classification of Computer Systems ..
1) Embedded Computers; Often embedded into household appliances
(washing machines, stove, ), Cars, .. etc. Designed to perform specific
tasks or functions for that product. For example, the most
used embedded systems in a vehicle (car) are adaptive cruise control,
airbag, in-vehicle entertainment system, emission control system,
parking system, navigation systems, collision sensors, climate
control, radio, anti-lock braking system, .. etc.
2) Mobile Devices; Very small device with some type of built-in
computing or Internet capability. E.g., Smart phones, Smart watches,
Portable digital media players, .. etc.
3) Personal Computers; Computer systems designed to be used by one
person at a time, also called a microcomputer. E.g., Desktop PCs,
Portable PCs (notebook/laptop, or Tablets).
4) Midrange Servers; A medium-sized computer used to host programs
and data for a small network, also called a minicomputer. Users
connect via a network with a Desktop PC, Portable PC, or a Dumb
14
Terminal consisting of just a monitor and keyboard.
Types of Software ..
Classification of Computer Systems ..

IBM's Blue Gene/P massively 5) Mainframe Computers;


parallel supercomputer. Larger, more expensive, and more powerful than
Parallel Computation/computing midrange servers. Used by several large
is a type of computation where organizations (e.g., hospitals, universities, large
many calculations or the businesses, banks, government offices) to manage
execution of processes are carried large amounts of centralized data. Located in
out simultaneously. climate-controlled data centers & connected to the
rest of the company computers via a network, &
usually operate 24 hours a day.
6) Super Computers;
Fastest, most expensive, most powerful type of
computers. Commonly built by connecting hundreds
of smaller computers (a supercomputing cluster).
Used for space exploration, satellites, weather
15
forecast, oil exploration, scientific research, etc.
What drove (is currently driving) the
development of computers?

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)

4th Generation 1971–2012: Microprocessor


Miniaturization took over; From SSI (10-100
components / chip), MSI (100-1000), LSI (1,000-
10,000), VLSI (10,000+) 17
5th Generation (Present & Beyond) ?!

It’s not characterized by hardware advancements ..

Artificial Intelligence!

18
Exercises
What have we learned?

▪ What is a program? What is programming?


▪ What are the differences between code and software?
▪ What are the different types of software?
▪ What are the different categories of computers?
▪ Give an example of an embedded system.
▪ Discuss the 5 computer generations along with the key
characteristic of the computer in each generation (Search the
internet to include more information & details).
Up Next ..
Additional Section 3.2
Resources
▪ How transistors work:
https://www.youtube.com/watch?v=WhNyURBiJcU

▪ How Computers Work: Hardware and Software:


https://www.youtube.com/watch?v=xnyFYiK2rSY

▪ Computer Science Basics: Hardware and Software


https://www.youtube.com/watch?v=vG_qmtdBPTU

▪ Inside a Google data center


https://www.youtube.com/watch?v=XZmGGAbHqa0

▪ Software Development Lifecycle in 9 minutes!


https://www.youtube.com/watch?v=i-QyW8D3ei0
Lecture 3: Computational Thinking – Part 3
3.1 Computer Software 3.2 Your First C Program
▪ Programs versus Software ▪ Why C?
▪ Software Engineering ▪ Code::Blocks IDE
▪ Types of Software ▪ MAIN Function
▪ Classification of Computer Systems ▪ Statements
▪ Generations of Computers ▪ PRINTF Function
▪ Strings
▪ Escape Sequences
▪ Preprocessor Directives
3.3 Compilation ▪ Header Files
▪ Preprocessor ▪ RETURN Statements
▪ Compiler ▪ MAIN returning a 0?
▪ Assembler ▪ Comments
▪ Linker ▪ Blank-lines / Spaces / Tabs
▪ Types of Errors
▪ Critical & Real-time Systems
Your First
C Program ..

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!

Let us print on screen .. “Hello, World!”

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).

How to setup Code::Blocks ..


1) Go to http://www.codeblocks.org/downloads
2) Download the binary release (select a setup package
depending on your platform - most likely the file:
codeblocks-17.12mingw-setup.exe).
3) Choose: Code Blocks Windows Installer (GNU C/C++
Compiler and Debugger).
4) Download and Setup.

Now let us run your first program .. 28


The MAIN Function
o main is the function name.
o int: means that the main function returns an integer value.
#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 (void): means that the main function doesn’t receive any
information.
o The "Function Body" is written between the left brace { and
the right brace }. 29
The MAIN Function

#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 Any C program should contain at least the MAIN function.


o Any C program begins executing at the MAIN function.
30
A Statement
o An instruction = A 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 It instructs the computer to perform an action.


o Every statement must end in a semi-colon ";".
31
The PRINTF Function
o The PRINTF function prints on the screen the string of
characters between the double quotations (“ ”).
#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 The f in PRINTF stands for “formatted”.


o The message is displayed as formatted between the “ ”,
except for the \n which is an escape sequence.
32
A String

#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 */

o The value 0 (which in an integer) indicates that the


program has terminated successfully.

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 */

o Only use them to improve a program’s readability.


o We can write more than an instruction in the same line
but doing that will affect the readability.
41
Blank-lines, Spaces, Tabs, .. etc.

#include <stdio.h>
int main(void){printf("Hello, World!\n");return 0;}

o We can write more than an instruction in the same line


but doing that will affect the readability.
42
This program is written in C, which is
a High-Level Language ..

#include <stdio.h>
int main(void) // Program execution begins here
{
printf( "Hello, World!\n" );
return 0; // program ended successfully
} /* The main function
ends here */

How is it translated into Machine Code?


43
Exercises
What have we learned?

▪ Define Escape Sequences (give 2 examples).

▪ Define Preprocessor Directives (give an example).

▪ What is the stdio.h header file?

▪ What is a C String?

▪ Describe the following functions: main, & printf.

▪ Describe the following keywords: include, int, & return.

▪ How are comments written in a C program.

▪ What’s an escape sequence? What’s an escape character?


Up Next ..
Additional Section 3.3
Resources
▪ "C" Programming Language: Brian Kernighan:
https://www.youtube.com/watch?v=de2Hsvxaf8M

▪ C Programming Language - Intro to Computer Science -


Harvard's CS50 (2018) [~2 Hours]:
https://www.youtube.com/watch?v=ix5jPkxsr7M

▪ C Programming Tutorial for Beginners [~4 Hours]:


https://www.youtube.com/watch?v=KJgsSFOSQv0

▪ Types of Programming Languages:


https://www.youtube.com/watch?v=aYjGXzktatA
Lecture 3: Computational Thinking – Part 3
3.1 Computer Software 3.2 Your First C Program
▪ Programs versus Software ▪ Why C?
▪ Software Engineering ▪ Code::Blocks IDE
▪ Types of Software ▪ MAIN Function
▪ Classification of Computer Systems ▪ Statements
▪ Generations of Computers ▪ PRINTF Function
▪ Strings
▪ Escape Sequences
▪ Preprocessor Directives
3.3 Compilation ▪ Header Files
▪ Preprocessor ▪ RETURN Statements
▪ Compiler ▪ MAIN returning a 0?
▪ Assembler ▪ Comments
▪ Linker ▪ Blank-lines / Spaces / Tabs
▪ Types of Errors
▪ Critical & Real-time Systems
How is a program executed?
How is it translated (compiled)
into binary Machine Code?

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.

Source Code → Compiler → Machine Code


hello.c hello.exe

49
Any computer can directly understand only its own machine
language (machine code); consists only of binary digits (0’s and 1’s).

01111111 01000101 01001100 01000110 00000010 00000001 00000001 00000000


00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000010 00000000 00111110 00000000 00000001 00000000 00000000 00000000
10110000 00000101 01000000 00000000 00000000 00000000 00000000 00000000
01000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
11010000 00010011 00000000 00000000 00000000 00000000 00000000 00000000
00000000 00000000 00000000 00000000 01000000 00000000 00111000 00000000
00001001 00000000 01000000 00000000 00100100 00000000 00100001 00000000
00000110 00000000 00000000 00000000 00000101 00000000 00000000 00000000
01000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
01000000 00000000 01000000 00000000 00000000 00000000 00000000 00000000
01000000 00000000 01000000 00000000 00000000 00000000 00000000 00000000
11111000 00000001 00000000 00000000 00000000 00000000 00000000 00000000
11111000 00000001 00000000 00000000 00000000 00000000 00000000 00000000
00001000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
00000011 00000000 00000000 00000000 00000100 00000000 00000000 00000000
00111000 00000010 00000000 00000000 00000000 00000000 00000000 00000000
... 50
“Compiling” source code into
machine code is made up of
smaller steps:

a) preprocessing
b) compiling
c) assembling
d) linking

52
“Compiling” source code into machine code is made up of smaller
steps:

preprocessing Preprocessing involves looking at lines


that start with a #, like #include, before
compiling everything else. For example, #include
<stdio.h> will look for that header file
assembling first, since it contains content that we
want to include in our program. Then,
linking
it will essentially replace the contents
of those header files into our program.

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.

GUIDANCE SYSTEM FAILURE EXPLANATIONS:


➢ The New York Times, reporting on the results of a review board, said that the error
stemmed from “the omission of a hyphen in some mathematical data”.
67
➢ In other accounts, the bug consisted of a period typed in place of a comma,
causing a FORTRAN DO loop statement to be misinterpreted, of the form
67
“DO 5 K = 1,3” (an iterative loop) interpreted as “DO 5 K = 1.3” (an assignment).
Why designing & optimizing software is important?
Critical Systems .. ?

Critical Systems are software systems where failure may have


catastrophic consequences, such as:

o Loss of life (safety-critical systems), and ..

o Loss of business (business-critical systems).

It is vital that such systems be as error-free as possible.

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.

▪ Draw a diagram that explains the basic steps for


compiling a program.

▪ Describe in your own words the steps required for


“Compiling” a source code into machine code.

▪ Describe in your own words Critical Systems & Real-time


Systems.
Up Next ..
Additional Lecture 4
Resources
▪ Introduction to Real-Time Software Systems
https://www.youtube.com/watch?v=_U6Le3_eL2I

▪ Short Lesson - Compilation vs Interpretation:


https://www.youtube.com/watch?v=JNMy969SjyU

▪ Compiling, assembling, and linking:


https://www.youtube.com/watch?v=N2y6csonII4

▪ COMPILER| INTERPRETER |Difference between Interpreter


and Compiler| Interpreter vs Compiler Animated:
https://www.youtube.com/watch?v=e4ax90XmUBc
Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 4: Variables, Constants, & Data Types in C
4.1 Variables & Data-Types (Part A)
▪ Solved Example: Convert Feet to Centimetres
▪ Prompt Messages
▪ Identifiers in C
▪ Data Types in C & their sizes

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

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:

Step 1: Input length in feet Lft


Step 2: Length in centimeters Lcm Lft × 30.48
Step 3: Print Lcm
4
Example 4.1: Convert Feet to Centimetres
Flowchart: Start

Input the length


in feet Lft

Lcm ← Lft × 30.48

Output Lcm; the


length in centi..

End 5
Example 4.1: Convert Feet to Centimetres
So, .. your program should behave like this:

Have you noticed the prompt messages? .. A prompt refers


to a message or window that appears, alerting the user or
asking for a(n) information / confirmation.

A very common e.g.:


6
Are you sure you want to continue? (Yes/No)
#include <stdio.h>
// The main function, execution starts here
int main()
{ Solved Example 4.1:
// Variables Declarations Convert Feet to Centimetres
float length_cm, length_ft;
// Prompt messages
printf("Hello!\n");
printf("This program converts a length in feet into centimetres\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
7
}
Memory
#include <stdio.h>
// The main function, execution starts here length_ft
int main()
{ length_cm
// Variables Declarations
float length_cm, length_ft;
A Variable name: a place in the memory
// Prompt messages where you store a value of a certain type.
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
8
}
#include <stdio.h>
// The main function, execution starts here
int main() Variable Declarations are definitions for
{ variables; variables MUST be declared
// Variables Declarations before using them.
float length_cm, length_ft; Declaring a variable means specifying
// Prompt messages both its identifier (e.g., length_cm) and
printf("Hello!\n"); its data type (e.g., float).
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
9
}
Identifiers in C ..

Rules for identifiers:


o Consist only of: A–Z, a–z, 0–9, & underscore ‘_’.
o Are case sensitive .. Thus, a1 ≠ A1.
o Must NOT be a keyword.
o Do NOT start with a Number.

Good Practices (Recommendations):


o Meaningful identifiers (E.g., sideLength, name).
o Should be ≤ 31 characters
o For single syllables, use small letters.
o For multiple syllables, use ‘_’ or begin each
syllable with a capital letter (E.g., total_cost,
TotalCost, number_of_students, numberOfStudents).
10
Identifiers in C .. Examples:
VALID:
age_of_person
PrintHeading
taxRateY2K
ageOfHorse

NOT VALID .. Why?


age#
2008TaxRate
Age-Of-Cat
11
Data Types in C/C++ ..
bool - a Boolean expression of either true or
false

char - a single character like ‘a’, ‘?’, or ‘2’

float - a real number with a decimal value/point

double - a floating-point value with even more


digits

int - integers up to a certain size, or number


of bits, & their negatives

long - integers with more bits, so they can


count higher

string - a(n) string/array of characters


12
..
Data Types in C/C++ .. their Sizes:

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.

We might save a program or file to our hard drive (or SSD)


for long-term storage, but when we open it, it gets copied
to RAM first. Though RAM is much smaller, and temporary
(until the power is turned off), it is much faster.

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 ..

An integer, with 4 bytes, will take up four of those boxes.

int score1 = 72;


int score2 = 73;
int score3 = 33;

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 ..

Example of int values:


4578 -4578 0 4

Example of float values:


95.274 95.0 0.265 -95.0 0.0

Example of char values:


‘B’ ‘d’ ‘4’ ‘?’ ‘*’

31
Exercises
What have we learned?

▪ Define Prompt Messages.


▪ Explain in detail how variables are declared in C.
▪ What are the rules for identifiers in C?
▪ List some of the available data types in C, and their
corresponding sizes.
Up Next ..
Additional Section 4.2
Resources
▪ C Language: Comments:
https://www.techonthenet.com/c_language/comments.php

▪ C Language: #include Directive:


https://www.techonthenet.com/c_language/directives/include.php

▪ C Language: Integer Variables:


https://www.techonthenet.com/c_language/variables/create_int.php

▪ C Language: Float Variables:


https://www.techonthenet.com/c_language/variables/create_float.php
Lecture 4: Variables, Constants, & Data Types in C
4.1 Variables & Data-Types (Part A)
▪ Solved Example: Convert Feet to Centimetres
▪ Prompt Messages
▪ Identifiers in C
▪ Data Types in C & their sizes

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

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 ..

The assignment statement:

length_cm = length_ft * 30.48;


2 1
Assign result to left side Evaluate right side
Assignment Memory
Operator
length_ft 2.0

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.

An example of a unary operator is the Address (or Address-


Of) Operator (&) which returns the memory address of a
43
variable (its operand), e.g., &y.
#include <stdio.h>
// The main function, execution starts here
int main() The printf function with a Format Control
{ String; %f is a Conversion Specifier; it
// Variables Declarations depends on the variable type.
float length_cm, length_ft;
// Prompt messages %f : Print the float value here ..
length_cm: The value to be printed ..
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
44
}
The printf with a Format Control String ..

You can make calculations in the printf


statement. So, for example, instead of ..

o length_cm = length_ft * 30.48; // Coverts feet to centimetres


o printf("The length in centimeters is %f \n", length_cm);

You can do the following:

o printf("The length in centimeters is %f \n", length_ft * 30.48);

What is the difference (in terms of the


variables in the memory)?
45
.. the difference (in terms of the variables in the
memory):
Memory

#include <stdio.h> length_ft 2.0


// The main function, execution starts here
int main() length_cm 60.96
{
// Variables Declarations The program can be written
float length_ft; without the length_cm variable.
// 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
// Converts feet to centimetres & Displays the length in centimetres
printf("The equivalent length in centimeters is %f \n", length_ft * 30.48;);
printf("Thank you!\n");
return 0; // Program ended successfully
46
}
Converting Length in Feet to Centimetres
Thus, .. your program should behave like this:

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

▪ C Input Output (I/O); scanf() and printf() functions:


https://www.programiz.com/c-programming/c-input-output
Lecture 4: Variables, Constants, & Data Types in C
4.1 Variables & Data-Types (Part A)
▪ Solved Example: Convert Feet to Centimetres
▪ Prompt Messages
▪ Identifiers in C
▪ Data Types in C & their sizes

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

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?

▪ What is a Constant Variable?


▪ What is a Symbolic Constant?
▪ What are the differences between Constant Variables &
Symbolic Constants?
▪ Rewrite the Example 4.1 (Converting Feet to Centimetres)
while defining the value 30.48 as:
1) a Constant Variable.
2) a Symbolic Constant.
Up Next ..
Additional Lecture 5
Resources

▪ C Language: #define Directive (macro definition):


https://www.techonthenet.com/c_language/constants/create_define.php

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
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’ Precedence
▪ Short-Circuit Evaluation

5.3 Bitwise Operators & Expressions


▪ bitwise AND, bitwise inclusive OR, bitwise exclusive OR, left shift, right shift, & the one's
complement
Recap
#include <stdio.h>
// The main function, execution starts here
int main()
{ Example 4.1:
// Variables Declarations Convert Feet to Centimetres
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
4
}
Recap
The Assignment Statement ..

The assignment statement:

length_cm = length_ft * 30.48;


2 1
Assign result to left side Evaluate right side
Assignment Memory
Operator
length_ft 2.0

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.

An example of a unary operator is the Address (or Address-


Of) Operator (&) which returns the memory address of a
6
variable (its operand), e.g., &y.
Operators in C / C++

7
Assignment Operator ..

o Assignment operators are used when assigning a


value to a variable.

o The left-side operand of the assignment operator is a


variable, and ..

o The right-side operand of the assignment operator is


a value.

o The value on the right side must be of the same data-


type of the variable on the left side otherwise the
compiler will (most likely) raise an error.

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

Note: the assignment statement overwrites old values with


new ones (destructive behavior).
Compound Assignment Operators ..

C provides several assignment operators for


abbreviating assignment expressions.

For example, the statement:


c = c + 3;
can be written as:
c += 3;
addition assignment operator

Note: The value of the variable is overwritten by the new


one.

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;

o Postincrement operator: c++;


o Postdecrement operator: c--;
o Preincrement operator: ++c;
o Predecrement operator: --c;
12
Increment / Decrement Operators ..
An Example ..
int c; /* defines the variable */

/* 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 */

/* demonstrates pre & post decrements */


x = 22; /* assigns 22 to x */
printf( "%d\n", --x ); /* prints 21 */
printf( "%d\n", x-- ); /* prints 21, then decrements */
printf( "%d\n", x ); /* prints 20 */

14
Exercises
What have we learned?

▪ Write a C program that reads 2 numbers; the


dividend and the divisor, and then calculates
the quotient, and the remainder.

▪ Write a C program that calculates the sum and


average of two decimal numbers.

▪ Write a C program that calculates the sum and


average of two integer numbers.
Up Next ..
Additional Section 5.2
Resources
▪ Assignment Operators in C/C++:
https://www.geeksforgeeks.org/assignment-operators-in-c-c/

▪ 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

5.2 Equality, Relational, & Logical Operators


▪ Equality Operators & Expressions
▪ Relational Operators & Expressions
▪ Logical Operators & Expressions
▪ Operators’ Precedence
▪ Short-Circuit Evaluation

5.3 Bitwise Operators & Expressions


▪ bitwise AND, bitwise inclusive OR, bitwise exclusive OR, left shift, right shift, & the one's
complement
Control Structures ..
Control
Structures

Selection Repetition
Sequence
(Decisions) (Loops)
Step-by-Step Choose a path Repeat a sequence
sequentially in from multiple of statements ..
order .. options ..
Conditions ..

To use both selection & repetition controls, we should have a


“condition” or a “logical expression”.
To write down such a condition, we need the following:
o Relational Operators,
.. they all evaluate to
o Equality Operators, .. and/or ..
True / False
o Logical Operators.

Note: In the C language,


o false is only the zero (0) value, .. but .. 19

o true is any nonzero value.


19
Equality, Relational, & Logical Operators ..

o They are used in Conditions (Decisions / Selection).

o They are also used in Repetitions (Loops / Iterations).

o They have Yes / No answers, i.e., either true or false.

o The Logical Operators specifically are used to form more

complex conditions by combining simple conditions.


Equality, Relational, & Logical Operators ..
C Equality or Relational Operators Meaning/Semantics
Algebraic Equality Operators
== x is equal to y?
!= x is not equal to y?
Relational Operators
> x is greater than y?
< x is less than y?
>= x is greater than or equal to y?
<= x is less than or equal to y?
Logical Operators (e.g., assuming that p and q are two simple conditions.)
&& Logical AND (p && q is true if both p and q are
true, & it's false otherwise).
|| Logical OR (p || q is true if either p or q or both
are true, otherwise it's false).
! Logical NOT "negation" (!p is false if p is true,
and !p is true if p is false).
Equality, Relational, & Logical Operators ..
Examples ..
Assume the following code fragment:
int x, y;
x = 4;
y = 6;
Logical Expression:
o x<y True
o x+2<y False
o x != y True
o x + 3 >= y True
o y == x False
o y == x + 2 True
Equality, Relational, & Logical Operators ..
Examples ..

o Logical ANDs and ORs need two conditions:

Condition 1 Condition 2 Condition 1 && Condition 1 ||


Condition 2 Condition 2
False False False False
False True False True
True False False True
True True True True

o Logical negation requires only one condition:


Condition !Condition
True False
False True
Precedence of Operators ..

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?

int age, height;


age = 25;
height = 70;

EXPRESSION VALUE___

!(age < 10) ?

!(height > 60) ?


What’s the value of the following expression?
.. Short-Circuit Evaluation Example 1 ..

int age, height;


age = 25;
height = 70;

EXPRESSION

(age > 50) && (height > 60)


False
Evaluation can stop now because the result of the &&
operator is only true when both sides are true. Thus, it is
already determined that the entire expression will be false.
What’s the value of the following expression?
.. Short-Circuit Evaluation Example 2 ..

int age, height;


age = 25;
height = 70;

EXPRESSION

(height > 60) || (age > 40)


True
Evaluation can stop now because result of the || operator
is true if one side is true. Therefore, it is already determined
that the entire expression will be true.
What’s the value of the following expression?
.. Short-Circuit Evaluation Example 3 ..

int age, weight;


age = 25;
weight = 65;

EXPRESSION

(weight < 80) && (age >= 20)


True
Must still be evaluated because truth value of entire
expression is not yet known. Why? Result of the && operator
is only true if both sides are true.
Write the C conditions for the following
English Statements ..
• A is between 0 and 5
(A > 0) && (A< 5)

• Temperature is less than or equal to 25 or humidity is less than 70%


(temperature <= 25) || (humidity < .70)

• Age is over 21 and less than 60


(age > 21) && (age < 60)

• Age is 21 or 22
(age == 21) || (age == 22)

• x and y are greater than 60


(x >60) && (y > 60)
Exercises
What have we learned?

▪ For the following arithmetic expressions, sort its


arithmetic operations.
a. A * B + A * ( B * D + C * E )
b. A – B + ( D + C / ( H * K ) )
c. A * [ B + C * ( D + E ) ] / F * ( G + H )
Up Next ..
Additional Section 5.3
Resources
▪ Relational and Logical Operators in C:
https://www.tutorialspoint.com/relational-and-logical-operators-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

5.2 Equality, Relational, & Logical Operators


▪ Equality Operators & Expressions
▪ Relational Operators & Expressions
▪ Logical Operators & Expressions
▪ Operators’ Precedence
▪ Short-Circuit Evaluation

5.3 Bitwise Operators & Expressions


▪ bitwise AND, bitwise inclusive OR, bitwise exclusive OR, left shift, right shift, & the one's
complement
Bitwise Operators

▪ Sometimes it becomes mandatory to consider data at the bit level.


We must operate on an individual data bit. We might need to turn
on/off a particular data bit during source code drafting.
▪ In such situations, we must use bitwise operators to manipulate
the bits easily (examples: cryptography, computer graphics, hash
functions, compression algorithms, network protocols, etc.).
▪ The C Programming Language provides us with different bitwise
operators to manipulate the bits.
▪ Bitwise operators operates on integer and character variables, but
NOT on float or double variables.
Bitwise Operators
C Programming Language supports
6 bitwise operators:
Bitwise Operators .. An Example
What is the Output of the following program:
// C Program to demonstrate use of bitwise operators
#include <stdio.h>
int main()
{
unsigned short int a = 5, b = 9;
// a = 5 (0000000000000101), b = 9 (0000000000001001)
printf("a = %d, b = %d\n", a, b);
printf("a & b = %d\n", a & b); // The result is 0000000000000001
printf("a | b = %d\n", a | b); // The result is 0000000000001101
printf("a ^ b = %d\n", a ^ b); // The result is 0000000000001100
printf("~a = %d\n", a = ~a); // The result is 1111111111111010
printf("b << 1 = %d\n", b << 1); // The result is 0000000000010010
printf("b >> 1 = %d\n", b >> 1); // The result is 0000000000000100
return 0;
}
Bitwise Operators .. An Example
What is the Output of the following program:
Exercises
What have we learned?

▪ Write a C program that uses Bitwise Operators (Shifting


Left / Right) to perform Multiplications / Divisions by
the powers of 2 (i.e., for example, multiply x by 21 or
divide x by 23).
Up Next ..
Additional Lecture 6
Resources
▪ C – Bit wise Operators:
https://fresh2refresh.com/c-programming/c-operators-
expressions/c-bit-wise-operators/

▪ Bitwise Operators in C/C++:


https://www.geeksforgeeks.org/bitwise-operators-in-c-cpp/

▪ 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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
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

6.2 Double-Selection Statements (If .. Else) & the Conditional Operator


▪ Double-Selection Statements: the If .. Else Statements
▪ Compound Statement (Block)
▪ The Conditional Operator ( ? : )

6.3 Multiple Selection Statements (Nested if & Switch Case)


▪ Multiple Selection Statements
▪ A Multiple Cases Example: the Nested if Statements
▪ Multiple Cases Statements: the Switch–Case Statements
Control Structures ..

Control
Structures

Selection Repetition
Sequence
(Decisions) (Loops)

Step-by-Step Choose a path Repeat a sequence


sequentially in from multiple of statements ..
order .. options ..
Example 6.1: Calculate the Power of two
numbers ..
Write a program that calculates the power of two numbers,
x and y. The program should prompt the user through a
message to input 2 numbers, then display “x to the power
of y”.

Pseudocode:

Step 1: Input 2 numbers x and y


Step 2: Power xy
Step 3: Print Power
5
Example 6.1: Calculate the Power of two
numbers .. Start
Flowchart:
Input two
numbers x and Y

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)

Step-by-Step Choose a path Repeat a sequence


sequentially in from multiple of statements ..
order .. options ..
Selection (Decisions / Branching) ..

IF Condition THEN Statement(s) ELSE Statement(s)

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:

Step 1: Input Grade


Step 2: If Grade >= 60
Step 3: Print “Passed”
13
Example 6.2: Determine Passed Students
Flowchart:

Start

Read Grade

Print Grade
“Passed” Yes >= 60
No
End

14
Example 6.2: Determine Passed Students

So, .. your program should behave like this:

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

6.2 Double-Selection Statements (If .. Else) & the Conditional Operator


▪ Double-Selection Statements: the If .. Else Statements
▪ Compound Statement (Block)
▪ The Conditional Operator ( ? : )

6.3 Multiple Selection Statements (Nested if & Switch Case)


▪ Multiple Selection Statements
▪ A Multiple Cases Example: the Nested if Statements
▪ Multiple Cases Statements: the Switch–Case Statements
Types of Selection Statements ..
Double-Selection Statements ..
if .. else statement (in the following Syntax):
if (condition)
Indentation; (the space before
Statement(s)_A; statements A and B) is a good
else programming practice.
Statement(s)_B;
true false
condition

Note: if .. else are keywords; written in small letters .. 19


Example 6.3: Determine Final Grade
Write a program to determine a student’s final grade, and
then indicate whether he/she is passing or failing. The final
grade is calculated as the average of four marks. The
program should prompt the user through a message to input
the marks, then displays “Pass” if that average was greater
than or equal to 50, and “Fail” otherwise.

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

So, .. your program should behave like this:

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

If the if’s/else's body has more than


one statement, curly braces should
enclose them. 24
Conditional Operator ( ? : )
.. .. ..
if ( grade >= 60)
{ printf( "Passed\n");}
// end if
else {
printf( "Failed\n" );
}// end else

≡ grade >= 60 ? printf("Passed") : printf("Failed ");


Condition Executed if true Executed if false

≡ printf( "%s\n", grade >= 60 ? "Passed" : "Failed");


Condition if true if false
25
Exercises
What have we learned?

▪ What is the output of the following program fragment?


length = 25;
width = 60;
if (length == 50)
height = 4;
else
height = 8;
printf ("%d %d %d", length, width, height);
Up Next ..
Additional Section 6.3
Resources
▪ C - if...else statement:
https://www.tutorialspoint.com/cprogramming/if_else_state
ment_in_c.htm
▪ Conditional or Ternary Operator (?:) in C/C++:
https://www.geeksforgeeks.org/conditional-or-ternary-
operator-in-c-c/
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

6.2 Double-Selection Statements (If .. Else) & the Conditional Operator


▪ Double-Selection Statements: the If .. Else Statements
▪ Compound Statement (Block)
▪ The Conditional Operator ( ? : )

6.3 Multiple Selection Statements (Nested if & Switch Case)


▪ Multiple Selection Statements
▪ A Multiple Cases Example: the Nested if Statements
▪ Multiple Cases Statements: the Switch–Case Statements
Example 6.4: A Multiple Cases Example
Nested if Statements ..
It tests for multiple cases by placing if .. else statement inside
other if .. else statements [called Nested if statements]:
Example:
Read a student’s grade from the user, & write the following:
A, for exam grades greater than or equal to 85,
B, for exam grades greater than or equal to 75,
C, for exam grades greater than or equal to 65,
D, for exam grades greater than or equal to 50,
F, for all other grades.
Example 6.4: A Multiple Cases Example
Nested if Statements ..
Start Flowchart
Read Grade

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 ..

o Nested if .. else can be very hard to follow, and


sometimes may be confusing.

o Therefore, a switch .. case statement is used for


multiple selection.

Note: only used with integer and character constants ..


Multiple Cases Statements ..
Switch – Case Statements ..
switch (controlling expression)
{
case value1:
If break; is forgotten ..
statements 1;
break; The first matching case
case value2: that is true + all of the
statements 2; consecutive cases will
break; be executed.
...
Don’t forget the
case valueN:
statements N; break!
break;
default:
statements;
}
Multiple Cases Statements ..
Switch – Case Statements ..
Example 6.5: A Basic Menu
An example on Switch–Case Statements ..
Your program should read two integer numbers from the
user, then display a menu to the user with 2 options:
- If (s)he typed 1 the two integers will be added and their
sum will be displayed, and ..
- If (s)he typed 2 the two integers will be subtracted and the
result will also be displayed.
- If (s)he typed any other value, a message should be
displayed indicating that this is an illegal option.
Example 6.5: A Basic Menu
An example on Switch–Case Statements ..
You should first:
- Read the 2 Numbers num1 & num2. Flowchart
- Display the Menu Options.
- Read the Menu Option menuNo.

Yes menuNo No
== 1
result =
num1 + num2 Yes No
menuNo
== 2
result =
break; num1 - num2 display
illegal choice
break;

- Display the result.


Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
default:
printf ("illegal choice");
} /* end switch */
printf ("The result is %d", result);
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2;
break;
case 2:
result = num1 - num2;
break;
Is the program’s logic
default:
correct? What is wrong
printf ("illegal choice");
with this printf statement?
} /* end switch */
printf ("The result is %d", result);
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2;
printf ("The result is %d", result); break;
case 2:
result = num1 - num2;
printf ("The result is %d", result); break;
default:
printf ("illegal choice"); a Solution ..
} /* end switch */
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2; break;
case 2:
result = num1 - num2; break;
default:
printf ("illegal choice"); another Solution ..
} /* end switch */
if (( menuNo == 1) || (menuNo == 2))
printf ("The result is %d", result);
Example 6.5: A Basic Menu
int num1, num2, menuNo, result;
printf ("Enter 2 integer numbers"); scanf ("%d %d", &num1, &num2);
printf ("Choose an operation (1 to ADD or 2 to SUBTRACT)");
scanf ("%d", &menuNo);
switch ( menuNo ) {
case 1:
result = num1 + num2; break;
case 2:
result = num1 - num2; break;
} /* end switch */
( menuNo == 1 || menuNo == 2) ? printf ("The result is %d", result) :
printf ("illegal choice");

a third Solution ..
Exercises
What have we learned?

▪ Write down an algorithm using pseudocode, represent


it graphically using a flowchart, and finally write the
corresponding C program that calculates the net salary
for an employee in a company, given that:
1) If the salary is greater than 3000$, tax is 10%.
2) If the salary is greater than 5000$, tax is 15%.
3) If the salary is less than 3000$, tax is 5%.
4) If the salary is between 1000$ and 1500$,
additional 200$ are added.
Up Next ..
Additional Lecture 7
Resources
▪ C – If..else, Nested If..else and else..if Statement with example:
https://beginnersbook.com/2014/01/c-if-else-statement-example/

▪ 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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
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

7.2 Notes & Examples on Counter–Controlled Loops

7.3 Sentinel–Controlled Loops & Break/Continue Statements


▪ Break Statement
▪ Continue Statement
▪ Sentinel–Controlled Repetitions
Control Structures ..
Control
Structures

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)

WHILE Condition Statement(s)

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?

▪ Write a C program that reads 20 students’ grades


and write “passed” if a grade is greater than or equal
60 (using the for, while, and do-while statements).

▪ Write a C program that sums the Even Values from 2


to 100 using a for Statement.

▪ A class of 10 students toke a quiz. Write a C program


(using a while loop) that reads their grades (ranges
from 0 to 100), & then determines the class average.
Up Next ..
Additional Section 7.2
Resources
▪ Loops in C (while, do-while, for)
https://www.youtube.com/watch?v=1vGfkBwIOXw

▪ While Loops - Intro to Computer Science


https://www.youtube.com/watch?v=lr7FO3rr8jg

▪ for and while Loops


https://www.youtube.com/watch?v=qUPXsPtWGoY
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

7.2 Notes & Examples on Counter–Controlled Loops

7.3 Sentinel–Controlled Loops & Break / Continue Statements


▪ Break Statement
▪ Continue Statement
▪ Sentinel–Controlled Repetitions
for Statement .. an Example

Reads 20 students’ grades and write “passed” if a grade is greater


than or equal 60.
int grade;
int counter; // control variable
for ( counter = 1 ; counter <= 20 ; counter++ )
{
printf(“Enter the grade of student No. %d”, counter);
scanf(“%d”, &grade);
if ( grade >= 60 )
{
printf( "Passed\n" );
} // end if
}
while Statement .. an Example

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 );

N.B., the do.. while body is executed at least once.


Notes about the Expressions ..
Off-by-One Error:
If you wrote counter < 10 instead counter <= 10, then the loop will be
executed only 9 times.

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)

Increment may be negative➔ decrement

If the loop-continuation is initially false:


➔ loop body will not be executed.
➔ but, a do .. while’s body is executed at least once.
18
Notes about the Expressions ..
An increment expression is exactly similar to a standalone statement:
• counter = counter + 1;
• counter += 1;
• ++count;

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 ..

Expressions in a for statement’s header are optional:


You can omit:
Expression 1:
- if the control variable is initialized before using the for
statement.
Expression 2:
- C assumes that the condition is true ➔ infinite loop
Expression 3:
- If the increment is in the for’s body, or if it’s not needed. 20
Examples of Expressions ..
for Statements ..
Examples of varying the control variable in a for statement:
Vary the control variable from 1 to 100 in increments of 1.

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;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ;
count
Trace this code segment ..

int count ;

count = 2;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ;

Output:
count
Trace this code segment ..
2

int count ;

count = 2;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ;

Output:
count
Trace this code segment ..
2

int count ;

count = 2;

while (count > 0) True!


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ;

Output:
count
Trace this code segment ..
2

int count ;

count = 2;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ; 2

Output:
count
Trace this code segment ..
2
1
int count ;

count = 2;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ; 2

Output:
count
Trace this code segment ..
2
1
int count ;

count = 2;

while (count > 0) True!


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ; 2

Output:
count
Trace this code segment ..
2
1
int count ;

count = 2;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ; 2
1

Output:
count
Trace this code segment ..
2
1
int count ;
0

count = 2;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ; 2
1

Output:
count
Trace this code segment ..
2
1
int count ;
0

count = 2;

while (count > 0) False!


{
printf( “%d \n ”, count ) ;
count-- ;
}
printf( “Done” ) ; 2
1

Output:
count
Trace this code segment ..
2
1
int count ;
0

count = 2;

while (count > 0)


{
printf( “%d \n ”, count ) ;
count-- ;
} 2
printf( “Done” ) ; 1
Done
Output:
the Accumulation Problem ..

Calculate the sum of numbers from 1 to 100:

int sum = 0; // Must be 0 to avoid any garbage values


int i;
for ( i = 1; i <= 100 ; i++ )
{
sum = sum + i; // or sum+=i;
}
printf (“The sum is %d”, sum);

Note: i++ is the same as i = i + 1, and as i += 1.


Trace this code segment ..

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;

for ( number = 2; number <= 100; number += 2 )


{
sum += number;
}
printf( “Sum is %d\n” , sum );
return 0;
}
while Statement .. an Example
Class Average by a Counter–Controlled Repetition
.. A class of 10 students toke a quiz. Read their grades (ranges
from 0 to 100), & determine the class average. ..
#include <stdio.h> To avoid “garbage” value ..
int main ( void ) {
int counter = 1; int sum = 0; int grade; float average;
while ( counter <= 10 ) {
printf( “Enter a grade\n” );
scanf( “%d”, &grade );
sum += grade;
counter++;
}
average = sum / 10.0;
printf( “The Average is %f\n” , average );
return 0;
}
Exercises
What have we learned?
▪ How many times will "Hello, World" be printed in the below program?
#include <stdio.h>
int main() {
int i = 1024;
for(; i; i >>= 1) printf("Hello, World!\n");
return 0; }
a) 10
b) 11
c) Infinite
d) Syntax error.
Up Next ..
Additional Section 7.3
Resources
▪ C Programming Tutorial 76 - While Loop
https://www.youtube.com/watch?v=OfJJsEIO1kE

▪ C Programming Tutorial 78 - Do While Loop


https://www.youtube.com/watch?v=BztbwUkMY_I

▪ C Programming Tutorial 77 - Nested While Loops


https://www.youtube.com/watch?v=v9igjbjjYPo

▪ 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

7.2 Notes & Examples on Counter–Controlled Loops

7.3 Sentinel–Controlled Loops & Break / Continue Statements


▪ Break Statement
▪ Continue Statement
▪ Sentinel–Controlled Repetitions
Break Statement
o The break statement, when executed in a:

while, for, do .. while, or switch .. case statement

.. causes an immediate exit from that statement.

o Program execution continues with the next/following statement.

o Common uses of the break statement are to escape early from a


loop, or to skip the remainder of a switch statement.

What happens if we omit the break in a switch–case


statement?
Break Statement
#include <stdio.h> 1 2 3 4
int main ( void ) Broke out of the loop at x = 5
{
int x;
for ( x = 1; x <= 10; x++ )
{
if ( x == 5 )
{
break;
}
printf( “%d ”, x );
}
printf( “\n Broke out of the loop at x = %d\n”, x );
return 0;
}
Continue Statement

o The continue statement, when executed in a while, for, or a do

.. while statement, skips the remaining statements in the body

of that control statement, and then performs the next

iteration of the loop.


Continue Statement
#include <stdio.h> 1 2 3 4 6 7 8 9 10
int main ( void ) Used continue to skip printing the value 5
{
int x;
for ( x = 1; x <= 10; x++ )
{
if ( x == 5 )
{
continue;
}
printf( “%d ”, x );
}
printf( “\n Used continue to skip printing the value 5\n” );
return 0;
}
Sentinel–Controlled Repetitions

o Undefined Repetition: Number of repetitions is not known in

advance.

o Use a special value called a “Sentinel value” (also called a

“signal value”, a “dummy value”, or a "flag value") to indicate

the “end of data entry.”

o E.g., enter -1 to end


while Statement with a Sentinel Value
Read a set of numbers, & compute their average
.. Pseudocode ..
• set average to zero
• set count to zero
• set total to zero

• read number
• while ( not end-of-data )
• increment count by 1
• total = total + number
• read number

• if ( count > 0 ) then


• average = total / count

• 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.

▪ What is the output of the following C program?


#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
Up Next ..
Additional Lecture 8
Resources
▪ Loop Control Statements − break and continue
https://www.youtube.com/watch?v=obJcPlAtGVM

▪ Conditionals and Loops (Solved Problem 1)


https://www.youtube.com/watch?v=SQCPZYAXoZs

▪ Conditionals and Loops (Solved Problem 2)


https://www.youtube.com/watch?v=1HeVryTa8s0
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 8 [ Part 1 ]
C Built-In Functions .. & ..
Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts
8.2 Variables in C, Long/Short Variables, sizeof() Function,
Signed/Unsigned Variables, Implicit Type Conversion & Explicit
Type Conversion (Type Casting), & bool.h
8.3 C Built-In Functions; Stdio.h, Math.h, & Stdlib.h
8.4 Operators and their Precedence (Assignment, Arithmetic,
Faculty of
Bitwise, Logical, Equality, & Relational)
Computing &
8.5 Decisions (if – then, if – else, nested if, switch – case) Artificial Intelligence
8.6 Loops (for .. while .. do – while .. nested loops)
8.7 Basic Programming Concepts using Scratch 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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 8: C Built-In Functions, & Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts

8.2 Variables in C: Long/Short Variables, sizeof() Function, Signed/Unsigned


Variables, Implicit Type Conversion & Explicit Type Conversion (Type Casting), &
bool.h
8.3 C Built-In Functions; Stdio.h, Math.h, & Stdlib.h

8.4 Operators and their Precedence (Assignment, Arithmetic, Bitwise, Logical,


Equality, & Relational)

8.5 Decisions (if – then, if – else, nested if, switch – case)


8.6 Loops (for .. while .. do – while .. nested loops)

8.7 Basic Programming Concepts using Scratch


Generic Steps when Solving a
Programming Problem:
1) Read the problem a couple of times (until you feel
comfortable with it); You CAN’T solve a problem you don’t
understand!

2) Determine your goal(s), and then think of a step-by-step


solution (i.e., an Algorithm) to your problem(s) to achieve
this/these goals(s).

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.

5) Write Pseudocode (or draw a Flowchart); After you’ve


worked out the general steps, writing out a pseudocode that
you can translate into code will help with defining the
structure of your code and make coding a lot easier.

• Write pseudocode line by line; You can do this either on


paper or as comments in your code editor.
Generic Steps when Solving a
Programming Problem:
6) Translate the pseudocode into code and debug; When you
have your pseudocode ready, translate each line into real code
in the language you are working on.

How .. ? If you wrote it out on paper, then type this up as


comments in your code editor, and then replace each line in
your pseudocode.

Debugging .. ? Call the function(s) and give it some sample


sets of data. Figure out if the code returns the results you
want (if the actual output is equal to the expected output).
“ .. a complete description of any algorithm has four
components:
• What: A precise specification of the problem that
the algorithm solves.
• How: A precise description of the algorithm itself.
• Why: A proof that the algorithm solves the
problem it is supposed to solve.
• How fast: An analysis of the running time of the
algorithm.”

“ .. An algorithm is an explicit, precise, unambiguous, mechanically-


executable sequence of elementary instructions, usually intended to
accomplish a specific purpose.”
Generic Steps when Designing
an Algorithm:
1) Determine the outcome of your code. What is the specific problem you
want to solve or the task you want it to accomplish? Once you have a
solid idea of what you're aiming to accomplish, you can determine the
steps it will take to get there.
2) Decide on a starting point. Finding your starting point is crucial to listing
the steps of the process. To determine a starting point, determine the
answers to questions such as:
• What data/inputs are available? Where is that data located?
• Are there any rules/conditions to work with the available data?
• What formulas are applicable to the issue at hand? .. .. etc.
3) Find the ending point of the algorithm. As with the starting point, you
can find the end point of your algorithm by focusing on questions such as:
• What changes from the start to the end?
• What will be added or no longer exists? .. .. etc.
Generic Steps when Designing
an Algorithm:
4) List the steps from start to finish and start with broad steps.
5) Review the algorithm; Your algorithm is designed to accomplish
something specific, so ask yourself the following questions (and address
each as necessary):
• Does the algorithm solve the problem/accomplish the task?
• Does it have clearly defined inputs and outputs?
• Should the end goal be redefined to be more general? More specific?
• Can any of the steps be simplified?
• Is the algorithm guaranteed to end with the correct result?
Representing / Describing
Algorithms ..?
1) In computer science, Pseudocode is a description of the steps in an

algorithm using plain informal language (pseudocode resembles skeleton

programs).

2) A flowchart is a type of diagram that represents a step-by-step approach

to solving a task (a diagrammatic representation of an algorithm).

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!

8.1: Design an Algorithm (represent it using pseudocode &


a flowchart) to Convert a Temperature in Celsius to
Fahrenheit.
o Given: F = 1.8 * C + 32.
Please pause the video and try to answer the question on your own!

8.2: Design an Algorithm (represent it using pseudocode &


a flowchart) to Divide 2 digits given by a user (if the divisor
is 0 print the result as unknown.
Please pause the video and try to answer the question on your own!

8.3: Design an Algorithm (represent it using pseudocode &


a flowchart) to Identify the form of water (solid “ice”, liquid, or
gaseous “vapor”), based on a temperature value given by
the user.
Please pause the video and try to answer the question on your own!

8.4: Design an Algorithm (represent it using pseudocode &


a flowchart) that reads a Letter Grade ‘g’ from the user &
Prints: Excellent! [if g = A], Very Good [g = B], Good [g = C],
You Need to Practice More! (g = D), You Failed :( [g = F]
Please pause the video and try to answer the question on your own!

8.5: Design an Algorithm (represent it using pseudocode &


a flowchart) that – in the case of an epidemic / pandemic –
Calculates the number of sick people after n days.
o Given: Each newly infected person infects 2 people the next day.
Up Next ..
Always Section 8.2
Remember

“First, solve the Problem.


Then, write the code.”
~John Johnson
Lecture 8: C Built-In Functions, & Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts

8.2 Variables in C: Long/Short Variables, sizeof() Function, Signed/Unsigned


Variables, Implicit Type Conversion & Explicit Type Conversion (Type Casting), &
bool.h
8.3 C Built-In Functions; Stdio.h, Math.h, & Stdlib.h

8.4 Operators and their Precedence (Assignment, Arithmetic, Bitwise, Logical,


Equality, & Relational)

8.5 Decisions (if – then, if – else, nested if, switch – case)


8.6 Loops (for .. while .. do – while .. nested loops)

8.7 Basic Programming Concepts using Scratch


Recap on some Memory Concepts

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

Implicit Type Conversion


a.k.a. Automatic Type Conversion
// An example of implicit conversion
#include<stdio.h> - Converting one datatype
int main() into another is known as type
{
int x = 10; // integer x casting or, type-conversion.
char y = 'a'; // character c - Implicit / Automatic Type
// y implicitly converted to int. ASCII
x = x + y; // value of 'a' is 97 Conversion is done by the
// x is implicitly converted to float compiler on its own, without
float z = x + 1.0;
printf("x = %d, z = %f", x, z); any external trigger from the
return 0; user.
}
x = 107, z = 108.000000
Please pause the video and try to answer the question on your own!

8.6: Write a C program to print all uppercase and


lowercase alphabets.
[ an example of: Implicit (Automatic) Type Conversion ]
o In this C program, we are going to print all uppercase alphabets
(from 'A' to 'Z') and lowercase alphabets (from 'a' to 'z').
o To print uppercase alphabets, we are using a for loop from 'A' to
'Z' and printing the characters, and to print lowercase alphabets,
we are using a another for loop from 'a' to 'z' and printing the
characters.

Capital (upper) case characters:


ABCDEFGHIJKLMNOPQRSTUVWXYZ
Lower case characters:
abcdefghijklmnopqrstuvwxyz
8.6: Write a C program to print all uppercase and
lowercase alphabets.
[ an example of: Implicit (Automatic) Type Conversion ]
/*C program to print all upper-case and lower-case alphabets.*/
#include <stdio.h>
int main()
{
char i;
printf("Capital (upper) case characters:\n");
for( i = 'A'; i <= 'Z'; i++ )
printf("%c ", i );
printf("\n\nLower case characters:\n");
for( i = 'a'; i <= 'z'; i++ )
printf("%c ", i );
return 0;
}
Please pause the video and try to answer the question on your own!

8.7: Write a C program to PRINT the ASCII TABLE/CHART


[ an example of: Implicit (Automatic) Type Conversion ]
o In this C program, we are going to print the characters with their
ASCII codes.

o ASCII stands for American Standard Code for Information


Interchange; it is a character encoding standards for information
interchange in electronics communication. Each alphabet, special
character, .. etc. is represented by an ASCII code. An ASCII code
takes 7 bits in the memory.

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!

8.7: Write a C program to PRINT the ASCII TABLE/CHART


32 - 33 - ! 34 - " 35 - # 36 - $ 37 - % 38 - & 39 - ' 40 - ( 41 - )
42 - * 43 - + 44 - , 45 - - 46 - . 47 - / 48 - 0 49 - 1 50 - 2 51 – 3
52 - 4 Output of-three
53 - 5 54 6 55 runs:
- 7 56 - 8 57 - 9 58 - : 59 - ; 60 - < 61 - =
62 - > 63 - ? 64 - @ 65 - A 66 - B 67 - C 68 - D 69 - E 70 - F 71 – G
72 - H 73 - I 74 - J 75 - K 76 - L 77 - M 78 - N 79 - O 80 - P 81 – Q
82 - R 83 - S 84 - T 85 - U 86 - V 87 - W 88 - X 89 - Y 90 - Z 91 - [
92 - \ 93 - ] 94 - ^ 95 - _ 96 - ` 97 - a 98 - b 99 - c 100 - d 101 – e
102 - f 103 - g 104 - h 105 - i 106 - j 107 - k 108 - l 109 - m 110 - n 111 – o
112 - p 113 - q 114 - r 115 - s 116 - t 117 - u 118 - v 119 - w 120 - x 121 – y
122 - z 123 - { 124 - | 125 - } 126 - ~ 127 - • 128 - Ç 129 - ü 130 - é 131 – â
132 - ä 133 - à 134 - å 135 - ç 136 - ê 137 - ë 138 - è 139 - ï 140 - î 141 – ì
142 - Ä 143 - Å 144 - É 145 - æ 146 - Æ 147 - ô 148 - ö 149 - ò 150 - û 151 – ù
152 - ÿ 153 - Ö 154 - Ü 155 - ¢ 156 - £ 157 - ¥ 158 - ₧ 159 - ƒ 160 - á 161 – í
162 - ó 163 - ú 164 - ñ 165 - Ñ 166 - ª 167 - º 168 - ¿ 169 - ⌐ 170 - ¬ 171 - ½
172 - ¼ 173 - ¡ 174 - « 175 - » 176 - ░ 177 - ▒ 178 - ▓ 179 - │ 180 - ┤ 181 - ╡
182 - ╢ 183 - ╖ 184 - ╕ 185 - ╣ 186 - ║ 187 - ╗ 188 - ╝ 189 - ╜ 190 - ╛ 191 - ┐
192 - └ 193 - ┴ 194 - ┬ 195 - ├ 196 - ─ 197 - ┼ 198 - ╞ 199 - ╟ 200 - ╚ 201 - ╔
202 - ╩ 203 - ╦ 204 - ╠ 205 - ═ 206 - ╬ 207 - ╧ 208 - ╨ 209 - ╤ 210 - ╥ 211 - ╙
212 - ╘ 213 - ╒ 214 - ╓ 215 - ╫ 216 - ╪ 217 - ┘ 218 - ┌ 219 - █ 220 - ▄ 221 - ▌
222 - ▐ 223 - ▀ 224 - α 225 - ß 226 - Γ 227 - π 228 - Σ 229 - σ 230 - µ 231 - τ
232 - Φ 233 - Θ 234 - Ω 235 - δ 236 - ∞ 237 - φ 238 - ε 239 - ∩ 240 - ≡ 241 - ±
242 - ≥ 243 - ≤ 244 - ⌠ 245 - ⌡ 246 - ÷ 247 - ≈ 248 - ° 249 - ∙ 250 - · 251 - √
252 - ⁿ 253 - ² 254 - ■Press any key to continue
24
8.7: Write a C program to PRINT the ASCII TABLE/CHART
[ an example of: Implicit (Automatic) Type Conversion ]

//Program to print ASCII table.


#include <stdio.h>
int main()
{
unsigned char count;
for( count = 32; count < 255; count += 1 )
{
printf( " %3d - %c", count, count );
if( count % 10 == 0 )
printf("\n");
}
return 0;
}
Please pause the video and try to answer the question on your own!

8.8: Write a C program to print the ASCII Value of a


character.
[ an example of: Explicit Type Conversion (Type Casting) ]
o In this C program, we will read (from the user) a character value (in
a character variable) and then store its ASCII value in an integer
variable. Finally, display the ASCII value to the user.

Enter any character: x


The ASCII value of the character x is: 120
8.8: Write a C program to print the ASCII Value of a
character.
[ an example of: Explicit Type Conversion (Type Casting) ]
/* Print the ASCII value of an entered character.*/
#include <stdio.h>
int main()
{
char ch;
int asciiValue;
printf("Enter any character: ");
scanf("%c", &ch);
asciiValue = (int) ch;
printf("ASCII value of character: %c is: %d\n", ch, asciiValue);
}
Please pause the video and try to answer the question on your own!

8.9: Write a C program to calculate the SUM and AVERAGE


of two DECIMAL numbers.
o In this C program, we are going to learn how to find sum and
average of two decimal numbers.
o In this program, we are taking an input from the user (two decimal
numbers), the first number will be stored in the variable a and the
second number will be stored in the variable b.
o The summation of the numbers is calculated by a + b and assigning
the output to the variable sum.
o The average of the numbers is calculated by ( a + b ) / 2 and
assigning the output to the variable avg.

Enter first number :10


Enter second number :15
Sum of 10.000000 and 15.000000 is = 25.000000
Average of 10 and 15 is = 12.500000
8.9: Write a C program to calculate the SUM and AVERAGE
of two DECIMAL numbers.
/* c program find the sum and average of two decimal numbers*/
#include <stdio.h>
int main()
{
float a, b, sum, avg;
printf("Enter the first number :");
scanf("%f", &a);
printf("Enter the second number :");
scanf("%f", &b);
sum = a + b;
avg = ( a + b ) / 2;
printf("\n Sum of %f and %f is = %f", a, b, sum);
printf("\n Average of %f and %f is = %f", a, b, avg);
return 0;
}
Please pause the video and try to answer the question on your own!

8.10: Write a C program to calculate the SUM and


AVERAGE of two INTEGER numbers.
o In this C program, we are going to learn how to find sum and
average of two integer numbers.
o In this program, we are taking an input from the user (two integer
numbers), the first number will be stored in the variable a and the
second number will be stored in the variable b.
o The summation of the numbers is calculated by a + b and assigning
the output to the variable sum.
o The average of the numbers is calculated by ( a + b ) / 2 and
assigning the output to the variable avg.

Enter first number :10


Enter second number :15
Sum of 10 and 15 is = 25
Average of 10 and 15 is = 12.500000
8.10: Write a C program to calculate the SUM and
AVERAGE of two INTEGER numbers.
/* c program find the sum and average of two integer numbers*/
#include <stdio.h>
int main()
{
int a, b, sum; float avg;
printf("Enter the first number :");
scanf("%d", &a);
printf("Enter the second number :");
scanf("%d", &b);
sum = a + b;
avg = ( a + b ) / 2;
printf("\n Sum of %d and %d is = %d", a, b, sum);
printf("\n Average of %d and %d is = %f", a, b, avg);
return 0;
}
8.10: Write a C program to calculate the SUM and
AVERAGE of two INTEGER numbers.

Run the program in the previous slide ..


Enter first number :10
Enter second number :15
Sum of 10 and 15 is = 25
Average of 10 and 15 is = 12.000000

What went wrong .. ?


How can we fix this .. ?
8.10: Write a C program to calculate the SUM and
AVERAGE of two INTEGER numbers. [ 1st FIX ]
/* c program find the sum and average of two numbers*/
#include <stdio.h>
int main()
{
int a, b, sum; float avg;
printf("Enter the first number :");
scanf("%d", &a);
printf("Enter the second number :");
scanf("%d", &b);
sum = a + b;
[ an example of: Implicit Type Conversion ]
avg = ( a + b ) / 2.0;
printf("\n Sum of %d and %d is = %d", a, b, sum);
printf("\n Average of %d and %d is = %f", a, b, avg);
return 0;
}
8.10: Write a C program to calculate the SUM and
AVERAGE of two INTEGER numbers. [ 2nd FIX ]
/* c program find the sum and average of two numbers*/
#include <stdio.h>
int main() [ an example of: Explicit Type Conversion (Type Casting) ]
{
int a, b, sum; float avg;
printf("Enter the first number :");
scanf("%d", &a);
printf("Enter the second number :");
scanf("%d", &b);
sum = a + b;
avg = ( float ) ( a + b ) / 2; Here, float is used to cast the type.
printf("\n Sum of %d and %d is = %d", a, b, sum);
printf("\n Average of %d and %d is = %f", a, b, avg);
return 0;
}
Recap on some C Data-Types concepts

Basic Data -Types in C


the difference between signed and unsigned
- In C, signed and unsigned are type modifiers. You can alter
the data storage of a data type by using them.

- 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.

- Considering the size of int is 4 bytes, variable y can hold


values from -231 to 231-1, whereas variable x can hold values
from 0 to 232-1.
Recap on some C Data-Types concepts
1 (small signed integers)
Basic Data -Types in C 2 (small unsigned integers)
3 (1.2x-1038: 3.4x1038)

their sizes, ranges, & format specifiers


Type Size (bytes) Format Specifier Range
--------------------------------------------------------------------------------------------------------------------------------
char 1 %c 0 : (28 – 1) [0 to 255]
signed char 1 1 %c -27 : (27 – 1) [-128 to 127]
Integer Types

unsigned char 2 1 %c 0 : (28 – 1) [0 to 255]


--------------------------------------------------------------------------------------------------------------------------------
short int 2 %hd -215 : (215 – 1) [-32,768 to 32,767]
unsigned short int 2 %hu 0 : (216 – 1) [0 to 65,535]
int 4 (or 2) %d, %i -231 : (231 – 1)
[-2,147,483,648 to 2,147,483,647]
unsigned int 4 (or 2) %u 0 : (232 – 1) [0 to 4,294,967,295]
long int 4 (or 8) %ld, %li -231 : (231 – 1)
long long int 8 %lld, %lli -263 : 263 – 1
unsigned long int 4 (or 8) %lu 0 : (232 – 1) [0 to 4,294,967,295]
unsigned long long int 8 %llu [0 to 18,446,744,073,709,551,615]
--------------------------------------------------------------------------------------------------------------------------------
float 4 %f [1.2E-38 to 3.4E+38] 3
Floating-

double 8 %lf [2.3E-308 to 1.7E+308]


Types
Point

long double 12 (or 16) %Lf [3.4E-4932 to 1.1E+4932]


Recap on some C Data-Types concepts

Ranges of Basic Data -Types in C


for Integer Types The macros defined in this header
(limits.h), limits the values of various
#include <stdio.h>
variable types like char, int and long.
#include <limits.h> They're defined with the #define directive.
int main() {
printf("MIN value for CHAR : %d\n", CHAR_MIN);
printf("MAX value for CHAR : %d\n", CHAR_MAX);
printf("MIN value for SIGNED CHAR : %d\n", SCHAR_MIN);
printf("MAX value for SIGNED CHAR : %d\n", SCHAR_MAX);
printf("MAX value for UNSIGNED CHAR : %d\n", UCHAR_MAX);
printf("MIN value for SHORT INT : %d\n", SHRT_MIN);
printf("MAX value for SHORT INT : %d\n", SHRT_MAX);
printf("MAX value for UNSIGNED SHORT: %d\n", USHRT_MAX);
printf("MIN value for INT : %d\n", INT_MIN);
printf("MAX value for INT : %d\n", INT_MAX);
printf("MAX value for UNSIGNED INT : %u\n", UINT_MAX);
printf("MIN value for LONG : %ld\n", LONG_MIN);
printf("MAX value for LONG : %ld\n", LONG_MAX);
printf("MAX value for UNSIGNED LONG : %lu\n", ULONG_MAX); }
Recap on some C Data-Types concepts

Ranges of Basic Data -Types in C


for Integer Types
Recap on some C Data-Types concepts

Ranges of Basic Data -Types in C


for Floating-Point Types For displaying floats in exponential
notation, also referred to as Scientific
#include <stdio.h>
notation (note that the "E" or "e"
#include <float.h> stands for "power-of-10 exponent").
int main() {
printf("MIN value for FLOAT : %e\n", FLT_MIN);
printf("MAX value for FLOAT : %e\n", FLT_MAX);
printf("MAX value for FLOAT : %f\n", FLT_MAX);
printf("MIN value for DOUBL : %e\n", DBL_MIN);
printf("MAX value for DOUBLE : %e\n", DBL_MAX);
printf("MAX value for DOUBLE : %lf\n", DBL_MAX); }
Please pause the video and try to answer the question on your own!

8.11: Write a C program to print the size of variables


using the sizeof( ) built-in function.
o sizeof() is a built-in function in the C programming language,
which is used to get the occupied size by a variable or a value. This
program demonstrates the usage of the sizeof() function by
printing the size of different types of variables.
8.11: Write a C program to print the size of variables
using the sizeof( ) built-in function.
#include <stdio.h>
int main() {
char a = 'A';
int b = 120; unsigned int c = 0;
short d; long e; long long f; unsigned long long g;
float h = 123.0; double i = 1222.90; long double j;
printf("\nSize of a Char: %d", sizeof( a ) );
printf("\nSize of an Int: %d", sizeof( b ) );
printf("\nSize of an Unsigned Int: %d", sizeof( c ) );
printf("\nSize of a Short Int: %d", sizeof( d ) );
printf("\nSize of a Long Int: %d", sizeof( e ) );
printf("\nSize of a Long Long Int: %d", sizeof( f ) );
printf("\nSize of an Unsigned Long Long Int: %d", sizeof( g ) );
printf("\nSize of a Float: %d", sizeof( h ) );
printf("\nSize of a Double: %d", sizeof( i ) );
printf("\nSize of a Long Double: %d", sizeof( j ) );
}
Here are some questions that should run through your
Up Next ..
mind when solving a programming problem: Section 8.3
▪ How can we divide this problem? What are the sub-
problems?
▪ How can a computer solve a specific sub-problem? Example:
How can a computer tell what is an even number? Divide that
number by 2 and see if its remainder is 0.
▪ What data do we need to read/input from the user?
▪ What data do we need to display/output to the user?
▪ Do we have any decisions to make? How many choices per
decision?
▪ Are then any repetitions? Any steps that need to be
repeated more than once? How will the repetition end?
▪ How many functions do we need? What is the goal of every
function?
▪ What are we passing into this function? What are we
returning at the end of this function?
▪ How many variables do we need? What will those variables
contain?
▪ What are the data types of the variables?
Lecture 8: C Built-In Functions, & Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts

8.2 Variables in C: Long/Short Variables, sizeof() Function, Signed/Unsigned


Variables, Implicit Type Conversion & Explicit Type Conversion (Type Casting), &
bool.h
8.3 C Built-In Functions; Stdio.h, Math.h, & Stdlib.h

8.4 Operators and their Precedence (Assignment, Arithmetic, Bitwise, Logical,


Equality, & Relational)

8.5 Decisions (if – then, if – else, nested if, switch – case)


8.6 Loops (for .. while .. do – while .. nested loops)

8.7 Basic Programming Concepts using Scratch


Recap: Header Files in C

C Built -in Functions: Selected


Header Files: Stdio.h, Math.h, & Stdlib.h
1] The stdio.h header file stands for Standard Input Output. It has the
information related to input/output functions.
Examples: Formatted input/output (printf & scanf), Unformatted
input/output (getchar & putchar), File access (fopen & fclose), Direct
input/output (fread & fwrite), Operations on files (remove & rename), File
positioning (fseek & rewind), .. etc.
2] The math.h header file defines various mathematical functions.
N.B. All the functions available in this library take double as an argument
and return double as the result.
Examples: pow(), sqrt(), round(), ceil(), floor(), sin(), cos(), tan(), log(),
log10(), .. etc.
3] The header file stdlib.h stands for Standard Library. It has the information
of memory allocation/freeing functions.
Examples: malloc(): allocates the memory during execution of program,
free(): frees the allocated memory, abort() & exit(): terminates the C
program, atol() / atoll() / atof(): converts a string to long int / long long int /
floating point value, rand(): returns a random integer value, .. etc.
Please pause the video and try to answer the question on your own!

8.12: Write a C program for PRINTING a value in DECIMAL,


OCTAL, HEXADECIMAL using printf.
[ an example of the C built-in functions in Stdio.h ]
o This C program will print an entered value in Decimal, Octal, and
Hexadecimal formats using the printf() function in the C
programming language. By using different format specifiers, we can
print the value in the specified format.

Here, the following format specifiers are used:


o %d - to print value in integer format.
o %o - to print value in octal format.
o %x - to print value in hexadecimal format (letters will print in
lowercase).
o %X - to print value in hexadecimal format (letters will print in
uppercase).
Please pause the video and try to answer the question on your own!

8.12: Write a C program for PRINTING a value in DECIMAL,


OCTAL, HEXADECIMAL using printf.
[ an example of the C built-in functions in Stdio.h ]

Please enter an integer value: 2567


Decimal value: 2567
Octal value: 5007
Hexadecimal value (Alphabet in small letters): a07
Hexadecimal value (Alphabet in capital letters): A07
8.12: Write a C program for PRINTING a value in DECIMAL,
OCTAL, HEXADECIMAL using printf.
[ an example of the C built-in functions in Stdio.h ]
/*Printing a value in Decimal, Octal, Hexadecimal using printf in C.*/
#include <stdio.h>
int main()
{
int x;
printf("Please enter an integer value: \n");
scanf("%d", &x);
printf("Decimal value: %d\n", x);
printf("Octal value: %o\n", x);
printf("Hexadecimal value (Alphabet in small letters): %x\n", x);
printf("Hexadecimal value (Alphabet in capital letters): %X\n", x);
return 0;
}
Please pause the video and try to answer the question on your own!

8.13: Write a C program to illustrate the use of printf()


[ an example of the C built-in functions in Stdio.h ]
#include <stdio.h>
int main ( )
{
// The Width Option
printf("%5d \n", 0); // _ _ _ _ 0 right-justified (printed in the right side of the field)
printf("%5d \n", -7); // _ _ _ -7 (i.e., right-aligned & front-filled with spaces)
printf("%-5d \n", 0); // 0 _ _ _ _ left-justified (printed in the left side of the field)
printf("%-5d \n", -7); // -7 _ _ _ (i.e., left-aligned)
// The Zero-Fill Option
printf("%05d \n", 0); // 00000
printf("%05d \n", -7); // -0007
// Print Positive Numbers (and Zero) with a sign
printf("%+5d \n", 0); // _ _ _ +0
printf("%+5d \n", -7); // _ _ _ -7
// Floating Numbers Precision For more information check the following article:
double e = 2.718281828; Secrets of “printf” by Prof. Don Colton
printf("%.0f \n", e); // 3 (Brigham Young University Hawaii):
printf("%.1f \n", e); // 2.7 https://www.cypress.com/file/54441/download
printf("%.2f \n", e); // 2.72
printf("%.6f \n", e); // 2.718282
printf("%f \n", e); // 2.718282 - default is %.6f (six digits after the decimal point)
printf("%.7f \n", e); // 2.7182818
}
Please pause the video and try to answer the question on your own!

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 ]
o In this C program, we are going to calculate the cube of an integer
number. We will implement the program by using two methods (1)
without using the “pow()” function, and (2) using the “pow()”
function.
o A cube can be found by calculating the power of 3 for any number.
For example, the cube of 2 will be 23 (2 to the power of 3).
o 1) Without using the pow() function; In this method, we will
just read an integer number and multiply it by itself for 3 times.
o 2) Using the pow() function; pow() is a library/built-in C
function of the math.h header file. It is used to calculate the
power of any number (we will use it to calculate the cube of any
given number).
Enter any integer number: 8
CUBE is: 512
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>
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!

8.15: Write a C program to print the Square, Cube, and


Square Root of all the numbers from 1 to N.
[ an example of the C built-in functions in Math.h ]

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!

8.15: Write a C program to print the Square, Cube, and


Square Root of all the numbers from 1 to N.
[ an example of the C built-in functions in Math.h ]
No Square Cube Square Root
1 1 1 1.00
2 4 8 1.41
3 9 27 1.73
4 16 64 2.00
5 25 125 2.24
6 36 216 2.45
7 49 343 2.65
8 64 512 2.83
9 81 729 3.00
10 100 1000 3.16
8.15: Write a C program to print the Square, Cube, and
Square Root of all the numbers from 1 to N.
[ an example of the C built-in functions in Math.h ]
/*Print the square, cube, & square root of all the numbers from 1 to N.*/
#include <stdio.h>
#include <math.h>
int main()
{
int i, n;
printf("Enter the value of N: "); scanf("%d", &n );
printf("No Square Cube Square Root\n", n );
for( i = 1; i <= n; i++ )
{
printf("%d \t %ld \t %ld \t %.2f\n", i, ( i * i ), ( i * i * i ), sqrt( (double) i ) );
}
return 0;
}
Please pause the video and try to answer the question on your own!

8.16: Write a C program to illustrate the use of the


following functions, (1) round, (2) ceil, (3) floor, & (4) fabs
[ examples of the C built-in functions in Math.h ]
#include <stdio.h>
#include <math.h>
int main ()
{
double value1 = 1.6, value2 = 1.2, value3 = -2.8, value4 = -2.3;
// C code to illustrate the use of round function.
printf("Rounding of ( %.1lf ) = %.1lf \n", value1, round( value1 ) );
printf("Rounding of ( %.1lf ) = %.1lf \n", value2, round( value2 ) );
printf("Rounding of ( %.1lf ) = %.1lf \n", value3, round( value3 ) );
printf("Rounding of ( %.1lf ) = %.1lf \n", value4, round( value4 ) );
// C code to illustrate the use of ceil function.
printf("Ceil of ( %.1lf ) = %.1lf \n", value1, ceil( value1 ) );
printf("Ceil of ( %.1lf ) = %.1lf \n", value2, ceil( value2 ) );
printf("Ceil of ( %.1lf ) = %.1lf \n", value3, ceil( value3 ) );
printf("Ceil of ( %.1lf ) = %.1lf \n", value4, ceil( value4 ) );
// C code to illustrate the use of floor function.
printf("Floor of ( %.1lf ) = %.1lf \n", value1, floor( value1 ) );
printf("Floor of ( %.1lf ) = %.1lf \n", value2, floor( value2 ) );
printf("Floor of ( %.1lf ) = %.1lf \n", value3, floor( value3 ) );
printf("Floor of ( %.1lf ) = %.1lf \n", value4, floor( value4 ) );
// C code to illustrate the use of fabs function
printf("The absolute value of ( %.1lf ) is %lf \n", value1, fabs( value1 ) );
printf("The absolute value of ( %.1lf ) is %lf \n", value3, fabs( value3 ) );
}
Please pause the video and try to answer the question on your own!

8.17: Write a C program to illustrate the use of the


following functions, (1) log, & (2) log10
[ examples of the C built-in functions in Math.h ]
8.17: Write a C program to illustrate the use of the
following functions, (1) log, & (2) log10
[ examples of the C built-in functions in Math.h ]

#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 ));

// finding value of log10 (10000)


x = 10000;
printf("log10( %lf ) = %lf \n", x, log10( x ));
}
Please pause the video and try to answer the question on your own!

8.18: Write a C Program to Shutdown / Restart the


Windows.
[ an example of the C built-in functions in Stdlib.h ]
This program turns off (i.e., shutdown) or restarts your computer system.
The System function of stdlib.h is used to run an executable file shutdown.exe
which is present in C:\WINDOWS\system32 folder in Windows 7 and XP.
o You can use various options while executing shutdown.exe, for example
you can use /t option to specify number of seconds after which the
shutdown occurs.
o Syntax: "shutdown /s /t x"; here x is the number of seconds after which
shutdown will occur.
o Example: By default, shutdown occurs after 30 seconds. To shutdown
immediately you can write "shutdown /s /t 0"
o If you wish to restart your computer then you can use "shutdown /r".
8.18: Write a C Program to Shutdown / Restart the
Windows.
[ an example of the C built-in functions in Stdlib.h ]
// Below is a program to shutdown Windows 7.
// system() is used to invoke an operating system command from a C/C++ program.
#include<stdio.h>
#include<stdlib.h> // to use the system() method

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

8.2 Variables in C: Long/Short Variables, sizeof() Function, Signed/Unsigned


Variables, Implicit Type Conversion & Explicit Type Conversion (Type Casting), &
bool.h
8.3 C Built-In Functions; Stdio.h, Math.h, & Stdlib.h

8.4 Operators and their Precedence (Assignment, Arithmetic, Bitwise, Logical,


Equality, & Relational)

8.5 Decisions (if – then, if – else, nested if, switch – case)


8.6 Loops (for .. while .. do – while .. nested loops)

8.7 Basic Programming Concepts using Scratch


Recap on some Arithmetic Concepts

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

o If one of the operands of a division operation is not an


integer, the result is not an integer value.
o E.g., 6 / 4.0 = 1.5 .. & .. 18.0 / 5 = 3.6

o N.B. Beware of the Division-by-Zero


o It results in a fatal run-time error: the program
terminates immediately.
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 ? ?
?
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

o The magnitude of m % n must always be less than the


divisor:

E.g., 299 % 100 = 99 (the results must by between


0 and 99).
Recap on some Arithmetic Concepts

Arithmetic Operations
Evaluating Expressions

Parentheses on the Same Level Nested Parentheses


2 outer
1 2
3 4 1
inner
5
Redundant parentheses?
Unnecessary?
Recap on some Arithmetic Concepts

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!

8.20: Write a C program to calculate the QUOTIENT and


the REMAINDER.

o In this C program, we will read 2 numbers; the dividend and the divisor, and

then we calculate the quotient, and the remainder.

o How to get the quotient and the remainder?

o The binary operator divide (/) returns the quotient.

E.g., if the dividend is 10 and the divisor is 3, then the quotient will be 3.

o The binary operator modulus (%) returns the remainder.

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!

8.20: Write a C program to calculate the QUOTIENT and


the REMAINDER.
Output of three runs:

Enter the dividend: 10


Enter the divisor: 3
Quotient: 3, Remainder: 1

Enter the dividend: 10


Enter the divisor: 2
Quotient: 5, Remainder: 0

Enter the dividend: 10


Enter the divisor: 100
Quotient: 0, Remainder: 10
8.20: Write a C program to calculate the QUOTIENT and
the REMAINDER.
#include <stdio.h>
int main()
{
int dividend, divisor;
int quotient, remainder;
printf("Enter the dividend: ");
scanf("%d", &dividend);
printf("Enter the divisor: ");
scanf("%d", &divisor);
quotient = dividend / divisor;
remainder = dividend % divisor;
printf("Quotient: %d, Remainder: %d\n", quotient, remainder);
return 0;
}
Please pause the video and try to answer the question on your own!

8.21: Write a C program to SWAP TWO NUMBERS using


TWO DIFFERENT methods.

o In this C program, we are going to learn how to swap two integer


numbers using two different methods;
o Given two integer numbers and we have to swap them using
different methods.
o The methods that we are going to use in this program are:
o Using a third variable.
o Without using a third variable.
Enter value of A ? 100
Enter value of B ? 200
Before swapping : A = 100, B = 200
After swapping (1st method) : A = 200, B = 100
After swapping (2nd method): A = 100, B = 200
8.21: Write a C program to SWAP TWO NUMBERS using
TWO DIFFERENT methods.

// C program to swap two numbers using two different methods.


#include <stdio.h>
int main() {
int a, b, t;
printf(" Enter value of A ? "); scanf( "%d", &a );
printf(" Enter value of B ? "); scanf( "%d", &b );
printf("\n Before swapping: A = %d, B = %d", a, b );
/**** first method using a third (temp) variable*/
t = a; a = b; b = t;
printf("\n After swapping (1st method) : A = %d, B = %d\n", a, b );
/**** second method without using a third variable*/
a = a + b; b = a - b; a = a - b;
printf("\n After swapping (2nd method): A = %d, B = %d\n", a, b );
return 0;
}
Please pause the video and try to answer the question on your own!

8.22: Write a C program that prints All the Leap Years


from 1 to N.

o This program will read the value of N and print all the Leap Years

from 1 to N.

o There are two conditions for a leap year:

o If the year is divisible by 400 (for Century years),

o If the year is divisible by 4 and must not be divisible by 100 (for

Non-Century years).
Please pause the video and try to answer the question on your own!

8.22: Write a C program that prints All the Leap Years


from 1 to N.

Enter the value of N: 2000


Leap years from 1 to 2000:
4 8 12 16 20 24 28 32 36 40
44 48 52 56 60 64 68 72 76 80
84 88 92 96 104 108 112 116 120 124
128 132 136 140 144 148 152 156 160 164
168 172 176 180 184 188 192 196 204 208
...
1820 1824 1828 1832 1836 1840 1844 1848 1852 1856
1860 1864 1868 1872 1876 1880 1884 1888 1892 1896
1904 1908 1912 1916 1920 1924 1928 1932 1936 1940
1944 1948 1952 1956 1960 1964 1968 1972 1976 1980
1984 1988 1992 1996 2000
8.22: Write a C program that prints All the Leap Years
from 1 to N.
#include <stdio.h> // C program to print all leap years from 1 to N.
int main()
{
printf("Enter the value of N: ");
int n; scanf("%d", &n);
printf("Leap years from 1 to %d:\n", n);
for( int year = 1; year <= n; year++ )
{
if( ( year % 400 == 0 ) || ( year % 4 == 0 && year % 100 != 0 ) )
{
printf("%d\t", year );
}
}
return 0;
}
Please pause the video and try to answer the question on your own!

8.23: Write a C program to find the HCF (Highest


Common Factor) of two numbers.
o This program will read two integer numbers and print the Highest
Common Factor (HCF).

Enter the first number: 100


Enter the second number: 40
HCF (Highest Common Factor) of 100, 40 is: 20
8.23: Write a C program to find the HCF (Highest
Common Factor) of two numbers.
#include <stdio.h> /*C program to find the HCF of two numbers.*/
int main()
{
int x, y, hcf;
printf("Enter the first number: "); scanf( "%d", &x );
printf("Enter the second number: "); scanf( "%d", &y );
int a = x, b = y, temp;
if( a == 0 || b == 0 ) hcf = 0;
else
{
while( b != 0 ) {
temp = a % b;
a = b;
b = temp;
}
hcf = a;
}
printf("HCF (Highest Common Factor) of %d, %d is: %d\n", x, y, hcf );
}
Please pause the video and try to answer the question on your own!

8.24: Write a C program that uses Bitwise Operators


(Shifting Left / Right) to perform Multiplications /
Divisions by the powers of 2.

That is, for example, multiply x by 21 or divide x by 24


o Example, if x = 60, display x multiplied / divided by 2 to the
powers of 1 to 3 (21, 22, & 23)
60 multiplied by ( 2^1 ) = 120
60 divided by ( 2^1 ) = 30

60 multiplied by ( 2^2 ) = 240


60 divided by ( 2^2) = 15

60 multiplied by ( 2^3 ) = 480


60 divided by ( 2^3 ) = 7
8.24: Write a C program that uses Bitwise Operators
(Shifting Left / Right) to perform Multiplications /
Divisions by the powers of 2.
For example, if x = 3:
#include <stdio.h> 0 0 1 1 [3]
int main() { 0 1 1 0 [6] shift left by 1
int x = 60; 1 1 0 0 [12] shift left by 2
for( int i = 1; i <= 3; i++ )
{
// Shifting left means multiplying by 2i
printf("%d multiplied by ( 2^%d ) = %-10d \n", x, i, x << i );
// Shifting right means dividing by 2i
printf("%d divided by ( 2^%d ) = %-10d \n \n", x, i, x >> i );
}
return 0;
}
Always Up Next ..
Section 8.5
Remember
Practice, Practice, Practice .. !
If you want to be a good problem-solver,
solve a lot of problems ☺
WHY .. ?
1) Even experienced developers always need practicing &
learning.
2) Practicing allows you to get helpful feedback.
3) Programming, like with anything, comes easier and more
naturally with time.
4) Problems share similar patterns; it’ll only be a matter of
time before you gain experience and start recognizing
that this problem could easily be solved with this concept
or that approach.
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 8 [ Part 2 ]
C Built-In Functions .. & ..
Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts
8.2 Variables in C, Long/Short Variables, sizeof() Function,
Signed/Unsigned Variables, Implicit Type Conversion & Explicit
Type Conversion (Type Casting), & bool.h
8.3 C Built-In Functions; Stdio.h, Math.h, & Stdlib.h
8.4 Operators and their Precedence (Assignment, Arithmetic,
Faculty of
Bitwise, Logical, Equality, & Relational)
Computing &
8.5 Decisions (if – then, if – else, nested if, switch – case) Artificial Intelligence
8.6 Loops (for .. while .. do – while .. nested loops)
8.7 Basic Programming Concepts using Scratch 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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 8: C Built-In Functions, & Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts

8.2 Variables in C: Long/Short Variables, sizeof() Function, Signed/Unsigned


Variables, Implicit Type Conversion & Explicit Type Conversion (Type Casting), &
bool.h
8.3 C Built-In Functions; Stdio.h, Math.h, & Stdlib.h

8.4 Operators and their Precedence (Assignment, Arithmetic, Bitwise, Logical,


Equality, & Relational)

8.5 Decisions (if – then, if – else, nested if, switch – case)


8.6 Loops (for .. while .. do – while .. nested loops)

8.7 Basic Programming Concepts using Scratch


Please pause the video and try to answer the question on your own!

8.25: What is the output of the following C program?


#include <stdio.h>
int main()
{
unsigned char i = 128;

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;

if ( i << 1 ) // Result is 256 128 in binary is '10000000', shifting that to the


{ right one bit gives '100000000' or 256. And
printf("Hola! \n" ); because i << 1 isn't being stored in I, there's no
} overflow and 256 remains the output.

if ( i <<= 1 ) // Result is 0 Here, i <<= 1 means i = i << 1, thus after


{ shifting 128 in binary (10000000) to the right
printf("Hey! \n" ); by one bit, the resulting 9 bits ('100000000' or
} 256) are being stored in the char i, resulting in
return 0; an overflow, and the value of i becomes 0.
}
Please pause the video and try to answer the question on your own!

8.26: What is the output of the following C program?

#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!

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
{
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!

8.28: What is the output of the following C program?

#include <stdio.h> a) x=4


int main() b) x=3
{ c) x=2
int x = 3; d) x=1
if (x == 2); x = 0; e) x=0
if (x == 3) x++; f) Syntax Error
else x += 2;
printf("x = %d", x);
return 0;
}
8.28: What is the output of the following C program?

#include <stdio.h> a) x=4


int main() b) x=3
{ c) x=2
int x = 3; d) x=1
if (x == 2); x = 0; e) x=0
if (x == 3) x++; f) Syntax Error
else x += 2;
printf("x = %d", x);
The executed statements (that
return 0;
affects the value of x) are:
} int x = 3;
x = 0;
x += 2;
Please pause the video and try to answer the question on your own!

8.29: Write a C program to check whether a given


number is EVEN or ODD.
Given an integer number, we have to check whether it is Even or Odd
using a C program.
o The numbers which are divisible by 2 are even numbers, while the
numbers which are not divisible by 2 are odd numbers.
o To check whether a given number is even or odd, we check its
modulus when dividing it by 2. If the modulus is 0, then it is
completely divisible by 2, and hence it is an even number,
otherwise it is an odd number.
For Example (the output of 2 runs):
Enter an integer number: 123
123 is an ODD number.
Enter an integer number: 110
110 an EVEN number.
8.29: Write a C program to check whether a given
number is EVEN or ODD.
/* a C program to check whether a number is even or odd*/
#include <stdio.h>
int main()
{
int num;
printf("Enter an integer number: ");
scanf("%d", &num);
/* If number is divisible by 2 then number
is EVEN otherwise number is ODD */
if ( num % 2 == 0 )
printf("%d is an EVEN number.", num);
else
printf("%d is an ODD number.", num);
return 0;
}
Please pause the video and try to answer the question on your own!

8.30: Write a C program to check whether a person is


ELIGIBLE FOR VOTING or not.
Given an age of a person, we have to check whether (s)he is eligible
for voting or not.
o To check that a person is eligible for voting or not, we need to
check whether that person’s age is greater than or equal to 18. For
this we are reading age in a variable age, and then checking the
condition age >= 18, if the condition is true, the that “person will be
eligible for voting”, else (s)he is not.
For Example (the output of 2 runs):

Enter the age of the person: 21


Eligible for voting
Enter the age of the person: 15
Not eligible for voting
8.30: Write a C program to check whether a person is
ELIGIBLE FOR VOTING or not.

#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!

8.31: Write a C program to find the LARGEST NUMBER


among three numbers using 2 methods.
o This program will take three integer numbers from the user and
find the largest number among them; we will find the largest
number using two methods: if .. else statement, .. and ..
conditional operators.
For Example (the output of 4 runs):
Enter three numbers (separated by space): 10 20 30
Largest number is = 30
Enter three numbers (separated by space): 10 30 20
Largest number is = 30
Enter three numbers (separated by space): 30 10 20
Largest number is = 30
Enter three numbers (separated by space): 30 30 30
Largest number is = 30
8.31: Write a C program to find the LARGEST NUMBER
among three numbers using 2 methods.
/* a C program to find the largest number among 3 numbers*/
#include <stdio.h>
int main() {
int a, b, c; int largest;
printf("Enter three numbers (separated by space):");
scanf("%d%d%d", &a, &b, &c);
if ( a >= b && a >= c )
largest = a;
else if ( b >= a && b >= c )
largest = b;
else
largest = c;
printf("Largest number is = %d", largest);
return 0;
}
8.31: Write a C program to find the LARGEST NUMBER
among three numbers using 2 methods.

/* a C program to find the largest number among 3 numbers*/


/* using ternary operator (? :) */
#include <stdio.h>
int main()
{
int a, b, c;
int largest;
printf("Enter three numbers (separated by space):");
scanf("%d%d%d", &a, &b, &c);
largest = ( ( a >= b && a >= c ) ? a : ( ( b >= a && b >= c ) ? b : c ) );
printf("Largest number is = %d", largest);
return 0;
}
Please pause the video and try to answer the question on your own!

8.32: Write a C program that reads marks and then prints


the overall PERCENTAGE & a PERFORMANCE CATEGORY.
In this C program, we are going to read a student’s marks in 3
subjects, we will find the total, the overall percentage, and then print
the performance category based on the percentage.
o Formula to get the percentage: Total Obtained Marks * 100 / Grand
Total (total of maximum marks).
o Performance Categories (based on the percentage), are:
o “First”, if percentage is greater than or equal to 75.
o “Second”, if percentage is greater than or equal to 65.
o “Third”, if percentage is greater than or equal to 50.
o “Fail”, if percentage is less than 50.
For Example:
Please enter the 3 marks (separated by space): 50 60 70
Total Marks: 180
Percentage is: 60.00
Third Category
#include<stdio.h>
int main()
{
int science, math, english, total; float per;
printf("Please enter the 3 marks (separated by space):");
scanf("%d%d%d", &science, &math, &english);
total = science + math + english; // Calculating the total
per = (float) total * 100 / 300; // Calculating the percentage
printf("Total Marks: %d\n", total);
printf("Percentage is: %.2f\n", per);
if ( per >= 75) // Checking the Performance Category & Printing
{ printf("First Category\n"); }
else if ( per >= 65 )
{ printf("Second Category"); }
else if ( per >= 50)
{ printf("Third Category"); }
else
{ printf("Fail\n"); }
return 0;
}
Please pause the video and try to answer the question on your own!

8.33: Write a CALCULATOR program with Basic


operations.

This program will read two integer numbers and an operator like +, -,

*, /, %, and then prints the result according to the given operator.

Thus, it is a complete calculator program for the basic arithmetic

operations.
Please pause the video and try to answer the question on your own!

8.33: Write a CALCULATOR program with Basic


operations.
Enter the first number: 10
Enter the second number: 20
Choose an operation to perform (+,-,*,/,%): +
Result: 10 + 20 = 30.000000

Enter the first number: 10


Enter the second number: 3
Choose an operation to perform (+,-,*,/,%): /
Result: 10 / 3 = 3.333333

Enter the first number: 10


Enter the second number: 3
Choose an operation to perform (+,-,*,/,%): >
Invalid Operation.
/*C program to design calculator with basic operations using switch.*/
#include <stdio.h>
int main() {
int num1,num2; float result; char ch; //to store operator choice
printf("Enter the first number: "); scanf("%d", &num1);
printf("Enter the second number: "); scanf("%d", &num2);
printf("Choose an operation to perform (+,-,*,/,%): "); scanf(" %c", &ch);
switch( ch )
{
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = (float) num1 / (float) num2; break;
case '%': result = num1 % num2; break;
default: printf("Invalid Operation.\n");
}
if ( ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%' )
printf("Result: %d %c %d = %f\n", num1, ch, num2, result);
return 0;
}
Please pause the video and try to answer the question on your own!

8.34: Write a C program to check whether a character is


A VOWEL OR A CONSONANT.

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!

8.35: What is the output of the following C program?

#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);

if ( w && x && z++ )


printf("The 2nd if statement is True. \n");
printf("The value of z is %d. \n", z);
}
8.35: What is the output of the following C program?
The 1st if statement is True.
#include <stdio.h> The value of y is 6.
int main() The value of z is 5.
{
int w = 1, x = 0, y, z;
y = z = 5;
if ( w && x || y++ ) // TRUE, value of y is incremented
printf("The 1st if statement is True. \n");
printf("The value of y is %d. \n", y); // Statement executed anyway
Short-Circuit Evaluation
if ( w && x && z++ ) // FALSE, value of z is not incremented
printf("The 2nd if statement is True. \n");
printf("The value of z is %d. \n", z); // Statement executed anyway
}
Always Up Next ..
Section 8.6
Remember
Practice, Practice, Practice .. !

"The only way to learn a new


programming language is by
writing programs in it."
- Dennis Ritchie

Programmers are mostly "learn by doing"


types. No amount of academic study or
watching other people code can compare to
breaking open an editor and start making
mistakes.
Lecture 8: C Built-In Functions, & Solved Examples (1st Set)
Solved Examples on:
8.1 Algorithms; Pseudocode & Flowcharts

8.2 Variables in C, Long/Short Variables, sizeof() Function, Signed/Unsigned


Variables, Implicit Type Conversion & Explicit Type Conversion (Type Casting), &
bool.h
8.3 C Built-In Functions: Stdio.h, Math.h, & Stdlib.h

8.4 Operators and their Precedence (Assignment, Arithmetic, Bitwise, Logical,


Equality, & Relational)

8.5 Decisions (if – then, if – else, nested if, switch – case)


8.6 Loops (for .. while .. do – while .. nested loops)

8.7 Basic Programming Concepts using Scratch


Please pause the video and try to answer the question on your own!

8.36: What is the output of the following C program?

#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!

8.37: How many times will “Hello, World!" be printed on


the screen?
#include <stdio.h> a) 10
int main() b) 11
{ c) Infinite
int i = 1024; d) Syntax error
for(; i; i >>= 1)
printf("Hello, World!\n");
return 0;
}
8.37: How many times will “Hello, World!" be printed on
the screen?
#include <stdio.h> a) 10
int main() b) 11
{ c) Infinite
int i = 1024; d) Syntax error
for(; i; i >>= 1)
printf("Hello, World!\n"); ..10000000000 [True, 1st iteration]
return 0; ..01000000000
..00100000000
}
..00010000000
..00001000000
..00000100000
..00000010000
..00000001000
..00000000100
..00000000010
..00000000001 [True, 11th iteration]
..00000000000 [False]
Please pause the video and try to answer the question on your own!

8.38: How many times will "Good Day!" be printed on


the screen?
#include <stdio.h> a) 10 times
int main() b) 5 times
{ c) Infinite times
int i = -5; d) 0 times
while( i <= 5 )
{
if( i >= 0 ) break;
else
{
i++;
continue;
}
printf("Good Day!\n");
}
}
8.38: How many times will "Good Day!" be printed on
the screen?
#include <stdio.h> a) 10 times
int main() b) 5 times
{ c) Infinite times
int i = -5; d) 0 times
while( i <= 5 )
{ when ..
if( i >= 0 ) break; i == -5, continue will be executed
i == -4, continue will be executed
else
i == -3, continue will be executed
{ i == -2, continue will be executed
i++; i == -1, continue will be executed
continue; i == 0, break be executed
}
printf("Good Day!\n");
}
}
Please pause the video and try to answer the question on your own!

8.39: What is the output of the following C program?

#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!

8.40: What is the output of the following C program?

#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!

8.41: Write a C program to calculate the SUM OF THE FIRST


N NATURAL NUMBERS.
o This program will read the value of N (from the user), and then
calculates the sum from 1 to N (i.e., the sum of the first N natural
numbers).

Enter the value of N :100


Sum is = 4950
8.41: Write a C program to calculate the SUM OF THE FIRST
N NATURAL NUMBERS.

/*C program to calculate the sum of the first N natural numbers.*/


#include <stdio.h>
int main()
{
int n, i, sum;
printf("Enter the value of N :");
scanf("%d", &n);
sum = 0;
for( i = 1; i <= n; i++ )
sum += i;

printf("\n Sum is = %d", sum);


return 0;
}
Please pause the video and try to answer the question on your own!

8.42: Write a C program to FIND THE FACTORIAL of a


Number.
o In this program, we will read an integer number, and calculate its
factorial.

For Example:
o The Factorial of 5 is:
5! = 120 [ That is equivalent to 5*4*3*2*1 = 120 .. ]

Enter an integer number: 7


Factorial of 7 is = 5040
8.42: Write a C program to FIND THE FACTORIAL of a
Number.
/*C program to find factorial of a number.*/
#include <stdio.h>
int main()
{
int num, i;
long int fact;
printf("Enter an integer number: ");
scanf("%d", &num);
/*the product of the numbers from num to 1*/
fact = 1;
for( i = num; i >= 1; i-- )
fact = fact * i;
printf("\n Factorial of %d is = %ld", num, fact );
return 0;
}
Please pause the video and try to answer the question on your own!

8.43: Write a C program to check whether A NUMBER IS


POSITIVE, NEGATIVE, OR ZERO, until the user quits.

o This program will read an integer number, and check

whether the entered number is Positive, Negative, or Zero,

until the user quits.


Please pause the video and try to answer the question on your own!

Enter an integer number: 0


Number is ZERO.

Want to check again (press Y/y for 'yes’): Y


Enter an integer number: 1234
Number is POSITIVE.

Want to check again (press Y/y for 'yes’): Y


Enter an integer number :-345
Number is NEGATIVE.

Want to check again (press Y/y for 'yes’): y


Enter an integer number: 45
Number is POSITIVE.

Want to check again (press Y/y for 'yes') :N

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!

8.44: Write a C program to PRINT THE TABLE OF NUMBERS


from 1 to 20.

o This program will print the table of numbers from 1 to 20

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

print the table of corresponding numbers).


1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
11 22 33 44 55 66 77 88 99 110
12 24 36 48 60 72 84 96 108 120
13 26 39 52 65 78 91 104 117 130
14 28 42 56 70 84 98 112 126 140
15 30 45 60 75 90 105 120 135 150
16 32 48 64 80 96 112 128 144 160
17 34 51 68 85 102 119 136 153 170
18 36 54 72 90 108 126 144 162 180
19 38 57 76 95 114 133 152 171 190
20 40 60 80 100 120 140 160 180 4200
8
8.44: Write a C program to PRINT THE TABLE OF NUMBERS
from 1 to 20.
#include <stdio.h> //Program to print the table of numbers from 1 to 20
int main()
{
int i, j; // We’ll use i for the outer loop counter & j for the inner one
for( i = 1; i <= 20; i++ ) /*to print table 1 to 20*/
{ /*each number has 10 multiples*/
/*to initialize number with i ( 1 to 20)*/
for( j = 1; j <= 10; j++ )
{ /*values will be padded with 3 spaces*/
printf("%3d\t", ( i * j ) );
}
printf("\n"); /*after printing table of each number*/
}
return 0;
}
Please pause the video and try to answer the question on your own!

8.45: Write a C program to print a 'Full Pyramid' Pattern.

o In this C program, we are going to learn how to print a Full


pyramid using asterisks and loops. We are reading the total
number of rows and printing the Full pyramid accordingly.
#include<stdio.h>
int main() {
int a, b, c, l = 1, rows;
printf("Enter number of rows\t");
scanf( "%d", &rows );
for( a = 1; a <= rows; a++ ) // Parent or Outer Loop
{
for( b = rows; b >= a; b-- ) // Inner Loop, Prints Spaces
{
printf(" ");
}
for( c = 1; c <= l; c++ ) // Inner Loop, Prints Asterisks
{
printf("*");
}
l = l + 2; // Increments the number of asterisks by 2
printf("\n");
}
return 0;
}
Please pause the video and try to answer the question on your own!

8.46: Write a C function that displays an Integer in bits


using bitwise operators.

For example, if value = 5


5 = 00000000000000000000000000000101
8.46: Write a C function that displays an Integer in bits
using bitwise operators.
void bit_dis( int value ) { size = 32
int i; mask = 10000000000000000000000000000000
int size = 8 * sizeof( int );
unsigned int mask = 1 << size - 1;
printf( "%d = ", value );
for ( i = 0; i < size; i++ ) {
( value & mask ) ? putchar('1'): putchar('0');
mask = mask >> 1; // or mask >> = 1
}
putchar('\n');
} For example, if value = 5
5 = 00000000000000000000000000000101
int main (void)
{ int x; printf("Please Enter an integer value to be displayed in bits.");
scanf("%d", &x); bit_dis(x); return; }
Up Next ..
Always Section 8.7
Remember

"Any fool can write code that a computer can


understand. Good programmers write
code that humans can understand."
– M. Fowler (1999)
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 9: User-Defined Functions ..
& .. the Scope of Variables
9.1 An Introduction to Functions
▪ Why Functions? .. Why Copy-Paste Coding is Bad!
▪ An Overview of Functions & Why define your own functions?
▪ User-Defined vs. Built-in Functions
9.2 Functions’ Definitions & Functions’ Prototypes (Declarations)
9.3 Returning Values and Arguments’ Types
9.4 How Functions Work? Function Calls, Returns, & Local Variables
▪ Function Calls, & Parameters versus Arguments
▪ The Return Statement & Returning Void
▪ Local Variable(s)
9.5 Variables’ Scope & Global Variables
Why #include <stdio.h>
i n t main() {
Functions? i n t threePowerFour = 1 ;
f o r ( i n t i = 0 ; i < 4 ; i = i + 1)
{
threePowerFour = threePowerFour * 3;
Copy-Paste }
printf(" 3^4 i s % d \ n " , threePowerFour);
Coding i n t sixPowerFive = 1 ;
f o r ( i n t i = 0 ; i < 5 ; i = i + 1)
(bad!) {
sixPowerFive = sixPowerFive * 6;
}
printf(" 6^5 i s % d \ n " , sixPowerFive);
i n t twelvePowerTen = 1 ;
f o r ( i n t i = 0 ; i < 10; i = i + 1)
{
twelvePowerTen = twelvePowerTen * 12;
}
printf(" 12^10 i s % d \ n " , twelvePowerTen);
re t urn 0 ;
}
Why
Functions?

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.

o Functions can take inputs and outputs and


can be reused across programs.

o Organizing programs into functions helps to


organize and simplify code.

o This is an example of abstraction; after


you've written a function, you can use the
function without having to worry about the
details of how the function is implemented.
Because of abstraction, others can use (or
"call") the function without knowing its
6
lower-level details as well.
All programs you've written in C already have one function: main.
However, programs in C can have more functions as well.

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

The Divide & conquer


concept ..
Divide a large
program into
functions ..

C Standard Library User–Defined Functions


(Built-in functions)
E.g., scanf, printf, pow, .. etc.
Why define your own functions?
• Organization: Functions help to break up a complicated problem
into more manageable subparts and help to make sure concepts
flow logically into one another.
• Code reuse (Reusability): (1) Functions only need to be written
once, and then can be used as many times as necessary, so you
can avoid duplication of code. (2) Lets other people use algorithms
you’ve implemented.
• Maintainability: To change the algorithm, just change the function
(instead of changing it everywhere you ever used it).
• Simplification: Smaller components are easier to design, easier to
implement, and far easier to debug. Good use of functions makes
code easier to read and problems easier to isolate.
• Readability: sqrt(5) is clearer than copy-pasting in an algorithm to
compute the square root.
Why #include <stdio.h>

Functions? / * Some code which raises an a r b i t r a r y


in t e g e r t o an a r b i t r a r y power */
int raiseToPower( int base, int power ) {
int result = 1;
Instead .. for ( int i = 0; i < power; i = i + 1 )
Function
with a {
result = result * base; Declaration
function }
return result; }
i n t main() Function Invocation
{ ( Function Call )
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 ;
}
Up Next ..
Additional Section 9.2
Resources
▪ Introduction to Functions in C:
https://www.youtube.com/watch?v=3lqgdqoY83o

▪ C Programming Tutorial 15 - Using Functions in C


https://www.youtube.com/watch?v=AMU3xDnECsU
Lecture 9: User-Defined Functions ..
& .. the Scope of Variables
9.1 An Introduction to Functions
▪ Why Functions? .. Why Copy-Paste Coding is Bad!
▪ An Overview of Functions & Why define your own functions?
▪ User-Defined vs. Built-in Functions
9.2 Functions’ Definitions & Functions’ Prototypes (Declarations)
9.3 Returning Values and Arguments’ Types
9.4 How Functions Work? Function Calls, Returns, & Local Variables
▪ Function Calls, & Parameters versus Arguments
▪ The Return Statement & Returning Void
▪ Local Variable(s)
9.5 Variables’ Scope & Global Variables
A Function Definition
Here's an example of the structure of a function definition.
A function definition gives all the information that the compiler needs to
know about a function. It describes how the function should be used,
how its body should be translated into machine-readable language that
the computer can execute, and what operations the code in its body will
perform.

int cube(int input)


{
int output = input * input * input;
return output;
}
This function, cube(), takes an int as input and returns the cubed value
of that int.
We'll next cover the components of a function definition in more detail.
A Function Definition
A function definition has a header and a body.
function name Header
int cube(int input)
return type parameter list
{
int output = input * input * input;
return output;
} Body
The header always contains these parts:
• Return type; The type of value that the function will output. In our
example, it is int.
• Function name; The name that is used to call this function. In our example,
it is cube.
A Function Definition
A function definition has a header and a body.
function name Header
int cube(int input)
return type parameter list
{
int output = input * input * input;
return output;
} Body
The header always contains these parts:
• Parameter list; The parameters are the types of arguments the function expects as
input, and the names by which the function will refer to those inputs. cube() takes
an int as its only argument, and this int will be referred to as input in the
function's body. Note that the parameter's list can be empty (indicating that the
function doesn't expect any arguments).
A Function Definition
A function definition has a header and a body.
function name Header
int cube(int input)
return type parameter list
{
int output = input * input * input;
return output;
} Body
The body is the code within the curly braces that is executed when the function is
called.
• It's important to remember that variables declared in the body of a function are
local in scope to that function and cannot be used in other functions!
• One or more of the statements in the function's body can be return statements. A
return statement ends the execution of the function and passes the return value back
to the function that called it.
A Function Definition
Other examples of function headers.

means for communicating


information between functions ..

Output from function Inputs to function


(return-value type) Function name
(parameter list)

int sum2int (int , int) { ……. }


double average2 ( float, float) { ……. }
#include <stdio.h>
An Example
int raiseToPower( int base, int power ) {
Function
int result = 1;
Declaration
for ( int i = 0; i < power; i = i + 1 )
{
result = result * base;
}
return result; }

int main() Function Invocation


{ ( Function Call )
int threePowerFour = raiseToPower( 3, 4 );
printf( "3^4 is %d", threePowerFour );
int sixPowerFive = raiseToPower( 6, 5 );
printf( "6^5 is %d", sixPowerFive );
int twelvePowerTen = raiseToPower( 12, 10 );
printf( "12^10 is %d", twelvePowerTen );
return 0;
}
Function Definition Syntax; An Example

Function name

i n t raiseToPower( i n t base, i n t power )


{
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

Return Type

i n t raiseToPower( i n t base, i n t power )


{
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

Parameter 1

i n t raiseToPower( i n t base, i n t power )


{
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;
}

• Parameters order matters:


– r a i s e To P o w e r ( 2 , 3 ) i s 2 ^ 3 = 8
– r a i s e To P o w e r ( 3 , 2 ) i s 3 ^ 2 = 9
Function Definition Syntax; An Example

Parameter 2

i n t raiseToPower( i n t base, i n t power )


{
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;
}

• Parameters order matters:


– r a i s e To P o w e r ( 2 , 3 ) i s 2 ^ 3 = 8
– r a i s e To P o w e r ( 3 , 2 ) i s 3 ^ 2 = 9
Function Definition Syntax; An Example

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

i n t raiseToPower( i n t base, i n t power )


{
i n t result = 1;
f o r ( i n t i = 0; i < power; i = i+ 1 )
{
Body result = result * base;
}
r e t u r n result;
}
Function Definition Syntax; An Example

i n t raiseToPower( i n t base, i n t power )


{
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;
}
Return Statement
Function Definition
• Function definitions need to occur before
invocations.

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:

i n t square( int ); i n t sq u are( i n t x ) ; i n t sq u are( i n t z ) ;

i n t cube( int x ) i n t cube( int x ) i n t cube( int x )


{ { {
r e t u r n x*square(x); r e t u r n x*square(x); r e t u r n x*square(x);
} } }

i n t square( int x ) i n t square( int x ) i n t square( int x )


{ { {
return x*x; return x*x; return x*x;
} } }
Up Next ..
Additional Section 9.3
Resources
▪ C Programming Tutorial 88 - Function Design
https://www.youtube.com/watch?v=NuRE91IDe-8

▪ Function Definition in C
https://www.youtube.com/watch?v=gF7wjwM9Jjs

▪ Function Declaration in C
https://www.youtube.com/watch?v=5wAf9nzX2R8

▪ C Programming Tutorial 90 - How to Create a


Function (Functions Part 1)
https://www.youtube.com/watch?v=DbR-0GfnQOs
Lecture 9: User-Defined Functions ..
& .. the Scope of Variables
9.1 An Introduction to Functions
▪ Why Functions? .. Why Copy-Paste Coding is Bad!
▪ An Overview of Functions & Why define your own functions?
▪ User-Defined vs. Built-in Functions
9.2 Functions’ Definitions & Functions’ Prototypes (Declarations)
9.3 Returning Values and Arguments’ Types
9.4 How Functions Work? Function Calls, Returns, & Local Variables
▪ Function Calls, & Parameters versus Arguments
▪ The Return Statement & Returning Void
▪ Local Variable(s)
9.5 Variables’ Scope & Global Variables
Returning a Value
• Up to one value may be returned; it must be
the same type as the return type.

For example:

i n t foo()
{
r e t u r n "hello"; // error
}

On the other hand:

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 );
}

Consider the following function invocations?


• printOnNewLine( 3 )
• printOnNewLine("hello")

Will anyone of them result in an error?


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 );
}

Consider the following function invocations?


• printOnNewLine( 3 )
• printOnNewLine('A')

Will anyone of them result in an error?


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 );
}

• 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

▪ C Programming Tutorial - 57 - Return Values


https://www.youtube.com/watch?v=ye2tvFir65g
Lecture 9: User-Defined Functions ..
& .. the Scope of Variables
9.1 An Introduction to Functions
▪ Why Functions? .. Why Copy-Paste Coding is Bad!
▪ An Overview of Functions & Why define your own functions?
▪ User-Defined vs. Built-in Functions
9.2 Functions’ Definitions & Functions’ Prototypes (Declarations)
9.3 Returning Values and Arguments’ Types
9.4 How Functions Work? Function Calls, Returns, & Local Variables
▪ Function Calls, & Parameters versus Arguments
▪ The Return Statement & Returning Void
▪ Local Variable(s)
9.5 Variables’ Scope & Global Variables
Let's put everything together now!
We've got our familiar main()
function which calls cube() using
#include <stdio.h> the function's name and the argument
int cube(int input); we want to pass. Note that here the
argument to cube() happens to be
int main(void) a variable, but more generally
{ arguments can be constants or other
int x = 2; expressions.
printf("x is %d\n", x);
x = cube(x);
printf("x is %d\n", x);
}

int cube(int input)


{
int output = input * input * input;
return output;
}
But what is that line above main() that
we've highlighted in yellow? This is called
a function prototype. As you can see, the
#include <stdio.h> function prototype matches the header of
int cube(int input); the function definition except that it ends
with a semicolon.
int main(void)
{
int x = 2;
printf("x is %d\n", x);
x = cube(x);
printf("x is %d\n", x);
}

int cube(int input)


{
int output = input * input * input;
return output;
}
Why do we need this prototype
before main()? The function prototype
lets us get away with calling a function
#include <stdio.h> when the compiler hasn't yet seen the
int cube(int input); function's full definition (the C compiler
reads from top to bottom) by providing
int main(void) the function’s type signature.
{
int x = 2;
printf("x is %d\n", x); In other words, the function
x = cube(x); prototype defines what
printf("x is %d\n", x); variable types the function
accepts as input and returns
}
as output so that the compiler
understands how the function
int cube(int input) should be used in main().
{
int output = input * input * input;
return output;
}
If you removed the prototype, you'd
get a compiler error "implicit
declaration of function 'cube' is invalid
#include <stdio.h> in C99". So, you have two choices: (1)
int cube(int input); move the definition of cube() above the
definition of main(), or (2) declare a
int main(void) function prototype for cube() above
{ main() as we did in this slide.
int x = 2;
printf("x is %d\n", x);
x = cube(x);
printf("x is %d\n", x);
}

int cube(int input)


{
int output = input * input * input;
return output;
}
Let's make sure you understand how
these functions are represented in
memory:

At the top of the program's memory is the


text segment, which contains the actual 0's
and 1's that make up your program. The
sections for initialized and uninitialized
data are used for storing global variables if
your program has any.

Most of a program's memory is reserved


for the stack and heap. We won't talk
about the heap today, but the stack
consists of chunks of memory piled on top
of each other. Just like the stack of trays in
the dining hall, the stack of a program
requires that the one on top be taken off
before any of the others can be taken off.
Let's zoom in on the stack.

The memory at the bottom of the stack is


first used for main(). Any functions
that main() calls have their memory
stacked on top, so we see our function
cube() right above main(). As functions
return, their chunks of memory are popped
off the stack.

The important function implication for us is


cube()'s locals that when main() calls cube(), cube()
creates copies of the variables passed to
cube()'s parameters it which are stored in cube()’s stack
frame. We'll see in the next example why
main()'s locals this is such a big deal.

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);
}

void swap(int a, int b)


{
int tmp = a;
a = b;
b = tmp;
}
Why doesn't this work?
#include <stdio.h> Well, swap() has made copies
of x and y in a different stack frame and
void swap(int a, int b);
is calling those copies a and b. Whatever
operations swap() performs on a and b
int main(void) have no bearing on our original x and
{ y variables in main()'s stack frame.
int x = 1; Discuss ways to fix this program!
int y = 2;
swap(x, y);
printf("x is %d\n", x);
printf("y is %d\n", y);
}

void swap(int a, int b)


{
int tmp = a;
a = b;
b = tmp;
}
#include <stdio.h>
void swap(int a, int b);

int main(void)
{
int x = 1;
int y = 2;
swap(x, y);
}

void swap(int a, int b)


{
int tmp = a;
a = b;
b = tmp;
printf("x is %d\n", a);
printf("y is %d\n", b);
}
Function Calls
Function
call
returns

Caller 1
6
Caller Called fn.
2
5
Called fn. 4
3

 Caller or Calling function


Function Calls
main ( ) {
funct1( );
..
}

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 }

int main (void) {


int x;
printf("Please enter the number");
scanf ("%d", &x);
square (x) ;
return 0;
}
the Return Statement
o If function doesn’t return a value (i.e. return-type-value is void)
o Return statement can be omitted or
o Execute return;

o If function does return a value, the statement:


o return expression;
o returns the value of expression to the caller.

o Main’s return type


o return 0; indicates that program terminates successfully.

o In C standard, the main implicitly returns 0 when terminated,


thus, the return statement can be omitted.
o You can explicitly return non-zero values from main to
indicate that a problem occurred during execution.
.. a program with Three Functions
.. the Square & Cube Functions

#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

int Square( int n )


{
int s; Local variables;
s = n * n; known only in this function
return s;
}

int Cube( int n )


{ Local variables;
int c = n * n * n ; known only in this function
return c;
}
Trace the following program, which uses a function square to
calculate and print the squares of the integers from 1 to 10:

#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

▪ C Programming Tutorial - 56 - Passing Arguments to


Functions
https://www.youtube.com/watch?v=_oyuKw3vBf8
Lecture 9: User-Defined Functions ..
& .. the Scope of Variables
9.1 An Introduction to Functions
▪ Why Functions? .. Why Copy-Paste Coding is Bad!
▪ An Overview of Functions & Why define your own functions?
▪ User-Defined vs. Built-in Functions
9.2 Functions’ Definitions & Functions’ Prototypes (Declarations)
9.3 Returning Values and Arguments’ Types
9.4 How Functions Work? Function Calls, Returns, & Local Variables
▪ Function Calls, & Parameters versus Arguments
▪ The Return Statement & Returning Void
▪ Local Variable(s)
9.5 Variables’ Scope & Global Variables
Scope: Global Variables

How many times is function foo() called?


Use a global variable to determine this.
– Can be accessed from any function

i n t numCalls = 0; Global Variable

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

int int int int


base int result num1 int result
exponent num2
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; At A, variables marked in
int result = 1; red are in scope ..
for ( int i = 0; i < exponent; i++ )
{
result = result * base;
} //A
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

int int int int


base int result A num1 int result
exponent num2
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; At B, variables marked in
int result = 1; red are in scope ..
for ( int i = 0; i < exponent; i++ )
{
result = result * base;
} //A
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 ; } / / B
return r e s u l t ;
}
raiseToPower function scope max function scope

int int int int


base int result num1 int result B
exponent num2
double squareRoot( double num ) { Loops and if / else statements also have their
double low = 1.0; own scopes. That is, Loop counters are in the
double high = num; same scope as the body of the for loop.
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
}
else {
double newLow = estimate; for loop scope
low = newLow; double
} int i estimate
}
return ( high + low ) / 2;
}
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;
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

2) Write a program in C which incorporates a function


that performs the addition of three numbers. The
main function of the program is to read the numbers
and print the result.

3) Write a C function that takes a positive integer n as


an argument and returns 1 if n is prime, and 0
otherwise.
Exercises
What have we learned?
4) Write a C function that takes in three arguments, a start temperature (in Celsius), an end
temperature (in Celsius), and a step size. Print out a table that goes from the start
temperature to the end temperature, in steps of the step size; you do not actually need
to print the final end temperature if the step size does not exactly match. You should
perform input validation: do not accept start temperatures less than a lower limit (which
your code should specify) or higher than an upper limit (which your code should also
specify). You should not allow a step size greater than the difference in temperatures.
Sample run:
Please enter a lower limit, limit >= 0: 10
Please enter a higher limit, 10 > limit <= 100: 20
Please enter a step size, 0 < step <= 10: 4
Celsius Fahrenheit
---------- ----------
10.000000 50.000000
14.000000 57.200000
18.000000 64.400000
Exercises
What have we learned?
5) Write a C function that finds the sum of all even numbers from 0 to 20.
6) Write a C function that accepts a char as input and returns true if the char is a
digit from 0 to 9 or false if the character is not a digit from 0 to 9.
7) Write a C program - with functions - that will display the calculator menu (see
the sample below). The main function will prompt the user to choose the
operation choice (from 1 to 5). Then it asks the user to input two integer values
for the calculation. Based on the operation choice, the main function calls the
appropriate function (Add, Subtract, …) and passes to it the two integers. After
the result is printed, the program also asks the user to decide whether s(he)
wants to continue the operation. If he/she input ‘y’, the program will prompt
the user to choose the operation again. Instead, the program will terminate.
MENU: 1. Add 2. Subtract 3. Multiply 4. Divide 5. Modulus
Enter your choice: 1
Enter your two numbers: 12 15
Result: 27
Continue? y
Up Next ..
Additional Lecture 10
Resources
▪ Scope of Variables - Local vs Global
https://www.youtube.com/watch?v=elMQ5YtZPxA

▪ C Programming Tutorial - 55 - Global vs Local Variables


https://www.youtube.com/watch?v=sAj_Jrqrg5g
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Lecture 10 Helwan University

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
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
Everything that goes on under the hood of a computer is done in
binary; the language of 0s and 1s.

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:

To represent the number 163, we've got a 3 in the 1s place (100), a 6


in the 10s place (101), and a 1 in the 100s place (102).

1 6 3
102 101 100

You get 163 when you multiply these digits by their respective
powers of 10 and sum them.

1*102 + 6*101 + 3*100 = 163


Decimal Numbers
“decem” (Latin) ► ten
✓ Base or Radix is 10
✓ Digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Least Significant
So, .. Digit
7329

= 7000 + 300 + 20 + 9
= 7*103 + 3*102 + 2*101 + 9*100
Coefficient Base Weight
0-9 or
Radix

The convention is to write only the coefficient and from


their positions deduce the necessary powers of 10.
Decimal Numbers
General Formula?
E.g., The decimal number 26.75 is represented as:
26.75
=2*101 + 6*100 + 7*10-1 + 5*10-2

In general, a number expressed in base r ,is represented as:

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.

1*27 + 0*26 + 1*25 + 0*24 + 0*23 +


0*22 + 1*21 + 1*20 = 163
Binary Data Representation:

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?

1) Convert the following binary numbers to decimal:


a) 1010
b) 11001
c) 10000
Up Next ..
Additional Section 10.2
Resources
▪ The Basics of Binary For Kids & Conversion to Decimal
(Under 3 minutes):
https://www.youtube.com/watch?v=2Z03p3yhGmk

▪ Binary Numbers for Kids | Convert Decimal to Binary |


Computers for Kids:
https://www.youtube.com/watch?v=hvteVokz7jE

▪ Binary Numbers and Base Systems as Fast as Possible:


https://www.youtube.com/watch?v=LpuPe81bc2w
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
Useful Number Systems
(in Computer Science):

System Base Symbols


Decimal 10 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Binary 2 0, 1
Octal 8 0, 1, 2, 3, 4, 5, 6, 7
Hexadecimal 16 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

More Systems ..?!


.. this is system
• Base 36: 0 1 2 .. 9 A B C .. X Y Z
Alphanumeric ..
• Base 62: 0 1 2 .. 9 A B C .. X Y Z a b c .. x y z
Very concise, for example:
zzzz62 ≡ 14,776,33610 .. and .. zzzzzzzzzz62 ≡ 839,299,365,868,340,22310
Can be used (for instance) in URL shortening; a technique on the
World Wide Web in which a Uniform Resource Locator (URL) may be
made substantially shorter and still direct to the required page.
Numbers with different bases:
Decimal (Base 10) Binary (Base 2) Octal (Base 8) Hexadecimal (Base 16)

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

A number expressed in base r can be converted to its


decimal equivalent by multiplying each coefficient with
the corresponding power of r and adding.
CONVERSION: Binary to Decimal
• Base or Radix is 2 (“binarius” in Latin ► two)
• Digits: 0, 1
• Example: 11001
2

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

To convert from decimal to other base-r systems, the


number is divided to:
• Integer part ► successive division
• Fraction part ► successive multiplication
CONVERSION: Decimal to Binary (Integer Part)
• Conversion of 2510 to binary

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

Stop when the fraction becomes 0


CONVERSION: Decimal to Binary (Fraction Part)
Example 2: Decimal → Binary

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.

• This process is continued until the number of digits have


sufficient accuracy.
CONVERSION: Decimal to Octal (Fraction Part)
Example 3: Decimal → Octal
CONVERSION: Integer Part versus Fraction Part)

( Integer Part . Fraction Part )?( = 10)r

= ( Integer Part Conversion . Fraction Part Conversion )r

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

• 23 = 8 ➔ Octal digit = 3 binary digits

10110001101011.1111000001102 = ?8

10 110 001 101 011 . 111 100 000 110

2 6 1 5 3 7 4 0 6

= 26153.74068
CONVERSION: between Number Systems
Example 2: Binary → Hexadecimal

• 24 = 16 ➔ Hexadecimal digit = 4 binary digits

10110001101011.111100102 = ?16

10 1100 0110 1011 . 1111 0010

2 C 6 B F 2

= 2C6B.F216
CONVERSION: between Number Systems
Example 3: Octal → Binary

7058 = ?2

7 0 5

111 000 101

= 1110001012
CONVERSION: between Number Systems
Example 4: Hexadecimal → Binary

10AF16 = ?2

1 0 A F

0001 0000 1010 1111

= 00010000101011112
CONVERSION: between Number Systems
Example 5
CONVERSION: between Number Systems
Example 6: Octal → Hexadecimal

10768 = ?16

1 0 7 6

001 000 111 110

2 3 E

= 23E16
CONVERSION: between Number Systems
Example 7: Hexadecimal → Octal

1F0C16 = ?8

1 F 0 C

0001 1111 0000 1100

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

▪ How To Convert Decimal to Binary:


https://www.youtube.com/watch?v=rsxT4FfRBaM

▪ Number Systems Introduction - Decimal, Binary, Octal,


Hexadecimal & BCD Conversions:
https://www.youtube.com/watch?v=L2zsmYaI5ww
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
Binary
Arithmetic
Binary Arithmetic.. the Addition
Binary Arithmetic.. the Multiplication

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.

Or .. You may use Long Division;


Binary Logic
& ..
Truth Tables.
Binary Logic
the Truth Tables of Logical Operations
Logical AND Logical OR Logical XOR
x y x y x y
(x ˄ y) (x ˅ y) (Exclusive OR)
XOR( x, y)
0 0 0 0 0 0
0 0 0
0 1 0 0 1 1
0 1 1
1 0 0 1 0 1
1 0 1
1 1 1 1 1 1
1 1 0
Logical NAND Logical NOR
x y Negated AND x y Negated OR
NAND( x, y) NOR( x, y) Logical NOT
x
0 0 1 0 0 1 Negation ⌐x
0 1 1 0 1 0 0 1
1 0 1 1 0 0 1 0
1 1 0 1 1 0
Exercises
What have we learned?
1) Perform the binary addition of: 3) Write a program that reads a number
a) 11 + 11 and its base, then asks the user what
is the base to which (s)he wants it to
b) 1001 + 110 be converted to. It should then print
c) 10001 + 1111 the number converted to the new
d) 111001 + 11111 base.
e) 11111 + 11111 4) Derive the truth tables for the
2) Perform the binary subtraction of: following expressions:
a) 10011 - 10001 a) NOT (A OR B)
b) 101000 – 1001 b) A OR (B AND C)
c) 10001 - 1111 c) (NOT A) OR B
d) 111001 - 11111 d) (A NAND B) AND C
e) 1001 - 110 e) (NOT A) AND (A OR (NOT B))
Up Next ..
Additional Section 10.4
Resources
▪ How To Add Binary Numbers - The Easy Way!:
https://www.youtube.com/watch?v=5F6orbqZigI

▪ How To Subtract Binary Numbers:


https://www.youtube.com/watch?v=OHf0Eg9ZhGQ

▪ Multiplying Binary Numbers:


https://www.youtube.com/watch?v=Va_UvwJULcI

▪ Dividing Binary Numbers:


https://www.youtube.com/watch?v=ubCCemtuZH8

▪ 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?

o Because the direct method of subtraction that uses the

borrow concept can’t be implemented with digital

hardware.

o So, computers do subtraction using complements.


Complements
r's complement [Radix Complement] (r - 1)'s complement [Diminished Radix
Complement]
10’s Complement 9’s Complement
…….…………………………………………… …….……………………………………………..
= 9’s Complement + 1 = (rn – 1) – N
Decimal

For example, if given number N = For example, if given number N = 1234,


1234, thus n = 4 digits, then: thus n = 4 digits, then:
9999 – 1234 = 8765 + 1 = 8766 9999 – 1234 = 8765
….... OR …....
= rn – N
10000 – 1234 = 8766
2’s Complement 1’s Complement
…….…………………………………………….. …….……………………………………………..
= 1’s Complement + 1 = (rn – 1) – N
For example, if given number N = For example, if given number N = 1010,
Binary

1010, thus n = 4 bits, then: thus n = 4 bits, then:


1111 – 1010 = 0101 + 1 = 0110 1111 – 1010 = 0101
……. OR ….... ….... OR …....
= rn – N toggle 1’s to 0’s and 0’s to 1’s
59
10000 – 1010 = 0110
Decimal Subtraction using Complements
Decimal Subtraction using 9’s Complement:
1823 – 1596 = ?
• The 9’s complement of the subtrahend: 9999 – 1596 = 8403
• 1823 + 8403 = 10226 ► (add the final carry) ► 227
5027 – 6281 = ?
• The 9’s complement of the subtrahend: 9999 - 6281 = 3718
• 5027 + 3718 = 8745 ► (no final carry, thus it’s a negative number “a 9's
complement”) ► [9999 – 8745 = 1254] ► – 1254

Decimal Subtraction using 10’s Complement:


2058 – 1729 = ?
• The 10’s complement of the subtrahend: 9999 – 1729 = 8270 + 1 = 8271
• 2058 + 8271 = 10329 ►(discard the final carry) ► 329
7398 – 9207 = ?
• The 10’s complement of the subtrahend: 9999 – 9207 = 792 + 1 = 793
• 7398 + 793 = 8191 ► (no final carry, thus it’s a negative number “a 10's
complement”) ► [9999 – 8191 = 1808 + 1 = 1809] ► – 1809 60
But .. What does the complements
approach do? Why it works?!
o Let’s try an example, 5010 – 510 = 4510

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

▪ Binary Subtraction using 1's Complement


https://www.youtube.com/watch?v=kx8DFNf6pQU

▪ Binary Subtraction using 2's Complement


https://www.youtube.com/watch?v=L_m7jBvtzpQ
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Lecture 11 Helwan University

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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
Lecture 11: Recursion, Function Overloading, .. & ..
Pass-by-Value versus Pass-by-Reference
11.1 An Introduction to Recursion
▪ Recursion & Recursive Functions
▪ Base Case (Recursion without a Base Case?)
▪ 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-Value


▪ Function Overloading
▪ Passing Arguments; Pass (Call) by-Value versus Pass (Call) by-Reference
▪ Returning Multiple Values
Recursion
Recursion is a programming concept whereby a function (code)
invokes (calls) itself.

Input Output

Recursion is typically used to solve problems that are decomposable into


sub-problems that are just like the original problem, but a step closer to
being solved.
Recursion without a Base Case
Here’s a recursive function called foo.
What happens when this function is called?

void foo( string str )


{
printf(“%s\n”, str );
foo( str );
}
foo will print a string and call itself, which will print
another string and call itself again, which will print
another string and call itself yet again .. and on and
on infinitely.

However, every time a function is called, some space


is set aside in the stack called a frame and every
function call results in a new frame being created.
Recursion without a Base Case
So, if foo calls itself infinitely, we’ll eventually run out
of stack memory and try to access memory

void foo( string str )


{
printf(“%s\n”, str );
foo( str );
}
that doesn’t belong to us, in which case our program
will fail with a segmentation fault.

To avoid this situation, we need to make sure there’s


always a way to break out of recursive calls -- we’ll call
this the base case. When the base condition is met,
the function should return without making a recursive
call. Let’s make sure we have a base case in the next
example :)
What is the simplest possible solution?
.. a Base Case ..

o The base-case is the simplest possible case, where we

know the answer.

o The base-case is the only case where we can provide an

explicit straightforward answer.

o When triggered, the base-case stops the recursive

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:

unsigned int factorial(unsigned int n) {


if (n <= 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
• factorial(3) returns 3 * factorial(2)
• factorial(2) returns 2 * factorial(1)
• factorial(1) is the base case and returns 1
Once the base case is reached, all of the factorial() calls will
return in succession to give us an answer of 6.

factorial(3) = 3 * factorial(2)

2 * factorial(1)

Let’s see what’s going on in the stack as this recursive function


executes!
Let’s zoom in on the stack as this function executes:
• main() calls factorial(3)

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 ( )

factorial(2) is now the active frame.


• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

heap

factorial ( 1 )
factorial ( 2 )
factorial ( 3 )

stack main ( )

factorial(1) is now the active frame.


• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

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 ( )

• factorial(1) returns 1 to factorial(2)


• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

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 ( )

• factorial(1) returns 1 to factorial(2)


• factorial(2) multiplies 1 * 2 and returns 2 to factorial(3)
• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

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.

Nice! Our function


calculated the correct
6 answer!
3! = 3 * 2 * 1 = 6
stack main ( )

• factorial(1) returns 1 to factorial(2)


• factorial(2) multiplies 1 * 2 and returns 2 to factorial(3)
• factorial(3) multiplies 2 * 3 and returns 6 to main()
Up Next ..
Additional Section 11.2
Resources
▪ 5 Simple Steps for Solving Any Recursive Problem:
https://www.youtube.com/watch?v=ngCos392W4w

▪ Recursion:
https://www.youtube.com/watch?v=mz6tAJMVmfM

▪ Recursion (Think Like a Programmer):


https://www.youtube.com/watch?v=oKndim5-G94

▪ Recursion for Beginners: A Beginner's Guide to


Recursion:
https://www.youtube.com/watch?v=AfBqVVKg4GE
Lecture 11: Recursion, Function Overloading, .. & ..
Pass-by-Value versus Pass-by-Reference
11.1 An Introduction to Recursion
▪ Recursion & Recursive Functions
▪ Base Case (Recursion without a Base Case?)
▪ 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-Value


▪ Function Overloading
▪ Passing Arguments; Pass (Call) by-Value versus Pass (Call) by-Reference
▪ Returning Multiple Values
Fibonacci Numbers/Sequence
In mathematics, the Fibonacci numbers, form a sequence, called
the Fibonacci sequence, such that each number is the sum of
the two preceding ones, starting from 0 and 1. That is,
F0 = 0, F1 = 1,
.. and ..
Fn = Fn-1 + Fn-2 (for n > 1)

The beginning of the sequence is thus: 0, 1, 1, 2, 3, 5, 8, 13, 21,


34, 55, 89, 144, ..

In some older books, the value F0 = 0 is omitted, so that the


sequence starts with F1 = F2 = 1, and the recurrence Fn = Fn-1 +
Fn-2 is valid for n > 2 .. thus: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, ..
Fibonacci Numbers/Sequence
Fibonacci Numbers/Sequence

fib( n ) = fib( n - 1 ) + fib( n - 2 ) ..


.. can be easily expressed via a recursive
implementation.

How?
Fibonacci Numbers/Sequence

fib( n ) = fib( n - 1 ) + fib( n - 2 ) ..


.. can be easily expressed via a recursive
implementation.
i n t fibonacci( int n )
{
i f (n == 0 || n == 1)
{
r e tu rn n ;
}
else
{
r e tu rn f i b o n a c c i ( n – 2 ) + f i b o n a c c i ( n – 1 ) ;
}
}
Fibonacci Numbers/Sequence

fib( n ) = fib( n - 1 ) + fib( n - 2 ) ..


.. can be easily expressed via a recursive
implementation.
i n t fibonacci( int n )
{
i f (n == 0 || n == 1)
{
r e t u rn n ; base case
}
else
{
r e tu rn f i b o n a c c i ( n – 2 ) + f i b o n a c c i ( n – 1 ) ;
}
}
Fibonacci Numbers/Sequence

fib( n ) = fib( n - 1 ) + fib( n - 2 ) ..


.. can be easily expressed via a recursive
implementation.
i n t fibonacci( int n )
{
i f (n == 0 || n == 1)
{
r e tu rn n ;
}
else
{
r e t u rn f i b o n a c c i ( n – 2 ) + f i b o n a c c i ( n – 1 ) ;
}
}
OUTPUT
Enter the number of terms in the series : 15
The Fibonnaci Series : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

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:

1) Subtraction-based 2) Using a mod 3) The recursive version


version operation to calculate if b = 0
(Euclid's original the remainder & a return a
version) temporary variable else
function gcd(a, b) function gcd(a, b) return gcd(b, a mod b)
while a ≠ b while b ≠ 0
if a > b t=b
a=a−b b = a mod b
else a=t
b=b−a return a
return a
Euclidean Algorithm
Computing the Greatest Common Divisor 'GCD'
Trace the 3 implementations using the following values: a = 80, & b = 20:
1) gcd( a = 80, b = 20)
while a ≠ b  .. if a > b  .. a = a − b (a = 80 – 20 = 60)
while a ≠ b  .. if a > b  .. a = a − b (a = 60 – 20 = 40) 1) Subtraction-based
while a ≠ b  .. if a > b  .. a = a − b (a = 40 – 20 = 20) version (Euclid's
original version)
while a ≠ b  .. return a (return 20) function gcd(a, b)
while a ≠ b
if a > b
a=a−b
else
b=b−a
return a
Euclidean Algorithm
Computing the Greatest Common Divisor 'GCD'
Trace the 3 implementations using the following values: a = 80, & b = 20:
2) gcd( a = 80, b = 20)
while b ≠ 0  .. t = b (t = 20) .. b = a mod b (b = 80 % 20 = 0) .. a = t (a = 20)
while b ≠ 0  .. return a (return 20)
2) Using a mod operation
to calculate the remainder
& a temporary variable
function gcd(a, b)
while b ≠ 0
t=b
b = a mod b
a=t
return a
Euclidean Algorithm
Computing the Greatest Common Divisor 'GCD'
Trace the 3 implementations using the following values: a = 80, & b = 20:
3) gcd( a = 80, b = 20)
if b = 0  .. return gcd(b, a mod b) (return gcd( 20, 80 % 20))
.. gcd( a = 20, b = 0)
if b = 0  .. return a (return 20)

3) The recursive version


if b = 0
return a
else
return gcd(b, a mod b)
Up Next ..
Exercises Section 11.3
What have we learned?
1) Trace the 3 varying implementations of the GCD
algorithm using the following the values:

a) a = 100, & b = 20

b) a = 11, & b = 77

2) Rewrite the Fibonacci Algorithm using a loop (with


no recursion), and then compare between both
algorithms.
Lecture 11: Recursion, Function Overloading, .. & ..
Pass-by-Value versus Pass-by-Reference
11.1 An Introduction to Recursion
▪ Recursion & Recursive Functions
▪ Base Case (Recursion without a Base Case?)
▪ 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-Value


▪ Function Overloading
▪ Passing Arguments; Pass (Call) by-Value versus Pass (Call) by-Reference
▪ Returning Multiple Values
Function Overloading
• Many functions with the same name, but
different arguments.
• The function called is the one whose arguments
match the invocation.
For example:
void printOnNewLine( int x )
{
printf( " I n t e g e r : % d " , x );
}
void printOnNewLine( char x )
{
printf( " C h a r a c t e r : % c " , x );
}

• printOnNewLine( 3 ) prints “Integer: 3”


• printOnNewLine('A' ) prints “Character: A”
Function Overloading
• Many functions with the same name, but
different arguments.
• The function called is the one whose arguments
match the invocation.
For example:
void printOnNewLine( int x )
{
printf( " O n e I n t e g e r : % d " , x );
}
void printOnNewLine( int x , i n t y )
{
printf( " T w o I n t e g e r s : % d , % d " , x, y );
}

• printOnNewLine( 3 ) prints “One Integer: 3”


• printOnNewLine( 4, 5 ) prints “Two Integers: 4,5”
The C language is pass-by-value without exception.

Pass-by-value versus Pass-by-reference


• So far, w e’ve been passing everything by value –
makes a copy of the variable; changes to the
variable within the function don’t occur outside
the function.
For example: What should be the output?

/ / 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 versus Pass-by-reference


• So far, w e’ve been passing everything by value –
makes a copy of the variable; changes to the
variable within the function don’t occur outside
the function.
For example: What should be the output?

/ / 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.

Pass-by-value versus Pass-by-reference


Main Function Scope

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.

Pass-by-value versus Pass-by-reference


Main Function Scope Increment Function
Scope

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.

Pass-by-value versus Pass-by-reference


Main Function Scope Increment Function
Scope

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-value versus Pass-by-reference


• If you w ant to modify the original variable as
opposed to making a copy, pass the variable by
reference (int &a instead of int a).

For example: What should be the output?

/ / 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-value versus Pass-by-reference


• If you w ant to modify the original variable as
opposed to making a copy, pass the variable by
reference (int &a instead of int a).

For example: What should be the output?

/ / 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).

Pass-by-value versus Pass-by-reference


Main Function Scope

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).

Pass-by-value versus Pass-by-reference


Main Function Scope Increment Function
Scope

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).

Pass-by-value versus Pass-by-reference


Main Function Scope Increment Function
Scope

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).

Implementing a Swap Function

void swap( int &a, int &b )


{
int temp = a;
a = b;
b = temp;
}

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).

Implementing a Swap Function


Main Function Scope

void swap( int &a, int &b )


{
q=3 r=5
int temp = a;
a = b;
b = temp;
}

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).

Implementing a Swap Function


Main Function Scope

void swap( int &a, int &b ) / / HERE


{
q=3 r=5
int temp = a;
a = b;
b = temp;
}

int main() Swap Function Scope


{
int q = 3;
int r = 5; a b
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).

Implementing a Swap Function


Main Function Scope

void swap( int &a, int &b )


{
q=3 r=5
int temp = a; / / HERE
a = b;
b = temp;
}

int main() Swap Function Scope


{
int q = 3;
int r = 5; temp
a b
swap( q, r ); =3
printf( "q %d", q ); // q 5
printf( "r %d", r ); // r 3
}
This is pass-by-reference in C++ (won't work in C).

Implementing a Swap Function


Main Function Scope

void swap( int &a, int &b )


{
q=5 r=5
int temp = a;
a = b; / / HERE
b = temp;
}

int main() Swap Function Scope


{
int q = 3;
int r = 5; temp
a b
swap( q, r ); =3
printf( "q %d", q ); // q 5
printf( "r %d", r ); // r 3
}
This is pass-by-reference in C++ (won't work in C).

Implementing a Swap Function


Main Function Scope

void swap( int &a, int &b )


{
q=5 r=3
int temp = a;
a = b;
b = temp; / / HERE
}

int main() Swap Function Scope


{
int q = 3;
int r = 5; temp
a b
swap( q, r ); =3
printf( "q %d", q ); // q 5
printf( "r %d", r ); // r 3
}
This is pass-by-reference in C++ (won't work in C).

Returning Multiple Values


• The return statement only allow s you to return 1
value. Passing output variables by reference
overcomes this limitation.

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

• C does not support passing a variable by


reference.
• In C, Pass-by-reference is simulated by
passing the address of a variable (a pointer)
and dereferencing that address within the
function to read or write the actual variable.
This w ill be referred to as "C style pass-by-
reference", or "pass-by-address".
Up Next ..
Additional Lecture 12
Resources
▪ Call By Value & Call By Reference in C:
https://www.youtube.com/watch?v=HEiPxjVR8CU

▪ C Programming Tutorial - 58 - Pass by Reference vs


Pass by Value:
https://www.youtube.com/watch?v=wAmq8eIkdI8

▪ Pass by value and Pass by reference (Animated):


https://www.youtube.com/watch?v=ErMKBh1pobg

▪ Pass by Value vs. Pass by Reference - Processing


Tutorial:
https://www.youtube.com/watch?v=hNR6fsksEu8 Thank you!
CS111 | COM101 Intro. to Computer Science
Computer Science Dept.
Helwan University
Lecture 12
Solved Examples
[ 2nd Set ]
Solved Examples on:
12.1 Functions [ Part A ]; Function Declaration & Prototype,
Function Call, Parameters versus Arguments, Returning Values,
Local Variables, & Pass-by-Value vs. Pass-by-Reference.
12.2 Functions [ Part B ]; Function Declaration & Prototype,
Function Call, Parameters versus Arguments, Returning Values,
Local Variables, & Pass-by-Value vs. Pass-by-Reference.
12.3 Recursion, Base Cases (and Recursion without a Base Faculty of
Case), & Recursive Functions. Computing &
12.4 Number Systems, Number Systems Conversions, Artificial Intelligence
Binary Notation, & Bitwise Operations.
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)

Course & Lectures are based on their counterparts in the following:


o Harvard University's CS50; An introduction to the intellectual enterprises of computer science and the art of programming,
Harvard School of Engineering and Applied Sciences.
o UNSW's CS1: Higher Computing, by Richard Buckland – The University of New South Wales.
o MIT's 6.087 Practical Programming in C (2010), 6.096 Introduction to C++ (2011), and 6.S096 Introduction to C and C++
(2013), MIT (Massachusetts Institute of Technology) OpenCourseWare.
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.2 Functions [ Part B ]; 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.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

12.1: C function to CALCULATE EMI (Equated


Monthly Installment)
o An EMI or Equated Monthly Installment is defined as "A fixed
payment amount made by a borrower to a lender at a specified date
each calendar month. Equated monthly installments are used to pay
off both interest and principal each month, so that over a specified
number of years, the loan is fully paid off along with interest."
o This program will read total loan amount (principal), rate (in years),
& time (in years), & prints the per month EMI of that loan amount.
o The formula used in this program is:
o ( P * R * ( 1 + R )T ) / ( ( ( 1 + R )T ) - 1 )
o P is a loan amount.
o R is the interest rate per month (we will read it as a yearly rate
and convert it to a monthly rate in our program).
o T is loan time period in year (we will read it as years and
convert it to months in our program). 4
Please pause the video and try to answer the question on your own!

12.1: C function to CALCULATE EMI (Equated


Monthly Installment)

Enter principal: 20000


Enter rate: 10
Enter time in year: 2
Monthly EMI is = 922.899536

5
/*EMI Calculator (C program to calculate EMI).*/
#include <stdio.h>
#include <math.h>

float calculate_emi( float p, float r, float t) {


float value;
value = ( p * r * pow( 1 + r, t ) ) / ( pow( 1 + r, t ) -1 );
return value; }

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!

12.2: C function to check whether NUMBER IS


PALINDROME or not
o A Palindrome Number - A number which is equal to its reverse is
know as Palindrome Number. For example, the number 12321 is a
Palindrome Number, because 12321 is equal to it’s reverse; which
is also 12321.

o In this program, we will read an integer number and check whether


it is a Palindrome Number or not. To check whether a number is
Palindrome or not, we will firstly calculate its Reverse Number. If
the input number is equal to its reverse number then that number
is considered to be a Palindrome.

7
Please pause the video and try to answer the question on your own!

12.2: C function to check whether NUMBER IS


PALINDROME or not

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!

12.3: C function to COUNT TOTAL NUMBER OF


DIGITS of an Integer number

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.

o The logic behind implementing this program is to successively


divide the number by 10 and count the digits until the number is
zero. Before using the counter variable, initialize it to 0.

Enter a number: 28765


Total numbers of digits are: 5 in the number: 28765.

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.2 Functions [ Part B ]; 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.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

12.4: C function to COUNT THE OCCURRENCE


OF A PARTICULAR DIGIT in a number

o In this program, we will read an integer number and a digit then


print the total number of occurrences of that input digit in that
number.

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).

Enter a number: 23111


Enter a digit to search: 1
Total occurrence of the digit is: 3 in the number: 23111.

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!

12.5: C function to find whether a given integer


is AN ARMSTRONG NUMBER or not
o An Armstrong number can be defined as a number that is equal to
the sum of the cubes of its digits. For example 0, 1, 153, 370, 371,
and 407 are all Armstrong numbers. Let's try to understand why -
for example - 153 is an Armstrong number:
o here 153 = ( 1 * 1 * 1 ) + ( 5 * 5 * 5 ) + ( 3 * 3 * 3 ).

o This program will read an integer number and check whether it is


an Armstrong Number or Not. To check an Armstrong number, we
have to calculate the sum of each digit’s cube, and then compare
the number to the calculated sum of cubes. If a number and the
sum of its digit’s cubes are equal, then the number is an Armstrong
Number, otherwise it's not.
15
Please pause the video and try to answer the question on your own!

12.5: C function to find whether a given integer


is AN ARMSTRONG NUMBER or not

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!

12.6: Write a C Program to Calculate ..


Permutation (nPr) .. and .. Combination (nCr)
nC and nPr are statistical quantities regarding possible subsets of a
r
set of objects, and they are defined as:
nP ( n, r ) = n! / ( n − r )!
r
nC ( n, r ) = nP ( n, r ) / r! = n! / ( r! ( n − r )! )
r r

Using sets to help define them:


o nPr is the formula to find permutations of n objects taking r at a
time. This answers the question of how many possible groups of
r objects from a set of n objects. And, ..
o nCr is the formula to find the unique permutations, otherwise
known as combinations, of n objects taking r at a time. This
answers the question of how many unique possible groups of r
objects can be made from n objects.
Please pause the video and try to answer the question on your own!

12.6: Write a C Program to Calculate ..


Permutation (nPr) .. and .. Combination (nCr)
Example: Take the set { 1, 2, 3, 4} and find all combinations and
permutations taking 2 at a time:

We can make this set of sets making every possible combination of


the 4 objects in the set taking 2 at a time (we aren't allowed to
reuse an object once we've use it):
------- {2, 1} {3, 1} {4, 1}
{1, 2} ------- {3, 2} {4, 2}
{1, 3} {2, 3} ------- {4, 3}
{1, 4} {2, 4} {3, 4} -------

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.6: Write a C Program to Calculate ..


Permutation (nPr) .. and .. Combination (nCr)
Example: Take the set { 1, 2, 3, 4} and find all combinations and
permutations taking 2 at a time:

Now, if we want to look at unique sets, then { 1, 2} = { 2, 1} and


likewise for all sets with the same numbers in them. Or, for this
case, we can remove half of the grid we've created.

------- {2, 1} {3, 1} {4, 1}


------- ------- {3, 2} {4, 2}
------- ------- ------- {4, 3}
------- ------- ------- -------

This leaves us with 6 unique groups, and we can confirm with


the nCr formula that we get 6:
nC ( 4, 2) = nP ( 4, 2) / r! = 12 / ( 2 ∗ 1 ) = 12 / 2 = 6
r r
12.6: Write a C Program to Calculate ..
Permutation (nPr) .. and .. Combination (nCr)
#include<stdio.h>

// Function Prototype Declarations


long factorial( int );
long find_npr( int, int ); Enter the values of n and r respectively :
long find_ncr( int, int ); 42

int main() { 4C2 = 6


int n, r; 4P2 = 12
long npr, ncr;
printf("Enter the value of n and r respectively: \n");
scanf("%d%d", &n, &r);
// Function Calls
npr = find_npr( n, r );
ncr = find_ncr( n, r );
printf("\n\t %dC%d = %ld\n", n, r, ncr );
printf("\n\t %dP%d = %ld\n", n, r, npr );
return 0;
}
// Function for Calculating nCr
long find_ncr( int a, int b )
{
return ( factorial( a ) / ( factorial( b ) * factorial( a - b ) ) );
}

// Function for Calculating nPr


long find_npr( int a, int b )
{
return ( factorial( a ) / factorial( a - b ) );
}

// Recursive Function for Calculating the Factorial


long factorial( int c )
{
if( c == 1 || c == 0 )
return 1;
else
return c * factorial( c - 1 );
}
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.2 Functions [ Part B ]; 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.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

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; }

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!

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; }

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!

12.9: Write a C Program to find whether a


Number is Prime or Composite using Recursion

o Prime Number: A number that is only divisible by 1 and


itself.
o Composite Number: A number that is not a prime number.
o Note: 1 is neither prime nor composite.

Enter a positive number to check if it's a Prime Number: 13


13 is a Prime Number.

Enter a positive number to check if it's a Prime Number: 20


20 is a Composite Number.
#include<stdio.h>

int isPrime( int, int ); // Prototype; Declaring the Recursive Function

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;
}

int isPrime( int n, int i ) // Function definition


{
if( i == 1 ) return 1; // Base-Case 1: terminates the recursion
else if( n % i == 0 ) return 0; // Base-Case 2: terminates recursion
else isPrime( n, i - 1 ); // Recursive Call
}
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.2 Functions [ Part B ]; 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.

12.4 Number Systems, Number Systems Conversions, Binary Notation, &


Bitwise Operations.
Please pause the video and try to answer the question on your own!

12.10: C program to CONVERT A DECIMAL


NUMBER TO BINARY

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!

12.10: C program to CONVERT A DECIMAL


NUMBER TO BINARY

For Example:

Convert Decimal to Binary:


-------------------------
Enter a number to convert : 25

The Binary of 25 is 11001.

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!

12.11: C program to CONVERT A BINARY


NUMBER TO A DECIMAL using for loop

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!

12.11: C program to CONVERT A BINARY


NUMBER TO A DECIMAL using for loop

Convert Binary to Decimal:


-------------------------
Input a binary number :11001

The equivalent Decimal Number : 25

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!

12.12: Write a C Program to find the Binary


Representation of an Integer using Bitwise
Operators

In this C program, we will read an integer (decimal) number, and


print its Binary Value (Binary Representation).

In this program, we are finding the Binary values of 16 bits


numbers. The logic is very simple – we have to just traverse each
bit using the Bitwise AND operator. To traverse each bit – we will
run loop from 15 to 0 (we are doing this to print the Binary
representation in a proper format).

Enter an Integer Number : 13


The Binary Value of 13 is = 0000000000001101
#include <stdio.h>
void getBinary( int );
int main()
{
int num = 0;
printf("Enter an Integer Number : ");
scanf("%d", &num );
printf("\nThe Binary Value of %d is = ", num );
getBinary( num );
return 0;
}

void getBinary( int n ) /* Function Definition : getBinary() */


{
int loop;
/* loop = 15, for representing a 16 bits value, 15th bit to 0th bit */
for( loop = 31; loop >= 0; loop-- )
{
if( ( 1 << loop ) & n )
printf("1");
else
printf("0");
}
}
Up Next ..
This was .. CS112
CS111 | COM101

an Introduction to
Computer Science

Thank you!

You might also like