Unit 1 of 4 · BCA Sem 1

Unit 1: Logic development and C fundamentals

Problem Solving Techniques notes · PTU syllabus (UGSEC2501)

6 min read10 topics17 exam questions
On this page
  1. Unit summary
  2. Data representation
  3. Problem analysis
  4. Algorithms and pseudocode
  5. Flowcharts
  6. Decision trees and decision tables
  7. Character set, identifiers and keywords
  8. Data types, constants and variables
  9. Expressions and statements
  10. Operators
  11. Library functions
  12. Key terms
  13. Quick revision
  14. Important questions

Unit summary

Programming starts with solving the problem on paper. This unit covers how data is represented in a computer, the tools for planning a solution — flowcharts, problem analysis, decision trees and tables, pseudocode and algorithms — and the building blocks of the C language: character set, identifiers and keywords, data types, constants, variables, expressions, statements, symbolic constants, the six groups of operators and library functions.

After this unit you can

  • Represent data in binary, octal and hexadecimal and convert between number systems
  • Analyse a problem and write an algorithm, pseudocode, flowchart, decision tree or decision table
  • Write valid C identifiers, declare variables of the correct data types and define constants
  • Evaluate expressions using arithmetic, unary, relational, logical, assignment and conditional operators with precedence
  • Use standard library functions

PTU syllabus topics

  • Data representation
  • flowcharts
  • problem analysis
  • decision trees/tables
  • pseudocode and algorithms
  • character set
  • identifiers and keywords
  • data types
  • constants
  • variables
  • expressions
  • statements
  • symbolic constants
  • arithmetic/unary/relational/logical/assignment/conditional operators
  • library functions
1

Topic 1

Data representation

A computer stores every piece of data — numbers, letters, images, sound — as bits (binary digits, 0 or 1). Eight bits make a byte.

ComparisonNumber systems
Base and digits
Example

Binary

Base 2 — 0, 1

1011₂ = 11

Octal

Base 8 — 0 to 7

17₈ = 15

Decimal

Base 10 — 0 to 9

25

Hexadecimal

Base 16 — 0 to 9, A to F

2F₁₆ = 47

ProcessConverting decimal 25 to binary (repeated division by 2)
  1. 1

    25 ÷ 2 = 12 remainder 1

  2. 2

    12 ÷ 2 = 6 remainder 0

  3. 3

    6 ÷ 2 = 3 remainder 0

  4. 4

    3 ÷ 2 = 1 remainder 1

  5. 5

    1 ÷ 2 = 0 remainder 1

  6. 6

    Read the remainders from bottom to top: 11001

Key formulasConversion rules
  • Binary to decimal

    Sum of digit × 2^position — 1011 = 8 + 0 + 2 + 1 = 11

  • Decimal to binary

    Divide by 2 repeatedly and read remainders upward

  • Binary to octal

    Group bits in threes from the right

  • Binary to hexadecimal

    Group bits in fours from the right

  • Octal or hex to binary

    Replace each digit by its 3-bit or 4-bit code

DecimalBinaryOctalHexadecimal
0000000
5010155
91001119
10101012A
15111117F
25110013119
Key termsRepresenting numbers and characters
Unsigned integer
n bits store 0 to 2ⁿ − 1
Signed integer (2's complement)
n bits store −2ⁿ⁻¹ to 2ⁿ⁻¹ − 1; negative = invert the bits and add 1
Floating point
Sign, exponent and mantissa (IEEE 754)
Characters
ASCII uses 7 bits — 'A' = 65, 'a' = 97, '0' = 48; Unicode covers all languages
Units
1 KB = 1024 bytes, 1 MB = 1024 KB, 1 GB = 1024 MB

Example

−5 in 8-bit 2's complement: 5 = 00000101; invert 11111010; add 1 gives 11111011.

2

Topic 2

Problem analysis

ProcessSteps in problem solving
  1. 1

    Understand and define the problem

  2. 2

    Identify the inputs, processing and outputs (IPO)

  3. 3

    Plan the solution — algorithm, flowchart, pseudocode

  4. 4

    Write the program in a language

  5. 5

    Compile, test and debug

  6. 6

    Document and maintain

IPO analysis of a problem

InputProcessingOutput
Area of a circleRadius rarea = 3.14159 × r × rArea
Simple interestP, R, TSI = P × R × T / 100Simple interest
Largest of threea, b, cCompare the numbersLargest value
Key termsProgramming errors
Syntax error
Violates the rules of the language — caught by the compiler
Logical error
Program runs but gives a wrong answer
Runtime error
Fails while running — divide by zero
Debugging
Finding and removing errors
Testing
Running with sample data including edge cases

Example

IPO for simple interest: Input: principal P, rate R, time T. Process: SI = P × R × T ÷ 100. Output: SI. For P = 10,000, R = 8 and T = 2, SI = ₹1,600. Errors: a missing semicolon is a syntax error; writing P + R + T is a logical error; dividing by zero is a run-time error.

3

Topic 3

Algorithms and pseudocode

An algorithm is a finite, step-by-step set of instructions to solve a problem.

Key termsCharacteristics of a good algorithm
Finiteness
It must end
Definiteness
Each step is clear
Input
Zero or more
Output
At least one
Effectiveness
Every step can be done
Correctness
Gives the right answer

Example

Algorithm to find the largest of three numbers: 1. Start. 2. Read A, B, C. 3. Set max = A. 4. If B > max, set max = B. 5. If C > max, set max = C. 6. Print max. 7. Stop.

Pseudocode is an informal, English-like description of an algorithm using programming constructs.

START
  READ A, B, C
  max ← A
  IF B > max THEN max ← B
  IF C > max THEN max ← C
  PRINT max
END

Algorithm vs pseudocode vs flowchart

AlgorithmPseudocodeFlowchart
FormNumbered steps in plain languageCode-like textDiagram of symbols
AdvantageEasy to writeClose to the programEasy to visualise flow
DisadvantageLong for complex logicNo standard syntaxTakes space, hard to edit
Key termsBasic control structures
Sequence
Steps executed one after another
Selection
IF–THEN–ELSE chooses a path
Iteration
Loops repeat steps (WHILE, FOR)
Subroutine
A named block called many times
4

Topic 4

Flowcharts

A flowchart is a diagram showing the steps of an algorithm with standard symbols connected by arrows. Flowchart symbols

Meaning
Oval (terminator)Start or End
ParallelogramInput or output
RectangleProcessing or assignment
DiamondDecision — two exits, Yes and No
ArrowDirection of flow
Circle (connector)Joins parts of a flowchart across pages
Rectangle with double sidesPredefined process (a function)
FlowchartEven or odd number
YesNoStartRead nn mod 2 = 0 ?Print "Even"Print "Odd"Stop
FlowchartLargest of three numbers
YesNoYesNoStartRead A, B, Cmax = AB > max ?max = BC > max ?max = CPrint maxStop
FlowchartSum of the first n natural numbers
YesNoStartRead nsum = 0, i = 1i <= n ?sum = sum + ii = i + 1Print sumStop
FlowchartFactorial of n
YesNoStartRead nf = 1, i = 1i <= n ?f = f × ii = i + 1Print fStop
FlowchartPrime number test
YesNoYesNoYesNoStartRead ni = 2, flag = 1i <= n / 2 ?n mod i = 0 ?flag = 0i = i + 1flag = 1 ?Print "Prime"Print "Not prime"Stop
FlowchartFirst n terms of the Fibonacci series
YesNoStartRead na = 0, b = 1, i = 1i <= n ?Print ac = a + ba = b, b = ci = i + 1Stop
ComparisonAdvantages and limitations of flowcharts
Advantages
Limitations

Clarity

Show the flow of logic visually

Large flowcharts become complex

Communication

Easy for non-programmers

Difficult to modify

Debugging

Helps find logical errors

No standard for details

Documentation

Useful for documentation

Time consuming

Example

Algorithm for the sum of the first N numbers: Step 1: Start. Step 2: Read N. Step 3: Set sum = 0 and i = 1. Step 4: If i > N, go to Step 7. Step 5: sum = sum + i. Step 6: i = i + 1 and go to Step 4. Step 7: Print sum. Step 8: Stop. For N = 5 the output is 15.

Exam tip

Oval = start/stop, parallelogram = input/output, rectangle = process, diamond = decision, arrows = flow.

5

Topic 5

Decision trees and decision tables

A decision tree shows choices and their outcomes as branches; a decision table lists conditions and the actions to take for each combination.

ClassificationDecision tree: choosing a mode of travel
Distance?
  • Under 2 km

    Walk

  • 2 to 10 km

    Is it raining? — Yes: Bus; No: Bicycle

  • Over 10 km

    Is budget high? — Yes: Taxi; No: Train

Condition / ActionRule 1Rule 2Rule 3Rule 4
Marks >= 40YYNN
Attendance >= 75%YNYN
Action: PassX
Action: DetainXXX
Key termsDecision table parts
Condition stub
List of conditions
Condition entries
Y or N for each rule
Action stub
List of possible actions
Action entries
X marks the action for a rule
Rules
Columns — each a combination of conditions
Number of rules
2ⁿ for n yes/no conditions
ComparisonDecision tree vs decision table
Decision tree
Decision table

Form

Branching diagram

Grid

Best for

Sequential choices

Many conditions at once

Completeness check

Hard

Easy — 2ⁿ rules

Example

A discount decision table: conditions are "Member?" and "Bill above ₹1,000?". Rule 1 (Yes, Yes): 20% discount. Rule 2 (Yes, No): 10%. Rule 3 (No, Yes): 5%. Rule 4 (No, No): no discount. Two conditions give 2² = 4 rules.

Exam tip

n conditions with yes/no answers give 2ⁿ rules.

6

Topic 6

Character set, identifiers and keywords

C is a general-purpose structured language developed by Dennis Ritchie (1972) at Bell Labs.

ClassificationC character set
Character set
  • Letters

    A–Z and a–z

  • Digits

    0–9

  • Special characters

    + − * / % = < > ( ) { } [ ] ; , . # & ! ~ ^ | \ ? : ' "

  • White space

    Blank, tab, newline

ProcessStructure of a C program
  1. 1

    Documentation comments

  2. 2

    Preprocessor directives — #include <stdio.h>

  3. 3

    Global declarations

  4. 4

    main() function

  5. 5

    Local declarations

  6. 6

    Executable statements

  7. 7

    User-defined functions

c#include <stdio.h>          /* header file */
int main(void)              /* every program starts here */
{
    printf("Hello, SBS!\n");
    return 0;
}

Identifiers are names of variables, functions and arrays.

Key termsRules for identifiers
Allowed characters
Letters, digits and underscore
First character
A letter or underscore — not a digit
Case
Case-sensitive: Total and total differ
Keywords
Cannot be used as identifiers
Length
At least the first 31 characters are significant
Spaces and symbols
Not allowed in names
ComparisonValid and invalid identifiers
Valid
Invalid

Examples

sum, _count, total1, studentName

1total (starts with digit), my-var (hyphen), float (keyword), roll no (space)

Keywords are reserved words with fixed meaning; C has 32 (C89). The 32 keywords of C

Keywords
Data typesint, char, float, double, void, short, long, signed, unsigned
Controlif, else, switch, case, default, for, while, do, break, continue, goto, return
Storageauto, register, static, extern
Othersconst, volatile, enum, struct, typedef, union, sizeof

Example

Valid or invalid identifier? total_marks, _count and sum1 are valid. 1sum is invalid (starts with a digit). total marks is invalid (contains a space). int is invalid (a keyword). a-b is invalid (contains a minus sign). Sum and sum are different, because C is case-sensitive.

7

Topic 7

Data types, constants and variables

ComparisonBasic data types (typical 32-bit compiler)
Size and range
Format specifier

char

1 byte, −128 to 127

%c

int

4 bytes, −2,147,483,648 to 2,147,483,647

%d

short int

2 bytes, −32,768 to 32,767

%hd

long int

4 or 8 bytes

%ld

unsigned int

4 bytes, 0 to 4,294,967,295

%u

float

4 bytes, about 6 decimal digits

%f

double

8 bytes, about 15 digits

%lf

void

No value — for functions and generic pointers

—

ClassificationClassification of data types
Data types
  • Primary (basic)

    int, char, float, double, void

  • Derived

    Array, pointer, function

  • User-defined

    struct, union, enum, typedef

Constants are fixed values that do not change. Types of constants

Examples
Integer25, −10, 0x1F (hex), 017 (octal)
Real (floating)3.14, −0.5, 2.5e3
Character'A', '5', '\n'
String"SBS", "Hello" — ends with '\0'
Escape sequences\n newline, \t tab, \\ backslash, \" quote, \0 null

Variables are named memory locations whose values may change; they must be declared before use.

cint age = 20;              /* declaration with initialisation */
float marks, percentage;   /* several variables of one type */
char grade = 'A';
ProcessVariable declaration and use
  1. 1Choose a meaningful name
  2. 2Declare with its data type
  3. 3Initialise — give a first value
  4. 4Use in expressions
  5. 5Print the result

Exam tip

An uninitialised local variable holds an unpredictable "garbage" value, so always initialise.

Symbolic constants

ComparisonWays to define constants
Syntax
Notes

#define (macro)

#define PI 3.14159

Text substitution before compilation, no semicolon, no type

const qualifier

const float PI = 3.14159;

Typed, stored in memory, read-only

enum

enum {RED, GREEN, BLUE};

Named integer constants 0, 1, 2

Example

Declarations and a common mistake: int age = 19; float fee = 4500.50; char grade = 'A'; use the format specifiers %d, %f and %c. float x = 5 / 2; stores 2.0, not 2.5, because 5 / 2 is integer division. Write 5 / 2.0 or (float)5 / 2 to get 2.5.

8

Topic 8

Expressions and statements

Key termsExpressions and statements
Expression
Combination of operands and operators giving a value — a + b * 2
Statement
Instruction ending with a semicolon
Expression statement
x = a + b;
Compound statement (block)
Statements within { }
Declaration statement
int x;
Control statements
if, switch, for, while
Null statement
A lone ;
ProcessEvaluation of an expression
  1. 1

    Brackets first

  2. 2

    Unary operators

  3. 3

    Multiplication, division and modulus (left to right)

  4. 4

    Addition and subtraction

  5. 5

    Relational and logical operators

  6. 6

    Conditional operator

  7. 7

    Assignment (right to left)

Example

x = 5 + 3 * 2 evaluates 3 * 2 = 6 first, so x = 11. Integer division: 7 / 2 = 3 but 7 / 2.0 = 3.5.

9

Topic 9

Operators

ComparisonTypes of operators in C
Operators
Example

Arithmetic

+ − * / %

a % b gives the remainder

Unary

++ −− − ! sizeof (type)

i++, −x

Relational

< <= > >= == !=

a > b gives 1 or 0

Logical

&& || !

(a > 0) && (b > 0)

Assignment

= += −= *= /= %=

x += 5 means x = x + 5

Conditional (ternary)

? :

max = (a > b) ? a : b

Bitwise

& | ^ ~ << >>

a & b

Comma

,

a = (1, 2)

Address and pointer

& *

&x, *p

ComparisonIncrement and decrement
Prefix (++i)
Postfix (i++)

Action

Increase first, then use

Use first, then increase

i = 5, j = ++i

i = 6, j = 6

—

i = 5, j = i++

—

i = 6, j = 5

Operator categoryOperatorsAssociativity
Postfix, brackets() [] -> . i++ i--Left to right
Unary! ~ ++i --i + - * & sizeofRight to left
Multiplicative* / %Left to right
Additive+ -Left to right
Shift<< >>Left to right
Relational< <= > >=Left to right
Equality== !=Left to right
Bitwise AND, XOR, OR& ^ |Left to right
Logical AND, OR&& ||Left to right
Conditional?:Right to left
Assignment= += -= *= /= %=Right to left
Comma,Left to right

Truth table of the logical operators

aba && ba || b!a
11110
10010
01011
00001

Exam tip

In C, any non-zero value is true and zero is false. Use == for comparison and = for assignment.

Example

With a = 10, b = 3: a / b = 3, a % b = 1, a > b is 1, (a > b) && (b > 5) is 0, a += b makes a = 13, and (a > b) ? a : b is 13.

10

Topic 10

Library functions

Library functions are ready-made functions in header files; include the header before using them. Common library functions

Purpose
stdio.hprintf, scanf, getchar, putchar, gets, puts, fopen, fclose
math.hsqrt(x), pow(x, y), abs(i), fabs(x), ceil(x), floor(x), sin(x), cos(x), log(x), exp(x)
string.hstrlen, strcpy, strcmp, strcat, strrev (non-standard), strlwr, strupr
ctype.hisalpha, isdigit, isupper, islower, toupper, tolower, isspace
stdlib.hatoi, atof, rand, srand, exit, malloc, free, abs
time.htime, clock
c#include <stdio.h>
#include <math.h>
int main(void) {
    double x = 16.0;
    printf("%.2f %.2f %.0f\n", sqrt(x), pow(x, 0.5), floor(3.7));   /* 4.00 4.00 3 */
    return 0;
}

Example

Common calls and results: sqrt(16) returns 4.0 and pow(2, 3) returns 8.0 (both need #include <math.h>). strlen("SBS") returns 3 (<string.h>). toupper('a') returns 'A' (<ctype.h>). abs(-7) returns 7 (<stdlib.h>).

Key terms

Bit and byte
Binary digit; eight bits
Algorithm
Finite sequence of steps to solve a problem
Pseudocode
Informal English-like description of an algorithm
Flowchart
Diagram of an algorithm using standard symbols
Decision table
Grid of conditions and actions
Identifier
Name given to a variable, function or array
Keyword
Reserved word with a fixed meaning in C
Data type
Kind of value a variable can hold
Constant
Fixed value that cannot change
Operator precedence
Order in which operators are evaluated

Quick revision

  • Binary base 2, octal 8, hexadecimal 16; 2's complement for negatives.
  • Steps: analyse (IPO) → algorithm → flowchart → code → test.
  • Flowchart symbols: oval, parallelogram, rectangle, diamond.
  • Identifiers: letters, digits, underscore; not starting with a digit; 32 keywords.
  • Types: char (1), int (4), float (4), double (8); constants — integer, real, character, string.
  • #define vs const; operators: arithmetic, unary, relational, logical, assignment, conditional.
  • Library functions need header files: stdio.h, math.h, string.h, ctype.h.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.Convert 25 to binary and 1011 to decimal.
  2. Q2.Define an algorithm. State its characteristics.
  3. Q3.What is pseudocode?
  4. Q4.Draw the flowchart symbols for decision and input/output.
  5. Q5.What is a decision table?
  6. Q6.State the rules for naming identifiers in C.
  7. Q7.Name the four primary data types of C with sizes.
  8. Q8.Differentiate between #define and const.
  9. Q9.What is the difference between ++i and i++?
  10. Q10.What is the output of 7 / 2 and 7 % 2 in C?
  11. Q11.State the use of the conditional operator.
  12. Q12.Name two functions each of math.h and string.h.

Long-answer questions

  1. Q1.Explain the steps of problem solving and draw a flowchart to find the factorial of a number.
  2. Q2.Write an algorithm, pseudocode and flowchart to test whether a number is prime.
  3. Q3.Explain the data types and constants available in C with examples.
  4. Q4.Explain the different categories of operators in C with the precedence of operators.
  5. Q5.Explain decision tables and decision trees with examples.

Stuck on this unit?

Message SBS on WhatsApp for help with Problem Solving Techniques, or to ask about studying BCA at Synetic.

WhatsApp us