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

Class 12 Computer Notes

The document provides comprehensive notes on computer programming concepts for Class 12, detailing the programming process in five main steps: defining the problem, planning the solution, coding, testing, and documenting. It also covers various programming languages, their characteristics, and the principles of Object-Oriented Programming (OOP) and Visual Programming. Additionally, the document includes multiple-choice questions and answers to reinforce learning.

Uploaded by

tariqmarium03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Class 12 Computer Notes

The document provides comprehensive notes on computer programming concepts for Class 12, detailing the programming process in five main steps: defining the problem, planning the solution, coding, testing, and documenting. It also covers various programming languages, their characteristics, and the principles of Object-Oriented Programming (OOP) and Visual Programming. Additionally, the document includes multiple-choice questions and answers to reinforce learning.

Uploaded by

tariqmarium03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 176

ME English Center

New Computer Book


Class 12th Notes

er
nt
(According Ce
to new book )
ish
gl

If you are needed for other classes guess papers


En

contact on this number 03408057780


E
M

Prepared by | Sir Aqib


2nd year CS - Chapter # 1

Class: 2nd year

Chapter # 1

Concept of Computer Programming

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 14


2nd year CS - Chapter # 1
Contents

Step 1: Defining the Problem ...................................................................................................................................................... 3


Step 2: Planning the Solution ...................................................................................................................................................... 3
Step 3: Coding the Program ........................................................................................................................................................ 3
Step 4: Testing the Program ........................................................................................................................................................ 3
Step 5: Documenting the Program .............................................................................................................................................. 4
Programming Languages in General............................................................................................................................................ 4
Programming Languages ............................................................................................................................................................. 4
Object Oriented Programming (OOP) ......................................................................................................................................... 6
Visual Programming.................................................................................................................................................................... 7
Section (A).................................................................................................................................................................................. 8

er
-: Answer Keys :-................................................................................................................................................................ 9
Section (B / C) .......................................................................................................................................................................... 10

nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 14


2nd year CS - Chapter # 1
The five main steps in the programming process are as follows:
1. Defining the problem
2. Planning the solution
3. Coding the program
4. Testing the program
5. Documenting the program

Step 1: Defining the Problem


The first step is to fully understand the problem by specifying:

 Objectives: Clear problem goals (e.g., generating a payroll report).


 Desired Output: What the program should produce (e.g., printed reports).
 Input Data: The data required to achieve the outputs (e.g., timecards).

er
 Processing Requirements: The resources and operations needed for execution (e.g., hardware and software).

nt
Step 2: Planning the Solution
This involves creating a logical approach using tools like:
Ce
1. Top-Down Design: Breaking the problem into smaller modules for clarity and simplicity.
ish
2. Algorithms: Using step-by-step instructions in human language to outline the program logic.
3. Flowcharts: Diagrammatic representation of program logic using ANSI-standard symbols.
gl

Step 3: Coding the Program


En

 Writing instructions in high-level languages (e.g., C++, Python).


 Translating the source program into machine language using:
E

o Interpreters: Translate and execute one statement at a time.


o Compilers: Convert the whole program into machine language in one step.
M

Step 4: Testing the Program


Testing ensures the program performs as intended and includes debugging to fix errors:

1. Types of Errors:
o Syntax Errors: Violations of programming language rules.
o Logic Errors: Incorrect logic causing unexpected output.
o Runtime Errors: Issues during execution (e.g., dividing by zero).
2. Debugging Techniques:
o Desk checking (proofreading code).
o Manual testing (dry run).
o Structured walkthrough (team review).
o Attempt at translation (using a translator program).
o Alpha testing (sample data).
o Beta testing (real-world data).

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 14


2nd year CS - Chapter # 1
Step 5: Documenting the Program
Documentation ensures the program is understandable and maintainable for:

1. Users: Manuals and online help for end-users.


2. Operators: Guidance on handling issues (e.g., error messages).
3. Programmers: Details for maintenance (e.g., comments, flowcharts).

Programming Languages in General


A programming language is a system of symbols and rules used to communicate instructions to a computer, enabling
it to perform specific tasks. Unlike human languages, programming languages are designed for precision and are
limited to specific operations, avoiding ambiguity.

Characteristics of Programming Languages

er
All programming languages share the following basic functions to control computer operations:

nt
1. Input/Output Instructions
o Direct the computer to interact with peripheral devices (e.g., reading data from a disk or printing
output).
2. Computation Instructions Ce
o Perform arithmetic operations (e.g., addition, subtraction, multiplication).
o Example: PAY = HOURS * RATE calculates gross pay.
ish
3. Control Instructions
o Alter the sequence of execution or terminate a program.
gl

o Example: Conditional logic for different customer payment statuses.


4. Assignment Instructions
En

o Move or copy data internally within memory locations.


o Example: Storing a computation result for later use.

Comments in Programming
E


M

Purpose: Provide explanations within the code to clarify its function.


 Ignored by Computer: Comments do not affect the program's execution or translation.
 Benefit: Improves readability and maintainability for programmers.

Programming Languages
Over 100 programming languages exist, each designed for specific purposes, such as solving business problems,
performing complex calculations, or creating graphics. All high-level languages require translation into machine
language using system software like compilers or interpreters before execution.

Early High-Level Languages

1. Procedure-Oriented Languages
o Require programmers to write step-by-step instructions.
o Solve general problems (business, scientific, or multipurpose).

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 14


2nd year CS - Chapter # 1
Key Programming Languages

1. FORTRAN

 Purpose: Mathematics, science, and engineering.


 Advantages:
o Handles complex formulas.
o Portable across computer types.
 Disadvantages:
o Inefficient for input/output operations.
o Limited for non-numeric data.

2. COBOL

 Purpose: Business applications like payroll and inventory.


 Advantages:
o Machine-independent and readable.

er
o Handles input/output and file operations well.
 Disadvantages:

nt
o Verbose, slowing productivity.
o Not suitable for complex mathematical processing.

3. BASIC


Ce
ish
Purpose: Beginner-friendly programming.
 Advantages:
o Easy to learn.
gl

o Interactive execution.
 Disadvantages:
En

o Slow processing.
o Portability issues with earlier versions.

4. Pascal
E


M

Purpose: Teaching structured programming and scientific use.


 Advantages:
o Easy to learn and elegant.
o Supports graphics programming.
 Disadvantages:
o Limited input/output capabilities.

5. C

 Purpose: System software and general-purpose programming.


 Advantages:
o Portable, fast, and efficient.
o Allows hardware-level programming.
 Disadvantages:
o Difficult to learn.
o Concise code may reduce readability.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 14


2nd year CS - Chapter # 1
6. PL/1

 Purpose: Combines features of FORTRAN and COBOL.


 Advantages: Suitable for both scientific and business applications.
 Disadvantages: Too complex to be widely adopted.

7. Logo

 Purpose: Teaching children programming through graphics.


 Advantages:
o Easy to learn.
o Extensive graphics capabilities.
 Disadvantages: Limited data processing capabilities.

8. Ada

 Purpose: Portability and reliability, especially for defense systems.

er
 Advantages:
o Modular structure for testing.

nt
o Error checking by the compiler.
 Disadvantages:
o Complex and hard to learn.
o Limited compiler availability.
Ce
ish
Object Oriented Programming (OOP)
Object-Oriented Programming (OOP) is a modern programming paradigm designed to simplify and accelerate
gl

software development by combining data and its associated processing instructions into self-contained units called
objects.
En

Key Features of OOP


E

1. Objects: Combine data and operations into a reusable, independent unit.


2. Reuse: Objects can be applied in multiple programs, reducing redundancy.
M

3. Real-World Modeling: Programs resemble real-world concepts, making development intuitive.


4. Focus on Actions: Programmers define what tasks need to be done rather than every step required.

Advantages of OOP

 Reusability: Pre-built objects can be used across various applications, saving time.
 Reduced Complexity: Objects represent real-world entities, simplifying program design.
 Cost-Effectiveness: Accelerates development and lowers overall project costs.

Challenges of OOP

 Learning Curve: Requires adopting a new mindset compared to traditional programming.


 Initial Development: Writing reusable objects takes time but pays off in the long term.

Examples of OOP Languages

 Smalltalk: Pioneered OOP concepts.


 C++: Combines OOP with system-level programming.
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 14
2nd year CS - Chapter # 1
Visual Programming
Visual programming simplifies program creation by using diagrams, icons, and graphical interfaces rather than
traditional code syntax. This method enhances accessibility and usability for both programmers and nonprogrammers.

Key Features

1. Graphical Interface: Programs are constructed by dragging and connecting objects visually.
2. No Syntax Learning: Focuses on problem-solving without requiring knowledge of complex programming
syntax.
3. Object-Oriented Foundation: Builds on the concepts of OOP but implements them visually.

Advantages

 Ease of Use: Simplifies the programming process, especially for beginners.


 Accelerated Development: Drag-and-drop tools enable faster application design.

er
User-Friendly: Intuitive for nonprogrammers to create functional programs.

nt
Popular Visual Programming Language

 Visual BASIC:
o Developer: Microsoft, early 1990s.
Ce
o Purpose: Creates Windows-compatible applications.
o Tools: Includes buttons, scroll bars, and menus for rapid application development.
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 14


2nd year CS - Chapter # 1

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. _________ is a relatively simple high-level language that was developed to help students learn programming.
(a) BASIC (b) COBOL (c) C (d) All of the above
2. In preparing a program, one should first
(a) plan the solution (b) document the program (c) code the program (d) define the problem
3. During the development of a program, drawing a flowchart is a means to
(a) plan the solution (b) define the problem (c) code the program (d) analyse the problem
4. Which of the following is used to design a program using English-like statements?

er
(a) Algorithm (b) program flowchart (c) control structures (d) None of the above
5. Compilers and interpreters are types of

nt
(a) programming languages (b) language translators (c) alpha testers (d) application generators

(b) logic
Ce
6. Which of the following type of error is detected by a language translator?
(a) program design (c) syntax (d) both b and c
ish
7. You test a program to find which of the following?
(a) flowcharting errors (b) logic errors (c) algorithmic errors (d) syntax errors
gl

8. In preparing a program, desk-checking and translating are examples of


En

(a) coding (b) testing (c) planning (d) documenting


9. Which of the following is not one of the steps in a programming project?
E

(a) planning the solution (b) coding the program (c) testing the program (d) selecting the hardware
M

10. In preparing a program, desk-checking and translating are examples of


(a) coding (b) planning (c) testing (d) documenting
11. Comments in the program itself are part of
(a) compiling (b) translating (c) linking (d) documenting
12. The first high-level language to be introduced was
(a) COBOL (b) FORTRAN (c) Pascal (d) BASIC
13. The language named for a French mathematician is
(a) C (b) Pascal (c) FORTRAN (d) COBOL
14. Specifying the kind of input, processing, and output required for a program occurs when
(a) planning the solution (b) coding the program (c) flowcharting the problem (d) defining the problem

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 14


2nd year CS - Chapter # 1
15. Error messages provided by a compiler are called
(a) bugs (b) translations (c) diagnostics (d) mistakes
16. After stating a solution in algorithm, you would next
(a) test the program (b) implement the program (c) code the program (d) translate the program
17. Software that translates assembly language into machine language is a(n)
(a) bínary translator (b) assembler (c) compiler (d) link-loader
18. A standardized business language is
(a) Pascal b) COBOL (c) BASIC (d) FORTRAN
19. In developing a program, documentation should be done
(a) as the last step (b) only to explain errors (c) throughout the process (d) only during the design phase
20. Which of the following languages is frequently used in object-oriented programming?

er
(a) COBOL (b) C (c) C++ (d) Pascal

nt
21. Popular object-oriented languages are
(a) Pascal, COBOL
(c) C++, Smalltalk
(b) C++, FORTRAN
(d) COBOL, BASIC
Ce
ish
gl

-: Answer Keys :-
En

1. a 6. c 11. d 16. c 21. c


2. d 7. b 12. b 17. b
E

3. a 8. b 13. b 18. b
M

4. a 9. d 14. d 19. c
5. b 10. b 15. c 20. c

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 14


2nd year CS - Chapter # 1

Section (B / C)
1.1. What is the difference between human languages and computer languages?

The primary differences between human languages and computer languages are:

1. Purpose:
o Human languages are used for communication among people.
o Computer languages are designed for instructing computers to perform tasks.
2. Structure:
o Human languages are complex, ambiguous, and have evolving grammar.
o Computer languages are precise, unambiguous, and follow strict syntax rules.
3. Interpretation:
o Human languages are interpreted by humans and vary by culture or region.
o Computer languages are processed by compilers or interpreters for execution.
4. Flexibility:

er
o Human languages are expressive and allow for multiple interpretations.
o Computer languages are rigid and require exact syntax to function.

nt
1.2. Descried the four general classes of instructions found in all computer languages.

Ce
The four general classes of instructions found in all computer languages are:

1. Data Transfer Instructions:


ish
o These instructions move data from one location to another.
o Example: Copying data from memory to a register or from input devices to memory.
o Common operations: LOAD, STORE, MOVE.
gl

2. Arithmetic and Logic Instructions:


o Perform mathematical operations (e.g., addition, subtraction) and logical comparisons (e.g., AND, OR,
En

NOT).
o Example: ADD, SUBTRACT, MULTIPLY, COMPARE.
3. Control Instructions:
E

o Direct the flow of execution within a program.


o Examples: Conditional jumps, loops, function calls, and return instructions.
M

o Common operations: IF, GOTO, CALL, RETURN.


4. Input/Output Instructions:
o Facilitate communication between the computer and external devices.
o Example: Reading data from the keyboard or writing results to the display.
o Common operations: READ, PRINT, WRITE.

1.3. What is the difference between a compiler and an interpreter? Why is each used?

Translates the entire program into machine code at


Translates and executes code line by line.
once.
Faster, as the entire program is precompiled into Slower, as translation and execution happen
machine code. simultaneously.
Generates an executable file. No separate executable file; runs code directly.
Detects all errors at compile time and lists them. Detects errors one line at a time during execution.
Best for programs requiring high performance and Ideal for debugging and dynamic programming
portability. environments.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 14


2nd year CS - Chapter # 1
Why Each is Used?

1. Compiler: Used when high performance and efficiency are critical, such as in software development for large-
scale applications.
2. Interpreter: Used in environments where immediate code execution and testing are required, such as scripting
languages and educational purposes.

1.4. What is the definition of a program?

A program is a set of instructions written in a programming language that a computer can execute to perform a
specific task or solve a problem. It serves as a bridge between the user and the hardware, guiding the computer on
how to process input, manage data, and produce output.

1.5. What is the definition of programming?

Programming is the process of designing, writing, testing, and maintaining the instructions (code) that a computer
follows to perform specific tasks. It involves using programming languages to create software, solve problems, or

er
automate processes.

nt
1.6. Explain the steps in a programming project.

Step

1. Planning and Analysis


Ce Description
Define the problem, understand requirements, and plan the solution.
ish
2. Design Create a design for the program, including flowcharts, diagrams, and algorithms.

3. Write the actual code based on the design, using the appropriate programming
gl

Coding/Implementation language.

Test the program for errors (bugs) and ensure it meets the requirements.
En

4. Testing
5. Debugging Identify and fix any bugs or issues found during testing.
6. Documentation Write clear and comprehensive documentation for code, usage, and functionality.
E

7. Deployment Deploy the program for use, whether it's a desktop, web, or mobile application.
M

8. Maintenance Provide ongoing support, updates, and improvements after deployment.

1.7. What is an algorithm?

An algorithm is a step-by-step, well-defined set of instructions or procedures designed to solve a specific problem or
perform a task. It takes an input, processes it through a series of logical steps, and produces an output.

In programming, algorithms form the foundation for writing code and are essential for problem-solving. They are
often expressed in a high-level way (e.g., pseudocode or flowcharts) before being translated into actual programming
languages.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 14


2nd year CS - Chapter # 1
1.8. Distinguish between syntax errors and logic errors.

Type of Error Syntax Error Logic Error


Definition Occurs when the code is syntactically
Occurs when the code does not follow the correct
correct, but it produces incorrect or
syntax of the programming language.
unintended results.
Cause Caused by mistakes in the language structure, such Caused by errors in the program’s logic,
as incorrect punctuation, missing parentheses, or where the algorithm does not perform as
wrong keywords. expected.
Detection Detected by the compiler or interpreter during the Not automatically detected and requires
compilation or execution process. testing or debugging to identify.
Example x = y + 10; if x > 10: print("x is
print("Hello World" (missing closing
greater") (incorrect logic for the
parenthesis). condition).
Impact Program runs, but the output or behavior is
Stops the program from running or compiling.

er
wrong.

nt
1.9. Explain how and why a program is tested and debugged?

Ce
1. Program Testing: Testing is the process of running the program with different sets of inputs to ensure that it
behaves as expected and meets the requirements. It is essential to identify any errors or unexpected behavior in the
program.
ish
 How to Test:
o Unit Testing: Test individual components or functions of the program separately.
gl

o Integration Testing: Test how different parts of the program work together.
o System Testing: Test the program as a whole in various scenarios.
En

o User Testing: Test the program based on how it will be used by real users.
o Boundary Testing: Check the program's behavior at the edges of input limits.
 Why Testing is Important:
o Identifies Bugs: Helps find errors or issues before the program is released.
E

o Ensures Functionality: Verifies that the program performs as intended and meets specifications.
M

o Improves Quality: Ensures reliability and robustness of the software.


o Reduces Risks: Prevents major failures after deployment by catching issues early.

2. Program Debugging: Debugging is the process of identifying, analyzing, and fixing the errors (bugs) found during
testing.

 How to Debug:
o Check Error Messages: Review any error messages or logs generated during testing to understand the
issue.
o Use Debugging Tools: Utilize built-in debugging tools in an IDE (Integrated Development
Environment) to trace the execution flow and examine variable values.
o Isolate the Problem: Narrow down where the bug occurs in the code by testing individual sections or
using print statements to track values.
o Fix and Retest: Modify the code to correct the issue, then retest to ensure the fix works and no new
issues arise.
 Why Debugging is Important:
o Fixes Errors: Ensures that the program operates correctly by removing defects.
o Improves Efficiency: Debugging helps optimize the program by fixing logical or performance issues.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 14


2nd year CS - Chapter # 1
o Enhances User Experience: By eliminating bugs, debugging ensures the program runs smoothly,
providing a better experience for users.
o Maintains Program Stability: Helps maintain consistent and reliable behavior of the software
throughout its use.

1.10 Explain some of the debugging tools, such as desk checking and structured walk-through.

1. Desk Checking:

 Definition: Desk checking is a manual process of reviewing the program's code or algorithm on paper (or
desk) without actually running the program. The programmer reads through the code step-by-step and
simulates its execution, checking if the logic, flow, and calculations are correct.
 How It Works:
o The programmer goes through the code or algorithm line by line, mentally tracking variables and logic.
o Any inconsistencies, errors, or potential bugs are identified during this review.
o Desk checking is often used early in the development process to catch simple logical errors or to verify
the flow of control in the program.

er
 Advantages:
o Simple and inexpensive.

nt
o Helps improve the understanding of the program’s logic.
o Can catch mistakes in logic or assumptions without needing to run the program.

2. Structured Walk-Through:


Ce
ish
Definition: A structured walk-through is a formalized debugging tool that involves a team of developers or
peers reviewing the code together. The programmer presents the code or algorithm, and the team reviews it
systematically to find errors and suggest improvements.

gl

How It Works:
o The developer explains the code or algorithm to the group while walking through it step by step.
En

o The group discusses the logic, identifies errors, and suggests corrections.
o Typically, the team checks the program’s structure, logic, flow, and possible edge cases.
o The process is often guided by a moderator to keep the discussion focused and productive.
 Advantages:
E

o Encourages collaboration and the exchange of ideas, potentially uncovering errors that a single
M

programmer may overlook.


o Helps to catch subtle or complex issues that may not be easily identified by one person.
o It also serves as a learning experience for less experienced programmers.

1.10. Why is proper documentation of a program necessary?

Proper documentation is necessary because it:

1. Improves Readability: Makes the code easier to understand for others (or yourself) in the future.
2. Aids Debugging: Helps identify and fix issues by explaining the program’s structure and functionality.
3. Facilitates Maintenance: Makes it easier to modify or update the program over time.
4. Supports Collaboration: Allows multiple developers to work on the same project by providing clear
explanations of the code.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 14


2nd year CS - Chapter # 1
1.11 List the most commonly used microcomputer high-level programming languages.

The most commonly used microcomputer high-level programming languages are:

1. Python
2. Java
3. C++
4. JavaScript
5. Ruby
6. PHP
7. Swift
8. C#

1.12What were the reasons behind the development of high-level programming languages?

The reasons behind the development of high-level programming languages include:

er
1. Ease of Use: To make programming easier and more understandable for humans, using syntax closer to natural
language.

nt
2. Portability: To enable programs to run on different hardware platforms without modification.
3. Efficiency: To reduce the complexity of writing and maintaining machine-level code.

Ce
4. Productivity: To allow faster development by providing abstraction from hardware details.
5. Error Reduction: To minimize programming errors through more structured and readable code.
ish
1.13What is the difference between procedure-oriented languages and object- oriented languages?

Aspect Procedure-Oriented Languages Object-Oriented Languages


gl

Focus Focuses on functions or procedures. Focuses on objects that combine data and methods.
En

Examples C, Fortran, Pascal Java, C++, Python

Data Handling Data is separate from functions. Data is encapsulated within objects.
E

Approach Top-down approach (divides tasks into functions). Bottom-up approach (builds around objects).
M

Reusability Limited, as functions are reused. High, through inheritance and polymorphism.

Maintainability Harder to maintain in large systems. Easier to maintain due to modularity.

1.14 What is visual programming?

Visual programming is a programming paradigm where users create programs by manipulating graphical elements
rather than writing text-based code. It uses a visual interface, often involving drag-and-drop blocks or icons, to
represent code structures, logic, and workflows.

Examples: Scratch, Blockly, and Microsoft Visual Basic.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 14


2nd year CS - Chapter # 2

Class: 2nd year

Chapter # 2

Algorithm and Flowcharts

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 20


2nd year CS - Chapter # 2
Contents
Algorithm ............................................................................................................................................................................... 3
Example 1: Count Students with First Division ................................................................................................................ 3
Example 2: Compute Distance Traveled ........................................................................................................................... 3
Pseudocode ............................................................................................................................................................................. 3
Mathematical Notations and Functions in Pseudocode .................................................................................................... 4
Applications of Pseudocode ............................................................................................................................................... 4
Algorithmic Notations........................................................................................................................................................ 5
Flowcharts ............................................................................................................................................................................. 6
Flowchart Categories ........................................................................................................................................................... 6
Control Structures................................................................................................................................................................ 6
Types of Flowchart .............................................................................................................................................................. 6

er
Flowcharting Rules ............................................................................................................................................................. 7
Advantages of Flowcharts................................................................................................................................................. 7

nt
Disadvantages of Flowcharts ........................................................................................................................................... 8

Ce
Section (A).................................................................................................................................................................................. 9
-: Answer Keys :-................................................................................................................................................................ 9
Section (B / C) .......................................................................................................................................................................... 10
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 20


2nd year CS - Chapter # 2
Algorithm
An algorithm is a finite sequence of unambiguous instructions designed to solve a specific problem, ensuring the
task terminates in a finite amount of time.

Key Features of an Algorithm

1. Finite Steps: Must have a clear start and end.


2. Unambiguous Instructions: Each step must be precisely defined.
3. Executable: Every step must be realistically achievable.

Example 1: Count Students with First Division

Problem: Count how many students achieved first division in their exam.
Algorithm:

er
1. Initialize TOTAL_FIRST_DIVISION and TOTAL_MARK_SHEETS_CHECKED to 0.
2. Take the next mark-sheet.

nt
3. If the division is FIRST, increment TOTAL_FIRST_DIVISION.
4. Increment TOTAL_MARK_SHEETS_CHECKED.
5.

Example 2: Compute Distance Traveled Ce


If all 50 mark-sheets are checked, print TOTAL_FIRST_DIVISION and exit. Else, repeat from step 2.
ish
Problem: Calculate the distance traveled by a train given its speed and time.
Algorithm:
gl

1. Start.
2. Input SPEED.
En

3. Input TIME.
4. Compute DISTANCE = SPEED × TIME.
5. Output DISTANCE.
E

6. Exit.
M

Pseudocode
Pseudocode is a tool used to describe algorithms in a language-neutral and logical way. It bridges the gap between
natural language and formal programming languages.

Key Characteristics

1. Simple and English-like: Focuses on expressing the algorithm’s logic.


2. Editable: Easy to modify during development.
3. Language-Independent: Can be adapted to any programming language.
4. Ambiguity-Free: Eliminates the vagueness of natural language.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 20


2nd year CS - Chapter # 2
Mathematical Notations and Functions in Pseudocode

Remainder Function (MOD)

 k MOD Mk \, \text{MOD} \, M: Remainder when kk is divided by MM.


Examples:
 11 MOD 2=111 \, \text{MOD} \, 2 = 1
 22 MOD 3=122 \, \text{MOD} \, 3 = 1
 24 MOD 7=324 \, \text{MOD} \, 7 = 3
 20 MOD 4=020 \, \text{MOD} \, 4 = 0

Integer Value Function (INT)

Converts a real number XX to an integer by truncating its fractional part.


Examples:

 INT(4.32)=4\text{INT}(4.32) = 4

er
 INT(−8.7)=−8\text{INT}(-8.7) = -8
 INT(9)=9\text{INT}(9) = 9

nt
Absolute Value Function (ABS)

Returns the non-negative value of a number XX.


Examples:
Ce
ish
 ABS(−15)=15\text{ABS}(-15) = 15
 ABS(6)=6\text{ABS}(6) = 6
gl

Factorial Function (!)


En

The product of all positive integers from 11 to nn.


E

n!=1×2×3×⋯×nn! = 1 \times 2 \times 3 \times \dots \times n


 0!=10! = 1 (by definition)
M

Examples:

 2!=22! = 2
 3!=63! = 6
 4!=244! = 24

Applications of Pseudocode

 Planning program logic before implementation.


 Creating algorithms for mathematical and computational problems.
 Serving as a foundation for translating logic into programming languages.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 20


2nd year CS - Chapter # 2
Algorithmic Notations
An algorithm is a finite and well-defined set of instructions designed to solve a problem. Specific symbols and
notations are used for clarity and consistency.

Example Algorithm (2.3)

This algorithm calculates the sum of two numbers, XXX and YYY:

Steps:

1. Read XXX.
[To get the first number]
2. Read YYY.
[To get the second number]
3. Set SUM=X+Y\text{SUM} = X + YSUM=X+Y.
[Calculate the sum]

er
4. Write SUM\text{SUM}SUM.
[Display the result]

nt
5. Exit.
[Terminate the algorithm]

Key Notations Ce
ish
1. Algorithm Name:
o Every algorithm should have a unique name (e.g., Algorithm 2.3).
2. Step Number:
gl

o Each instruction is numbered sequentially (e.g., Step 1, Step 2, etc.).


3. Variable Names:
En

o Use capital letters for variable names (e.g., X,Y,SUMX, Y, \text{SUM}X,Y,SUM).


4. Input:
o Use Read to take input from the user.
E

5. Assignment:
o Use Set to assign values to variables.
M

6. Termination:
o Use Exit to indicate the end of the algorithm.
7. Comments:
o Use brackets ......... or remarks to explain steps.
8. Control Transfer:
o Use Goto Step n to transfer control to a specific step (if necessary).

Purpose and Structure

The purpose of an algorithm:

 Describes its goal.


 Identifies variables used.
 Lists required input data.

Structure:
 Part 1: Purpose and definitions.
 Part 2: Step-by-step instructions.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 20


2nd year CS - Chapter # 2
Flowcharts
 Definition: A graphical representation of the sequence of operations in a program.
 Purpose: Helps in program planning, debugging, and documentation.
 Symbols:
1. Terminal (Oval): Start/Stop/Halt.
2. Input/Output (Parallelogram): For reading and writing data.
3. Process (Rectangle): For computations or data movement.
4. Decision (Diamond): For conditions with branches.
5. Flowlines (Arrows): Indicate direction and sequence.
6. Connectors (Circle): Avoids crossing flowlines; used for continuation.
7. Predefined Process: Represents subroutines or procedures.
8. Annotation: Adds descriptive comments or explanations.

er
nt
Flowchart Categories

1. System Flowchart: Illustrates data flow in a system.


2. Program/Logic Flowchart:
o Micro: Shows major events only.
Ce
ish
o Macro: Includes all events (major and minor).

Control Structures
gl

1. Sequence:
En

o Executes steps in the written order.


o Example: Reading and adding three numbers sequentially.

2. Selection:
E

o If: Executes based on a condition.


M

o If-Else: Executes one path if a condition is true, another if false.


o Example: Assigning grades based on marks.

3. Iteration (Loops):
o While: Tests the condition before executing the loop body.
o Do-While: Executes the loop body at least once, then tests the condition.
o For: Executes a set number of times.
o Example: Adding ten numbers using While, Do-While, or For loops.

Types of Flowchart
1. Sequential Flowchart
o The simplest type, with no decisions, branches, or loops.
o Represents a straight sequence of actions.
o Example: Ordering a meal, receiving the bill, and paying it.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 20


2nd year CS - Chapter # 2
2. Branch (or Jump) Flowchart
o Introduces decision points with "yes" or "no" outcomes.
o Actions depend on the result of the decision.
o Example: Leaving a tip depending on service quality.

3. Loop Flowchart
o Represents procedures repeated a definite or indefinite number of times.
o Example: Reading a definition until it’s fully understood.

4. Nested Loops in a Flowchart


o Contains loops within loops to handle complex, repeated tasks.
o Example: Cutting rods into 2-meter pieces, where the inner loop cuts a single rod, and the outer loop
processes multiple rods.

Flowcharting Rules

er
While programmers have a good deal of freedom in creating flowcharts, there are a number of general rules and

nt
guidelines recommended by the American National Standards Institute (ANSI) to help standardise the flowcharting
process. Various computer manufacturers and data processing departments usually have similar flowcharting
standards. Some of these rules and guidelines are as follows:

1. First chart the main line of logic, then incorporate detail.


Ce
ish
2. Maintain a consistent level of detail for a given flowchart.
3. Do not chart every detail or the flowchart will only be a graphic representation, step by step, of the program. A
gl

reader who is interested in greater details can refer to the program itself.
4. Words in the flowchart symbols should be common statements and easy to understand. It is recommended to use
En

descriptive titles written in designer's own language rather then in machine oriented language.
5. Be consistent in using names and variables in the flowchart.
E

6. Go from left to right and top to bottom in constructing flowcharts.


M

7. Keep the flowchart as simple as possible. The crossing of flow-lines should be avoided as far as practicable.
8. If a new flowcharting page is needed, it is recommended that the flowchart be broken at an input or output point.
Moreover properly labelled connectors should be used to link the portions of the flowchart on different pages.

Advantages of Flowcharts
1. Better Communication: Helps programmers easily explain logic to others.

2. Effective Analysis: Simplifies breaking down complex systems for detailed study.

3. Effective Synthesis: Combines individual parts into a visualized overall design for large projects.

4. Proper Documentation: Maintains a historical record of the program, aiding future modifications.

5. Efficient Coding: Guides programmers during the coding stage.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 20


2nd year CS - Chapter # 2
6. Systematic Debugging: Facilitates error detection and correction by reviewing program logic visually .

Disadvantages of Flowcharts
1. Time-Consuming: Drawing flowcharts, especially for complex programs, takes considerable time.

2. Space-Consuming: Large programs require multiple pages, making them hard to read.

3. Inflexible to Changes: Modifications often require redrawing the entire flowchart.

4. Lack of Standardization: No fixed guidelines on the level of detail needed.

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 20


2nd year CS - Chapter # 2

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. A pictorial representation of a problem is called
(a) a flowchart (b) an algorithm
(c) a pseudocode (d) None of the above
2. Which of the following is not one of the three program logic constructs?
(a) simple sequence (b) condition
(c) loop (d) go to
3. What do you call the step-by-step solution to a programming problem?

er
(a) recipe (b) structure chart
(c) syntax (d) algorithm

nt
4. What does the symbol in a flowchart represent?
(a) decision
(c) start/stop
(b) process
(d) predefined process
Ce
ish
5. What does the symbol in a flowchart represent?
(a) process (b) terminal
gl

(c) input/output procedure (d) predefined process


En

6. Which of the following control structures use DO-WHILE?


(a) sequence (b) selection
E

(c) iteration (d) None of the above


M

-: Answer Keys :-
1. 2. 3. 4. 5. 6.

a d d b c c

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 20


2nd year CS - Chapter # 2

Section (B / C)
2.1. What is an algorithm?

An algorithm is a step-by-step set of instructions or rules designed to perform a specific task or solve a
particular problem. It is written in a logical sequence and is independent of any programming language.

2.2. What are the three control structures used in coding?

The three control structures used in coding are:

1. Sequence: Executes instructions one after the other in order.


2. Selection (Decision-making): Makes choices between alternatives (e.g., if-else, switch).
3. Iteration (Looping): Repeats a block of code (e.g., for, while, do-while).

2.3. Explain the difference between the two loop (iteration) structures, WHILE DO-WHILE.

er
1. WHILE Loop:

nt
o The condition is checked before the loop body executes.
o If the condition is false initially, the loop body may not execute even once.
o Example:

while (condition) {
// code to execute
Ce
ish
}

2. DO-WHILE Loop:
gl

o The condition is checked after the loop body executes.


o The loop body will execute at least once, even if the condition is false.
En

o Example:

do {
// code to execute
E

} while (condition);
M

2.4. Write algorithm showing the logic required to calculate and print the sale on a purchase of four
items.

1. Start
2. Input the prices of the four items: item1, item2, item3, item4.
3. Calculate the total purchase amount:
total = item1 + item2 + item3 + item4 .
4. Determine the sale percentage based on the total purchase:
o If total > 500, apply a 20% discount (sale = total * 0.20).
o Else if total > 200, apply a 10% discount (sale = total * 0.10).
o Otherwise, no discount (sale = 0).
5. Calculate the final amount after the sale:
finalAmount = total - sale.
6. Print the following:
o Original total amount (total).
o Sale amount (sale).
o Final amount to pay (finalAmount).
7. End
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 20
2nd year CS - Chapter # 2
2.5. Write the algorithm for each of the following tasks listed sequentially:

(a) Write algorithm to generate numbers from 1 to 10. (using WHILE loop)

1. Start

2. Set X = 0

3. WHILE X < 10

Set X = X + 1

Write X.

[End of WHILE loop.]

4. Exit.

er
nt
(b) Write algorithm to generate numbers from 1 to 10. (using IF-ELSE structure).

1. Set X = 0

2. Set X = X + 1
Ce
ish
3. Write X.

4. IF X = 10 then
gl

Exit.
En

ELSE
E

Goto step 2.
M

[End of IF structure.]

(c) Write algorithm to write any number 10 times.

1. Read N.

2. FOR K = 1 to 10 by 1

Write N.

[End of FOR loop.]

3. Exit.

(d) Write algorithm to add numbers till input zero is given.

1. Set S = 0
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 20
2nd year CS - Chapter # 2
2. WHILE N ≠ 0

Read N.

Set S = S + N

[End of WHILE loop.]

3. Write S.

4. Exit.

(e) Write algorithm to write odd numbers from 1 to 11.

1. FOR K = 1 to 11 by 2

Write K.

er
[End of FOR loop.]

nt
2. Exit.
Ce
(f) Write algorithm to take sum of array of 10-elements (first take input and then add).
ish
1. FOR K = 1 to 10

Read N[K].
gl

[End of FOR loop.]


En

2. Set S = 0
E

3. FOR K = 1 to 10
M

Set S = S + N[K]

[End of FOR loop.]

4. Write S.

5. Exit.

2.6. What is a flowchart and how may types of flowcharts are there?

Flowchart:

A flowchart is a graphical representation of an algorithm or process, using symbols like arrows, rectangles, and
diamonds to illustrate the sequence of steps or decisions.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 20


2nd year CS - Chapter # 2
Types of Flowcharts:

1. System Flowchart: Shows how data flows within a system or process.


2. Program Flowchart: Focuses on the sequence of steps in a program or algorithm.
3. Process Flowchart: Used to illustrate the steps in a manufacturing or business process.
4. Data Flow Diagram (DFD): Focuses on the flow of data between components in a system.
5. Workflow Flowchart: Maps workflows within an organization or project.

2.7. What are the various symbols used in flowcharting? Give their pictorial representation.

1. Oval (Terminator):
o Purpose: Represents the start or end of a process.

2. Rectangle (Process):

er
o Purpose: Represents a process or task to be performed.

nt
3. Diamond (Decision):
o Purpose: Represents a decision point, typically yes/no or true/false.

4. Parallelogram (Input/Output):
Ce
o Purpose: Represents an input or output operation (e.g., entering data, displaying results).
ish
5. Arrow (Flowline):
o Purpose: Represents the direction of flow between steps.
gl

2.8. Describe the function of the various flowcharting symbols.


En

Functions of Various Flowcharting Symbols:


E

1. Oval (Terminator):
M

o Function: Represents the start or end of a process. It indicates where the process begins or terminates.

2. Rectangle (Process):
o Function: Represents a specific task, operation, or action to be performed.

3. Diamond (Decision):
o Function: Represents a decision point where a question is asked, and the flow branches based on the answer

(e.g., Yes/No or True/False).


4. Parallelogram (Input/Output):
o Function: Represents an input operation (e.g., entering data) or output operation (e.g., displaying results).

5. Arrow (Flowline):
o Function: Represents the flow of process steps and connects different symbols to show the sequence of

actions.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 20


2nd year CS - Chapter # 2
2.9. Determine the appropriate flowchart symbol in which each of the following instructions or
questions should be placed:

(a) Read A, В, С

(b) Is A =0?

(c) Add B to C giving A

(d) Start

(e) Is A is less than B?

Ans.

(a) Parallelogram, since it is an input instruction.

er
(b) Diamond, since it asks a question.

nt
(c) Rectangle, since it is a process (calculation).

(d) Oval.

(e) Diamond, since it asks a question.


Ce
ish
2.10. Determine the minimum number of arrows connected to a diamond in a flowchart.
gl

There must be at least one arrow going to the diamond, and at least two arrows leaving the diamond;
hence there are at least three arrows connected to a diamond.
En

2.11. Why are there standards for the symbols used in drawing flowcharts?
E

Standards for flowchart symbols exist to ensure clarity, uniformity, and ease of understanding across
M

different users and industries. They help:

1. Facilitate Communication: Standard symbols make it easier for everyone to interpret the flowchart
consistently.
2. Improve Collaboration: Teams from diverse backgrounds can work together without confusion.
3. Ensure Accuracy: Using standardized symbols minimizes errors in understanding processes.
4. Enable Universal Application: Standards allow flowcharts to be shared globally and understood by people
regardless of their location or language.

2.12. How does a flowchart help a programmer in program development?

A flowchart helps a programmer in program development by:

1. Visualizing Logic: It provides a clear, graphical representation of the program's logic and flow.
2. Identifying Errors: Helps spot logical errors before coding begins.
3. Simplifying Complex Processes: Breaks down processes into manageable steps.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 20


2nd year CS - Chapter # 2
4. Facilitating Communication: Makes it easier to explain the program to others, such as team members or
stakeholders.
5. Serving as a Guide: Acts as a blueprint during coding, ensuring the program follows the intended structure.

2.13. What are the various guidelines to be followed while drawing a flowchart?

Here are some key guidelines for drawing a flowchart:

1. Start and End: Use rounded rectangles (terminators) for the start and end points.
2. Process: Use rectangles for process steps or actions.
3. Decision: Use diamonds for decision points (yes/no questions).
4. Flow Direction: Use arrows to indicate the flow of control.
5. Clarity: Keep the chart simple and easy to understand.

er
6. Consistency: Use standard symbols consistently.
7. Labeling: Label all steps and decisions clearly with brief descriptions.

nt
8. Avoid Crossing Lines: Minimize or avoid crossing lines to improve readability.

Ce
2.14. What are the advantages of flowcharts when they are used to solve a problem?
ish
The advantages of using flowcharts to solve a problem include:

1. Clarity: They provide a clear visual representation of the process, making it easier to understand.
gl

2. Organization: Help break down complex problems into simpler, manageable steps.
En

3. Error Identification: Make it easier to identify errors in logic or processes.


4. Communication: Serve as a useful tool for explaining solutions to others.
E

5. Documentation: Act as a helpful reference for future troubleshooting or modifications.


M

2.15. What are the disadvantages of flowcharts?

The disadvantages of flowcharts include:

1. Complexity: For large processes, flowcharts can become too complex and hard to follow.
2. Time-Consuming: Drawing detailed flowcharts can take significant time and effort.
3. Limited Flexibility: Changes in the process may require major revisions to the flowchart.
4. Over-Simplification: Flowcharts might oversimplify processes, missing important details or exceptions.
5. Not Ideal for All Problems: Not suitable for all types of problems, especially abstract or non-linear ones.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 15 of 20


2nd year CS - Chapter # 2
2.16. How can a counter be used to keep track of the number of times a loop has been executed?

A counter can be used to keep track of the number of times a loop has been executed by incrementing the
counter variable each time the loop runs. Here's how:

1. Initialize: Set the counter variable to 0 before the loop starts.


2. Increment: Inside the loop, increase the counter by 1 on each iteration.
3. Display/Use: After the loop ends, the counter will hold the total number of iterations.

Example in pseudocode:

counter = 0 # Initialize counter


for i in range(10): # Loop 10 times
counter += 1 # Increment counter
print(counter) # Output the number of iterations

2.17. Is it possible to have more than one flowchart for a given problem? Give reasons for your answer.

er
Yes, it is possible to have more than one flowchart for a given problem.

nt
Reasons:

Ce
1. Different Approaches: Multiple solutions or approaches to the same problem may result in different
flowcharts.
ish
2. Level of Detail: Flowcharts can vary in detail—some may focus on high-level steps, while others provide
more specific steps.
gl

3. Simplification: Some flowcharts may use more abstraction, while others might break the process down
further.
En

4. Design Choices: Different designers might visualize the process in slightly different ways, leading to varied
flowchart representations.
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 16 of 20


2nd year CS - Chapter # 2
2.18. Three numbers, denoted by the variables A, B, and C are supplied as input data. Draw a
flowchart for the logic to pick and print the smallest of the three numbers.

er
nt
Ce
ish
gl
En

2.19. Analyse the flowchart shown in Fig. 2.18 and list the final output.
E

If the input is
M

N1 = 5 N2 = 10 N3 = 15

Then the output would be 5 which is N1.

2.20. Consider the flowchart in Fig. 2.19. Find the output if the input is

(a) A = 5 B = 10 C = 15 and

(b) A = 15 B = 10 C=5

Ans.

(a) Since A is less than B, BONUS = 100 is executed, and 100 is outputted.

(b) A is greater than B, and B is greater than C; so BONUS = 300 is executed, and 300 is outputted.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 17 of 20


2nd year CS - Chapter # 2
2.21. The first 20 records in a data set are to be read and printed. Draw a flowchart to do this job.
Make sure that the processing stops after the twentieth record.

1. Start
2. Initialize counter (i = 1)
3. Read record i
4. Print record i
5. Increment counter (i = i + 1)
6. Is i ≤ 20?
o Yes: Go to step 3
o No: Proceed to step 7
7. Stop

er
2.22. Draw a flowchart for the logic to find out whether a given triangle ABC is a right-angled triangle.

nt
Assume that the sides of the triangle are supplied as input data. Print the answer as yes or no.

Ce
ish
gl
En
E
M

2.23. Consider Fig. 2.20. Find the output if the input is (a) A = 5 B = 10 (b) A = 20 B = 10

Ans.

(a) 40

(b) 40

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 18 of 20


2nd year CS - Chapter # 2
2.24. Consider the flowchart in Fig. 2.21. Find the output if the input is (a) A = 5 B = 10 C = 20

(b) A = 30 B = 10 C = 20

Ans.

(a) 40

(b) 70
𝟏 𝟏 𝟏 𝟏
2.25. Draw a flowchart that calculates: SUM= + + + ….. +
𝟏 𝟑 𝟓 𝟐𝟓

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 19 of 20


2nd year CS - Chapter # 2
2.26. Consider the equation y = x4 + 2x3 - 4x2 - 16x + 32. Draw a flowchart that calculates y for values
of x from 4 to 4 in step of 0.25, and write each x and its corresponding y.

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 20 of 20


2nd year CS - Chapter # 3

Class: 2nd year

Chapter # 3

An Overview of C Language

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 14


2nd year CS - Chapter # 3
Contents

Introduction to C Language ......................................................................................................................................................... 3


Why Learn C? .................................................................................................................................................................... 3
The IDE of Turbo C++ Compiler ................................................................................................................................................... 3
Preparing to Program.................................................................................................................................................................. 4
The Basic Structure of a C Program ............................................................................................................................................. 4
Key Concepts: .................................................................................................................................................................... 4
Running a Program ..................................................................................................................................................................... 5
Escape Sequences ....................................................................................................................................................................... 5
Good Programming Pratice ......................................................................................................................................................... 6
Section (A).................................................................................................................................................................................. 7

er
-: Answer Keys :-................................................................................................................................................................ 7
Section (B / C) ............................................................................................................................................................................ 8

nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 14


2nd year CS - Chapter # 3
Introduction to C Language
C is a powerful programming language developed by Dennis Ritchie at Bell Laboratories in 1972. It evolved from
BCPL and B languages. Initially designed for structured programming, C supports explicit data typing, control
structures like IF-ELSE, WHILE loops, and block-structured programming, which aids in easier debugging.

By 1978, C gained popularity with Kernighan and Ritchie's book, The C Programming Language. In 1983, C was
standardized by the ANSI committee, ensuring compatibility across platforms. It became the development language
for UNIX and is widely used for system and application software. In 1983, C++, an object-oriented superset of C, was
created by Bjarne Stroustrup to improve the design of complex software projects.

Why Learn C?

C has several advantages:

er
1. Efficiency: Ideal for various computer systems, from personal to mini-computers.
2. Versatility: It can be used for developing operating systems, accounting software, etc.

nt
3. Portability: Programs written in C can be easily transferred to different machines.

Ce
4. Control: Provides low-level control over hardware, similar to assembly language but more readable.
5. Modular Development: Its block-structured nature allows for easier debugging and modular expansion.
ish
6. Flexibility: Developers can create custom function modules for unique requirements.
7. Execution Speed: Fast execution due to its closeness to assembly language, making it suitable for
gl

performance-critical tasks.
8. Industry Standard: Widely used by companies for developing software packages and embedded systems.
En

C remains a key language in programming, essential for a variety of fields and industries, with an increasing demand
for C programmers.
E
M

The IDE of Turbo C++ Compiler


Turbo C++ is an integrated development environment (IDE) designed for C++ programming. It includes a variety of
options for managing files, editing code, compiling, debugging, and running projects. Here's a summary of the main
features:

1. Menu Bar: Contains options like File, Edit, Search, Run, Compile, Debug, Project, Options, Window, and
Help. You can activate a menu by pressing its shortcut key or selecting it from the bar.
2. File Menu: Allows actions like creating a new file, opening, saving, printing, and exiting.
3. Edit Menu: Provides commands for text manipulation (cut, copy, paste, undo, redo).
4. Search Menu: Allows searching and replacing text or navigating to specific lines in the code.
5. Run Menu: Includes options to run programs, reset, and perform debugging.
6. Compile Menu: Commands for compiling code and linking it into executable files.
7. Debug Menu: Tools for inspecting variables, setting breakpoints, and managing the debugging process.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 14


2nd year CS - Chapter # 3
8. Project Menu: Manages project files, allowing you to open, add, or remove files from your project.
9. Options Menu: Configures IDE settings for compilation, linking, and environment preferences.
10. Window Menu: Controls the window layout, including zooming, tiling, or cascading open windows.
11. Help Menu: Provides help with topics, tutorials, and version information.

Turbo C++ also provides quick-reference keys and an integrated help system to aid in development.

Preparing to Program
The preparation for programming involves designing the solution before writing code. For complex problems, a well -
thought-out design can minimize bugs and maintenance costs. The first step is to define the problem, and then
consider whether an existing solution can be reused before developing new software. After designing, the development
process typically includes:

er
1. Source Code: Written in a text editor with a .CPP extension.
2. Compilation: Convert source code to an object file .OBJ using Turbo C++ (via Compile or Alt + F9).

nt
3. Linking: Combine the .OBJ file with libraries to create an executable file.

Ce
The development cycle is iterative, involving writing, compiling, linking, running, debugging, and repeating these
steps to resolve issues until the program works correctly.
ish
The Basic Structure of a C Program
gl

In C programming, every program is made up of functions, which are groups of C statements designed to accomplish
specific tasks. Many functions are predefined in libraries, and you can use them instead of writing your own. You only
En

need to write your own function if the task isn't covered by the library functions.

A basic C program structure consists of:


E

1. Pre-processing Directives (#include): To include necessary libraries, e.g., #include<stdio.h> for


M

input/output.
2. Main Function: The entry point of every C program. It is defined as void main(void) and has a body
enclosed in {}.
3. Statements: Inside the function, you write statements like printf() to perform tasks.
4. Semicolons: Every statement must end with a semicolon.

For example:

#include<stdio.h>
void main(void) {
printf("This is my first C program");
}

Key Concepts:

 #include<stdio.h>: Includes the standard input/output library.


 void main(void): Main function, no arguments and does not return a value.
 printf(): Function to print to the screen.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 14


2nd year CS - Chapter # 3
 Arguments: Passed to functions like printf() to specify what to print.

After coding, you compile the program with Alt + F9. If there are errors, the compiler will show them in the Message
window. You can then fix them and recompile.

Running a Program
After the program has been compiled, you are ready to run it. Pull down the Run menu (Alt+R), then press ‫ ﻠ‬or R to
start the program, ‫ ﻠ‬alone does the job, as run is the top option. You can also press Ctrl+F9 to run the program.
The program FIRST.CPP prints the message This is my first C program and then quickly (almost instantaneously)
return to the Edit window. To see the output on your screen, press Alt-F5. It will appear together with leftover DOS
commands and other old results. The output is just the words you put inside quotation marks. To return to the Edit
window, press J.

Escape Sequences

er
Escape sequences in C are special codes used to control the cursor movement or perform other functions like beeping

nt
or printing special characters. These sequences begin with a backslash \, followed by a second character that tells the
compiler to interpret it in a special way.

Here are some common escape sequences: Ce


ish
Escape
Meaning Effect
Sequence
\n New line Moves the cursor to the beginning of the next line
gl

\t Tab Moves the cursor to the next tab stop


\a Alert (beep) Produces a beep sound
En

Moves the cursor to the beginning of the current line without


\r Carriage return
moving to the next line
\b Backspace Moves the cursor one position back
E

\f Form feed Moves the cursor to the next logical page


M

\\ Backslash Prints a backslash (\)


\' Single quote Prints a single quote mark (')
\" Double quote Prints a double quote mark (")
\? Question mark Prints a question mark (?)
Hexadecimal escape
\xhh ASCII code in hexadecimal notation (hh)
sequence
\ddd Octal escape sequence ASCII code in octal notation (ddd)

Example:
printf("This is\n\tmy first\n\t\tC program");

This will output:

This is
my first
C program

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 14


2nd year CS - Chapter # 3
Additional Notes:

 \n creates a new line at the point where it appears.


 \t moves the cursor to the next tab stop.
 \r returns the cursor to the beginning of the current line without moving to the next.
 \b moves the cursor back one character, but does not delete the character.

Example with \r:


printf("Left\rRight");

This will overwrite the word "Left" with "Right" and display only "Right" because of the carriage return.

Good Programming Pratice


1. Put function definitions and braces on separate lines for readability.

er
2. Use comments to describe the purpose of the program or function.

nt
3. Indent the body of functions for clarity.
4. Always end printed output with \n to position the cursor at the beginning of the next line.

Ce
5. C is case-sensitive, so use lowercase for commands and function names (e.g., printf() instead of PRINTF()).
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 14


2nd year CS - Chapter # 3

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. C is traditionally called the development language of the
(a) Windows 98 operating system (b) Windows NT operating system
(c) UNIX operating system (d) MS Word
2. In 1983, C++ was developed by Bjarne Stroustrup at the
(a) Bell Laboratories. (b) Microsoft
(c) IBM (d) U.S. Defence Department
3. Borland International Inc., USA released its own version of C++ in 1992 and called its complier as

er
(a) Turbo C++ (b) R&K C++
(c) SuperSoft C++ (d) DBS C++

nt
4. All C programs consist of one or more
(a) functions
(c) printf( ) statements
(b) scanf( ) statements
(d) pointers
Ce
ish
5. At a minimum, all C programs must specify one function called
(a) basic function (b) main function
gl

(c) primary function (d) elementary function


En

6. You begin a comment with the characters


(a) */ (b) /*
E

(c) \* (d) *\
M

-: Answer Keys :-
1. c

2. a

3. a

4. a

5. b

6. b

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 14


2nd year CS - Chapter # 3

Section (B / C)
3.1. Briefly explain the history of C language.

The C language was developed in 1972 by Dennis Ritchie at Bell Laboratories. It was designed as a system
programming language for the Unix operating system, offering low-level memory access and efficient
performance.

C evolved from an earlier language called B and incorporated features from the BCPL language. Over time, it
became widely used for developing operating systems, compilers, and embedded systems due to its portability
and versatility. Its influence is seen in modern languages like C++, Java, and Python.

3.2. Where was C originally developed and by whom? What has been done to standardise the
language?

C was originally developed at Bell Laboratories by Dennis Ritchie in 1972. To standardize the language, the

er
American National Standards Institute (ANSI) established the ANSI C standard in 1989, ensuring
consistency across different platforms. This was later adopted by the International Organization for

nt
Standardization (ISO) in 1990 as ISO C.

3.3. What is C++? What is the relationship between C and C++?


Ce
C++ is an object-oriented programming language developed by Bjarne Stroustrup in the early 1980s at Bell
Labs. It is an extension of C, adding features like classes, inheritance, and polymorphism, which support
ish
object-oriented programming. While C focuses on procedural programming, C++ builds on C by incorporating
both procedural and object-oriented paradigms, making it a superset of C.
gl

3.4. What are the general characteristics of C?


En

The general characteristics of C are:

1. Simple and Efficient: C has a simple syntax and provides efficient execution.
E

2. Structured Language: Supports modular programming with functions for better code organization.
M

3. Low-Level Access: Offers direct access to memory and hardware, enabling low-level programming.
4. Portable: Programs written in C can run on different systems with minimal modifications.
5. Rich Library Support: Comes with standard libraries for various functionalities.
6. Fast Execution: Compiled language with minimal runtime overhead, ensuring speed.
7. Flexible: Allows both high-level and low-level programming in the same code.
8. Extensibility: Supports the addition of user-defined functions for specific tasks.

3.5. What is the purpose of the statement #include<stdio.h> in a C program?

The statement #include<stdio.h> in a C program includes the Standard Input Output header file
(stdio.h). It provides declarations for standard input/output functions like:

 printf() (for output)


 scanf() (for input)

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 14


2nd year CS - Chapter # 3
 Other file handling functions like fopen(), fclose(), etc.

Without including stdio.h, these functions cannot be used.

3.6. What is a statement terminator?

A statement terminator in C is a semicolon (;). It marks the end of a statement, instructing the compiler that
the current statement is complete and ready for execution.

For example:

int a = 5; // Semicolon terminates the statement

3.7. What is the purpose of comments in a C program?

Comments in a C program are used to explain the code, making it easier to understand for programmers. They
are ignored by the compiler and do not affect the program's execution.

er
 Single-line comment: Starts with //.

nt
 Multi-line comment: Enclosed within /* and */.

Example:

// This is a single-line comment


/* This is a
Ce
ish
multi-line comment */

3.8. Describe the composition of a function in C. Explain the main( ) function.


gl

Composition of a Function in C:
En

A function in C is composed of three main parts:


E

1. Return Type: Specifies the type of value the function will return (e.g., int, void, float).
2. Function Name: Identifies the function, allowing it to be called (e.g., main, sum).
M

3. Parameter List: Variables passed to the function for input (enclosed in parentheses).
4. Function Body: The code block enclosed in {} that defines the functionality.

main() Function:

 The main() function is the entry point of every C program.


 It defines the program's execution flow.
 Syntax:

int main() {
// Code statements
return 0; // Returns control to the OS
}

 Purpose: The operating system calls main() to start the program, and return 0 indicates successful
execution.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 14


2nd year CS - Chapter # 3
3.9. Why do you use a parameter when calling a function?

Parameters are used when calling a function to:

1. Pass Input Values: They allow you to provide specific data to the function that it needs to perform its task.
2. Reusability: Functions with parameters can be used with different inputs, making them more flexible and
reusable.
3. Custom Behavior: Parameters let you customize the function's output or operations based on the input
provided.

For example:

int add(int a, int b) {


return a + b;
}

int result = add(5, 3); // Parameters 5 and 3 are passed to the function.

er
Here, parameters a and b receive the values 5 and 3, allowing the add() function to work with different inputs.

nt
3.10. What is the general structure of a C program?

Ce
The general structure of a C program consists of the following sections:

1. Preprocessor Directives: Includes header files and macros.


ish
Example: #include<stdio.h>
2. Global Declarations: Variables or functions declared globally, accessible throughout the program.
3. Main Function: The entry point of the program.
gl

Syntax:
En

int main() {
// Code here
return 0;
}
E

4. User-Defined Functions: Additional functions defined by the programmer for modularity.


M

Example:
#include<stdio.h> // Preprocessor Directive

// Global Declaration
int globalVar = 10;

// Main Function
int main() {
printf("Hello, World!\n");
return 0;
}

// User-Defined Function
void display() {
printf("This is a user-defined function.\n");
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 14


2nd year CS - Chapter # 3
3.11. Why are some of the statements within a C program indented?

Indentation in C programs is used for the following reasons:

1. Improves readability: It helps to visually separate different blocks of code, making it easier to understand
the program’s structure.
2. Indicates code hierarchy: Indentation shows the relationship between control structures (like loops or
conditionals) and their corresponding blocks of code.
3. Code maintenance: It makes it easier to modify and debug the code by clearly defining which statements
belong to which blocks.

3.12. Write a program that displays the following on the screen:

(a) Welcome to Computer Lab.

#include <stdio.h>

er
int main() {
printf("Welcome to Computer Lab.\n");

nt
return 0;
}

(b) Board of Intermediate Education, Karachi. Ce


ish
#include <stdio.h>

int main() {
gl

printf("Board of Intermediate Education, Karachi.\n");


return 0;
}
En

3.13. Write the printf( ) instructions for printing your name, address, and telephone number, centered
on the screen.
E
M

#include <stdio.h>
int main() {
// Printing the name, address, and telephone number centered
printf("\n\n\n\n\n\n\n\n\n\n\n");
printf(" Your Name\n");
printf(" Your Address\n");
printf(" Your Telephone Number\n");
return 0;
}

3.14. Explain what is wrong with the following program:

#include<stdio.h>
void main(void)
{
printf("I am a College Student");
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 14


2nd year CS - Chapter # 3
The main function should return an int type, not void. This allows the program to return an exit status to the
operating system, typically 0 for successful execution.

Here’s the corrected version of the program:

#include<stdio.h>

int main(void)
{
printf("I am a College Student");
return 0; // Returns 0 to indicate successful execution
}

3.15. ANSI C does not provide for the nesting of comments, although many compilers provide an
option for this. Try the following line on your compiler and see what happens.

/*This is an attempt/*to nest*/a comment.*/

er
This happens because the C compiler will interpret the first /* as the beginning of a comment and the first */ as

nt
the end, leaving the rest of the code (including the inner /*to nest*/) as invalid syntax.

3.16. What are escape sequences?


Ce
Escape sequences in C are special character combinations that are used to represent certain characters or
ish
actions that cannot be directly typed into the string. They begin with a backslash ( \) followed by a character.

Here are some common escape sequences:


gl

 \n : Newline (moves to the next line)


En

 \t : Horizontal tab
 \\ : Backslash (\)
 \" : Double quote (")
 \r : Carriage return (moves the cursor to the beginning of the line)
E

 \b : Backspace
M

 \a : Bell (produces a beep)


 \v : Vertical tab
 \f : Form feed

3.17. What is the difference between \n and \r escape sequence?

1. \n (Newline):
o Moves the cursor down to the next line.
o It also moves the cursor to the beginning of the line (line feed).
o Example:
o printf("Hello\nWorld");

Output:

Hello
World

2. \r (Carriage Return):
o Moves the cursor back to the beginning of the current line without advancing to the next line.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 14


2nd year CS - Chapter # 3
o The rest of the line will be overwritten by whatever is printed after the \r.
o Example:
o printf("Hello\rWorld");

Output:

Worldo

3.18. Are C programs required to be typed in lowercase? Is uppercase ever used in C program?
Explain.

C programs are not required to be typed in lowercase, but there are conventions and rules for using
uppercase and lowercase in C programming:

1. Keywords: C keywords (like int, if, while, etc.) are always lowercase. These are reserved words in the

er
C language and must be typed in lowercase.
2. Identifiers: User-defined identifiers (such as variable names, function names, etc.) can be written in both

nt
lowercase and uppercase.

Ce
3. Case Sensitivity: C is a case-sensitive language, which means variable, Variable, and VARIABLE are all
treated as different identifiers.

Example:
ish
#include <stdio.h>
gl

#define MAX_SIZE 100 // Uppercase constant


int main() {
En

int max_size = MAX_SIZE; // Mixing uppercase macro and lowercase


variable
printf("%d\n", max_size);
E

return 0;
M

3.19. State some rules of a good programming practice.

Good programming practices include:

1. Use meaningful names for variables and functions.


2. Indent and format code consistently.
3. Comment to explain complex logic.
4. Avoid hardcoding values; use constants.
5. Keep functions small and focused.
6. Handle errors properly.
7. Minimize global variables.
8. Follow DRY (Don't Repeat Yourself) principle.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 14


2nd year CS - Chapter # 3
9. Test your code regularly.
10. Follow coding standards and conventions.
11. Use version control (e.g., Git).

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 14


2nd year CS - Chapter # 4

Class: 2nd year

Chapter # 4

C Fundamentals

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 18


2nd year CS - Chapter # 4
Contents

C Fundamentals: ....................................................................................................................................................................... 3
1. C Character Set .............................................................................................................................................................. 3
2. Identifiers and Keywords ............................................................................................................................................... 3
Naming Conventions:......................................................................................................................................................... 3
3. Keywords in C ................................................................................................................................................................ 3
Data Types: ................................................................................................................................................................................ 4
Basic Data Types ................................................................................................................................................................ 4
Type Modifiers ................................................................................................................................................................... 4
Integer Range and Format ................................................................................................................................................ 4
Floating-Point Range and Format ..................................................................................................................................... 5

er
Character Data Type ......................................................................................................................................................... 5
Constants: .................................................................................................................................................................................. 5

nt
Variables: ................................................................................................................................................................................... 5

Ce
Section (A).................................................................................................................................................................................. 8
-: Answer Keys :-................................................................................................................................................................ 8
ish
Section (B / C) ............................................................................................................................................................................ 9
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 18


2nd year CS - Chapter # 4
C Fundamentals:
In C programming, data is input into the computer, processed, and output as information. However, before processing
data, the program needs to know what type of data it will handle.

1. C Character Set

A character in C represents any alphabet, digit, or special symbol used for information. The allowed characters are:

 Alphabets: A, B, C, ..., Z, a, b, c, ..., z


 Digits: 0, 1, 2, ..., 9
 Special characters: + - % & # @$!?^"'~\ <>()[]{}:; (and a blank space)

2. Identifiers and Keywords

Identifiers are names used for program elements like variables, functions, and arrays. Some rules for identifiers in C:

er
 Start: An identifier must begin with a letter or an underscore (_).

nt
 Content: It can contain letters, digits, or underscores.
 No spaces or special characters (except for the underscore _).


Length: Cannot exceed 31 characters.
Ce
Case Sensitivity: Identifiers are case-sensitive (e.g., MAX and max are different).

Some valid identifiers:


ish
 x, table, sum_1, tax_rate_auto
gl

Some invalid identifiers (with reasons):


En

 sum_2 (valid, but listed here for context)


 temperature (valid, for context)
 illegal name (blank space)
E

 tax-rate (hyphen is not allowed)



M

5th (cannot start with a digit)


 "x" (quotes are invalid)
 est#west (special characters like # are invalid)

Naming Conventions:

 Underscore for libraries: Some standard libraries use _ as the first letter for functions/variables to avoid
naming collisions.
 Meaningful names: It's good practice to use descriptive names, e.g., tax_rate, price, tax in a tax calculation
program.

3. Keywords in C

There are reserved keywords in C that cannot be used as identifiers. These keywords have predefined meanings in the
language. Some of them include:

 auto, break, case, char, const, continue, do, double, else, enum, extern, float, for, goto, if, int,
long, return, short, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 18


2nd year CS - Chapter # 4
For example, auto is a keyword in C and cannot be used as a variable name, but you can use auto_type because it’s
treated as one word.

Data Types:
In C, data types are used to define the type of data a variable will hold. They ensure that data is manipulated correctly
and are represented in memory efficiently. C supports several basic data types, each with specific memory
requirements.

Basic Data Types

1. int: Represents integer values (positive, negative, or zero).


o Memory: 2 bytes
o Example: int num = 5;

2. char: Represents a single character.

er
o Memory: 1 byte
o Example: char ch = 'A';

nt
3. float: Represents floating-point numbers (numbers with a decimal point).
o Memory: 4 bytes
o Example: float pi = 3.14;
Ce
4. double: Represents double-precision floating-point numbers (higher precision than float).
ish
o Memory: 8 bytes
o Example: double bigNum = 12345.6789;
gl

Type Modifiers
En

Modifiers can adjust the range or precision of the basic data types:

 short: Shorter integer size (usually 2 bytes).


E

 long: Larger integer size (usually 4 bytes).



M

signed: Allows both positive and negative values.


 unsigned: Allows only positive values.

For example:

long int i;
unsigned int count;

Integer Range and Format

Data Type Range Bytes Format


short signed int -32768 to 32767 2 %d

short unsigned int 0 to 65535 2 %u

long signed int -2147483648 to 2147483647 4 %ld

long unsigned int 0 to 4294967295 4 %lu

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 18


2nd year CS - Chapter # 4
Floating-Point Range and Format

Data Type Range Bytes Format


float 3.4e-38 to 3.4e+38 4 %f
double 1.7e-308 to 1.7e+308 8 %lf
long double 3.4e-4932 to 1.1e+4932 10 %Lf

Character Data Type

The char type is used for characters. It typically occupies 1 byte and can store any ASCII character. It can also store
numeric values but distinguishes between the character '1' and the integer 1. Examples of character assignments:

char ch = 'A'; // Character 'A'


char num = 65; // ASCII value of 'A'

Constants:

er
 Integer Constants: They are whole numbers without decimals and can be positive or negative. They can be

nt
written in decimal, octal (starting with 0), or hexadecimal (starting with 0x or 0X) formats.


o Examples: 273, -597, 0x2, -0573.

Ce
Floating-Point Constants: These represent real numbers and can be written in either fractional form or
ish
exponential form.
o Examples: 0.002e+3, -0.5, 3e-7.
gl

 Character Constants: A single character enclosed in single quotes. They represent individual characters or
symbols.
En

o Examples: 'B', 'm', '5'.

 String Constants: A sequence of characters enclosed in double quotes, often used to represent text.
E

o Example: "The quick brown fox" .


M

 Symbolic Constants: These are user-defined constants that represent values. They can be defined using const
or #define.
o Examples using const:
 const float PI = 3.14159;
 const int YEAR_LENGTH = 12;

o Examples using #define:


 #define PI 3.14
 #define TRUE 1

Variables:
A variable is a programmer-defined identifier whose value can change during program execution. It must have a
name and a data type. The data type determines how the data is represented internally.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 18


2nd year CS - Chapter # 4
 Common data types: int (integer), float (real numbers), double (more precise floating-point), char
(character).

Rules for Constructing Variable Names:

 Must start with an alphabet.


 Cannot contain commas or blanks.
 Only underscores (_) are allowed as special symbols.

Declaration of Variables: A variable declaration associates variables with a specific data type.

 Single Declaration:
int num;
float tax_rate;

 Multiple Declarations: You can declare multiple variables of the same type in one line:
int count, students, year;
float tax_rate, discount;

er
 Initial Value Assignment: You can assign an initial value to a variable at the time of declaration:

nt
int count = 5;
char initial = 'A';


float rate = 0.55;

Ce
Alternatively, you can assign values separately after the declaration:
count = 5;
ish
initial = 'A';
rate = 0.55;
gl

Arrays:
En

An array is a collection of data items that all share the same name and must be of the same data type (e.g., integers,
characters, etc.).

o String Arrays: Since C doesn't have a built-in string type, strings are represented as arrays of
E

characters. Each character in the string is stored consecutively in memory.


M

Declaring Arrays:

o Basic Syntax:

char VARNAME[N];

Where VARNAME is the name of the array, and N is the maximum number of characters the array can
hold.

o Important Note: You need to account for the null character (\0), which marks the end of a string in C.
Therefore, the number N in char VARNAME[N]; must be one more than the number of characters you
want to store. For example, to store a string of up to 9 characters, you need char VARNAME[10];.

Examples:

o Declaring a string to store a student's name:

char student[10];

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 18


2nd year CS - Chapter # 4
If the name exceeds 9 characters (including the null character), it will cause a runtime error.

o String Initialization: A string can also be initialized without specifying its size:

char student[] = "Aqib Ilyas";

This will automatically create an array of 10 elements: 9 for the characters and 1 for the null character
(\0).

Considerations:

o Ensure you allocate enough space for the string, including the null character.
o If the string length exceeds the allocated space, the program will result in a runtime error.

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 18


2nd year CS - Chapter # 4

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. Char constant values
(a) must be enclosed in double quotes
(b) must be enclosed in single quotes
(c) can be enclosed in either single or double quotes
(d) does not need to be enclosed in quotes
2. int constant values
(a) can include an optional comma to improve readability

er
(b) can include an optional dollar sign when representing money
(c) can include an optional plus or minus sign

nt
(d) can consist only of digits
3. Symbolic constants
(a) must appear in capital letters
Ce
ish
(b) are disliked by serious programmers
(c) enhance the readability of a program
gl

(d) can include keywords


En

4. Variables
(a) are created using the #define directive
E

(b) are floating-point by default


M

(c) should have simple names


(d) can be defined as having any C data type
5. A variable definition differs from a declaration in that
(a) the declaration sets aside storage space.
(b) the declaration specifies the name and type of the variable.
(c) the definition sets aside storage space.
(d) the definition specifies the name and type of the variable.

-: Answer Keys :-
1. 2. 3. 4. 5.

b c c d c

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 18


2nd year CS - Chapter # 4

Section (B / C)
4.1. List five keywords and explain their use.

1. int
o Used to declare integer variables.
Example: int age = 25;

2. return
o Ends a function and optionally returns a value to the calling function.
Example: return 0;

3. if
o Used for conditional execution of code.
Example:
if (x > 0) {
printf("Positive number");

er
}

nt
4. for
o Implements a loop with initialization, condition, and increment/decrement.
Example:
for (int i = 0; i < 5; i++) {

}
printf("%d ", i);
Ce
ish
5. void
o Indicates that a function does not return a value.
gl

Example:
void display() {
En

printf("Hello!");
}

4.2. State the rules which must be observed while constructing identifiers.
E
M

1. Start with a letter or underscore: Must begin with A-Z, a-z, or _.


2. Contain letters, digits, or underscores: No spaces or special characters.
3. No keywords: Cannot use reserved words like int or if.
4. Case-sensitive: value ≠ Value.
5. Avoid starting with _: Reserved for system use.

4.3. Which of the following are not valid identifiers and why?

2y yes ono_o_no 00_go star*it me to-2 xYint int

1. 2y: Invalid because it starts with a digit.


2. yes: Valid.
3. ono_o_no: Valid.
4. 00_go: Invalid because it starts with digits.
5. star*it: Invalid because * is not allowed in identifiers.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 18


2nd year CS - Chapter # 4
6. me to-2: Invalid because it contains spaces and -.
7. xYint: Valid.
8. int: Invalid because it's a reserved keyword.

4.4. What are the keywords in C? What restrictions apply to their use?

Keywords in C

Keywords are reserved words in C with predefined meanings and purposes. Some common keywords are:
int, float, return, if, else, while, for, break, continue, void, switch, case, default, do, char.

Restrictions on Keywords

1. Keywords cannot be used as identifiers (variable or function names).


2. They are case-sensitive (int is a keyword, but Int is not).
3. Keywords cannot be modified or redefined.

er
nt
4.5. Which data type is each of the following?

(a) TRUE

(b) 3958
Ce
ish
(c) "&"
gl

(d) 9
En

(e) "9"

(f) "This is my home."


E

(a) TRUE: Boolean (if supported, or int as 1 in C).


M

(b) 3958: int (Integer).


(c) "&": char (Character).
(d) 9: int (Integer).
(e) "9": char[] (String, an array of characters).
(f) "This is my home.": char[] (String, an array of characters).

4.6. Are these integers valid or invalid?

(a) 485

(b) 000

(c) 3854&

(d) -935
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 18
2nd year CS - Chapter # 4
(e) 96,109

(a) 485: Valid


(b) 000: Valid (equivalent to 0)
(c) 3854&: Invalid (contains &, which is not allowed in integers)
(d) -935: Valid (negative integers are valid)
(e) 96,109: Invalid (commas are not allowed in integers)

4.7. Are these valid floating-point numbers? If not, change them so they will be valid?

(a) +953.0

(b) -0.3874

er
(c) 6,209.85

nt
(d) %385.86

(e) 395e + 3

(a) +953.0: Valid


Ce
ish
(b) -0.3874: Valid
(c) 6,209.85: Invalid (commas are not allowed).
gl

Correction: 6209.85
En

(d) %385.86: Invalid (% is not allowed).


Correction: 385.86
(e) 395e + 3: Invalid (space is not allowed between e and +3).
E

Correction: 395e+3
M

4.8. Determine which of the following are valid character constants?

(a) t'

(b) " U "

(c) '#'

(d) '\n'

(e) '\1876'

(f) '\\'

(a) t': Invalid (character constants must be enclosed in single quotes and consist of a single character).
Correction: 't'
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 18
2nd year CS - Chapter # 4
(b) " U ": Invalid (double quotes are used for strings, not character constants).
Correction: 'U'

(c) '#': Valid (a single character enclosed in single quotes).

(d) '\n': Valid (represents the newline escape character).

(e) '\1876': Invalid (a character constant cannot have more than three octal digits in an escape sequence).
Correction: '\123' (use up to three valid octal digits, if applicable).

(f) '\': Valid (represents a backslash character as an escape sequence).

4.9. Determine which of the following are valid string constants?

(a) " 1.7E +23"

(b) '4:40 Α.Μ.'

er
(c) "STUDENT:

nt
(d) "Chap-3 (cont \ 'd ) "
Ce
(a) " 1.7E +23": Valid (a valid string enclosed in double quotes).
ish
(b) '4:40 Α.Μ.': Invalid (strings must be enclosed in double quotes, while single quotes are used for character
constants).
Correction: "4:40 Α.Μ."
gl

(c) "STUDENT:: Invalid (the string is missing a closing double quote).


En

Correction: "STUDENT:"

(d) "Chap-3 (cont \ 'd ) ": Valid (the string uses escape characters \' correctly to include a single quote inside
E

the string).
M

4.10. What is a char data type?

The char data type in C is used to store single characters. It typically occupies 1 byte of memory and can
hold any ASCII character (values from 0 to 255) or can be used to store small integers.

Example:

char letter = 'A'; // Stores the character 'A'


char number = 65; // Stores the ASCII value of 'A' (65)

4.11. How is the data type string different from the data type char?

char holds one character, while a string is an array of char that holds multiple characters.

4.12. How does the character '3' differ from the number 3?

'3' is a character with an ASCII value of 51, while 3 is an integer representing the number itself.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 18


2nd year CS - Chapter # 4
4.13. What data type would you use for a variable storing area of a triangle?

For a variable storing the area of a triangle, you would typically use a floating-point data type because the area
can have decimal values.

The most common choices are:

 float: If you need a lower precision for smaller values.


 double: For higher precision and larger values.

Example:

double area; // For higher precision


float area; // For lower precision

4.14. Why would a program need to use the long int data type?

er
A program would use the long int data type when it needs to store larger integer values than those that can
be held by the standard int data type.

nt
 On most systems, long int usually holds 4 bytes (32 bits) or 8 bytes (64 bits), depending on the platform.

Example:

long int largeNumber = 1234567890;


Ce
// Storing a large integer value
ish
4.15. Why would you use a double float type?
gl

You would use the double data type when you need to store floating-point numbers (decimals) with higher
precision than what the float type provides.
En

When to use:
E

 For calculations requiring high precision, such as scientific, engineering, or financial applications where
M

small differences matter.

Example:

double pi = 3.141592653589793; // Higher precision for floating-point numbers

4.16. Name and describe the four basic data types in C.

1. int (Integer):
o Used to store whole numbers (both positive and negative).
o Typically occupies 4 bytes of memory (depends on the system).
o Example: int age = 25;

2. char (Character):
o Used to store single characters.
o Typically occupies 1 byte of memory.
o It can hold ASCII values ranging from 0 to 255.
o Example: char letter = 'A';

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 18


2nd year CS - Chapter # 4
3. float (Floating-point):
o Used to store decimal numbers (single precision).
o Typically occupies 4 bytes of memory.
o Example: float price = 19.99;

4. double (Double precision floating-point):


o Used to store decimal numbers with higher precision than float.
o Typically occupies 8 bytes of memory.
o Example: double pi = 3.141592653589793;

4.17. What is a variable?

Variable

A variable in C is a named storage location in memory that holds a value. The value stored in a variable can
change during the program's execution.

er
Key points:

nt
1.Declaration: A variable must be declared with a data type before it is used.
 Example: int age; (declaring a variable of type int named age).

Ce
2.Initialization: A variable can be initialized with a value at the time of declaration.
 Example: int age = 25; (declaring and initializing age with 25).
3.Value Changes: The value of a variable can change throughout the program.
ish
 Example: age = 30; (updating the value of age).

4.18. What is the difference between a constant and a variable?


gl

1. Constant:
En

o A constant is a value that cannot be changed once it is assigned.


o Declared using the const keyword or #define preprocessor directive.
o Example: const int MAX_SIZE = 100; or #define PI 3.14;
E

o Constants provide fixed values throughout the program.


M

2. Variable:
o A variable is a storage location that can hold a value and that value can change during the
program's execution.
o Example: int age = 25;
o Variables are used to store data that may change over time.

4.20. Does C have a string data type?

No, C does not have a built-in string data type. Instead, strings are represented as arrays of characters.

A string in C is essentially an array of char with a special null terminator ( '\0') to mark the end of the string.

Example:
char str[] = "Hello, World!"; // String as an array of characters

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 18


2nd year CS - Chapter # 4
 The string "Hello, World!" is stored as a character array: {'H', 'e', 'l', 'l', 'o', ',', '
', 'W', 'o', 'r', 'l', 'd', '!', '\0'}.
 The '\0' at the end indicates the end of the string.

4.21. Describe two different ways that floating-point constants can be written. What special rules
apply in each case?

1. Decimal Notation:
o The floating-point constant is written as a normal decimal number with a fractional part.
o Example: 3.14, 0.5, 12.0
o Rules:
 The number must include a decimal point (e.g., 3.14 or 0.5).
 No need for an exponent or scientific notation.

2. Scientific Notation (Exponent Notation):


o The floating-point constant is written with an exponent to indicate the power of 10.
o Example: 1.23e4, 2.5E-3, 5.6e+2

er
o Rules:
 The number is written as a base followed by an exponent (e or E).

nt
 The exponent can be either positive or negative and indicates how many places the decimal
point should be shifted.

Ce
 For example, 1.23e4 means 1.23 * 10^4 = 12300 , and 2.5E-3 means 2.5 * 10^-3 =
0.0025.
ish
 Decimal notation is for regular floating-point numbers with a fractional part.
 Scientific notation is used to represent very large or very small numbers using an exponent.
gl

4.22. Can a variable have the same value throughout the entire program?
En

Yes, a variable can have the same value throughout the entire program if it is declared as a constant.

4.23. How do you change the value of a constant?


E

In C, once a constant is declared using the const keyword or #define, its value cannot be changed
M

throughout the program. Attempting to modify a constant will result in a compilation error.

Constants are meant to provide immutable values during the program execution. If you need a value that can
change, use regular variables instead.

4.24. Distinguish between the following:

(a) float and double data type

(b) constant and variable

(c) integer and character constant

(a) float vs double:

 float: Single precision, 4 bytes, less precision.


 double: Double precision, 8 bytes, more precision.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 15 of 18


2nd year CS - Chapter # 4
(b) constant vs variable:

 constant: Value cannot be changed.


 variable: Value can change during program execution.

(c) integer vs character constant:

 integer constant: Whole numbers (e.g., 100).


 character constant: Single character (e.g., 'A').

4.25. Decide what types of data you need, and write their declarations, for a program that computes
the sum and average of four numbers.

You need integers or floating-point numbers for the values. Here's how you can declare the data types:

int num1, num2, num3, num4; // For storing the four numbers
float sum, average; // For storing the sum and average

er
 Use int for the numbers if they are integers.

nt
 Use float for the sum and average to handle decimal values.

Ce
4.27. Explain what is wrong in the following program segment:

char student [3] = "Rizwan"


ish
void main (void)
float tax_rate;
char name (10);
gl

int num [10]


tax_due = "Rs.1,284.00";
En

1. Array Initialization Error:


E

char student[3] = "Rizwan";


M

o The array student[3] can only hold 3 characters, but "Rizwan" has 6 characters, so the array size is
too small. It should be char student[7] = "Rizwan"; (including the null terminator).

2. Incorrect Syntax in Variable Declarations:

char name(10);

o The correct syntax for declaring an array is char name[10]; (not parentheses).

3. Missing Semicolon:
o There is a missing semicolon after int num[10]. It should be int num[10];.

4. Incorrect Assignment to tax_due:

tax_due = "Rs.1,284.00";

o tax_due is not declared, and it should be declared as a char array or pointer to store the string.
Example: char tax_due[] = "Rs.1,284.00"; .

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 16 of 18


2nd year CS - Chapter # 4
Corrected Code:
char student[7] = "Rizwan";
void main(void) {
float tax_rate;
char name[10];
int num[10];
char tax_due[] = "Rs.1,284.00";
}

4.28. Write appropriate declaration for following variables and arrays.

(a) Integer variables: a, b

(b) Unsigned integer variable: students

(c) Floating-point variables: x, y, z

er
(d) Character variables: l, m, n

nt
(e) 60-element character array: message

(a) Integer variables: a, b Ce


ish
int a, b;

(b) Unsigned integer variable: students


gl

unsigned int students;


En

(c) Floating-point variables: x, y, z

float x, y, z;
E

(d) Character variables: l, m, n


M

char l, m, n;

(e) 60-element character array: message

char message[60];

4.29. Write appropriate declaration and assign the given initial values to following variables and
arrays.

(a) Integer variables: a = 485 , b = - 278

(b) Unsigned integer variable: students = 96854

(c) Floating-point variables: x = 0.4 , y = 0.0005 , z = 45.7

(d) Double-precision variables: d1 = 𝟏. 𝟔𝟖 ∗ 𝟏𝟎−𝟔

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 17 of 18


2nd year CS - Chapter # 4
(a) Integer variables: a = 485, b = -278

int a = 485, b = -278;

(b) Unsigned integer variable: students = 96854

unsigned int students = 96854;

(c) Floating-point variables: x = 0.4, y = 0.0005, z = 45.7

float x = 0.4, y = 0.0005, z = 45.7;

(d) Double-precision variables: d1 = 1.68 * 10^(-6)

double d1 = 1.68e-6;

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 18 of 18


2nd year CS - Chapter # 5

Class: 2nd year

Chapter # 5

Operators and Expressions

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 15


2nd year CS - Chapter # 5
Contents
Network Information ..................................................................................................................... Error! Bookmark not defined.
Advantages of Networking.................................................................................................... Error! Bookmark not defined.
Section (A).................................................................................................................................................................................. 7
-: Answer Keys :-................................................................................................................................................................ 7
Section (B / C) ............................................................................................................................................................................ 8
Benefits of Networks: ............................................................................................................. Error! Bookmark not defined.

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 15


2nd year CS - Chapter # 5
Expressions
An expression is a collection of operands (one or more) and operators (zero or more) that can be evaluated to a single
value. An operand is a constant, variable, or another expression. The most general form is

operand-1 operation operand-2

The result is a new value. For example:

2 + 6 evaluates to 8

4 * 5 evaluates to 20

48/8 evaluates to 6

10 - 3 evaluates to 7

er
18.4 – 4 evaluates to 14.4

nt
Classifications of Operators
Operators fall into three classes:

1. Unary Operator: Those that requires one operand.


Ce
ish
2. Binary Operator: Thos that requires two operands.
gl

3. Ternary Operator: This one is unique. It requires three operands.


En

C is very rich in operators and is sometimes called "the language of operators". It has as many as 45 different
operators. Some commonly used operators are:
E

1. Arithmetic operators
M

2. Assignment operators

3. Relational operators

4. Logical/Boolean operators

5. Increment and Decrement operators

Arithmetic Operator
Operator Operation Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (Remainder) a % b

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 15


2nd year CS - Chapter # 5
Operator Precedence & Associativity

Operator Operation Precedence Associativity


* / % Multiplication, Division, Modulus Higher Left to Right
+ - Addition, Subtraction Lower Left to Right

Examples with Integer and Floating-Point Variables

Given:

int i = 3, j = 4;
float f = 2.5, g = 1.0;
Expression Calculation Result
i + j + f + g 3 + 4 + 2.5 + 1 10.5
i + f * j + g 3 + (2.5 * 4) + 1 14.0

er
f / g + i / j (2.5 / 1) + (3 / 4) 2.5 (integer division 3/4 is 0)

nt
f - g * i + g / j 2.5 - (1 * 3) + (1/4) -0.25

f / 0 Undefined (division by zero) Error

Assignment Operator
Ce
ish
The basic assignment operator in C is =. It assigns the value of an expression to a variable.
gl

General form:

identifier = expression;
En

where:

 identifier is typically a variable.


E

 expression can be a constant, a variable, or a complex expression.


M

Examples:

Expression Meaning
x = y; Assign the value of y to x.
sum = 25.23; Assign 25.23 to sum.
a = b + c; Assign b + c to a.
area = length * breadth; Assign the multiplication of length and breadth to area.

Compound Assignment Operators

C provides shortcut assignment operators that combine an arithmetic operation with assignment.

Operator Operation Example Equivalent To


+= Add-assign a += b; a = a + b;

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 15


2nd year CS - Chapter # 5
-= Subtract-assign a -= b; a = a - b;

*= Multiply-assign a *= b; a = a * b;

/= Divide-assign a /= b; a = a / b;

%= Modulus-assign a %= b; a = a % b;

Example:
Instead of writing:
number_of_students = number_of_students * 2;

We can write:
number_of_students *= 2;

This is shorter, easier to read, and reduces the chance of errors.

Relational Operators

er
Relational operators compare two numeric values and return 1 (true) or 0 (false). The operands can be variables,

nt
constants, or expressions that evaluate to numerical values. Since characters have ASCII values, relational operators
can also compare characters.

List of Relational Operators Ce


ish
Operator Meaning
< Less than
>
gl

Greater than
<= Less than or equal to
En

>= Greater than or equal to


== Equal to
!= Not equal to
E
M

Example Usage

int a = 5, b = 10;
printf("%d", a < b); // Output: 1 (true)
printf("%d", a > b); // Output: 0 (false)

Relational Expressions

A relational expression contains two arithmetic expressions connected by a relational operator.

 If the condition is true, the result is 1.


 If the condition is false, the result is 0.

Example:

int a = 5, b = 10, c = 2;
printf("%d", (a + c) < (b / 2)); // (5+2) < (10/2) → 7 < 5 → 0 (false)

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 15


2nd year CS - Chapter # 5
Logical/Boolean Operators
Combine expressions to return either true (1) or false (0). Named after George Boole.

 Types of Logical Operators:


o && (AND): True if both operands are true.
o || (OR): True if at least one operand is true.
o ! (NOT): Inverts the operand’s truth value.

 Precedence: ! > && > ||. Logical operators have lower precedence than relational and arithmetic operators.

 Examples: Demonstrate truth table evaluations and complex expressions with logical operators.

Increment and Decrement Operators


o ++ and -- modify a variable's value by 1.

er
o Prefix (++a): Increments first, then uses the new value.

nt
o Postfix (a++): Uses the value first, then increments.

Casts
Ce
Examples: Show usage of logical, relational, and increment/decrement operators in expressions.
ish
Converts a value from one data type to another using (data type) expression.
gl

 Example:
En

float f;
int i = 6, j = 4;
f = (float) i / j; // Output: f = 1.5
E

 Why Casting?: Without casting, i / j performs integer division, giving 1 instead of 1.5.
M

 Correct Usage:
o (long) ('A' + 1)
o (float) ((int) j + 1)
o (double) (x = 45)

 Incorrect Usage: (double) x = 45; (syntax error).

 Operator Precedence: Cast operator () has higher precedence than arithmetic operators and is right-to-left
associative.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 15


2nd year CS - Chapter # 5

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer

1. Which of the following is an example of initialising a variable?


(a) num = 2; (b) int num; (c) num < 2; (d) int num = 2;
2. Floating point variables are used instead of integers to
(a) avoid being too specific about what value a number has
(b) permit the use of decimal points in numbers
(c) make possible the use of even numbers
(d) conceal the true value of the numbers

er
3. Which of the following is an arithmetic operator?

nt
(a) + (b) & (c) && (d) <
4. Are the following expressions true or false?
(a) 1 > 2 (b) 'a' < 'b' (c) 1 == 2
Ce
(d) '2' == '2'
ish
5. Precedence determines which operator
(a) is most important (b) is used first
gl

(c) is fastest (d) operates on the largest number


En

6. A relational operator is used to


(a) combine values (b) compare values
E

(c) distinguish different types of variables (d) change variables to logical values
M

7. The standard library contains many useful functions called


(a) initial functions (b) basic functions
(c) library commands (d) library functions

-: Answer Keys :-
1. d
2. b
3. a
4. (a) False (b) True (c) False (d) True
5. b
6. b
7. d

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 15


2nd year CS - Chapter # 5

Section (B / C)
5.1. What is an operator? Describe several different types of operators.

Operator in C

An operator is a symbol that tells the compiler to perform specific mathematical or logical operations on one or more
operands.

Types of Operators in C

1. Arithmetic Operators: Perform basic mathematical operations.


o + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulus)

2. Relational Operators: Compare two values.


o == (Equal), != (Not equal), > (Greater than), < (Less than), >= (Greater than or equal to), <= (Less than or equal

er
to)

nt
3. Logical Operators: Used for logical operations.
o && (Logical AND), || (Logical OR), ! (Logical NOT)

4. Bitwise Operators: Perform operations at the bit level.


o
Ce
& (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise NOT), << (Left shift), >> (Right shift)
ish
5. Assignment Operators: Assign values to variables.
o = (Assign), += (Add and assign), -= (Subtract and assign), *= (Multiply and assign), /= (Divide and assign), %=
(Modulus and assign)
gl

6. Increment and Decrement Operators: Increase or decrease a value by 1.


En

o ++ (Increment), -- (Decrement)

7. Ternary Operator: Shortens conditional expressions.


o condition ? expression1 : expression2
E
M

8. Comma Operator: Separates multiple expressions.


o expr1, expr2

9. Sizeof Operator: Determines the size of a data type or variable.


o sizeof(variable)

10. Type Casting Operator: Converts one data type into another.

 (type)value (e.g., (float)5)

5.2. What is an operand? What is the relationship between operators and operands?

Operators act on operands to perform calculations or logical operations. For example, in a + b, + is the
operator, and a and b are operands.

5.3. Describe the five arithmetic operators. Summarise the rules associated with their use.

1. + (Addition): Adds two values.


o Example: a + b
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 15
2nd year CS - Chapter # 5
2. - (Subtraction): Subtracts the second value from the first.
o Example: a – b

3. * (Multiplication): Multiplies two values.


o Example: a * b

4. / (Division): Divides the first value by the second.


o Example: a / b
o Note: Division by zero results in an error.

5. % (Modulus): Returns the remainder of division.


o Example: a % b
o Note: Works only with integer types.

Rules:

 Order of Operations: Follows standard precedence: multiplication, division, and modulus have higher

er
precedence than addition and subtraction. Parentheses can change the order.
 Integer Division: When dividing integers, the result is an integer, and the fractional part is discarded.

nt
 Division by Zero: Causes undefined behavior. Always check the divisor before dividing.

5.4. What is the difference between the operators / and %?

1. / (Division):
Ce
ish
o Performs division and returns the quotient (result of division).
o Example: 7 / 3 gives 2 (integer division discards the decimal).
gl

2. % (Modulus):
o Returns the remainder of division.
En

o Example: 7 % 3 gives 1 (remainder after division).

5.5. What is meant by operator precedence? What are the relative precedences of the arithmetic
operators?
E
M

Operator precedence determines the order in which operators are evaluated.

Precedence of Arithmetic Operators:

1. *, /, % (Highest precedence)
2. +, - (Lower precedence)

Evaluation follows left to right within each precedence level.

5.6. What is meant by associativity? What is the associativity of the arithmetic operators?

Associativity defines the order in which operators of the same precedence are evaluated.

Associativity of Arithmetic Operators:

 Left-to-right: Most arithmetic operators (+, -, *, /, %) are evaluated from left to right.
o Example: a - b + c is evaluated as (a - b) + c.
 Right-to-left: The assignment operator (=) has right-to-left associativity.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 15


2nd year CS - Chapter # 5
5.7. When should parentheses be included within an expression? When should the use of parentheses
be avoided?

Use parentheses when:

 You need to control the order of operations and override default precedence.
o Example: (a + b) * c ensures addition happens before multiplication.

Avoid parentheses when:

 The default order of operations already gives the desired result.


o Example: a + b * c doesn't need parentheses since multiplication has higher precedence than
addition.

5.8. In what order are the operations carried out within an expression that contains nested
parentheses?

er
In an expression with nested parentheses, operations are carried out from the innermost parentheses outward.

nt
Example:

For the expression ((a + b) * (c - d)), the order is:

1.
Ce
First, evaluate the innermost parentheses: (a + b) and (c - d).
ish
2. Then, perform the multiplication * between the results of (a + b) and (c - d).

Thus, operations inside the innermost parentheses are evaluated first, followed by the outer ones.
gl

5.9. Suppose a, b and c are integer variables that have been assigned the values a = 8 , b = 3 and c = - 5
En

Determine the value of each of the following arithmetic expressions.

1. a + b + c (Ans. 6)
E

2. 2 * b + 3 * (a - c) (Ans. 45)
M

3. a/b (Ans. 2)
4. a/c (Ans. -1)
5. a % b (Ans. 2)
6. a * b / c (Ans.-4)
7. a * (b / c) (Ans. 0, because b/c is zero)

5.10. Suppose a, b and e are floating-point values alpha = 8.8 b = 3.5 and variables that have been
assigned the c = - 5.2 following arithmetic expressions. Determine the value of each of the

1. a + b + c (Ans. 7.1)
2. 2 * b+ 3 * (a - c) (Ans. 49)
3. a/b (Ans. 2.51429)
4. a/c (Ans. -1.69231)
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 15
2nd year CS - Chapter # 5
5. a % b (Ans. The remainder operator is not defined for floating-point operands.)
6. a / (b + c) (Ans. -5.17647)
7. (a / b) + c (Ans. -2.68571)
8. 2 * a / 3 * b (Ans. 20.53333)
9. 2 * a / (3 * b) (Ans. 1.67619)

5.11. Describe the six relational operators. With what type of operands can they be used? What type
of expression is obtained?

5.12. Describe the three logical operators. What is the purpose of these operators? With what type of
operands can they be used? What type of expression is obtained?

er
1. == (Equal to): Checks if two operands are equal.
o Example: a == b

nt
2. != (Not equal to): Checks if two operands are not equal.
o Example: a != b
Ce
3. > (Greater than): Checks if the left operand is greater than the right.
ish
o Example: a > b

4. < (Less than): Checks if the left operand is less than the right.
gl

o Example: a < b
En

5. >= (Greater than or equal to): Checks if the left operand is greater than or equal to the right.
o Example: a >= b

6. <= (Less than or equal to): Checks if the left operand is less than or equal to the right.
E

o Example: a <= b
M

Operand Types:

 Relational operators are used with numeric types (e.g., int, float, double) or characters (since characters have
numeric values based on ASCII).

Expression Result:

 These operators return a boolean value:


o 1 (true) if the condition is met.
o 0 (false) if the condition is not met.

5.13. Write the logical statements for the following:

(a) basic_pay is more than 2200 for all employees whose category is P,

(b) stock of all items whose item_no is 100 and in the shop A.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 15


2nd year CS - Chapter # 5
(a) if (category == 'P' && basic_pay > 2200)

(b) if (item_no == 100 && shop == 'A')

5.14. What are the relative precedences of the relational and logical operators with respect to one
another and with respect to the arithmetic operators?

Relative Precedence:

1. Arithmetic Operators (+, -, *, /, %):


o Have higher precedence than relational and logical operators.
2. Relational Operators (==, !=, >, <, >=, <=):
o Have higher precedence than logical operators, but lower precedence than arithmetic
operators.
3. Logical Operators (&&, ||):
o Have the lowest precedence among the three.

er
Order of Evaluation:

nt
1. Arithmetic (evaluated first)
2. Relational (evaluated second)
3. Logical (evaluated last)
Ce
5.15. Describe the logical NOT operator. What is its purpose? Within which precedence group is it
ish
included? How many operands does it require?

Logical NOT Operator (!):


gl

 Purpose: The logical NOT operator is used to invert the boolean value of an expression. If the expression is
En

true (non-zero), it returns false (0), and if the expression is false (0), it returns true (1).
o Example: !0 gives 1 (true), !1 gives 0 (false).
E

 Precedence: The logical NOT operator has a higher precedence than logical AND (&&) and logical OR (||),
but lower precedence than relational and arithmetic operators.
M

 Operands: It requires one operand (the expression to be inverted).

Example:
if (!(a > b)) // Checks if a is not greater than b

5.16. Explain the difference between prefix and postfix increment and how does it affect the result of
an expression?

Prefix Increment (++a):

 Operation: The value of a is incremented before it is used in an expression.


 Effect: The value of a is increased, and then the updated value is used in the expression.
 Example:
int a = 5;
int b = ++a; // a becomes 6, then b is assigned the value 6

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 15


2nd year CS - Chapter # 5
Postfix Increment (a++):

 Operation: The value of a is used before it is incremented.


 Effect: The current value of a is used in the expression, and then a is incremented.
 Example:
int a = 5;
int b = a++; // b gets 5, then a becomes 6

5.17. Explain the difference between count=count+1 and count++.

 count = count + 1: Increments count by 1 and then assigns the new value back to count.
 count++: Increments count by 1, but returns the original value before the increment (in an expression).

5.18. What is the difference between --count and count--.

 --count: Decrements count first, then uses the updated value.


 count--: Uses the current value of count, then decrements it.

er
5.19. Can you mix different types of data in the same operation? If so, how will it affect the results of

nt
the operations.

Ce
Yes, you can mix different types of data in the same operation. The resulting type is determined by type
promotion rules, where the lower-type operand is promoted to the higher-type.
ish
 Example: In int a = 5; float b = 2.5; , a + b promotes a to float, and the result will be a float (7.5).
 Effect: Mixing types can cause precision loss or rounding errors when converting to a larger or smaller type.
gl

5.20. What is the result after the execution of the following program segment.
En

a=7
b=a+5;
c = b + 10
E

1. a = 7;: a is set to 7.
M

2. b = a + 5;: b is calculated as 7 + 5, so b = 12.


3. c = b + 10;: c is calculated as 12 + 10, so c = 22.

5.21. What is an expression?

An expression is a combination of variables, constants, operators, and function calls that evaluates to a value. It
can perform calculations, comparisons, or other operations.

Example:
a + b * c

5.22. Evaluate following expressions independent of each other. Assume that i, j, k are integers with
values 3, 4, and 2 respectively.

(a) i++ - j --

(b) i-- % j++

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 15


2nd year CS - Chapter # 5
(c) j++ / i --

(d) k++ * - - i

(e) i – 1 % j + 1

Given values:

 i = 3, j = 4, k = 2

Evaluating expressions:

(a) i++ - j--

 i++: Post-increment i (use i = 3, then increment i to 4).


 j--: Post-decrement j (use j = 4, then decrement j to 3).

er
 Result: 3 - 4 = -1.

nt
(b) i-- % j++

Ce
 i--: Post-decrement i (use i = 4, then decrement i to 3).
 j++: Post-increment j (use j = 3, then increment j to 4).
 Result: 4 % 3 = 1.
ish
(c) j++ / i--
gl

 j++: Post-increment j (use j = 4, then increment j to 5).


 i--: Post-decrement i (use i = 3, then decrement i to 2).
En

 Result: 4 / 3 = 1 (integer division).

(d) k++ * --i


E

 k++: Post-increment k (use k = 2, then increment k to 3).


M

 --i: Pre-decrement i (decrement i to 2, then use i = 2).


 Result: 2 * 2 = 4.

(e) i – 1 % j + 1

 i = 2, j = 4
 First, 1 % j: 1 % 4 = 1.
 Then: i - 1 + 1 = 2 - 1 + 1 = 2.

5.23. Write corresponding to the following. Assume all quantities are of the type integer.

(a) (ax + b) / (ax - b)

(b) (2x + 3y) / (x3 - 6)

(c) x5 + 10x4 + 8x3 + 4x + 2

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 15


2nd year CS - Chapter # 5
(d) (4a + 3) / (2y2 + 2z + 2)

(a) (ax + b) / (ax - b)

(int)(a * x + b) / (a * x - b)

(b) (2x + 3y) / (x³ - 6)

(2 * x + 3 * y) / (x * x * x - 6)

(c) x⁵ + 10x⁴ + 8x³ + 4x + 2

(x * x * x * x * x) + (10 * x * x * x * x) + (8 * x * x * x) + (4 * x) + 2

(d) (4a + 3) / (2y² + 2z + 2)

(4 * a + 3) / (2 * y * y + 2 * z + 2)

er
5.24. What is the final value of f in the following program segment:

nt
float f;
int i;
f = 2.5;
f= (f + 0.04) * 10 ;
Ce
ish
f= (2.5 + 0.04)* 10
f= 2.54 * 10
gl

f= 25.4
En

5.25. What does the cast operator do? Why is it useful?

The cast operator ((type)) is used to explicitly convert a variable from one data type to another.
E

Purpose:
M

 It allows you to change the type of a value to ensure compatibility in operations or to avoid type mismatches.

Example:
int a = 10;
float b = (float) a; // casts int 'a' to float, b becomes 10.0

Usefulness:

It is useful when:

 Converting between data types (e.g., from int to float).


 Preventing loss of precision or incorrect results in mathematical operations.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 15 of 15


2nd year CS - Chapter # 6

Class: 2nd year

Chapter # 6

Input and Output Statements

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 18


2nd year CS - Chapter # 6
Contents

Unformatted I/O Functions......................................................................................................................................................... 3


Formatted I/O Functions............................................................................................................................................................. 4
Section (B / C) ............................................................................................................................................................................ 5

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 18


2nd year CS - Chapter # 6
Unformatted I/O Functions
1. Single Character Input Functions

 getchar(): Reads a single character and requires pressing Enter.

char ch;
ch = getchar();

 getch(): Reads a single character without echoing it on the screen.

char ch;
ch = getch();

 getche(): Reads a single character and displays it immediately.

char ch;
ch = getche();

er
2. Single Character Output Functions

nt
 putchar(): Outputs a single character.

putchar('A'); Ce
ish
 putch(): Similar to putchar(), but specific to Turbo C++.

putch('B');
gl

3. String Input Functions


En

 gets(): Reads a string and adds a null terminator (\0).

char name[30];
E

gets(name);
M

4. String Output Functions

 puts(): Outputs a string and moves to a new line.

puts("Hello, World!");

Function Input/Output Echoes Character? Requires Enter?


getchar() Input Yes Yes
getch() Input No No
getche() Input Yes No
putchar() Output N/A N/A
putch() Output N/A N/A
gets() Input Yes Yes
puts() Output Yes Yes

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 18


2nd year CS - Chapter # 6
Formatted I/O Functions
1. scanf() Function (Formatted Input)

 Reads various data types from input.


 Uses format specifiers (e.g., %d, %f, %c, %s).
 Skips whitespace (except for %c).
 Requires & (address operator) for all variables except strings.
 Stops reading at the first non-matching character.
 Not recommended for multi-word strings (use gets() instead).

Example:

int num;

er
scanf("%d", &num); // Reads an integer

nt
2. printf() Function (Formatted Output)


Prints all data types.
Uses format specifiers (e.g., %d, %f, %c, %s). Ce
ish
 Can format numbers (e.g., decimal places, alignment).
 Allows combining text and variables.
gl

 Requires correct order of arguments.


En

Example:

int age = 17;


printf("My age is %d years", age);
E
M

Function Purpose Input Handling Output Formatting


scanf() Reads input Uses format specifiers No formatting
printf() Displays output Uses format specifiers Formats output

Other Input Functions:

Function Use Notes


getchar() Single character Press Enter after input
getch() / getche() Single character No Enter required, getche() echoes input
gets() Strings Reads entire line, including spaces

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 18


2nd year CS - Chapter # 6

Section (B / C)
6.1. What are the commonly used input/output functions in C? How are they accessed?

Commonly used I/O functions in C:

 printf( ): Output formatted data.


 scanf( ): Input formatted data.
 getchar( )/putchar( ): Single character I/O.
 gets( )/puts( ): String I/O (unsafe, avoid gets( )).
 fgets( )/fputs( ): Safe string I/O.

They are accessed via the stdio.h library.

6.2. What is the purpose of the getchar function? How is it used within a C program?

er
The getchar( ) function reads a single character from standard input (keyboard).

nt
Usage in C program:

#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
Ce
ish
ch = getchar();
printf("You entered: %c", ch);
return 0;
gl

}
En

6.3. Why is it necessary to press after a getchar( ) input?

Pressing Enter (Return key) after getchar() input is necessary because getchar() reads a single character,
E

but the Enter key generates a newline (\n) character, which remains in the input buffer.
M

6.4. What are two ways to use getchar( )?

1. Direct Assignment: char ch = getchar(); – Stores the input character in ch.


2. Inside a Loop: Reads multiple characters until a condition is met, e.g., while ((ch = getchar()) !=
'\n') { /* process ch */ } .

6.5. What is output?

Output is the processed data or results displayed by a computer, usually on a screen, printer, or speaker.

6.6. What is the purpose of the putchar function? How is it used within a C program? Compare with
the getchar function.

The putchar function outputs a single character to the screen. It is used as:

putchar('A');

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 18


2nd year CS - Chapter # 6
Comparison with getchar:

 getchar() reads a character from input.


 putchar() prints a character to output.

6.7. What types of arguments can be used in a puts( ) function?

The puts() function accepts a string (character array) as an argument. It must be a null-terminated string (char
*). Example:

puts("Hello, World!");

It cannot take individual characters or numbers as arguments.

6.8. Write the puts( ) instructions for printing your name and address.

puts("John Doe");

er
puts("123 Main Street, New York, NY, USA");

nt
6.9. Write the puts( ) instruction that centers the word Title on the screen. The screen is 80 characters
wide.

puts(" Ce Title");
ish
(80-character width, with "Title" centered at position 40.)

6.10. What types of arguments can be used in a putchar( ) function?


gl

The putchar() function accepts a single character as an argument, which can be:
En

1. Character constant: e.g., putchar('A');


2. Character variable: e.g., char ch = 'B'; putchar(ch);
3. Integer representing a character (ASCII value): e.g., putchar(65); // Prints 'A'
E
M

6.11. What is a character-type array? What does each element of a character-type array represent?
How are character-type arrays used to represent multi-character strings.

A character-type array is an array of characters (char type) used to store multiple characters.

 Each element represents a single character.


 Used for strings by storing characters sequentially, ending with a null character ( '\0').
 Example: char str[] = "Hello"; stores H, e, l, l, o, \0.

6.12. How would you display the quote symbol on the screen?

Use the escape sequence \" to display the quote symbol.

printf("\"");

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 18


2nd year CS - Chapter # 6
6.13. What is the purpose of the scanf function? How is it used within a C program? Compare it with
the getchar function.

It reads input from the user and stores it in specified variables.

scanf("%d", &variable);

Comparison with getchar:

 scanf reads formatted input (e.g., integers, strings).


 getchar reads a single character at a time.

6.14. What are the advantages of using scanf( ) for input?

Advantages of scanf():

1. It allows reading formatted input (e.g., integers, floats, strings).

er
2. It stores multiple values in different variables in a single statement.
3. It provides input validation through format specifiers (e.g., %d, %f).

nt
6.15. When would you use gets( ) rather than scanf( ) to input a string?

Ce
Use gets() when you need to input an entire line, including spaces, into a string.
ish
Example:

char str[100];
gl

gets(str); // reads a line including spaces


En

However, gets() is unsafe and deprecated due to buffer overflow risks. It's recommended to use fgets()
instead.

6.16. What are the advantages and disadvantages of formatted scanf( ) input?
E
M

Advantages of scanf():

1. It allows reading formatted input (e.g., integers, floats, strings).


2. It stores multiple values in different variables in a single statement.
3. It provides input validation through format specifiers (e.g., %d, %f).

Disadvantages of scanf():

1. Buffer overflow risk if input exceeds allocated memory.


2. Limited error handling: Incorrect input can cause undefined behavior.
3. Whitespace handling: %s stops at whitespace, which can be problematic for multi-word inputs.

6.17. What is the purpose of the control string in a scanf function? What type of information does it
convey? Of what is the control string composed?

The control string in scanf() specifies the format of the input data.

 It tells scanf() how to interpret the input and what type of data to expect.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 18


2nd year CS - Chapter # 6
Information conveyed:

 Specifies the type of data (e.g., integer, float, string) and how to process it.

Composition:

 Composed of format specifiers (e.g., %d, %f, %s) that match the expected input type. For example:
 scanf("%d %f %s", &intVar, &floatVar, strVar);

6.18. If a control string within a scanf function contains multiple character groups, how are the
character groups separated? Are whitespace characters required?

In a scanf() control string with multiple character groups, the groups are separated by spaces or other
delimiters like commas, but whitespace characters are not required between them.

Example:

er
scanf("%d %f %s", &intVar, &floatVar, strVar);

nt
o The whitespace between %d, %f, and %s is optional in the control string.


Ce
Note: scanf() automatically skips over any whitespace characters (spaces, tabs, or newlines) in the
input.
ish

6.19. What is the address operator?


gl

The address operator (&) is used to obtain the memory address of a variable.
En

Example:
int x = 10;
E

int *ptr = &x; // ptr now holds the address of x


M

Here, &x gives the memory address of x, which is assigned to the pointer ptr.

6.20. What special symbol must be included with the arguments, other than the control string, in a
scanf function? In what way are array names treated differently than other arguments?

The special symbol required with arguments, other than the control string, in a scanf() function is the address
operator (&), except for array names.

 Array names are treated as pointers to the first element, so no & is needed with them in scanf().

Example:
int x;
scanf("%d", &x); // Using & for a regular variable

char str[20];
scanf("%s", str); // No & for an array

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 18


2nd year CS - Chapter # 6
6.21. When entering data via the scanf function, what relationships must there be between the data
items and the corresponding arguments? How are multiple data items separated from one
another?

When entering data via the scanf() function:

1. Data types of the input must match the format specifiers in the control string (e.g., %d for integers, %f
for floats).
2. The order of the data items entered must match the order of the arguments in the scanf()
statement.

Separation of Data Items:

 Multiple data items are separated by whitespace (spaces, tabs, or newlines).


 scanf() automatically skips any whitespace between input items.

er
Example:

nt
int a;
float b;
scanf("%d %f", &a, &b); // Input: 10 3.14

Ce
6.22. What happens if an input data item contains more characters than the maximum allowable field
width? What if the data item contains fewer characters?
ish
 More characters than allowable field width:
If the input exceeds the specified field width (e.g., using %5s for a string), only the first 5 characters are
gl

read, and the remaining characters are left in the input buffer.
En

 Fewer characters than allowable field width:


If the input contains fewer characters than the specified field width, the input is read fully, and the
E

remaining space is padded with null characters for strings or zeros for numbers.
M

Example:
char str[5];
scanf("%4s", str); // Input: "Hello" (Only "Hell" will be read)

6.23. How can the minimum field width for a data item be specified within the printf function.

The minimum field width is specified by placing a number before the conversion character (e.g., %5d).

6.24. Is it necessary to assign initial values to all variables?

It is not strictly necessary, but it is good practice to assign initial values to variables to avoid undefined
behavior.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 18


2nd year CS - Chapter # 6
6.25. What is the purpose of the printf function? How is it used within a C program? Compare with
the putchar function.

printf outputs formatted data to the screen.

Comparison with putchar:

putchar outputs a single character, while printf can output formatted text.

6.26. What are the two parts of the printf( ) instruction?

1. Control string
2. Arguments to be printed.

6.27. What are the advantages of printf( ) over puts( )?

er
printf() allows for formatted output, while puts() just prints a string with a newline.

nt
6.28. In what ways does the control string within a printf function differ from the control string within
a scanf function?
Ce
In printf, the control string defines the output format. In scanf, it defines how input should be read.
ish
6.29. If the control string within a printf function contains multiple character groups, how are the
character groups separated? How are the separators interpreted?
gl

Character groups are separated by whitespace or other characters and are interpreted as literal characters unless
they're format specifiers.
En

6.30. Summarise the meaning of the more commonly used conversion characters within the control
string of a printf function. Compare with the conversion characters that are used in a scanf
E

function.
M

%d (integer), %f (float), %s (string) for printf; %d, %f, %s for scanf (input interpretation).

6.31. Write the printf( ) instructions for printing your name and address.

printf("Name: John Doe\nAddress: 123 Main St.");

6.32. Write the printf( ) instruction that outputs the values of the following variables:

float length, width, height, volume;

printf("Length: %.2f, Width: %.2f, Height: %.2f, Volume: %.2f", length,


width, height, volume);

6.33. Differentiate the following:

(a) scanf( ) and printf( )

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 18


2nd year CS - Chapter # 6
(b) getchar( ) and putchar( )

(c) gets( ) and puts( )

(a) scanf() reads input, printf() outputs formatted data.


(b) getchar() reads one character, putchar() outputs one character.
(c) gets() reads a string (unsafe), puts() outputs a string with a newline.

6.34. A program will display a person's name and age. Write a printf( ) instruction that displays the
values of the variables:

char name [12];


int age;

er
printf("Name: %s, Age: %d", name, age);

nt
6.35. A program has these variables:

char item[] "Floppy disk";


float cost 25.50;
Ce
ish
float sale tax = 0.15;
gl

Write the printf( ) instructions that display:


En

Item Name: Floppy disk


Item Cost: 25.50
Sale tax: 0.15
E

Note the alignment of the values.


M

printf("Item Name: %-20s\nItem Cost: %-10.2f\nSale Tax: %.2f", item, cost,


saleTax);

6.36. Write a program that sounds a bell.

#include <stdio.h>

int main() {

printf("\a"); // bell sound

return 0;

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 18


2nd year CS - Chapter # 6
6.37. A C program contains the following statements:

#include <stdio.h>
char a, b, c;

(a) Write appropriate getchar statements that will allow values for a, b and c to be entered into
the computer.

(b) Write appropriate putchar statements that will allow the current values of a, b and c to be
displayed on monitor.

(a) a = getchar();

b = getchar();

c = getchar();

er
(b) putchar(a);

nt
putchar(b);

putchar(c);

6.38. A C program contains the following statements:


Ce
ish
#include <stdio.h>
int i, j, k;
gl
En

Write an appropriate scanf function to enter numerical values for i, j and k assuming

(a) The values for i, j and k will be decimal integers.


E

(b) The values for i, j and k will be octal integers.


M

(c) The value for i will be a decimal integer, j an octal integer and k a hexadecimal integer.

(d) The values for i and j will be hexadecimal integers and k will be an octal integer.

(a) Decimal integers:

scanf("%d %d %d", &i, &j, &k);

(b) Octal integers:

scanf("%o %o %o", &i, &j, &k);

(c) Mixed decimal, octal, hexadecimal:

scanf("%d %o %x", &i, &j, &k);

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 18


2nd year CS - Chapter # 6
(d) Hexadecimal and octal:

scanf("%x %x %o", &i, &j, &k);

6.39. Show the output displayed by the following program lines when the data entered are 5 and 7:

/ program 6-21.cpp */
#include<conio.h>
#include<stdio.h>
void main(void)
{
int numl, num2;
clrscr();
printf("Enter two integers: ");
scanf("%d %d", &numl, &num2);
numl = numl + 5;
num2 = 3 * num2;

er
printf("\tnuml = %d\n\tnum2= %d\n", numl, num2);

nt
getch();
}
Ce
ish
Enter two integers: 5 7

num1 = 10
gl

num2 = 21
En

6.40. Interpret the meaning of the control string in each of the following scanf functions.

(a) scanf("%12ld %15lf %15le, &a, &b, &c);


E
M

(b) scanf("%10lx %6o %14lu, &a, &b, &c);

(c) scanf("%ld %lf %15e, &a, &b, &c);

(d) scanf("%2d %2f %151f, &a, &b, &c);

(a) %12ld %15lf %15le: Reads a long decimal, double, and scientific notation.
(b) %10lx %6o %14lu: Reads hexadecimal, octal, and unsigned long.
(c) %ld %lf %15e: Reads a long decimal, double, and scientific.
(d) %2d %2f %151f: Reads 2-digit integers and floats.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 18


2nd year CS - Chapter # 6
6.41. A C program contains the following variable declarations.

int i = 12345, j = 0xabcd9, k = 077777;

Show the output resulting from each of the following printf statements.

(a) printf("%d %x %o", i, j, k);

(b) printf("%3d %3x %3o", i, j, k);

(c) printf("%8d %8x %8o", i, j, k);

(d) printf("%-8d %-8x %-80", i, j, k);

(e) printf("%+8d %+8x %+8o", i, j, k);

er
(f) printf("%08d %#8x %#8o", i, j, k);

nt
(a) 12345 abcda 77777

(b)

(c)
12345 abcda 77777

12345 abcda 77777


Ce
ish

(d) 12345 abcda 77777


gl

(e) +12345 +abcd9 +077777


En

(f) 00012345 0xabcda 077777

6.42. Write a program which prints two groups of five numbers each with right justification as,
E
M

1
12
123
1234
12345
-1
-12
-123
-1234
-12345

Code:

/* program 6-22.cpp */
#include<stdio.h>
#include<conio.h>
void main(void)
{
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 18
2nd year CS - Chapter # 6
clrscr();
printf("%6d\n", 1);
printf("%6d\n", 12);
printf("%6d\n", 123);
printf("%6d\n", 1234);
printf("%6d\n", 12345);
printf("%6d\n", -1);
printf("%6d\n", -12);
printf("%6d\n", -123);
printf("%6d\n", -1234);
printf("%6d\n", -12345);
getch();
}

6.43. What is a format specifier?

A format specifier is a placeholder in a control string used in printf or scanf to specify the data type of the

er
variable being input or output.

nt
6.44. How do you display the value of a numeric variable?

Ce
Display the value of a numeric variable using printf, e.g., printf("%d", num); for integers, or
printf("%f", num); for floats.
ish
6.45. What is meant by the precision of an output data item? To what types of data does this apply?

Precision refers to the number of digits displayed after the decimal point for floating-point numbers or the
gl

maximum field width for integers.


En

6.46. How can the precision be specified within a printf function?

Precision can be specified using a period (.) in the format specifier. For example, %.2f will display two decimal
places.
E
M

6.47. Write a program that inputs three numbers, then displays the numbers in reverse order-the last
number input is displayed first, etc.

#include <stdio.h>
int main() {
int num1, num2, num3;
scanf("%d %d %d", &num1, &num2, &num3);
printf("%d %d %d", num3, num2, num1);
return 0;
}

6.48. Write a program that uses getchar( ), gets( ), and scanf( ).

#include <stdio.h>
int main() {
char ch;
char str[20];
int num;

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 15 of 18


2nd year CS - Chapter # 6
ch = getchar();
gets(str);
scanf("%d", &num);

printf("%c %s %d", ch, str, num);


return 0;
}

6.49. Write a program that asks the user to enter the radius of a circle and then computes and
displays the circle's area. Use the formula
area = PI × radius × radius
where Pl is the constant whose value is 3.14159.

#include <stdio.h>
#define PI 3.14159
int main() {
float radius, area;

er
printf("Enter radius: ");
scanf("%f", &radius);

nt
area = PI * radius * radius;
printf("Area of circle: %.2f", area);

}
return 0;
Ce
ish
6.50. Write a program to test the results of printing the integer value 12345 and the floating-point
value 1.2345 in various size fields. What happens when the values are printed in fields containing
fewer digits than the values?
gl

#include <stdio.h>
En

int main() {
int num = 12345;
float flt = 1.2345;
E

printf("%d %f\n", num, flt);


M

printf("%5d %.3f\n", num, flt);


return 0;
}

6.51. Write a program that prints the value 100.453627 rounded to the nearest digit, tenth,
hundredth, thousandth and ten thousandth.

#include <stdio.h>
int main() {
float num = 100.453627;
printf("%.0f %.1f %.2f %.3f %.4f", num, num, num, num, num);
return 0;
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 16 of 18


2nd year CS - Chapter # 6
6.52. Write a program that converts Fahrenheit temperatures to Celsius temperatures with 3 digits of
precision. Use the formula

Celsius = 5.0/9.0 * (Fahrenheit - 32); to perform calculation.

#include <stdio.h>
int main() {
float fahrenheit, celsius;
printf("Enter Fahrenheit: ");
scanf("%f", &fahrenheit);
celsius = 5.0 / 9.0 * (fahrenheit - 32);
printf("Celsius: %.3f", celsius);
return 0;
}

6.53. Write a program that determines whether? can be printed as part of a printf control string as

er
a character rather than using the \? escape sequence.

nt
#include <stdio.h>
int main() {

sequence.");
return 0;
Ce
printf("Question? Can be printed using %%? without escape
ish
}

6.54. Write a program that inputs the value 437 using each of the scanf integer format specifiers.
gl

Print each input value using all the integer format specifiers.
En

#include <stdio.h>
int main() {
int num1;
E

printf("Enter an integer: ");


M

scanf("%d", &num1);
printf("Decimal: %d\n", num1);
printf("Octal: %o\n", num1);
printf("Hexadecimal: %x\n", num1);
return 0;
}

6.55. Write a program that uses each of the conversion specifiers e and f to input the value 1.2345.
Print the values of each variable to prove that each format specifier can be used to input this
same value.

#include <stdio.h>
int main() {
float num;
printf("Enter a number: ");
scanf("%e", &num); // Using scientific notation input
printf("Scientific: %e\n", num);

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 17 of 18


2nd year CS - Chapter # 6
scanf("%f", &num); // Using regular floating-point input
printf("Floating: %f\n", num);
return 0;
}

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 18 of 18


2nd year CS - Chapter # 7

Class: 2nd year

Chapter # 7

Selection Control Structures

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 15


2nd year CS - Chapter # 7
Contents

if Statement ................................................................................................................................................................................ 3
If-else Statement ........................................................................................................................................................................ 3
Example: Using if-else to Check If a Number Is Positive or Negative.......................3
Nested if-else (if-else-if Ladder): ................................................................................................................................................. 3
Switch Statements: ..................................................................................................................................................................... 4
Example: Using switch to Display Day of the Week .........................................4
Section (A).................................................................................................................................................................................. 5
-: Answer Keys :-................................................................................................................................................................ 6
Section (B / C) ............................................................................................................................................................................ 7

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 15


2nd year CS - Chapter # 7

These control structures are essential for directing the flow of execution in a program and come in three basic forms:
sequence (the simplest), selection (if, if/else, switch), and iteration (while, for, do/while).

 Sequence Control: Executes statements in the order they appear.


 Selection Control: Executes actions based on conditions (if, if/else).
 Iteration Control: Repeats actions (while, for).

if Statement
The if statement is central to selection control. It tests conditions and executes code accordingly. The flowchart
illustrates the decision-making process of if statements. Logical operators (AND, OR, NOT) are introduced to check
multiple conditions. Nested if statements allow for more complex logic.

If-else Statement

er
The if-else statement provides an alternative action if the condition is false.

nt
Example: Using if-else to Check If a Number Is Positive or Negative

#include<stdio.h> Ce
ish
void main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
gl

if (num > 0) {
En

printf("The number is positive.\n");


} else if (num < 0) {
printf("The number is negative.\n");
E

} else {
printf("The number is zero.\n");
M

}
}

Nested if-else (if-else-if Ladder):


Nested if-else structures test for multiple conditions in sequence.

Example: Converting a month number to its name using if-else-if.

Syntax:

if (condition1) {
// code block 1
} else if (condition2) {
// code block 2
} else {
// default code block
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 15


2nd year CS - Chapter # 7
Switch Statements:
Switch statements are used to select one of several options based on the value of a variable.

Syntax:

switch(variable) {
case value1:
// code block for value1
break;
case value2:
// code block for value2
break;
default:
// default code block if no case matches
}

er
Key Features of switch:

nt
 switch is ideal for handling multiple conditions based on a single variable, but it only checks for equality
and works with int or char types.

 Ce
It requires break statements to avoid "fall-through" where the program continues to execute subsequent
case statements.
ish
Example: Using switch to Display Day of the Week
gl

void main() {
int day;
En

printf("Enter a number (1-7) for the day of the week: ");


scanf("%d", &day);

switch(day) {
case 1:
E

printf("Monday\n");
break;
M

case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
case 6:
printf("Saturday\n");
break;
case 7:
printf("Sunday\n");
break;
default:
printf("Invalid input! Please enter a number between 1 and 7.\n");
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 15


2nd year CS - Chapter # 7

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. Structured programming
(a) is hard to follow but worthwhile (b) calls for one way in, one way out structures
(c) makes debugging difficult (d) relies heavily on if-else statements
2. Which of these expressions are true
(a) 0 (b) 1 (c) 5*3 < 15 (d) 1 == 1 (e) -1
3. The statement if (x 0) printf("X = 0");
(a) is incorrect syntax (b) is correct syntax, but x = 0 will never print

er
(c) causes a run-time error (d) has no effect on the program
4. In a simple if statement with no else, what happens if the condition following the if is false?

nt
(a) the program searches for the last else in the program

Ce
(b) nothing, or control falls through' to the statements following the if
(c) the body of the if statement is executed
ish
(d) the program as a whole is executed
5. The statements following a particular if-else in an if-else-if ladder are executed when
gl

(a) the conditional expression following the if-else is true and all previous conditions are true
En

(b) the conditional expression following the if-else is true and all previous conditions are false
(c) the conditional expression following the if-else is false and all previous conditions are true
E

(d) the conditional expression following the if-else is false and all previous conditions are false
M

6. Which if in a program does an else pair up with?


(a) the last if with the same indentation as the else
(b) the last if not matched with its own else
(c) the last if not enclosed in braces
(d) the last if not enclosed in braces and not matched with its own else
7. The advantage of a switch statement over an if-else-if construction is
(a) a default condition can be used in the switch
(b) the switch is easier to understand
(c) several different statements can be executed for each case in a switch
(d) several different conditions can cause one set of statements to be executed in a switch

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 15


2nd year CS - Chapter # 7
8. The switch statement
(a) can always be used as a substitute for the ladder structure
(b) can be used only with an if-else statement
(c) is most useful when testing a variable having a limited range of possibilities
(d) all of the above

-: Answer Keys :-

1. b

2. b

er
3. a

nt
4. b

5.

6.
Ce b

b
ish
7. d
gl

8. c
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 15


2nd year CS - Chapter # 7

Section (B / C)
7.1. Write a program that asks the user for an integer and then tells the user if that number is even or
odd. (Hint: Use C's modulus operator %).

#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);

if (num % 2 == 0)
printf("The number is even.\n");
else
printf("The number is odd.\n");

er
return 0;

nt
}

100.

#include <stdio.h>
Ce
7.2. Write a program that inputs a number, then reports whether the number is in the range from 1 to
ish
int main() {
int num;
gl

printf("Enter a number: ");


scanf("%d", &num);
En

if (num >= 1 && num <= 100)


printf("The number is in the range 1 to 100.\n");
E

else
printf("The number is not in the range 1 to 100.\n");
M

return 0;
}

7.3. How do you perform more than one statement when a condition is true?

if (condition) {
statement1;
statement2;
statement3;
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 15


2nd year CS - Chapter # 7
7.4. The following is supposed to cause an action whenever x is greater than y.

if(x > y) then

printf("x is greater than y");

Why is this wrong?

Ans.

Unlike other languages, in C the if statement does not use the then keyword.

7.5. The following is supposed to cause an action whenever x is equal to y.

if(x = y)

printf("x equals y");

er
nt
Is there anything wrong with this?

Ans.
Ce
This is a common mistake in C. The expression mistakenly uses the assignment operator = instead of a
relational operator =. The effect is to assign the value of y to x. The expression then takes on the value
ish
of the assignment. If y happens to be 0, the assignment makes x equal 0. Because 0 is interpreted as
false, the printf statement cannot execute even though x does in fact equal y!
gl

7.6. Write a program that demonstrates multiple statements following if.


En

/* program 7-21.cpp */
#include<stdio.h>
#include<conio.h>
E

void main(void)
M

{
clrscr();
char ch;
ch getche();
if(ch == 'z')
{
printf("\n\nYou typed z.");
printf("\nNot some other letter.");
}

getch();
}

7.7. What is the propose of the else command?

The else command provides an alternative action when the if condition is false.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 15


2nd year CS - Chapter # 7
7.8. Write a program that requests two numbers and then displays either their sum or product,
depending upon what the user selects.

#include <stdio.h>
int main() {
int num1, num2, choice;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Enter 1 for sum, 2 for product: ");
scanf("%d", &choice);

if (choice == 1)
printf("Sum: %d\n", num1 + num2);
else if (choice == 2)
printf("Product: %d\n", num1 * num2);
else

er
printf("Invalid choice\n");

nt
return 0;
}

Ce
7.9. Explain how an if command can be used to test for valid input.
ish
if (input >= 0 && input <= 100) {
// valid input logic
}
gl

else {
// invalid input message
En

7.10. Explain the use of nested if statements.


E
M

Nested if statements allow you to test multiple conditions inside each other. They are useful for checking
multiple conditions sequentially.

7.11. Write a program that reads temperature and prints a message as given below:

Temperature Message
> 35 Its hot day!
>= 25 and <= 35 Its nice day!
< 25 Its cold day!
#include <stdio.h>
int main() {
int temp;
printf("Enter temperature: ");
scanf("%d", &temp);

if (temp > 35)


Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 15
2nd year CS - Chapter # 7
printf("It's a hot day!\n");
else if (temp >= 25 && temp <= 35)
printf("It's a nice day!\n");
else
printf("It's a cold day!\n");

return 0;
}

7.12. Write a program that reads three numbers and prints the largest.

#include <stdio.h>
int main() {
int num1, num2, num3;
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);

er
if (num1 >= num2 && num1 >= num3)

nt
printf("The largest number is %d\n", num1);
else if (num2 >= num1 && num2 >= num3)

else Ce
printf("The largest number is %d\n", num2);

printf("The largest number is %d\n", num3);


ish
return 0;
}
gl
En

7.13. What is the difference between the if-else-if ladder and the series of one-way if statements?

Ans.
E

The one-way if series is not as efficient as the ladder and does not show mutual exclusion because
M

more than one statement can execute. In fact, all the expressions could be true, so each if statement has
to be checked to determine its logical value.

7.14. Correct the syntax errors.

if x > 25.0
{
y = x
else
y = z ;
}
if (x > 25.0) {
y = x;
} else {
y = z;
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 15


2nd year CS - Chapter # 7
7.15. What value is assigned to fee by the if statement when speed is 75?

if (speed > 35)


fee 20.0;
else if (speed > 50)
fee 40.0;
if (speed>75)
fee 60.0;

Ans: The fee is 40.0, as the second condition ( speed > 50) is true.

7.16. Explain the difference between the statements on the left and the statements on the right. For
each group of statements, give the final value of x if the initial value of x is 1.

if(x >= 0) if(x >=0)

er
x = x + 1; x = x+1;
else if(x >= 1) if(x >=1)

nt
x = x + 2; x = x+2;

1. x = x + 1; will be executed since x >= 0.


Ce
2. In the second block, x will be incremented by 1 as x = 1.
ish
7.17. The ASCII codes for the lowercase letters are separated from the uppercase letters by a
difference of 32. Therefore, to convert a lowercase letter to an uppercase one, simply subtract 32
gl

from it. Write a program that reads characters from the keyboard and displays lowercase letters
as uppercase ones. Stop when Enter is pressed.
En

#include <stdio.h>
int main() {
char ch;
E

while (1) {
M

ch = getchar();
if (ch == '\n') break;
if (ch >= 'a' && ch <= 'z')
ch -= 32;
putchar(ch);
}
return 0;
}

7.18. Using a nested if statement, write a program that prompts the user for a number and then
reports if the number is positive, zero, or negative.

#include <stdio.h>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 15


2nd year CS - Chapter # 7

if (num > 0)
printf("The number is positive.\n");
else if (num == 0)
printf("The number is zero.\n");
else
printf("The number is negative.\n");

return 0;
}

7.19. How does the switch command differ from the if command?

switch is used when there are multiple possible values for a variable, while if is used for any condition or
range.

er
7.20. What is wrong with this segment of program?

nt
float f;
scanf("%f", &f);
switch(f) {
case 12.05:
.
Ce
ish
.
gl

Cannot use floating-point values in a switch statement. Use int or char values.
En

7.21. Write a switch statement that outputs messages indicating what day has been numerically input
(for example, 1 → Monday, 2→ Tuesday ...).
E

#include <stdio.h>
int main() {
M

int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);

switch(day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
case 7: printf("Sunday\n"); break;
default: printf("Invalid day\n");
}
return 0;
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 15


2nd year CS - Chapter # 7
7.22. What output line(s) are displayed by the statements that follow when-grade is 'I'? When grade is
'B'? When grade is 'b'?

switch(grade)
{
case 'A':
points = 4;
break;
case 'B':
points = 3;
break;
case 'C':
points = 2;
break;
case 'D':

er
points = 1;

nt
break;
case 'E':
case 'I':
case 'Y':
points = 0;
Ce
ish
}
if (points > 0)
gl

printf("Passed, points earned %d\n", points);


else
En

printf("Failed, no points earned\n");


E

 If grade is 'I', the output is "Failed, no points earned".


M

 If grade is 'B', the output is "Passed, points earned 3".


 If grade is 'b', no case for 'b' will match, and the output will be "Failed, no points earned".

7.23. What will be printed by this carelessly constructed switch statement if the value of colour is 'R'?

switch(colour) /* break statements missing */


{
case 'R':.
printf("red\n");
case 'B':
printf("blue\n");
case 'Y':
printf("yellow\n");
}
Ans: All cases without break will print all messages: "red", "blue", and "yellow".
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 15
2nd year CS - Chapter # 7
7.24. Write a program that computes the area of either a circle, rectangle, or triangle. Use an if-
else-if ladder. Rewrite this program using switch statement.

Using else-if:

#include <stdio.h>
int main() {
int choice;
printf("Select shape: 1 for circle, 2 for rectangle, 3 for triangle: ");
scanf("%d", &choice);

if (choice == 1) {
float radius, area;
printf("Enter radius: ");
scanf("%f", &radius);
area = 3.14 * radius * radius;
printf("Area of circle: %.2f\n", area);
}

er
else if (choice == 2) {
float length, width, area;

nt
printf("Enter length and width: ");
scanf("%f %f", &length, &width);

}
area = length * width;
Ce
printf("Area of rectangle: %.2f\n", area);

else if (choice == 3) {
ish
float base, height, area;
printf("Enter base and height: ");
scanf("%f %f", &base, &height);
gl

area = 0.5 * base * height;


printf("Area of triangle: %.2f\n", area);
En

} else {
printf("Invalid choice.\n");
}
return 0;
E

}
M

Using switch:

#include <stdio.h>
int main() {
int choice;
printf("Select shape: 1 for circle, 2 for rectangle, 3 for triangle: ");
scanf("%d", &choice);

switch(choice) {
case 1: {
float radius, area;
printf("Enter radius: ");
scanf("%f", &radius);
area = 3.14 * radius * radius;
printf("Area of circle: %.2f\n", area);
break;
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 15


2nd year CS - Chapter # 7
case 2: {
float length, width, area;
printf("Enter length and width: ");
scanf("%f %f", &length, &width);
area = length * width;
printf("Area of rectangle: %.2f\n", area);
break;
}
case 3: {
float base, height, area;
printf("Enter base and height: ");
scanf("%f %f", &base, &height);
area = 0.5 * base * height;
printf("Area of triangle: %.2f\n", area);
break;
}
default:
printf("Invalid choice.\n");

er
}
return 0;

nt
}

#include <stdio.h>
#include <ctype.h>
Ce
7.25. Improve the program 7-20 by using an toupper() or tolower() function.
ish
int main() {
char ch;
gl

printf("Enter a character: ");


ch = getchar();
En

ch = toupper(ch); // Converts to uppercase


putchar(ch);
E

return 0;
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 15 of 15


2nd year CS - Chapter # 8

Class: 2nd year

Chapter # 8

Iteration Control Structures

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 15


2nd year CS - Chapter # 8
Contents
for loop: ...................................................................................................................................................................................... 3
while Loop:............................................................................................................................................................................... 3
do-while Loop:........................................................................................................................................................................ 3
for Loop vs. while Loop: ......................................................................................................................................................... 4
Nested Loops: ............................................................................................................................................................................. 4
break Statement:...................................................................................................................................................................... 4
continue Statement: ............................................................................................................................................................... 4
Section (A).................................................................................................................................................................................. 5
-: Answer Keys :-................................................................................................................................................................ 6
Section (B / C) ............................................................................................................................................................................ 7

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 15


2nd year CS - Chapter # 8

Iteration (looping) allows a program to repeat instructions until a condition is false. C provides three types of loops:

1. for loop – Used for definite repetition (fixed number of iterations).


2. while loop – Used for indefinite repetition (condition-based).
3. do-while loop – Similar to while, but executes at least once.

for loop:
Syntax:
for(initialization; condition; increment/decrement) {
// Code to execute
}

 Nested loops (loop inside another loop) help create complex patterns.

Example: Print Numbers 1 to 10

er
#include <stdio.h>
int main() {

nt
for(int i = 1; i <= 10; i++) {
printf("%d ", i);

}
}
return 0;
Ce
ish
Output: 1 2 3 4 5 6 7 8 9 10

while Loop:
gl

 Executes a block of code while a condition is true.


En

 Used when the number of iterations is unknown.


 Example:
E

int i = 1;
while (i <= 10) {
M

printf("%d ", i);


i++;
}

do-while Loop:
 Similar to while, but executes at least once before checking the condition.
 Example:

int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 10);

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 15


2nd year CS - Chapter # 8
for Loop vs. while Loop:
 for is used when the number of iterations is known.
 while is used when the loop runs until a condition changes dynamically.
 Both can achieve the same result.

Nested Loops:
 A loop inside another loop for complex iterations, such as printing patterns or calculating factorials.

break Statement:
 Exits a loop immediately when encountered.
 Example:

for (int i = 1; i <= 10; i++) {

er
if (i == 5) break;
printf("%d ", i);

nt
}

continue


Statement:
Ce
Skips the rest of the loop's body and continues to the next iteration.
ish
 Example:

for (int i = 1; i <= 10; i++) {


if (i == 5) continue;
gl

printf("%d ", i);


}
En

(Output: 1 2 3 4 6 7 8 9 10, skipping 5)


E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 15


2nd year CS - Chapter # 8

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. The main difference in operation between an if statement and a while statement is
(a) the conditional expression following the keyword is evaluated differently
(b) the while loop body is always executed, the if loop body only if the condition is true
(c) the body of the while statement may be executed many times, the body of the if statement only once
(d) the conditional expression is evaluated before the while loop body is executed but after the if loop body
2. Assuming x does not equal 0, the statement while(x==0) printf("X=0")
(a) is an infinite loop (b) will never output

er
(c) causes a syntax error (d) will output once
3. Assuming x does not equal 0, the statement do printf("X=0") while(x==0)

nt
(a) is an infinite loop (b) will never output
(c) causes a syntax error (d) will output once
4. A single-statement for loop is terminated with a
Ce
ish
(a) right bracket (b) right brace (c) comma (d) semicolon
5. The statement for (x = 0; x < 1; x++) printf("X=0")
gl

(a) is an infinite loop (b) will never output


En

(c) causes a syntax error (d) will output once


6. The statement for (x = 0; x <= -1; x++) printf("X=0")
E

(a) is an infinite loop (b) will never output


M

(c) causes a syntax error (d) will output once


7. A while loop is more appropriate than a for loop when
(a) the terminating condition occurs unexpectedly
(b) the body of the loop will be executed at least once
(c) the program will be executed at least once
(d) the number of times the loop will be executed is known before the loop is executed
8. A do-while loop is useful when
(a) the body of the loop will never be executed
(b) the body of the loop will be executed at least once
(c) the body of the loop may never be executed
(d) none of the above

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 15


2nd year CS - Chapter # 8
9. The advantage of putting complete assignment statements inside loop expressions is
(a) to avoid awkward program constructions
(b) to simplify the flow of control in the program
(c) to reduce the number of program statements
(d) to clarify the operation of the program
10. The break statement is used to exit from which part of a loop?
(a) beginning (b) middle (c) end (d) none of the above

-: Answer Keys :-

er
c b

nt
1. 6.

2. b

d
Ce
7. a

b
ish
3. 8.

4. d 9. c
gl
En

5. d 10. b
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 15


2nd year CS - Chapter # 8

Section (B / C)
8.1. What is meant by looping?

Looping is the process of executing a set of statements repeatedly until a specified condition is met.

8.2. What is the purpose of the for statement? How does it differ from the while statement and the do-
while statement?

The for loop is used for iteration with a fixed number of repetitions. It differs from:

 while: Condition is checked first; loop may not execute.


 do-while: Executes at least once before checking the condition.

8.3. How many times will a for loop be executed? Compare with the while loop and the do-while loop.

er
 for: Executes based on initialization, condition, and increment/decrement.

nt
 while: Executes while the condition is true.

Ce
 do-while: Executes at least once, then checks the condition.

8.4. How would you use a compound assignment operator to count by 2?


ish
Ans. for(count = 1! ; count <= 21 count+= 2)
gl

8.5. Write a for loop that counts backwards from 100 to 0 by 10.
En

Ans. for(count = 100; count >= 0 ; count = 10)

8.6. Find the error in the following statement (Note: there may be more than one error).
E

for( i = 100 i >= 1 ; i++)


M

Errors:

 Missing semicolon after initialization (i = 100;)


 Wrong increment; should be i-- instead of i++

8.7. What are the functions performed in a for argument?

 Initialization
 Condition checking
 Increment / Decrement

8.8. What stops a for loop?

The loop stops when the condition evaluates to false.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 15


2nd year CS - Chapter # 8
8.9. What is a nested loop?

A loop inside another loop, where the inner loop executes completely for each iteration of the outer loop.

8.10. Write a program that displays the multiplication table for numbers 0 to 9.

#include <stdio.h>

int main() {

for(int i = 0; i <= 9; i++) {

for(int j = 0; j <= 9; j++) {

printf("%d\t", i * j);

er
printf("\n");

nt
}

}
return 0; Ce
ish

8.11. Write nests of loops that cause the following output to be displayed:
gl

* * * * *
En

* * * *
* * *
* *
*
E

* *
M

* * *
* * * *
* * * * *
#include <stdio.h>
int main() {
for(int i = 5; i > 0; i--) {
for(int j = 0; j < i; j++) printf("* ");
printf("\n");
}
for(int i = 2; i <= 5; i++) {
for(int j = 0; j < i; j++) printf("* ");
printf("\n");
}
return 0;
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 15


2nd year CS - Chapter # 8
8.12. What is displayed by the following program segment, assuming m is 3 and n is 5?

for(i = n; i > 0; - - i)
{
for(j= m; j > 0; --j)
{
printf("*");
}
printf("\n");
}

Output:

***
***
***
***

er
***

nt
8.13. During execution of the following program segment, how many lines of asterisks are displayed?

for(i=0; i < 10; ++i)


for(j=0; j < 5; ++j)
printf("**********\n");
Ce
ish
Ans. 50
gl

8.14. Compare and discuss program 8-29 with one given in practical 7(b). Discuss
En

the similarities and differences.

/* program 8-29.cpp */
E

#include<stdio.h>
#include<conio.h>
M

void main (void)


{
clrscr();
int a, b;

for( b = 1 b < 12 ; b++) /* stepping down */


{
for( a = 1 a < 12 ; a++) /* stepping right */
if((a+b)%2==0 && a!=b)
printf("\xDB"); /* print filled square */
else if( a ==b) /* left top diagonal */
printf("\xB0"); /* print gray */
else
printf(" "); /* print blank square */
printf("\n"); /* new line */
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 15


2nd year CS - Chapter # 8
getch();
}

Errors:

 b = 1 b < 12; → b = 1; b < 12;


 a = 1 a < 12; → a = 1; a < 12;

8.15. Explain what is wrong with this program:

#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
float row, column;
puts("\t\tMy Handy Multiplication Table\n");

er
for (ow = 1; row <= 10 ; row++)

nt
{
for (column=1; column <= 10 ; column+)

}
printf("%d", row*column);
printf("\n"); Ce
ish
getch();
}
gl

Errors in the given program


En

 ow should be row
 column+ should be column++
E

 %d format specifier should be %f for floating-point values


M

8.16. What does the following program, output?

/* program 8-30.cpp */
#include<stdio.h>
#include<conio.h>
void main(void)
{
clrscr();
int i, j, k;
k = 0;
for ( i = 1 i <= 30 ; i++)
for( j = 1 j <= 20 j++)
if (j%3 == 0)
k++;
printf ("\nk = %d", k);
getch();
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 15


2nd year CS - Chapter # 8
Output:

k = 200

8.17. What will be the output of the following programs:

(a) void main(void)

{
char i = 1;
while( i <= 212 )
{
printf("%d\n", i);
i = i + 1;
}
}

er
Infinite loop (char type wraps around).

nt
(b) void main(void)

{
int i = 1;
while (i <= 212)
Ce
ish
printf("%d\n", ++i);
}
gl

Outputs numbers from 2 to 213.


En

(c) void main(void)

{
E

int i;
M

for (i = 1; i <= 212; i++);


printf("%d", i);
}

Outputs 213.

8.18. Write a program that inputs ten numbers between 0 and 25.

#include <stdio.h>
int main() {
int num, i;
for(i = 1; i <= 10; i++) {
do {
printf("Enter a number (0-25): ");
scanf("%d", &num);
} while(num < 0 || num > 25);
}

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 15


2nd year CS - Chapter # 8
return 0;
}

8.19. Write a program to print the sum of even numbers from 1 to 100.

#include <stdio.h>
int main() {
int sum = 0;
for(int i = 2; i <= 100; i += 2) sum += i;
printf("Sum: %d", sum);
return 0;
}

8.20. Write a program to print the squares of all the numbers from 1 to 20.

#include <stdio.h>

er
int main() {
for(int i = 1; i <= 20; i++) printf("%d^2 = %d\n", i, i*i);

nt
return 0;
}
Ce
8.21. Write a program to print prime numbers up to a specified range using for and nested for loop.
ish
Ans. We can test whether a number is prime or not, by dividing it successively by all numbers from 2
to one less than itself. If remainder of any of these divisions is zero, the number is not a prime.
gl

Following is the program to do this


En

/* program 8-31.cpp */
#include<stdio.h>
#include<conio.h>
E

void main(void)
M

{
clrscr();
int i, j, num;
printf("Enter the number: ");
scanf("%d", &num);
for( i = 2 i <= num; i++)
{
for( j = 2 ; j < i j++)
{
if( i%j ==0)
break;
}
if ( i ==j)
printf("%d\t", i);
}

getch();

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 12 of 15


2nd year CS - Chapter # 8
}

8.22. What is the purpose of the while statement? When is the logical expression evaluated? What is
the minimum number of times that a while loop can be executed?

Executes a block of code repeatedly while a condition is true. The condition is checked before execution. The
loop executes at least 0 times.

8.23. How is the execution of a while loop terminated?

When the condition becomes false.

8.24. When are a for loop and a while loop the same?

When the initialization, condition, and update are explicitly stated inside the while loop, making it functionally
identical to for.

er
8.25. What is the purpose of the do-while statement? How does it differ from the while statement?

nt
Executes at least once before checking the condition, unlike while, which checks first.

Ce
8.26. What is the minimum number of times that a do-while loop can be executed? Compare with a
while loop and explain the reasons for the differences.
ish
 do-while: Executes at least once.
 while: May execute zero times if the condition is false initially.
gl

8.27. What is the value of i after each of these segments?


En

(a) while ( i++ <=10);


(b) while(++i <= 10);
(c) i = 0
E

do
M

++i;
while ( i ++<10);

Value of i after execution

(a) i = 11
(b) i = 10
(c) i = 11

8.28. What criteria do you use to select a for, while or do-while loop?

 for: When loop runs a known number of times.


 while: When the condition controls the execution.
 do-while: When at least one execution is required.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 13 of 15


2nd year CS - Chapter # 8
8.29. State all the loop control structures supported by C and compare them.

 for
 while
 do-while

8.30. What does the following code segment display? Try each of these inputs: 345, 82, 6. Then,
describe the action of the code.

printf("\nEnter a positive integer: ");


scanf("%d", &num);
do
{
printf("%d", num%10);
num / = 10 ;
}
while(num > 0);

er
printf("\n");

nt
Ans.

Enter a positive integer: 345

5 4 3
Ce
ish
Enter a positive integer: 82
gl

2 8
En

Enter a positive integer: 6

6
E

The code displays the digits of an integer in reverse order and separated by spaces.
M

8.31. Write a loop that will calculate the sum of every third integer, beginning with i = 2 (i.e., calculate
the sum 2+5+8+11+...) for all values of i that are less than 100. Write the loop in three different
ways.

(a) Using a for statement.

int sum = 0;
for(int i = 2; i < 100; i += 3) sum += i;

(b) Using a while statement.

int sum = 0, i = 2;
while(i < 100) { sum += i; i += 3; }

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 14 of 15


2nd year CS - Chapter # 8
(c) Using a do-while statement.

int sum = 0, i = 2;
do { sum += i; i += 3; } while(i < 100);

8.32. What is the purpose of the break command?

Used to exit a loop prematurely when a condition is met.

8.33. State the use of the following giving an example of each.

(a) break

Terminates the loop immediately.

for(int i = 1; i <= 10; i++) {


if(i == 5) break;

er
printf("%d ", i);
}

nt
Output: 1 2 3 4

(b) continue Ce
ish
Skips the current iteration and moves to the next.

for(int i = 1; i <= 10; i++) {


gl

if(i == 5) continue;
printf("%d ", i);
En

Output: 1 2 3 4 6 7 8 9 10
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 15 of 15


2nd year CS - Chapter # 9

Class: 2nd year

Chapter # 9

Functions

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 10


2nd year CS - Chapter # 9
Contents

Functions: ................................................................................................................................................................................... 3
Examples: ........................................................................................................................................................................... 3
Section (A).................................................................................................................................................................................. 4
-: Answer Keys :-................................................................................................................................................................ 5
Section (B / C) ............................................................................................................................................................................ 6

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 10


2nd year CS - Chapter # 9
Functions:
Used to break a complex problem into smaller tasks.

1. Advantages:
o Reduces code repetition.
o Easier to read, debug, and maintain.
o Can return values and process information.
o Can be reused in multiple programs.
o Supports recursion.

2. Types of Functions:
o Built-in (Library) Functions: Predefined in <math.h>, <stdio.h>, etc.
o User-Defined Functions: Created by the programmer.

er
3. Components of a Function:

nt
o Function Declaration (Prototype): Informs the compiler about function name, return type, and
arguments.
o
o
Ce
Function Definition: Contains the function body (code to execute).
Function Call: Executes the function in main() or another function.
ish
4. Function Variations:
o With or without arguments.
gl

o With or without return values.


En

5. Passing Arguments:
o Can pass single or multiple values (actual → formal parameters).
E

o Must match type, order, and number.


M

Examples:

 Library function: sqrt(x) (finds square root).


 User-defined function:

void display(void) {
printf("Hello World");
}

Called using display(); in main().

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 10


2nd year CS - Chapter # 9

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. True or false: Functions are called mini-programs because they are usually short and have input, output, and
computations.
2. A program module in C is called a function.
3. According to the principles of software design, functions
(a) should compute at least two results to be worth the overhead.
(b) should be short and compute one result.
(c) should be as long as necessary but compute one result.
(d) are not really necessary for good software design.

er
4. Which of these are valid reasons for using functions?

nt
(a) they use less memory than repeating the same code.
(b) they run faster.
(c) they keep different program activities separate. Ce
ish
(d) they keep variables safe from other parts of the program.
5. True or false: The function header and the function call have identical syntax.
gl

6. A function prototype
En

(a) is an outline of the purpose of the function.


(b) is the same as the function header.
E

(c) is the same as the function call.


M

(d) is not necessary in Turbo C++.


7. True or false: Function prototypes are not needed in C.
8. Function is invoked with a function call.
9. Use the void data type when the function does not return a value.
10. True or false: A function can still be useful even if you cannot pass it any information and cannot get any
information back from it.
11. True or false: In C language, you can place the function main() any where in your program but it will still be
executed first.
12. A variable that is known only within the function in which it is defined is called a local variable.
13. A global variable is defined in a declaration
(a) in main() only. (b) in the first function that uses it.
(c) in any function that uses it. (d) outside of any function.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 10


2nd year CS - Chapter # 9
14. A global variable can be referenced in a declaration
(a) in main() only. (b) in the first function that uses it.
(c) in any function chat uses it. (d) outside of any function.
15. Which of the following are valid reasons for using arguments in functions?
(a) to tell the function where to locate itself in memory.
(b) to convey information to the function that it can operate on.
(c) to return information from the function to the calling program.
(d) to specify the type of the function.
16. True or false: A global variable can be used in main( ) only.
17. True or false: The variables commonly used in C functions are accessible to all other functions.
18. Which of the following can be passed to a function via arguments?

er
(a) constants. (b) variables (with values).

nt
(c) preprocessor directives. (d) expressions (that evaluate to a value).
(e) functions (that return values).
19. Which of the following is true?
Ce
ish
(a) C functions are all equal.
(b) C functions can be nested within each other.
gl

(c) C functions are arranged in a strict hierarchy.


En

(d) C functions can only be called from main().


20. True or false: To return from a function you must use the keyword return.
E

21. A function that calls itself is a recursive function.


M

-: Answer Keys :-
1. True 6. b 11. False 16. False 21. True

2. True 7. False 12. True 17. False

3. b 8. True 13. d 18. a,b,c,d,e

4. a,c,d 9. True 14. c 19. a


5. False 10. True 15. b 20. False

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 10


2nd year CS - Chapter # 9

Section (B / C)
9.1. What is the difference between a function in the C library and a function you write yourself?

 Library function: Predefined in C (e.g., printf(), sqrt()).


 User-defined function: Created by the programmer to perform specific tasks.

9.2. What are five advantages of using functions?

1. Code reusability
2. Modularity
3. Easy debugging
4. Improved readability
5. Efficient memory usage

er
9.3. What is a function prototype?

nt
Function prototype

Ce
A declaration of a function before its definition to specify its return type and parameters.

Example:
ish
int add(int, int);
gl

9.4. What occurs after a function is performed?


En

Control returns to the calling function, and if the function has a return value, it is returned.

9.5. Explain the difference between local and global variables.


E

Local vs Global Variables


M

 Local variables: Declared inside a function, accessible only within it.


 Global variables: Declared outside functions, accessible throughout the program.

9.6. How do you pass a value to a function?

By value (func(x)) or by reference (func(&x)).

9.7. How can you return a float value?

Declare the function with float return type:

float area(float r) { return 3.14 * r * r; }

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 10


2nd year CS - Chapter # 9
9.8. Is the use of functions a more efficient use of the programmer's time or the computer's time?
Explain your answer.

Functions save the programmer's time by reducing redundancy, improving readability, and making debugging
easier.

9.9. When do you use the keyword return while defining a function? When do you not use the
keyword return when defining a function?

 Use return if the function must return a value.

 Don't use return for void functions (unless used to exit early).

9.10. Writ a quiz program that asks four questions, each question and answer in a different function.

#include <stdio.h>

er
void q1() { printf("Q1: What is 2+2?\nA: 4\n"); }
void q2() { printf("Q2: Capital of France?\nA: Paris\n"); }

nt
void q3() { printf("Q3: 5 * 6?\nA: 30\n"); }
void q4() { printf("Q4: Largest planet?\nA: Jupiter\n"); }
int main() { q1(); q2(); q3(); q4(); return 0; }
Ce
9.11. Write a program in C to call a function which returns the cube of a given number.
ish
int cube(int n) { return n * n * n; }
gl

9.12. Write a C program that asks for a distance in meters and converts it into feet.
En

float metersToFeet(float m) { return m * 3.28084; }

9.13. Write a program in C that prints out the larger of two numbers entered from the keyboard. Use
E

a function to do the actual comparison of the two numbers. Pass the two numbers to the function
as arguments, and have the function return the answer.
M

int larger(int a, int b) { return (a > b) ? a : b; }

9.14. Write a program that inputs a number and then uses a function to calculate and display the
number to the fourth power.

int power4(int n) { return n * n * n * n; }

9.15. Write a program in C that asks the user to input length of the two sides of a right angled
triangle. Make use of the built-in functions pow and sqrt functions to compute the length of the
hypotenuse using the Pythagorean theorem.

#include <math.h>
float hypotenuse(float a, float b) { return sqrt(pow(a, 2) + pow(b, 2)); }

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 10


2nd year CS - Chapter # 9
9.16. Explain what is wrong with the following program:

#include<stdio.h>
void dothis(void)
{
puts("This is first");
main();
}
void main(void)
{
puts("This is second");
}

Error

er
 main() is called inside dothis(), causing infinite recursion.

nt
9.17. Is the following a correctly structured program?
#include<stdio.h>
void main(void)
{
Ce
ish
int three=3;
type(three);
}
gl

void type(float num)


{
En

printf("%f", num);
}
E

Errors
M

 type() is declared after main().


 int argument is passed to a float parameter.

9.18. Is this correctly written function?

abs (num);
{
int num;
if (num<0)
num = -num;
return(num);
}
Error

 Incorrect declaration (abs(num); should be int abs(int num)).


 Missing function name before {.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 10


2nd year CS - Chapter # 9
9.19. Write a program using a function to calculate the area of a rectangle.

int area(int l, int w) { return l * w; }

9.20. Write a function pow(x,y) to calculate the value of x raised to y.

int pow(int x, int y) {


int result = 1;
for(int i = 0; i < y; i++) result *= x;
return result;
}

9.21. Write a function which receives a float and an int from main(), finds the product of these two
and returns the product which is printed through main().

float multiply(float a, int b) { return a * b; }

er
9.22. Write a function which receives 5 integers and returns the product, sum and average of these

nt
numbers. Call this function from main() and print the results in main().

*avg) {
*sum = a + b + c + d + e;
Ce
void compute(int a, int b, int c, int d, int e, int *sum, int *prod, float
ish
*prod = a * b * c * d * e;
*avg = *sum / 5.0;
}
gl
En

9.23. What happens if the user calls recursive function with a negative argument?

Ans. The function goes into infinite recursion if the argument is negative since the base case is never
reached.
E
M

9.24. Rewrite the following mathematical expressions using C functions:


𝒘
(a)√(𝒙 − 𝒚)𝟒 (b)√𝒖 + 𝒗 × 𝒘 4 (c) |𝒙𝒚 − |
𝒛

(a) sqrt(pow(x-y, 4))


(b) sqrt(u+v) * pow(w, 4)
(c) fabs(x*y - w/z)

9.25. A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of
digits of the 5-digit number:

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 10


2nd year CS - Chapter # 9
(a) without using recursion.

int sumDigits(int n) {
int sum = 0;
while(n > 0) { sum += n % 10; n /= 10; }
return sum;
}

(b) using recursion.

int sumDigits(int n) {
return (n == 0) ? 0 : (n % 10 + sumDigits(n / 10));
}

9.26. Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci
sequence the sum of two successive terms gives the third term. Following are the first few terms

er
of the Fibonacci sequence:

nt
0 1 1 2 3 5 8 13 21 34 55 89 ...

int fibonacci(int n) {
if(n <= 1) return n;
Ce
ish
return fibonacci(n-1) + fibonacci(n-2);
}
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 10


2nd year CS - Chapter # 10

Class: 2nd year

Chapter # 10

Arrays

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 10


2nd year CS - Chapter # 10
Contents

Arrays: ........................................................................................................................................................................................ 3
Section (A).................................................................................................................................................................................. 4
-: Answer Keys :-................................................................................................................................................................ 6
Section (B / C) ............................................................................................................................................................................ 7

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 10


2nd year CS - Chapter # 10
Arrays:
An array is a collection of variables of the same type stored in contiguous memory locations.

1. Declaration:

type array_name[size];

Example:

int temps[5]; // Array of 5 integers

2. Indexing: Arrays use zero-based indexing (first element is at index 0).

3. Initialization:

int temps[5] = {53, 85, 29, 19, 63};

er
o If size is omitted, it’s determined from the values:

nt
int temps[] = {53, 85, 29, 19, 63};

4. Input with a loop:

for (int i = 0; i < 5; i++) {


Ce
ish
scanf("%d", &temps[i]);
}
gl

5. Sorting (Bubble Sort Algorithm):


o Repeatedly compares adjacent elements and swaps them if needed.
En

o Requires n-1 passes for an array of n elements.

6. Searching (Linear Search Algorithm):


E

o Sequentially checks each element.


M

o Efficient for small/unsorted arrays but slow for large datasets.

7. Passing Arrays to Functions:


o Pass a single element like a normal variable.
o Pass the whole array by using its name (arrays are passed by reference).

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 10


2nd year CS - Chapter # 10

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. An array is a collection of variables of
(a) different data types scattered throughout memory.
(b) the same data type scattered throughout memory.
(c) the same data type placed next to each other in memory.
(d) different data types placed next to each other in memory.
2. A simple variable differs from an array variable because a simple variable
(a) can have only one value during the entire execution of a program.

er
(b) can have many values at one time during the execution of a program.
(c) can have many values but only one value at any given time.

nt
(d) has a many-to-one relationship between the variable and its associated data.

Ce
3. Individual elements of an array are referred to by means of an index or subscript.
4. Is this a correct array declaration?
ish
int max(7);

5. Which element of the array does this expression reference?


gl

list[2] /*Third element (index 2) of the array list*/


En

6. What is the difference between the 5s in these two expressions?


int temps [5];
E

temps [5] = 84;


M

(a) first is particular element, second is type.


(b) first is size, second is particular element.
(c) first is particular element, second is array size.
(d) both specify array elements.
7. The following declares a float array whose elements are numbered 0 through 10:
(a) float rainfall[10]; (b) float rainfall[11];
(c) float rainfall[9]; (d) float rainfall [0:10];

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 10


2nd year CS - Chapter # 10
8. What does this combination of statements do?
#define MAXSIZE 10
int list[MAXSIZE];

(a) make MAXSIZE a subscript. (b) makes MAXSIZE a variable of type float.
(c) makes list[] an array of type MAXSIZE. (d) makes list[] an array of size MAXSIZE.
9. The following sets all cells of a five-element array to the value of 10?
(a) int x {10, 10, 10, 10, 10};

(b) int x[] = {5*10};


(c) int x[5] = {5*10};
(d) int x[] = {10, 10, 10, 10, 10);
10. What will happen if you try to put so many elements into an array when you initialise it that the size of the array

er
exceeded?

nt
(a) nothing. (b) possible system malfunction.
(c) error message form the compiler.
Ce
(d) other data may be overwritten.
11. What will happen if you put too few elements in an array when you initialise it?
ish
(a) nothing. (b) possible system malfunction.
(c) error message from the compiler. (d) unused elements will be filled with 0s or garbage.
gl

12. What will happen if you assign a value to an element of an array whose subscript exceeds the size of the array?
En

(a) the element will be set to 0. (b) nothing, it is done all the time.
(c) other data may be overwritten. (d) possible system malfunction.
E

13. A one-dimensional array is sometimes called a contiguous list.


M

14. When you pass an array as an argument to a function, what is actually passed?
(a) the address of the array. (b) the values of the elements in the array.
(c) the address of the first element in the array. (d) the number of elements in the array.
15. True or false: A function operates on an integer array passed to it as an argument by placing the values of that array int
separate place in memory know only to the function.
16. True or false: Individual array elements cannot be passed easily to a function.
17. True or false: To pass a whole array to a function, you specify the array name.
18. True or false: Address of a floating-point variable is always a whole number.
19. To pass an individual element of an array to a function, you must specify
(a) the data type of the array, its name, and the element number.
(b) the name of the array and the element number as two separate arguments.
(c) the name of the array and the element number as one argument.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 10


2nd year CS - Chapter # 10
(d) just the element number.
20. Assuming the array declaration float values [MAX_VALUE]; which statement will pass the whole array to funct
calc_max?
(a) calc_max(float values[]); (b) calc_max(values[MAX_VALUE]);
(c) calc_max(float values [MAX_VALUE]); (d) calc_max(values);
21. True or false: Multi-dimensional arrays are sometimes called arrays of arrays.
22. True or false: Up to three dimensions for an array are allowed in C.
23. True or false: Multi-dimensional arrays allow multiple data types.
24. True or false: In a two-dimensional array, the first dimension always refers to the row and the second dimension alway
refers to the column.
25. Two-dimensional arrays are sometimes called matrices or tables.

er
26. The following declares a two-dimensional double array with four rows and three columns.

nt
(a) double x [3,4]; (b) double x[4,3]; (c) double x[3][4] (d) double x[4][3] ;
27. Can you initialise a two-dimensional array this way?
int array [3][3] = { {1,2,3}, {4, 5, 6), {7,8,9} };

28. The following initialises a two-dimensional array to all ones?


Ce
ish
(a) int x[3][2] = {7 * 1}; (b) int x[3][2] = {1, 1, 1, 1, 1, 1} ;
(c) int x[3][2] = {1} ; (d) int x[3][2] = { {1, 1} } , { {1, 1} } , { {1, 1} } ;
gl

29. Which statement initialises the array so that it looks like the pictures?
En

7 7 6 6 6
7 6 6 6 6
E
M

(a) x[5][2] = { {7,7}, {7,6), (6,6}, {6,6}, {6,6} }; (b) x[2] [5] = ( {7,7,6,6,6}, {7,6,6,6,6} );
(c) x[5][2] = { {7,7,6,6,6}, {7,6,6,6,6} }; (d) x[2][5] = { {7,7,6,6,6}, {7,6,6,6} };

-: Answer Keys :-
1. c 6. b 11. d 16. False 21. True 26. d
2. c 7. b 12. c 17. True 22. False 27. True
3. True 8. d 13. True 18. False 23. False 28. b
4. False 9. d 14. c 19. b 24. True 29. b
5. index(2) 10. c 15. False 20. d 25. True

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 10


2nd year CS - Chapter # 10

Section (B / C)
10.1. What is an array?

An array is a collection of elements of the same data type stored in contiguous memory locations.

10.2. Can an array store more than one type of variable?

No, an array can store only one data type (e.g., all integers or all floats).

10.3. How do yn array?

int arr[5]; // Declares an integer array with 5 elements

10.4. What is the difference in meaning between x3 and x[3]?

er
 x3 is a variable.
 x[3] refers to the 4th element of an array x (indexing starts at 0).

nt
10.5. The simple variable x can take on different values, such as 5 and 12. Why is x not called an
array?
Ce
Ans. The value of any simple variable can change overtime. Yet at any given time, only one value can be
ish
associated with a simple variable. There is a one-to-one correspondence between its name and its current
value. By contrast, an array has a one-to-many correspondence between its name and its current values.
gl

10.6. For the declaration char num[7]; how many memory cells are allocated for data storage?
What type of data can be stored there? How does one refer to the initial array element? To the
En

final array element?

 Allocates 7 bytes of memory.


E

 Stores characters.
 Initial element: num[0], Final element: num[6].
M

10.7. What is the relationship between the value of the subscript and the value of the array element?

The subscript (index) determines the position, and the element holds the actual value.

10.8. If an array is declared as float x[10], does that mean that the indices are also floating point?

Ans. No! The data type of an array is the kind of data that can be stored in the individual cells of the arrays.
The index of any array is always an integer in the range of 0 to (array size - 1).

10.9. Initialise a five-element array to the values 10, -43, 32, 93, 76.

int arr[5] = {10, -43, 32, 93, 76};

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 10


2nd year CS - Chapter # 10
10.10. Declare one array for storing the square roots of the integers from 0 through 10 and a second
array for storing the cubes of the same integers.

float sqrtArr[11], cubeArr[11];


for(int i = 0; i <= 10; i++) {
sqrtArr[i] = sqrt(i);
cubeArr[i] = i * i * i;
}

10.11. Write a program that reads n integers and prints the smallest along with its index in the list.

#include <stdio.h>
int main() {
int n, i, min, index;
printf("Enter number of elements: ");
scanf("%d", &n);

er
int arr[n];
for(i = 0; i < n; i++) scanf("%d", &arr[i]);

nt
min = arr[0], index = 0;
for(i = 1; i < n; i++) if(arr[i] < min) min = arr[i], index = i;

}
return 0; Ce
printf("Smallest: %d at index %d\n", min, index);
ish
10.12. What happens if an array is referenced outside of its bounds?
gl

Ans. Out-of-bounds references are allowed but they are not checked and the results are unpredictable! As the
En

programmer you are responsible for ensuring that all arrays are correctly referenced.

10.13. If an array has been defined this way:


float cost[MAX];
E

is the following a good way to read values into all the elements of the array?
M

for(j=0; j <= MAX; j++)


scanf("%f", cost[j]);

Error: j <= MAX should be j < MAX, otherwise it goes out of bounds.

10.14. How do we set all the cells of a 100-element array to 1?

Ans. Assume that the array j has been declared, use a for loop:

for(index=0; index < 100; index++)

j[index]=1;

10.15. How can you change array data?

Ans. As with simple variables, you can change array data with an input statement such as scanf or with an
assignment statement as in list[4]=9; As the programmer you must be sure to supply a well-defined
subscript for the array.
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 10
2nd year CS - Chapter # 10
10.16. Is this a correct way to initialise a one-dimensional array?

int array = {1, 2, 3, 4};

Error: Arrays should be initialized using square brackets:

10.17. Write a program that reads two integer arrays, x and y, having 4 elements each and prints the
sum of the products as given below.

sum = x[1] × y[1] + x[2] × y[2] + x[3] × y[3] + x[4] × y[4]

#include <stdio.h>
int main() {
int x[4], y[4], sum = 0;
printf("Enter 4 elements for x: ");
for(int i = 0; i < 4; i++) scanf("%d", &x[i]);

er
printf("Enter 4 elements for y: ");
for(int i = 0; i < 4; i++) scanf("%d", &y[i]);

nt
for(int i = 0; i < 4; i++) sum += x[i] * y[i];
printf("Sum of products: %d\n", sum);

}
return 0;
Ce
ish
10.18. Explain what is wrong with this program?

#include<stdio.h>
gl

#include<conio.h>
void main(void)
En

{
clrscr();
int count[10];
int index;
E

for(index = 0; index < 100; index++)


M

{
printf("Enter a number &d: ", index);
scanf("%d", &count [index]);
}
}

Errors:

 clrscr(); is non-standard, should be removed.


 Loop runs from 0 to 99, but count[10] only has 10 elements (out-of-bounds error).
 Format specifier %d is incorrectly written as &d.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 10


2nd year CS - Chapter # 10
10.19.A problem calls for a list of numbers to be. input. The user decides how many numbers, as
shown below:

int size, list[size];


printf("\nEnter the size of the list");
scanf("%d", &size);

What is wrong with this program segment?

Ans. The size of a declared array must be a constant. Because the value of size is not fixed at compile time, the
array is not described correctly and the declaration generates a syntax error. We have to estimate a
reasonable maximum size for the array and use that number in the array declaration.

10.20. Write a program that reads ten numbers entered by the user and reports if any of them match.

#include <stdio.h>

er
int main() {
int arr[10], i, j, flag = 0;

nt
printf("Enter 10 numbers: ");
for(i = 0; i < 10; i++) scanf("%d", &arr[i]);
for(i = 0; i < 10; i++) {
for(j = i + 1; j < 10; j++) { Ce
if(arr[i] == arr[j]) { flag = 1; break; }
ish
}
}
if(flag) printf("Duplicate found\n");
gl

else printf("No duplicates\n");


return 0;
En

10.21. Change the sorting program shown in program 10-8 so that it sorts data of type float.
E
M

void sort(float arr[], int size) {


for(int i = 0; i < size - 1; i++)
for(int j = 0; j < size - i - 1; j++)
if(arr[j] > arr[j + 1]) {
float temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

10.22. What are the two- and three-dimensional arrays? How do you declare them?

 Two-dimensional array:
int arr[3][4]; // 3 rows, 4 columns

 Three-dimensional array:
int arr[2][3][4]; // 2 layers, 3 rows, 4 columns

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 10


2nd year CS - Chapter # 11

Class: 2nd year

Chapter # 11

Strings

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 8


2nd year CS - Chapter # 11
Contents

Strings ......................................................................................................................................................................................... 3
Section (A).................................................................................................................................................................................. 4
-: Answer Keys :-................................................................................................................................................................ 5
Section (B / C) ............................................................................................................................................................................ 6

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 8


2nd year CS - Chapter # 11
Strings
A string is an array of characters terminated by \0.

1. Declaration:
o char name[10]; (Allocates 10 characters including \0.)

2. Initialization:
o char msg[6] = "Hello"; (Automatically adds \0.)

3. Input & Output:


o scanf("%s", name); (No spaces allowed.)
o gets(name); (Allows spaces but is unsafe.)
o puts(name); (Displays and moves to a new line.)

er
4. Built-in Functions (from <string.h>):
o strcmp(s1, s2): Compares strings.

nt
o strlen(s): Returns string length.
o strcat(s1, s2): Concatenates strings.
o strcpy(s1, s2): Copies s2 to s1.
o strchr(s, ch): Finds a character in a string.
Ce
ish
5. Array of Strings:
gl

o Declared as char names[5][20]; (Stores 5 names, max 19 chars each.)


o Example: char names[5][20] = {"Ali", "Ahmed", "Sara"};
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 8


2nd year CS - Chapter # 11

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. A string is
(a) a list of character. (b) a collection of characters.
(c) an array of characters. (d) an exaltation of characters.
2. True or false: Turbo C++ does not distinguish between 'C' and "C".
3. What is the following expression?
"Karachi\n"
(a) a string variable. (b) a string array.

er
(c) a string constant. (d) a string of characters.
4. True or false: Strings are stored as arrays of characters.

nt
5. The string "I like programming" needs 19 memory cells.
6. String functions are accessible through the <string.h> header.
7. An array of strings is actually a character array.
Ce
ish
8. Which is more appropriate for reading in a multiword string?
(a) gets() (b) printf() (c) scanf() (d) puts()
gl

9. The statement strlen(string)


En

(a) returns the length of the string including the null character.
(b) returns the length of the string excluding the null character.
E

(c) returns the length of the string as specified in its declaration.


M

(d) returns the declared length of the string minus 1.


10. The statement strcpy(stringl, string2)
(a) adds string2 to the end of stringl. (b) adds string1 to the end of string2.
(c) overwrites stringl with string2. (d) overwrites string2 with stringl.
11. The statement strcmp("Syed", "Asif")
(a) is not legal because "Syed" and "Asif" are not string variables.
(b) returns the value 0 because the strings are not equal.
(c) returns the value -1 because the strings are not equal.
(d) returns a positive value because "Syed" is greater than "Asif".
12. True or False: The gets function is accessed through <string.h>.
13. The statement strchr("Asif", 'i')

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 8


2nd year CS - Chapter # 11
(a) returns 0 because 'i' is contained in "Asif".
(b) returns a negative value because 'i' is contained in "Asif".
(c) returns a positive value because 'i' is contained in "Asif".
(d) is a syntax error because "Asif" is not a string variable.
14. What does this program fragment display?
char x[80] = "gorilla";
char y[80] = "giraffe";
strcpy(x, y);
printf("%s %s\n", x, y);

(a) gorilla giraffe (b) giraffegorilla gorilla


(c) gorilla gorilla (d) giraffe giraffe

er
15. What does this program fragment display?
char x[80] = "gorilla";

nt
char y[80] = "giraffe";
strcat(x, y);
printf("%s %s\n", x, y);

(a) gorillagiraffe giraffe


Ce
(b) giraffegorilla gorilla
ish
(c) gorilla gorilla (d) giraffe giraffe
gl
En

-: Answer Keys :-
1. c 11. d
E

2. False 12. False


M

3. c 8. a 13. c
4. True 9. b 14. d
10. c 15. a

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 8


2nd year CS - Chapter # 11

Section (B / C)
11.1. Is 'C' the same as "C"?

Ans. No! 'C' is a character constant and is not equal to the string constant "C".

11.2. Where is the '\0' character in a string?

Ans. Turbo C++ supplies '\0' if you provide space for it in the array. The '\0' is important for string
processing because it indicates the logical endpoint of a given string.

11.3. How do you compare two strings?

Use strcmp() from <string.h>:

if (strcmp(str1, str2) == 0)

er
printf("Strings are equal");

nt
11.4. How do you assign a value to a string variable?

char str[] = "Hello"; // Initialization


Ce
strcpy(str, "World"); // Assignment (requires <string.h>)
ish
11.5. Assuming the following initialisation:

char string[] = "Pakistan";


gl

how would you refer to the string "tan" (the last three letters of the string)?
En

Using pointer:

char *sub = &string[5]; // Points to "tan"


E
M

11.6. What is the wrong with the following declaration?

name "Azeem";

Error

 Missing data type and assignment operator. Correct:

char name[] = "Azeem";

11.7. Output the third character from a 40-character string.

char str[40];
printf("%c", str[2]); // Index 2 for the third character

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 8


2nd year CS - Chapter # 11
11.8. Output the third string from a 40-string array of strings.

char strArr[40][50];
printf("%s", strArr[2]); // Index 2 for the third string

11.9. Copy the alphabetically smaller of two strings into the third position of a string array.

if (strcmp(str1, str2) < 0) strcpy(strArr[2], str1);


else strcpy(strArr[2], str2);

11.10. Copy the fifth string from an array of strings to a single string variable.

char str[50];
strcpy(str, strArr[4]); // Copy 5th string (index 4)

11.11. Copy the seventh string from an array of strings to the ninth string of a string array.

er
strcpy(strArr[8], strArr[6]); // Copy 7th (index 6) to 9th (index 8)

nt
11.12. Write a program to find whether a character string is a palindrome. A palindrome reads the

#include <stdio.h>
#include <string.h>
Ce
same whether it is read from left to right or right to left [ABBA is a palindrome].
ish
int main() {
char str[100], rev[100];
gl

printf("Enter string: ");


scanf("%s", str);
En

strcpy(rev, str);
strrev(rev);
if (strcmp(str, rev) == 0) printf("Palindrome\n");
E

else printf("Not a palindrome\n");


return 0;
M

11.13. What expression would you use to find the length of the string name?

strlen(name);

11.14. Write a program to input word and then print number of vowels, with appropriate message.
For example if you enter word Computer it should print following message:

Number of vowels in word Computer is 3.

#include <stdio.h>
#include <ctype.h>
int main() {
char str[50];
int count = 0;
printf("Enter word: ");

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 8


2nd year CS - Chapter # 11
scanf("%s", str);
for (int i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
count++;
}
printf("Number of vowels in word %s is %d.\n", str, count);
return 0;
}

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 8


2nd year CS - Chapter # 15

Class: 2nd year

Chapter # 15

Data Management Systems

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 11


2nd year CS - Chapter # 15
Contents

Database vs. Manual Data Management: ................................................................................................................................... 3


Database Management System (DBMS): .................................................................................................................................... 3
Objectives of DBMS ................................................................................................................................................................ 3
Components of DBMS ............................................................................................................................................................. 4
Database Models .................................................................................................................................................................... 4
Section (A).................................................................................................................................................................................. 5
-: Answer Keys :-................................................................................................................................................................ 6
Section (B / C) ............................................................................................................................................................................ 7

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 11


2nd year CS - Chapter # 15
Database vs. Manual Data Management:

o Manual data handling is slow and error-prone.


o Databases store data electronically, making it easy to search, retrieve, and update information.

Database Components:

o Character: The smallest unit (letters, numbers, special characters).


o Entity: Any object or event stored in a database (e.g., student, machine, accident).
o Field/Attribute: A characteristic of an entity (e.g., employee name, salary).
o Key Field: A unique identifier used to sort and retrieve records (e.g., Employee ID, NIC).
o Record: A collection of related fields (e.g., an employee’s full details).
o File: A collection of related records (e.g., all employees' records).

er
o Database: A collection of related files forming a structured system.

nt
Database Management System (DBMS):
o
Ce
A software that allows users to create, manage, and manipulate a database (e.g., Oracle, MS Access,
dBASE).
ish
Advantages of DBMS:

o Reduces data redundancy (avoiding duplicate data).


gl

o Ensures data consistency (changes reflect system-wide).


En

o Provides program independence (standardized formats make maintenance easier).


o Enhances user productivity (easy to use, requires no technical expertise).
E

o Improves security (restricted access via passwords).


M

Disadvantages of DBMS:

o High cost (installation, maintenance, and training).


o Security risks (unauthorized access to sensitive data).
o Privacy concerns (data misuse, e.g., medical data affecting job promotions).
o Hardware demands (DBMS requires significant storage and processing power).

Objectives of DBMS

1. Efficient Use of Resources – Should work without requiring expensive hardware upgrades.
2. Speed – Must provide quick responses to queries.
3. Compatibility – Should integrate smoothly with existing hardware/software.
4. Efficient Data Updates – Allows easy addition, deletion, and modification of records.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 11


2nd year CS - Chapter # 15
5. Accessibility – Provides user-friendly query languages for retrieving information.
6. Data Integrity – Ensures data is accurate and protected against failures or accidental deletions.
7. Privacy & Security – Limits access to authorized users with passwords and access codes.

Components of DBMS

1. Query Language – Used to retrieve and manipulate data (e.g., SQL).


2. Data Dictionary – Stores definitions of database structure and ensures data integrity.
3. Utilities – Includes tools for data maintenance, deletion, and performance monitoring.
4. Report Generator – Helps users create structured reports easily.
5. Access Security – Controls user privileges to protect data.
6. System Recovery – Recovers lost transactions in case of system failure.

er
Database Models

nt
1. Hierarchical Model – Organizes data in a tree structure with parent-child relationships.

Ce
2. Network Model – Allows multiple parent-child relationships (more flexible than hierarchical).
3. Relational Model – Uses tables with key fields to link related data, providing flexibility and ease of querying.
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 11


2nd year CS - Chapter # 15

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. Which of the following hardware components is the most important to the operation of a database
management system?
(a) high-resolution video display (b) printer
(c) high speed, large capacity disk (d) plotter (e) mouse
2. Which of the following is not function of a DBMS?
(a) providing security to database
(b) providing facilities for back up and recovery of data
(c) providing facilities to generate code for a given set of specifications

er
(d) none of the above

nt
3. Database management systems are intended to:
(a) eliminate data redundancy
Ce
(b) establish relationships among records in different files
ish
(c) manage file access
(d) maintain data integrity
gl

(e) all of the above


En

4. Which of the following can help speed up data retrieval?


(a) program file (b) key field (c) offline storage (d) data file (e) all of these
E

5. Which of the following is not characteristic of a relational database model?


M

(a) tables (b) treelike structure


(c) complex logical relationships (d) records (e) fields
6. Which of the following is a type of DBMS software?
(a) database manipulation language (b) query language
(c) utilities (d) report writer (e) all of the above
7. A data dictionary doesn't provide information about:
(a) where data is located (b) the size of the disk storage device
(c) who owns or is responsible for the data (d) how the data is used
(e) security and privacy limitations
8. To retrieve information from a database, users can use a(n) easy-to-use computer language. an
(a) data dictionary (b) report generator (c) data mining structure (d) query language

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 11


2nd year CS - Chapter # 15
9. To extract data from a database and display it or print it to in a preformatted form, users can use a(n)
(a) DBMS utility (b) QBE
(c) report generator (d) shared database
(e) none of the above

-: Answer Keys :-
1. c 6. e
2. c 7. b
3. e 8. d

er
4. b 9. c

nt
5. b

Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 11


2nd year CS - Chapter # 15

Section (B / C)
15.1. Why is a database management system important to many organisations?

A DBMS helps manage large amounts of data efficiently, ensures data integrity, allows multiple users to access
data simultaneously, provides security, and supports quick data retrieval for decision-making.

15.2. What is the difference between a primary key and a secondary key?

 Primary Key: Uniquely identifies each record in a table.


 Secondary Key: Used for searching and indexing but not necessarily unique.

15.3. List some of the advantages and disadvantages of database system.

Advantages:

er
1. Data consistency
2. Reduced redundancy

nt
3. Improved security
4. Data integrity
5. Multi-user access

Disadvantages:
Ce
ish
1. High cost
2. Complexity
gl

3. Need for regular maintenance


4. Performance issues with large data
En

15.4. What is a database management system?

A Database Management System (DBMS) is software that stores, retrieves, and manages data in a structured
E

way.
M

15.5. What characteristics should a good DBMS exhibits?

1. Data integrity
2. Security features
3. Multi-user support
4. Efficient data retrieval
5. Scalability and reliability

15.6. Evaluate the three major data models. In what situations would one be better than the others,
and why?

1. Hierarchical Model – Data organized in a tree structure. Best for one-to-many relationships.
2. Network Model – More flexible than hierarchical, allowing many-to-many relationships.
3. Relational Model – Data stored in tables with relationships. Best for complex queries and user-friendliness.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 11


2nd year CS - Chapter # 15
15.7. What are the advantages of organising a database according to a relational model as opposed to
a network model?

 Easier to use and maintain


 Simple structure using tables
 Powerful query support
 More flexibility in data retrieval

15.8. For each of the following types of database management systems, describe how data relate to one
another:

(a) Relational DBMS

Data stored in tables, related using keys.

(b) Hierarchical DBMS

er
Parent-child relationships in a tree structure.

nt
(c) Network DBMS

Ce
Many-to-many relationships using pointers.
ish
15.9. Describe, using both your own words and an example, how a relational database works.

Tables store data, and relationships are made using primary and foreign keys.
gl

Example: A Students table stores student info, and an Enrollments table links students to courses.
En

15.10. What kinds of things should a DBMS report generator be able to do?

 Formatting reports

E

Filtering data
 Summarizing data
M

 Exporting reports

15.11. Name at least five advantages and four disadvantages of database management system.

Advantages:

1. Reduced redundancy
2. Better security
3. Data integrity
4. Faster access
5. Scalability

Disadvantages:

1. High cost
2. Complexity
3. Training required
Prepared by: Aqib Ilyas (BSCS, SMIU) Page 8 of 11
2nd year CS - Chapter # 15
4. Hardware dependency

15.12. What is a query language and why is it a valuable aspect of DBMS software?

A Query Language (e.g., SQL) is used to retrieve and manipulate data in a DBMS, making data access easier.

15.13. What does the data dictionary in a DBMS provide?

Stores metadata (data about data), including table structures, relationships, and constraints.

15.14. Refer to the two tables in the sample relational database, and answer the following questions:

Employee Table Office Table


Location Manager
Emp. Name Location Department Salary Khairpur Faheemuddin
M. Amir Hyderabad Accounting 5800
Kotri M. Saad
Bashir Ahmed Karachi Sales 7000

er
Rohri M. Ali
Maqbool Siddiqui Kotri Sales 4500
Sohail Aslam Khairpur Accounting 6200 Hyderabad Qasim Abbas

nt
Pervaiz Malik Rohri Accounting 7300
Baqir Ali Khairpur Sales 5600

Ce
ish
(a) What is the average salary of an employee in the Sales department?

Average salary of Sales department


gl

(7000 + 4500 + 5600) / 3 = 5700


En

(b) Which employees does M. Ali supervise?


E

Employees supervised by M. Ali


M

Pervaiz Malik (Rohri)

(c) What is the average salary under Faheemuddin's supervision?

Average salary under Faheemuddin

(6200 + 5600) / 2 = 5900

(d) In which of the preceding questions did you have to relate data in both tables to get an
answer? Through what fields did you relate tables?

Used Location as the common field to relate Employee Table and Office Table.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 9 of 11


2nd year CS - Chapter # 15
15.15. Referring to the table given below, answer the following with respect to the relational database.

(a) What are the name, address, and telephone number of the owner of restaurant R3?

(b) Which restaurants have annual sales of 450000 or less? Who owns the restaurants in
question?

(c) What initial fee was charged for restaurant R5? What are the royalty and advertising
percentages in effect for this restaurant?

(d) How much does restaurant R3 owe to the corporation in royalty and advertising fees for the
coming year? (answer in rupees, as opposed to percentage.)

(e) Which contract type has the highest initial fee? What is that amount?

(f) Which restaurant has the highest annual sales? How much?

er
(g) Which franchisees do not live in Karachi?

nt
(h) What is the total paid to the corporation in initial fees for the five existing restaurants?

(i) Who owns the restaurant with the highest annual sales?Ce
ish
(a) Restaurant File

Restaurant Annual Contract


Street Address City Province Franchise
gl

Number Sales Type


R1 34 Ground Street Karachi Sindh 600000 F1 C1
En

R2 21 Mall Road Hyderabad Sindh 450000 F2 C2


R3 14 Kashif Lane Kotri Sindh 250000 F3 C3
R4 45 Silver Street Lahore Punjab 975000 F4 C4
R5 76 Green Street Khairpur Sindh 50000 F5 C5
E
M

(b) Franchisee File

Franchise Street
Franchise Name Telephone City Province
Number Address
F1 Kabir Ahmed 3274623 95 Millat Road Karachi Sindh
F2 Arif Hussain 9876728 45 Peak Street Karachi Sindh
F3 Qazi Samad 3848189 85 Park Street Lahore Punjab
F4 Munawar Ali 3846219 56 Main Street Peshawar NWFP

(c) Contract File

Contract
Team (years) Initial Fee Royalty % Advertising
Type
C1 99 250000 2% 2%
C2 5 50000 4% 3%
C3 10 75000 3% 3%

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 10 of 11


2nd year CS - Chapter # 15
(a) Owner of R3: Qazi Samad, 85 Park Street, Lahore, 3848189
(b) Restaurants with ≤ 450,000 sales: R2 (Arif Hussain), R3 (Qazi Samad), R5 (F5)
(c) Initial Fee, Royalty, and Advertising for R5: 50,000; 4%; 3%
(d) R3 Owes:

250000 × ( 3% + 3%) = 15,000

(e) Highest Initial Fee: C1 – 250,000


(f) Highest Annual Sales: R4 – 975,000
(g) Franchisees Not in Karachi: Qazi Samad, Munawar Ali
(h) Total Initial Fees:

250,000 + 50,000 + 75,000 +...

er
(i) Owner of highest sales restaurant (R4): Munawar Ali

nt
15.16 Consider the relation scheme containing book data for a bookstore:

Ce
BOOK (TITLE, AUTHOR, ISEN, PUBLISHER, PUB_DATE, CITY, QTY_ON_HAND)
ish
(a) Write out the table for an instance of this relation.

TITLE AUTHOR ISBN PUBLISHER PUB_DATE CITY QTY_ON_HAND


gl

C Programming Dennis Ritchie 123456 Pearson 1988 NY 10


En

(b) Identify a primary key, and a secondary key, writing out any assumptions you need to make
to justify your choice.
E

Primary Key: ISBN (Unique for each book)


M

Secondary Key: TITLE (Used for searches)

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 11 of 11


2nd year CS - Chapter # 16

Class: 2nd year

Chapter # 16

Basics of MS Access 2000

er
nt
Ce
( According to old book )
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 1 of 7


2nd year CS - Chapter # 16

Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
1. Which Access object is considered primary?
(a) table (b) query (c) form (d) report
2. Which screen element is used to easily design or open the objects within a database?
(a) close button (b) status bar (c) database toolbar (d) database window
3. A database contains the first name, last name, and phone number for a group of students. The first name
entries are what kind of data?
(a) fields (b) records (c) queries (d) tables
4. During which phase of the database design are the output specifications identified?

er
(a) defining the purpose (b) planning the objects

nt
(c) creating and relating tables (d) creating queries
5. How many database files can be open simultaneously?
(a) one (b) two (c) three (d) four Ce
ish
6. Which data type is used to store long text entries?
(a) text (b) memo (c) numeric (d) OLE object
gl

7. The upper pane in the Table Design window is used to enter


En

(a) field names (b) field data types (c) Held properties (d) a and b
8. Which of the following statements is false?
E

(a) When you open an Access database, the database window is displayed
M

(b) To create database objects, you must first open the database file containing them.
(c) All Access database objects are contained in one file.
(d) When you open a database file, a new table is automatically created.
9. What field type uses a checkbox to store field data?
(a) text (b) number (c) date/time (d) yes/no
10. Which of the following data types allows you to specify a field size?
(a) text (b) number (c) date/Time (d) currency
11. You are designing a table containing name and address information. How many characters should you
reserve for the Name field, which is a text data type?
(a) 255 (b) 50 (c) 10 (d) 5

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 2 of 7


2nd year CS - Chapter # 16
12. Which view do you use to enter data into a table?
(a) Table Design view (b) Datasheet view
(c) Database Location view (d) Database Design view
13. A warning appears when you
(a) insert a field (b) delete a field (c) edit field data (d) change fields
14. The Undo feature cannot reverse
(a) inserting a field (b) editing a field (c) deleting a field (d) rearranging fields
15. To insert new fields in a database table,
(a) select the field that follows the new field, and click the Insert Rows button on the toolbar.
(b) select the field that follows the new field, and press Insert.
(c) select a record in the table, and press Enter.

er
(d) select the field that follows the new field, and choose File, Insert New Record.

nt
16. Key fields must contain
(a) filtered data (b) default values
Ce
(c) unique data
17. To locate a record in a database table quickly, use the
(d) presorted information
ish
(a) Find feature (b) Replace feature. (c) Datasheet (d) Print Preview feature
18. Options available in the Find dialog box enable you to do all the following except
gl

(a) match any part of the field


En

(b) move up or down from the active data field


(c) replace field contents automatically
E

(d) search for text with capitalization that exactly matches the text typed
M

19. Updating records includes all the following activities except


(a) changing an address (b) creating a new database
(c) inserting new records (d) removing obsolete records
20. To delete a record from a table,
(a) select a field in the table and press Enter
(b) select a field in a form and press Delete
(c) click the frame button or record selection bar and press Delete
(d) select Datasheet View and press Enter
21. Which of the following is not true concerning the sort feature in Access?
(a) Records can be sorted in ascending or descending order according to the values in a specific field.
(b) Information about the sort can be saved with the table design properties.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 3 of 7


2nd year CS - Chapter # 16
(c) Dates are sorted from most recent to least recent when using the Sort Descending feature.
(d) The case of text entries does not matter when sorting records.
22. To identify the field you want to use for sorting records,
(a) click the Sort Ascending button
(b) select the entire table
(c) position the insertion point somewhere in the desired field
(d) click the Sort Descending button
23. To restore a deleted record,
(a) press Ctrl+Page Down (b) close the database without saving and reopen it
(c) click the Undo button (d) retype the record

er
nt
-: Answer Keys :-
1.

2. d
a 6.

7.
b
d
11.

12.
Ceb
b
16.

17.
c
a
21.

22.
b
c
ish
3. a 8. d 13. b 18. c 23. b
4. a 9. d 14. c 19. b
gl

5. a 10. b 15. a 20. c


En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 4 of 7


2nd year CS - Chapter # 16

Section (B / C)
16.1. What is the database window?

The database window in Microsoft Access is the main interface that allows users to manage database objects
like tables, queries, forms, and reports.

16.2. How many object classes are there in Access?

Microsoft Access has six main object classes:

1. Tables
2. Queries
3. Forms
4. Reports
5. Macros

er
6. Modules

nt
16.3. All database objects are displayed in which screen element?

Ce
All database objects are displayed in the Navigation Pane.

16.4. Which database object is used to create and format printed output?
ish
The Report object is used to create and format printed output.
gl

16.5. Microsoft Access is based upon which model?


En

Microsoft Access is based on the Relational Database Model.

16.6. How do fields and records differ?


E


M

A field is a single piece of data (like Name, Age).


 A record is a complete set of fields (e.g., a row in a table).

16.7. How does a database differ from a table?

 A database is a collection of related tables and other objects.


 A table is just one part of a database, storing structured data.

16.8. How does a record differ from a field?

 A database is a collection of related tables and other objects.


 A table is just one part of a database, storing structured data.

16.9. What is the default data type listed in the Table Design window?

The default data type is Short Text.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 5 of 7


2nd year CS - Chapter # 16
16.10. Where do you change the properties of a field in a table?

In Table Design View, under the Field Properties section.

16.11. Why is the AutoNumber data type often used for a table's primary key?

AutoNumber ensures that each record has a unique, automatically generated ID, preventing duplication.

16.12. How do you create a table in Access?

Open Access → Click Create → Click Table Design → Define fields → Set primary key → Save the table.

16.13. What is displayed on the screen when you open an Access database file?

The Navigation Pane and database objects are displayed.

16.14. Where in the database window are tables displayed?

er
Tables are displayed in the Navigation Pane under the "Tables" section.

nt
16.15. How do you add a new record to a table using Datasheet view?

Click on the (New) row at the bottom and enter data. Ce


ish
16.16. How does inserting fields in Table Design view affect the Datasheet view?

New fields appear as columns in Datasheet view.


gl

16.17. Can you make a field a key field after you have added data to a table?
En

Yes, but it may require removing duplicates first.


E

16.18. What button on the toolbar do you use to switch from Datasheet view to Table Design view and
back?
M

The View button (top-left corner).

16.19. When you change the table structure, what must you do before returning to Datasheet view?

You must save the table.

16.20. What is the difference between finding and replacing data?

 Finding locates data.


 Replacing changes existing data with new values.

16.21. What is the difference between finding and replacing?

Same as 16.20 – Finding locates data, while Replacing modifies it.

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 6 of 7


2nd year CS - Chapter # 16
16.22. What is an easy method for locating records to update?

Use the Find feature (Ctrl + F) in Datasheet view.

16.23. What is the most efficient way to add new records that closely resemble existing records?

Copy an existing record, paste it, and edit the necessary fields.

16.24. To sort records from highest to lowest based on numeric values in a Number field, which sort
button on the toolbar would you use?

The Descending Sort button (Z → A with a down arrow).

er
nt
Ce
ish
gl
En
E
M

Prepared by: Aqib Ilyas (BSCS, SMIU) Page 7 of 7

You might also like