0% found this document useful (0 votes)
41 views22 pages

UNIT - 1 Notes

The document outlines structured problem-solving using a Problem Analysis Chart (PAC) that breaks down problems into inputs, processing, and outputs. It discusses the development of algorithms, flowcharts, and pseudocode, as well as the structure of C programs, including headers, the main function, and error types. Additionally, it emphasizes the importance of comments, indentation, and understanding error messages in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views22 pages

UNIT - 1 Notes

The document outlines structured problem-solving using a Problem Analysis Chart (PAC) that breaks down problems into inputs, processing, and outputs. It discusses the development of algorithms, flowcharts, and pseudocode, as well as the structure of C programs, including headers, the main function, and error types. Additionally, it emphasizes the importance of comments, indentation, and understanding error messages in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT – 1

Problem Solving:
A Problem Analysis Chart (PAC) is a fundamental tool for structured
problem-solving, especially in computer programming. It forces a
systematic understanding of a problem before any code is written by
organizing it into three core components: inputs,
processing, and outputs. This step-by-step breakdown ensures that
the logical sequence of a solution is clear and well-organized.
No

Yes
The three components of a PAC

1.Inputs

This section identifies all the data a program needs to receive to solve the
problem. You must consider not only the type of data (e.g., integer, string,
float) but also any
constraints or assumptions about that data.

Detailed explanation:
 What it is: Raw data and instructions fed into the computer.
 How to find it: Read the problem description and list every piece of
information that the program will need to be given.
 Example (Add two numbers): The program needs to know the two
numbers it will add together.
o Input 1: An integer a.
o Input 2: An integer b.
2. Processing

This is the "recipe" or algorithm—the set of operations that the computer


will perform on the inputs to transform them into the desired output.

Detailed explanation:
 What it is: The logical steps, calculations, and instructions that
manipulate the input data.
 How to find it: Figure out what mathematical formulas,
comparisons, or logical decisions are necessary to get from the
input to the output.
 Example (Add two numbers): The processing step is the core
arithmetic operation.
o Processing: The program calculates the sum: sum = a
+ b.

3. Outputs

This section lists the final result or results that the program should
produce after processing the inputs.

Detailed explanation:
 What it is: The result, answer, or information displayed to the
user.
 How to find it: Read the problem description and identify what the
program is supposed to provide as its final answer.
 Example (Add two numbers): The user needs to see the result of
the addition.
oOutput: The variable sum, which holds
Problem
the Inputs
result. Deeper dive into the example charts Processing Outputs

Example 1: Add two numbers


Add two numbers a, b (integers) sum = a + b sum

 Detailed explanation: A human enters two integer values, such as 5


and 7, into the program. The program internally adds those two
numbers, resulting in 12. Finally, the program displays the single
value, 12, to the user.

Example 2: Celsius → Fahrenheit


Problem Inputs Processing Outputs

Celsius → Fahrenheit c (floating-point number) f = c * 9/5 + f


32
 Detailed explanation: The program receives a temperature in Celsius,
like
25.5°C. It then applies the specific mathematical formula for
conversion. The result, 77.9°F, is then displayed as the program's
output. A floating-point number is used to allow for decimal values in
the temperature.

Thinking

Kicking off 5

searches Looking

at 98 sites Putting

it all together

To fully develop a problem-solving solution for a computer program, a


systematic approach moves from a high-level analysis to detailed
instructions

. This includes:
Start

Yes
c«6
StO
p Print 3*c

Output
given npuŁ

Algorhhm
Problem Analysis Chart (PAC): The initial breakdown of the problem.
 Developing an Algorithm: A step-by-step logical plan in plain
language.
 Flowchart: A visual diagram of the algorithm's control flow.
 Pseudocode: A text-based, code-like representation of the
algorithm.

b)Developing an algorithm (plain steps)

An algorithm is a clear, concise, step-by-step set of instructions for


solving a specific problem or performing a task. It uses simple, plain
language that is not tied to any
specific programming syntax. For the Even/Odd problem, the
algorithm is straightforward because it involves a simple
conditional check.
Detailed explanation for Even/Odd:

1. Start: Begin the process.

2. Read input: Obtain a number from the user. Let's call


this number n.

3. Check condition: Test if the number n is perfectly divisible by 2.


The modulo operator (%) is used for this, which returns the
remainder of a division.

4. Display result (Even): If the remainder of n divided by 2 is 0,


display the message "Even."

5. Display result (Odd): If the remainder is not 0, display the message


"Odd."

6. End: The process is complete.

c)Flowchart (symbols)

A flowchart is a visual representation of an algorithm or process, using


standard symbols to show the sequence of steps and the flow of
control. This makes the logic easy to follow and understand at a glance.

Standard symbols:
 Oval (∘composed with∘): Represents the beginning or end of
the process.
 Parallelogram (∠ I/O⌝ ): Used for input and output operations,
such as reading data or displaying a result.
 Diamond (◊): Represents a decision or a conditional check, which
has one entry point and multiple exit points (e.g., "Yes" and "No").

Flowchart for Even/Odd:

mermai

d graph

TD

A[Star
t] -->
B(Inpu
t n)

B -->
C{n
%2
==
0?}

C -->|
Yes|
D[Prin
t
"Even
"]

C -->|
No|
E[Prin
t
"Odd"
]

D -->
F[End
]

E -->
F

Use
code
with
caution
.

d)Pseu
doco
de
(near-
Engli
sh)

Pseudocode is a text-based, simplified, and informal description of an


PROGRAM STRUCTURE:
Modern C program structure provides a clear, standardized framework for
writing programs that are readable, maintainable, and efficient. The
components work together to set up the necessary tools, define the
program's starting point, and execute the core logic.

1.Headers (#include <stdio.h>)

This is the preprocessor section where you include header files. A header
file
(extension .h) contains function declarations, macros, and other
definitions from C's standard library.
 #include: This is a preprocessor directive that tells the compiler to
literally copy and paste the contents of a specified file into your
source code before compilation.
 <stdio.h>: This is a standard header file that stands for "Standard
Input/Output".
It provides declarations for essential functions like printf() for
printing to the console and scanf() for reading user input. Without
it, the compiler wouldn't recognize these common functions.

2.The main function (int main(void))

The main function is the mandatory entry point for every C program.
Execution always begins with the first line of code inside main.
 int: This is the return type of the function, indicating that main will
return an integer value. This value is an exit code that the
operating system can use to check if the program ran
successfully.
 main: This is the universal name for the function where
program execution begins. It cannot be renamed.
 (void): This specifies that the main function does not accept any
command-line arguments. Using (void) instead of empty
parentheses () is considered a best practice in modern C.
 Alternative for arguments: For programs that need to process
command-line arguments, main can be declared as int main(int
argc, char *argv[]).

3.Blocks ({ })

Curly braces are used to define a block of code, which groups related
statements together.
 Function Body: The main function uses braces to define its body,
which holds all the declarations and executable statements.
 Control Flow: Braces are also used to define the scope of control
statements like if, for, and while loops, determining which
statements are executed
conditionally or repeatedly.

4.Statements and terminators (;)

Instructions given to the compiler are called statements, and each one
must be ended with a semicolon to indicate its completion.
 Declarations: For example, int a, b; declares two integer variables.
 Assignments: For example, sum = a + b; performs an addition
and stores the result.
 Function Calls: For example, printf("Hello World"); calls the printf
function to display text.

5.Exit status (return 0;)

This statement is found at the end of the main function and serves a
crucial purpose: it returns an integer to the operating system.
 return 0;: By convention, returning 0 signals to the operating
system that the program has executed successfully.
 Non-zero values: A non-zero return value indicates that an error
occurred,
allowing for basic error-handling and debugging by other programs or
scripts that called the C program

The compilation and execution process in C :

The journey of a C program from source code to execution is a multi-step


process that is different from interpreted languages like Python.

1.Edit (write prog.c)


 This is the initial step where the programmer writes the C source
code using a text editor (like Vim, VS Code, or Notepad).
 The code is saved in a text file with a .c extension, for example,
prog.c.

2.Compile (gcc prog.c -o prog)


 The C source code is translated into a machine-readable
executable file by a compiler like GCC (GNU Compiler Collection).
 The compilation process itself has several steps:

1. Preprocessing: Handles preprocessor directives (lines starting


with #). It includes header files (#include), expands macros
(#define), and removes comments.

2. Compiling: The preprocessed code is translated into assembly


language, checking for syntax errors.

3. Assembling: The assembly code is converted into machine


code, creating an object file (e.g., prog.o). The object file is not
yet executable.

4. Linking: The linker resolves all external function calls by


combining the object file with code from necessary libraries
(like stdio.h for printf and scanf). It produces the final
executable file.
 Command: gcc prog.c -o prog instructs the GCC compiler to:
o Compile the source file prog.c.
o Create an output executable file named prog (-o is the flag
for output).

3. Run (./prog)
 This step executes the compiled program.
 On Linux/macOS, the command ./prog runs the executable file prog
located in the current directory.
On Windows, you would typically run prog.exe from the

command line. Types of errors in C

Errors can occur at different stages of the

development cycle. Compile-time errors (Syntax and

Semantic)

These errors prevent the code from compiling and


are flagged by the compiler.
 Syntax Errors: Violations of the C language's
grammar rules.
o Example: Forgetting a semicolon at the end of a
statement (printf("hello")).
 Semantic Errors: The code is syntactically correct, but the meaning is
illogical or unclear to the compiler.
o Example: Using an undeclared variable (printf("%d",
num); without declaring num).

Linker errors

These occur after successful compilation when the linker cannot combine
object files into a single executable.
 Example: Using a mathematical function like sqrt() without linking
the math library. To fix this, you add the -lm flag to the compile
command: gcc prog.c -o prog -lm.

Run-time errors

These happen while the program is running, after successful compilation


and linking.
 Example: Dividing by zero (int result = 5 / 0;), which can cause
the program to crash.

Logical errors

The program compiles and runs successfully, but the output is incorrect
due to a flaw in the algorithm. These are the hardest errors to detect.
 Example: In a program to calculate an average, dividing the sum by
2 instead of the actual number of items.

C is not an interactive language like Python (No REPL)

A Read-Eval-Print Loop (REPL) provides an interactive environment


where users can type code and see the results instantly, line by line.
 Python: Is an interpreted language and famously uses a REPL. You
can type 3 + 5 and immediately get the output 8.
 C: Is a compiled language. It requires a distinct compilation phase
before any code can be executed. You cannot interactively enter and
execute C statements one by one.

Interactive vs. Script-based execution in C:


 "Interactive" in a C context typically refers to the program's
behavior at runtime. An interactive program (like one for a bank's
ATM) reads input from a user using functions like scanf and provides
output in real time.
 "Script mode" refers to automating the build and execution process,
often with scripts or Makefiles, rather than executing a program
line-by-line like a Python script.
Comments, Indentation, Error
Messages :

Comments

In C, comments are used to add explanations or documentation


within the source code. The compiler completely ignores them
during the compilation process, so they do not affect the
program's functionality. They are intended for human readers to
help them understand the purpose, logic, and reasoning behind
the code.

Two primary types of comments in C


 Single-line comments (//): Everything from the // to the end
of the line is a comment. They are best used for short,
inline explanations.

int sum = a + b; // Calculate the sum of a and b

Use code with caution.


 Multi-line comments (/* ... */): Everything between the
opening /* and closing */ is treated as a comment, and it can
span multiple lines. These are ideal for longer, more detailed
descriptions, such as explaining a complex algorithm or
providing a file-level header.

/*
* This program takes two numbers from the user

* and displays their sum.

*/

Use code with caution.

Best practices for commenting


 Explain the "why," not just the "what." The code itself often
shows what is happening. Comments should explain the
intent or a complex algorithm.
 Avoid redundant comments. Don't comment on obvious
code, as it clutters the code and can become outdated.
 Keep comments up-to-date. Outdated comments that no
longer match the code are misleading and can cause
confusion.

Indentation

Indentation refers to the use of whitespace at the beginning of


a line of code to visually organize and structure code blocks.
While the C compiler ignores
whitespace, consistent indentation is crucial for readability and
making the code easier for humans to understand.
Common C indentation rules
 Consistent spacing: Choose a standard indentation size,
typically 2 or 4 spaces, and use it consistently throughout
the project. Avoid mixing tabs
and spaces, as this can lead to misaligned code across
different text editors.
 Reflect block structure: Indentation should clearly represent
the nesting of code blocks. For instance, code within a
function or a loop should be indented one level deeper than
its enclosing code.
 Brace placement: There are two popular styles for placing
braces ({}):
o KsR style: The opening brace is on the same line as
the statement it belongs to.

if (condition) {

// ...

Use code with caution.


o Allman style: The opening brace is on its own line.

if (condition)

{
}

Use code with caution.


 Consistency is key: Regardless of the style chosen,
consistency is more important than the specific style itself.
Following a consistent style, whether KsR, Allman, or a
variant, makes the code predictable and easy to follow.

Error messages

Error messages are crucial feedback from the compiler or


runtime environment that help developers find and fix
problems.

Types of errors and how to interpret them


 Compile-time errors (Syntax errors): These are reported
by the compiler when it encounters code that violates C's
grammar rules.
o Interpretation: The compiler will stop and output an
error message, often providing the line number and a
description of the problem.
o Example: error: expected ';' before 'return'
indicates a missing semicolon on or before the
specified line.
 Linker errors: These occur after compilation when the linker
cannot find a definition for a function or variable that was
declared.
o Interpretation: The error message will typically say
undefined reference to.... This means the linker
could not find the actual compiled code for a
function you called.
o Example: Using a mathematical function like sqrt()
without linking the math library. The compiler needs the
header (<math.h>), and the linker needs the library (-lm
flag).
 Run-time errors: These errors happen while the program is
running and can cause it to crash.
o Interpretation: You typically won't see a compiler
error, but the program will terminate abruptly with
an error message like "Segmentation fault" or
"Division by zero".
 Logical errors: The program compiles and runs without
crashing, but the output is incorrect because the logic is
Data: Types, Constants, Variables, Reserved Words:
a)Primitive Data Types

C offers a small set of fundamental data types for storing


different kinds of information. The size and range of these types
can vary depending on the system's architecture (e.g., 32-bit vs.
64-bit), which is why the sizeof operator is important for
portability.
 char:
o Meaning: A single byte character, used for storing
characters like letters, digits, or symbols.
o Example: 'A', 'z', '5'. Single quotes are used.
o Format: %c is used in printf and scanf for character
input/output.
 int:
o Meaning: A basic integer type for storing whole
numbers.
o Example: 10, -500.
o Format: %d (for decimal integer) is used.
 float:
o Meaning: A single-precision floating-point number for
storing numbers with decimal points. The f suffix is
often used to explicitly mark it as a float literal.
o Example: 3.14f, -0.05f.
o Format: %f is used.
 double:
o Meaning: A double-precision floating-point number,
offering more precision and a larger range than float.
o Example: 3.1415G, -1.2e-5. Double literals don't
require a suffix.
o Format: %lf is used in scanf and printf.

b)Variables

Variables are named storage locations in the computer's


memory that hold data.
 Declaration: You must declare a variable before using it, which
involves specifying its data type and name. You can also
initialize it with a value at the time of declaration.
o Example: int age = 20; declares an integer variable age
and initializes it to 20.
 Naming Rules:
o Start with: A letter (a-z, A-Z) or an underscore (_).
o Contain: Letters, digits (0-G), and underscores.
o No spaces: Spaces are not allowed in variable names.
o Case-sensitive: age, Age, and AGE are treated as different
variables.
 Good practice: Use descriptive variable names (e.g., user_age
instead of x).

c)Constants

Constants are fixed values that do not change during program


execution.
 Literals: Hardcoded values directly in the code.
o Examples: 10 (int), 3.5 (double), 'A' (char).
 const keyword: Declares a variable whose value cannot be
changed after initialization. This is a type-safe and modern
approach.
o Example: const float PI = 3.1415Gf;
 #define preprocessor directive: A traditional C method for
defining symbolic constants. The preprocessor replaces every
occurrence of the identifier with the defined value before
compilation.
o Example: #define MAX 100

d)Reserved Words

These are keywords with special meanings in C and cannot be


used as identifiers (variable names, function names, etc.).
 Examples: int, float, if, else, for, while, return, switch, case,
break, continue, void, char, double, const, sizeof.

6.Operators

a)Arithmetic Operators

Perform mathematical calculations.

 + (Addition)
 - (Subtraction)
 * (Multiplication)
 / (Division): Integer division truncates the decimal part. 7 / 3
is 2.
 % (Modulus): Returns the remainder of an integer division. 7
% 3 is 1.

b)Relational Operators
 == (Equal to)
 != (Not equal to)
 > (Greater than)
 < (Less than)
 >= (Greater than or equal to)
 <= (Less than or equal to)

c)Logical
Operators

Combine
multiple
relational
expressions.
 s s (Logical AND): expr1 s s expr2 is true only if both
expr1 and expr2 are true.
 | (Logical OR): expr1 | expr2 is true if at least one of expr1
or expr2 is true.
 ! (Logical NOT): Inverts the boolean value of an
expression. !true is false.

d)Bitwise
Operators

Work on
individual bits
of integer types.
 s (Bitwise
AND)
 | (Bitwise OR)
 ^ (Bitwise
XOR)
 ~ (Bitwise
NOT)
 << (Left
shift)
 >> (Right
shift)

e)Assignment
Operators

Assign a value to a variable. Compound assignment operators


(+=, -=, etc.) are shortcuts.
f)Conditional (Ternary) Operator

A shorthand for a simple if-else statement.


 Syntax: condition ? expression_if_true :
expression_if_false;
 Example: printf("%s", (n % 2 == 0) ? "Even" : "Odd");
is equivalent to:

if (n % 2 == 0) {

printf("Even");

} else

{ printf("O

dd");
}

Input/Output functions (stdio.h):


The stdio.h header file provides functions for performing standard input
and output operations, which primarily involve the keyboard and the
screen.
 Output: printf()
o Purpose: The printf() function is used to print formatted
output to the console.
o Syntax: printf("Sum = %d\n", s);
o Explanation:
o "Sum = %d\n" is the format string. It contains plain
text and a format specifier (%d).
o %d is a placeholder for an integer value.
o \n is an escape sequence that inserts a newline
character, moving the cursor to the next line.
o s is the variable whose value will be
inserted into the %d placeholder.
 Input: scanf()
o Purpose: The scanf() function is used to read formatted
input from the standard input (usually the keyboard).
o Syntax: scanf("%d", Cn);
o Explanation:
o "%d" specifies that the function should read an
integer value.
o Cn is the crucial "address-of" operator. scanf needs the
memory address of the variable n to directly store the
user's input into that variable.
 Character I/O: getchar(), putchar()
o getchar(): Reads a single character from the standard input
stream (stdin) and returns it as an integer.
o putchar(c): Writes a single character to the standard
output stream (stdout).
o Example:

char c;

printf("Enter a

character: "); c =

getchar();

printf("You entered:

"); putchar(c);

Use code with


caution.
 String I/O:
fgets()
o Purpos
e:
fgets()
is a
safer
and
more
robust
alterna
tive to
the
older gets() function for reading strings. It prevents buffer
overflows by allowing you to specify a maximum number of
o stdin specifies that the input should be read from the
standard input (keyboard).

"Built-in" (Standard Library) functions:


C provides a rich standard library with functions for common tasks.
To use these functions, you must include the corresponding header
file.
 <stdio.h> (Standard Input/Output):
o Functions: printf, scanf, getchar, putchar.
 <math.h> (Mathematics):
o Functions: sqrt(x) (square root), pow(x, y) (x raised to the
power of y), fabs(x) (absolute value of a floating-point
number).
o Important: When compiling a program that uses math.h, you
must link the math library with the -lm flag (e.g., gcc prog.c -o
prog -lm).
 <string.h> (String Handling):
o Functions: strlen(s) (get length of a string), strcpy(dest,
src) (copy string), strcmp(s1, s2) (compare two strings).
 <ctype.h> (Character Classification and Conversion):
o Functions: toupper(c) (convert to uppercase), tolower(c)
(convert to lowercase), isalpha(c) (check if character is an
alphabet).
 <stdlib.h> (Standard Library Utilities):
o Functions: abs(n) (absolute value of an integer), rand()
(generate a pseudo-random integer), srand(seed) (seed
the random number generator), exit(status) (terminate
the program).

You might also like