Class 12 Computer Notes
Class 12 Computer Notes
er
nt
(According Ce
to new book )
ish
gl
Chapter # 1
er
nt
Ce
( According to old book )
ish
gl
En
E
M
er
-: Answer Keys :-................................................................................................................................................................ 9
Section (B / C) .......................................................................................................................................................................... 10
nt
Ce
ish
gl
En
E
M
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
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).
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
Comments in Programming
E
M
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.
1. Procedure-Oriented Languages
o Require programmers to write step-by-step instructions.
o Solve general problems (business, scientific, or multipurpose).
1. FORTRAN
2. COBOL
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
5. C
7. Logo
8. Ada
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
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
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
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
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
(a) planning the solution (b) coding the program (c) testing the program (d) selecting the hardware
M
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
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
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:
NOT).
o Example: ADD, SUBTRACT, MULTIPLY, COMPARE.
3. Control Instructions:
E
1.3. What is the difference between a compiler and an interpreter? Why is each 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.
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.
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
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
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.
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
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.
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
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.
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?
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?
Focus Focuses on functions or procedures. Focuses on objects that combine data and methods.
En
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.
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.
Chapter # 2
er
nt
Ce
( According to old book )
ish
gl
En
E
M
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
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.
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
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)
E
Examples:
2!=22! = 2
3!=63! = 6
4!=244! = 24
Applications of Pseudocode
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
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).
Structure:
Part 1: Purpose and definitions.
Part 2: Step-by-step instructions.
er
nt
Flowchart Categories
Control Structures
gl
1. Sequence:
En
2. Selection:
E
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.
3. Loop Flowchart
o Represents procedures repeated a definite or indefinite number of times.
o Example: Reading a definition until it’s fully understood.
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:
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
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.
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.
er
nt
Ce
ish
gl
En
E
M
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
-: Answer Keys :-
1. 2. 3. 4. 5. 6.
a d d b c c
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.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 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.
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.]
1. Read N.
2. FOR K = 1 to 10 by 1
Write N.
3. Exit.
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
3. Write S.
4. Exit.
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
2. Set S = 0
E
3. FOR K = 1 to 10
M
Set S = S + N[K]
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.
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
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
5. Arrow (Flowline):
o Function: Represents the flow of process steps and connects different symbols to show the sequence of
actions.
(a) Read A, В, С
(b) Is A =0?
(d) Start
Ans.
er
(b) Diamond, since it asks a question.
nt
(c) Rectangle, since it is a process (calculation).
(d) Oval.
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
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.
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.
2.13. What are the various guidelines to be followed while 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
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.
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:
Example in pseudocode:
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
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
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.
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
(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
er
nt
Ce
ish
gl
En
E
M
Chapter # 3
An Overview of C Language
er
nt
Ce
( According to old book )
ish
gl
En
E
M
er
-: Answer Keys :-................................................................................................................................................................ 7
Section (B / C) ............................................................................................................................................................................ 8
nt
Ce
ish
gl
En
E
M
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?
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
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.
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.
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:
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.
Example:
printf("This is\n\tmy first\n\t\tC program");
This is
my first
C program
This will overwrite the word "Left" with "Right" and display only "Right" because of the carriage return.
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
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) \* (d) *\
M
-: Answer Keys :-
1. c
2. a
3. a
4. a
5. b
6. b
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.
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.
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:
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:
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:
Composition of a Function in C:
En
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:
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.
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 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:
Syntax:
En
int main() {
// Code here
return 0;
}
E
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");
}
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.
#include <stdio.h>
er
int main() {
printf("Welcome to Computer Lab.\n");
nt
return 0;
}
int main() {
gl
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;
}
#include<stdio.h>
void main(void)
{
printf("I am a College Student");
}
#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.
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.
\t : Horizontal tab
\\ : Backslash (\)
\" : Double quote (")
\r : Carriage return (moves the cursor to the beginning of the line)
E
\b : Backspace
M
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.
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
return 0;
M
er
nt
Ce
ish
gl
En
E
M
Chapter # 4
C Fundamentals
er
nt
Ce
( According to old book )
ish
gl
En
E
M
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
1. C Character Set
A character in C represents any alphabet, digit, or special symbol used for information. The allowed characters are:
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).
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
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.
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:
For example:
long int i;
unsigned int count;
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:
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
String Constants: A sequence of characters enclosed in double quotes, often used to represent text.
E
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;
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.
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
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:
char student[10];
o String Initialization: A string can also be initialized without specifying its size:
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
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
4. Variables
(a) are created using the #define directive
E
-: Answer Keys :-
1. 2. 3. 4. 5.
b c c d c
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
4.3. Which of the following are not valid identifiers and why?
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
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"
(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
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
Correction: 6209.85
En
Correction: 395e+3
M
(a) t'
(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'
(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).
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
Correction: "STUDENT:"
(d) "Chap-3 (cont \ 'd ) ": Valid (the string uses escape characters \' correctly to include a single quote inside
E
the string).
M
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:
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.
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.
Example:
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:
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
Example:
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';
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).
1. Constant:
En
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.
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
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.
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.
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.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:
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).
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];.
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"; .
er
(d) Character variables: l, m, n
nt
(e) 60-element character array: message
float x, y, z;
E
char l, m, n;
char message[60];
4.29. Write appropriate declaration and assign the given initial values to following variables and
arrays.
double d1 = 1.68e-6;
er
nt
Ce
ish
gl
En
E
M
Chapter # 5
er
nt
Ce
( According to old book )
ish
gl
En
E
M
er
nt
Ce
ish
gl
En
E
M
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:
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
Arithmetic Operator
Operator Operation Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (Remainder) a % b
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
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:
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.
C provides shortcut assignment operators that combine an arithmetic operation with assignment.
*= 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;
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.
Greater than
<= Less than or equal to
En
Example Usage
int a = 5, b = 10;
printf("%d", a < b); // Output: 1 (true)
printf("%d", a > b); // Output: 0 (false)
Relational Expressions
Example:
int a = 5, b = 10, c = 2;
printf("%d", (a + c) < (b / 2)); // (5+2) < (10/2) → 7 < 5 → 0 (false)
Precedence: ! > && > ||. Logical operators have lower precedence than relational and arithmetic operators.
Examples: Demonstrate truth table evaluations and complex expressions with logical operators.
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)
Operator Precedence: Cast operator () has higher precedence than arithmetic operators and is right-to-left
associative.
Section (A)
Multiple Choice Questions (MCQs)
Choose the correct answer
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) distinguish different types of variables (d) change variables to logical values
M
-: Answer Keys :-
1. d
2. b
3. a
4. (a) False (b) True (c) False (d) True
5. b
6. b
7. d
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
er
to)
nt
3. Logical Operators: Used for logical operations.
o && (Logical AND), || (Logical OR), ! (Logical NOT)
o ++ (Increment), -- (Decrement)
10. Type Casting Operator: Converts one data type into another.
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.
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.
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
5.5. What is meant by operator precedence? What are the relative precedences of the arithmetic
operators?
E
M
1. *, /, % (Highest precedence)
2. +, - (Lower precedence)
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.
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.
You need to control the order of operations and override default precedence.
o Example: (a + b) * c ensures addition happens before multiplication.
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:
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
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:
(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.
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:
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?
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
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?
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).
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
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 --
(d) k++ * - - i
(e) i – 1 % j + 1
Given values:
i = 3, j = 4, k = 2
Evaluating expressions:
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
(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.
(int)(a * x + b) / (a * x - b)
(2 * x + 3 * y) / (x * x * x - 6)
(x * x * x * x * x) + (10 * x * x * x * x) + (8 * x * x * x) + (4 * x) + 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
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:
Chapter # 6
er
nt
Ce
( According to old book )
ish
gl
En
E
M
er
nt
Ce
ish
gl
En
E
M
char ch;
ch = getchar();
char ch;
ch = getch();
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
char name[30];
E
gets(name);
M
puts("Hello, World!");
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
Example:
Section (B / C)
6.1. What are the commonly used input/output functions in C? How are they accessed?
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
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
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');
The puts() function accepts a string (character array) as an argument. It must be a null-terminated string (char
*). Example:
puts("Hello, World!");
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.)
The putchar() function accepts a single character as an argument, which can be:
En
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.
6.12. How would you display the quote symbol on the screen?
printf("\"");
scanf("%d", &variable);
Advantages of scanf():
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
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():
Disadvantages of scanf():
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.
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
The address operator (&) is used to obtain the memory address of a variable.
En
Example:
int x = 10;
E
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
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.
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
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).
It is not strictly necessary, but it is good practice to assign initial values to variables to avoid undefined
behavior.
putchar outputs a single character, while printf can output formatted text.
1. Control string
2. Arguments to be printed.
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.
6.32. Write the printf( ) instruction that outputs the values of the following variables:
6.34. A program will display a person's name and age. Write a printf( ) instruction that displays the
values of the variables:
er
printf("Name: %s, Age: %d", name, age);
nt
6.35. A program has these variables:
#include <stdio.h>
int main() {
return 0;
#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);
Write an appropriate scanf function to enter numerical values for i, j and k assuming
(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.
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) %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.
Show the output resulting from each of the following printf statements.
er
(f) printf("%08d %#8x %#8o", i, j, k);
nt
(a) 12345 abcda 77777
(b)
(c)
12345 abcda 77777
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();
}
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
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;
}
#include <stdio.h>
int main() {
char ch;
char str[20];
int num;
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
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;
}
#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
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);
er
nt
Ce
ish
gl
En
E
M
Chapter # 7
er
nt
Ce
( According to old book )
ish
gl
En
E
M
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
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).
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
} else {
printf("The number is zero.\n");
M
}
}
Syntax:
if (condition1) {
// code block 1
} else if (condition2) {
// code block 2
} else {
// default code block
}
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
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");
}
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
-: 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
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
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;
}
Ans.
Unlike other languages, in C the if statement does not use the then keyword.
if(x = 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
/* 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();
}
The else command provides an alternative action when the if condition is false.
#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
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);
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);
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.
if x > 25.0
{
y = x
else
y = z ;
}
if (x > 25.0) {
y = x;
} else {
y = z;
}
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.
er
x = x + 1; x = x+1;
else if(x >= 1) if(x >=1)
nt
x = x + 2; x = x+2;
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);
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;
}
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
7.23. What will be printed by this carelessly constructed switch statement if the value of colour is 'R'?
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
} 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;
}
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
return 0;
M
Chapter # 8
er
nt
Ce
( According to old book )
ish
gl
En
E
M
er
nt
Ce
ish
gl
En
E
M
Iteration (looping) allows a program to repeat instructions until a condition is false. C provides three types of loops:
for loop:
Syntax:
for(initialization; condition; increment/decrement) {
// Code to execute
}
Nested loops (loop inside another loop) help create complex patterns.
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
int i = 1;
while (i <= 10) {
M
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);
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:
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:
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
-: 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
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:
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.5. Write a for loop that counts backwards from 100 to 0 by 10.
En
8.6. Find the error in the following statement (Note: there may be more than one error).
E
Errors:
Initialization
Condition checking
Increment / Decrement
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() {
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;
}
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?
8.14. Compare and discuss program 8-29 with one given in practical 7(b). Discuss
En
/* program 8-29.cpp */
E
#include<stdio.h>
#include<conio.h>
M
Errors:
#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
ow should be row
column+ should be column++
E
/* 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();
}
k = 200
{
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
{
E
int i;
M
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);
}
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
/* 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();
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.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
do
M
++i;
while ( i ++<10);
(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
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.
er
printf("\n");
nt
Ans.
5 4 3
Ce
ish
Enter a positive integer: 82
gl
2 8
En
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.
int sum = 0;
for(int i = 2; i < 100; i += 3) sum += i;
int sum = 0, i = 2;
while(i < 100) { sum += i; i += 3; }
int sum = 0, i = 2;
do { sum += i; i += 3; } while(i < 100);
(a) break
er
printf("%d ", i);
}
nt
Output: 1 2 3 4
(b) continue Ce
ish
Skips the current iteration and moves to the next.
if(i == 5) continue;
printf("%d ", i);
En
Output: 1 2 3 4 6 7 8 9 10
E
M
Chapter # 9
Functions
er
nt
Ce
( According to old book )
ish
gl
En
E
M
Functions: ................................................................................................................................................................................... 3
Examples: ........................................................................................................................................................................... 3
Section (A).................................................................................................................................................................................. 4
-: Answer Keys :-................................................................................................................................................................ 5
Section (B / C) ............................................................................................................................................................................ 6
er
nt
Ce
ish
gl
En
E
M
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
5. Passing Arguments:
o Can pass single or multiple values (actual → formal parameters).
E
Examples:
void display(void) {
printf("Hello World");
}
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
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
-: Answer Keys :-
1. True 6. b 11. False 16. False 21. True
Section (B / C)
9.1. What is the difference between a function in the C library and a function you write yourself?
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
Control returns to the calling function, and if the function has a return value, it is returned.
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?
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
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
9.14. Write a program that inputs a number and then uses a function to calculate and display the
number to the fourth power.
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)); }
#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
printf("%f", num);
}
E
Errors
M
abs (num);
{
int num;
if (num<0)
num = -num;
return(num);
}
Error
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().
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.25. A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of
digits of the 5-digit number:
int sumDigits(int n) {
int sum = 0;
while(n > 0) { sum += n % 10; n /= 10; }
return sum;
}
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
Chapter # 10
Arrays
er
nt
Ce
( According to old book )
ish
gl
En
E
M
Arrays: ........................................................................................................................................................................................ 3
Section (A).................................................................................................................................................................................. 4
-: Answer Keys :-................................................................................................................................................................ 6
Section (B / C) ............................................................................................................................................................................ 7
er
nt
Ce
ish
gl
En
E
M
1. Declaration:
type array_name[size];
Example:
3. Initialization:
er
o If size is omitted, it’s determined from the values:
nt
int temps[] = {53, 85, 29, 19, 63};
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);
(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};
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
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.
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} };
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
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.
No, an array can store only one data type (e.g., all integers or all floats).
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
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.
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.
is the following a good way to read values into all the elements of the array?
M
Error: j <= MAX should be j < MAX, otherwise it goes out of bounds.
Ans. Assume that the array j has been declared, use a for loop:
j[index]=1;
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?
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.
#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
{
printf("Enter a number &d: ", index);
scanf("%d", &count [index]);
}
}
Errors:
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
10.21. Change the sorting program shown in program 10-8 so that it sorts data of type float.
E
M
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
Chapter # 11
Strings
er
nt
Ce
( According to old book )
ish
gl
En
E
M
Strings ......................................................................................................................................................................................... 3
Section (A).................................................................................................................................................................................. 4
-: Answer Keys :-................................................................................................................................................................ 5
Section (B / C) ............................................................................................................................................................................ 6
er
nt
Ce
ish
gl
En
E
M
1. Declaration:
o char name[10]; (Allocates 10 characters including \0.)
2. Initialization:
o char msg[6] = "Hello"; (Automatically adds \0.)
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
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
(a) returns the length of the string including the null character.
(b) returns the length of the string excluding the null character.
E
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);
-: Answer Keys :-
1. c 11. d
E
3. c 8. a 13. c
4. True 9. b 14. d
10. c 15. a
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".
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.
if (strcmp(str1, str2) == 0)
er
printf("Strings are equal");
nt
11.4. How do you assign a value to a string variable?
how would you refer to the string "tan" (the last three letters of the string)?
En
Using pointer:
name "Azeem";
Error
char str[40];
printf("%c", str[2]); // Index 2 for the third character
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.
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
strcpy(rev, str);
strrev(rev);
if (strcmp(str, rev) == 0) printf("Palindrome\n");
E
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:
#include <stdio.h>
#include <ctype.h>
int main() {
char str[50];
int count = 0;
printf("Enter word: ");
er
nt
Ce
ish
gl
En
E
M
Chapter # 15
er
nt
Ce
( According to old book )
ish
gl
En
E
M
er
nt
Ce
ish
gl
En
E
M
Database Components:
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:
Disadvantages of DBMS:
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.
Components of DBMS
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
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
-: 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
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?
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
A Database Management System (DBMS) is software that stores, retrieves, and manages data in a structured
E
way.
M
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.
15.8. For each of the following types of database management systems, describe how data relate to one
another:
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.
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:
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?
(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.
(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
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
Contract
Team (years) Initial Fee Royalty % Advertising
Type
C1 99 250000 2% 2%
C2 5 50000 4% 3%
C3 10 75000 3% 3%
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.
(b) Identify a primary key, and a secondary key, writing out any assumptions you need to make
to justify your choice.
E
Chapter # 16
er
nt
Ce
( According to old book )
ish
gl
En
E
M
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
(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
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
(d) search for text with capitalization that exactly matches the text typed
M
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
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.
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
M
16.9. What is the default data type listed in the Table Design window?
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.
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?
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?
16.17. Can you make a field a key field after you have added data to a table?
En
16.18. What button on the toolbar do you use to switch from Datasheet view to Table Design view and
back?
M
16.19. When you change the table structure, what must you do before returning to 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?
er
nt
Ce
ish
gl
En
E
M