Problem solving, algorithms and the C environment — Unit 1 Notes (Programming for Problem Solving in C)

BCS101 · Unit 1

Problem solving, algorithms and the C environment notes — Unit 1

Free unit-wise study notes on problem solving, algorithms and the c environment for Programming for Problem Solving in C, Semester 1 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.

Twenty hand-written sheets covering the whole first unit: turning a statement into an algorithm, drawing the matching flowchart, understanding how a translator turns C into an executable, and writing your first correct programs. Every sheet keeps the worked example and the mistake examiners look for side by side.

Notebook — 20 pages

Page 1

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

1. Introduction to Problem Solving

What problem solving means here

  • A computer has no judgement; it repeats instructions exactly as written.
  • Problem solving is the human half — deciding the method before touching a keyboard.
  • The method must be finite, unambiguous and produce a result for every valid input.
  • The same method can then be written in C, Python or Java without change of logic.

Stages of solving a problem

Understand

Given, wanted, constraints

Design

Steps, language free

Express

Algorithm / flowchart

Implement

C program

Test

Boundary values

Next — Page 2 — Input, Process, Output analysis

1 of 20

Page 2

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

2. Input — Process — Output Analysis

Split every problem into what enters, what happens and what leaves. It exposes a missing requirement in seconds and mirrors how marks are distributed in a programming answer.

IPO table for three familiar problems
ProblemInputProcessOutput
Simple interestP, R, TSI = (P × R × T) / 100SI value
Largest of threea, b, cPairwise comparisonThe maximum
Roots of a quadratica, b, cDiscriminant, then case splitReal or complex roots

Row three has no single formula — it has cases. Problems with cases are where careless answers lose marks, because the special case (D = 0, or a = 0) is quietly skipped.

Next — Page 3 — Algorithm: definition and properties

2 of 20

Page 3

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

3. Algorithm — Definition and Properties

An algorithm is a finite sequence of well-defined steps that transforms a given input into the required output.

Five properties every algorithm must satisfy

Finiteness

It must terminate after a limited number of steps.

Definiteness

Each step has exactly one meaning — no "do it suitably".

Input

Zero or more clearly stated inputs.

Output

At least one output, related to the input.

Effectiveness

Each step is basic enough to be carried out by hand.

Next — Page 4 — Writing algorithms: worked examples

3 of 20

Page 4

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

4. Writing Algorithms — Worked Examples

Algorithm: area of a circle

  1. 1.Start.
  2. 2.Read radius r.
  3. 3.If r ≤ 0, print "invalid radius" and go to step 6.
  4. 4.area ← 3.14159 × r × r.
  5. 5.Print area.
  6. 6.Stop.

Algorithm: largest of three numbers

  1. 1.Start. Read a, b, c.
  2. 2.big ← a.
  3. 3.If b > big then big ← b.
  4. 4.If c > big then big ← c.
  5. 5.Print big. Stop.

The second version scales: with the same pattern you can find the largest of a hundred numbers, while a chain of if-else comparisons cannot be extended.

Next — Page 5 — Flowchart symbols

4 of 20

Page 5

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

5. Flowchart Symbols

SymbolNameUse
OvalTerminalStart and Stop
ParallelogramInput / OutputRead values, print results
RectangleProcessCalculation or assignment
DiamondDecisionA condition with Yes / No branches
CircleConnectorJoins parts of a split diagram
ArrowFlow lineDirection of control
  • Every decision diamond has exactly one entry and two exits.
  • Flow normally runs top to bottom; label any upward arrow (that is a loop).
  • One Start and one Stop per flowchart, however many branches exist.

Next — Page 6 — Flowcharts for real problems

5 of 20

Page 6

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

6. Flowcharts for Real Problems

Even or odd

Start

Read n

n % 2 = 0 ?

Yes → Even

No → Odd

Stop

Sum of first N natural numbers

Start

Read N; s ← 0, i ← 1

i ≤ N ?

Yes: s ← s + i, i ← i + 1 (loop back)

No: print s

Stop

Next — Page 7 — Pseudocode conventions

6 of 20

Page 7

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

7. Pseudocode Conventions

Pseudocode sits between an algorithm and a program: structured like code, readable like English, free of syntax rules.

Pseudocode — factorial of n
BEGIN
  READ n
  fact <- 1
  FOR i <- 1 TO n DO
      fact <- fact * i
  ENDFOR
  PRINT fact
END
  • Keywords in capitals: READ, PRINT, IF, WHILE, FOR, ENDIF, ENDWHILE.
  • Use ← or <- for assignment, = only for comparison.
  • Indent the body of every decision and loop; indentation is the structure.

Next — Page 8 — Program development life cycle

7 of 20

Page 8

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

8. Program Development Life Cycle

  1. 1.Problem definition — write down what the program must do, in one sentence.
  2. 2.Analysis — identify inputs, outputs, formulae and invalid cases.
  3. 3.Design — algorithm, flowchart, and how data will be stored.
  4. 4.Coding — translate into C, one logical block at a time.
  5. 5.Testing and debugging — normal, boundary and invalid inputs.
  6. 6.Documentation and maintenance — comments, and later corrections.

Next — Page 9 — Generations and classification of languages

8 of 20

Page 9

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

9. Classification of Programming Languages

Machine language

Binary; directly executed; fastest but unreadable and machine dependent.

Assembly language

Mnemonics such as MOV, ADD; needs an assembler; still machine dependent.

High level language

C, Java, Python; portable, readable; needs a compiler or interpreter.

GenerationExampleCharacter
1GLMachine codeBinary instructions
2GLAssemblySymbolic mnemonics
3GLC, PascalProcedural, structured
4GLSQLProblem oriented, declarative

C is called a middle-level language because it offers 3GL structure with 2GL access to memory addresses through pointers.

Next — Page 10 — Translators: compiler, interpreter, assembler

9 of 20

Page 10

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

10. Translators — Compiler, Interpreter, Assembler

Compiler versus interpreter — the four-point answer
PointCompilerInterpreter
Unit of workWhole program at onceOne statement at a time
OutputProduces an object / executable fileProduces no separate file
Error reportingAll errors listed after the passStops at the first error
SpeedSlower to translate, faster to runFaster to start, slower to run
  • Assembler: assembly language → machine code.
  • Linker: joins your object code with library code into one executable.
  • Loader: places the executable in memory and starts it.

Next — Page 11 — How a C program is built

10 of 20

Page 11

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

11. How a C Program Is Built

hello.c to a running process

Preprocessor

Handles #include, #define

Compiler

Produces assembly

Assembler

Produces hello.o

Linker

Adds library code

Loader

Runs ./hello

Seeing each stage with gcc
gcc -E hello.c -o hello.i    # after preprocessing
gcc -S hello.i -o hello.s    # assembly
gcc -c hello.s -o hello.o    # object file
gcc hello.o -o hello         # linked executable

Next — Page 12 — History and features of C

11 of 20

Page 12

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

12. History and Features of C

  • Developed by Dennis Ritchie at Bell Laboratories, 1972, to write the UNIX operating system.
  • Standardised as ANSI C (C89), then C99, C11 and C17.
  • Descended from BCPL and B, which is where the name comes from.
Features worth quoting in an answer

Structured

Code is organised into functions and blocks.

Portable

The same source compiles on different machines.

Efficient

Compiles to compact, fast machine code.

Rich operator set

Bitwise, increment, conditional operators.

Extensible

Standard library plus user-defined functions.

Low-level access

Pointers reach memory directly.

Next — Page 13 — Structure of a C program

12 of 20

Page 13

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

13. Structure of a C Program

The six sections, in order
/* 1. Documentation: purpose, author, date */
#include <stdio.h>        /* 2. Link section  */
#define PI 3.14159        /* 3. Definition    */
float radius;             /* 4. Global declaration */
float area(float r);      /* prototype */

int main(void) {          /* 5. main function */
    printf("%.2f\n", area(2.0f));
    return 0;
}

float area(float r) {     /* 6. subprograms */
    return PI * r * r;
}
  • Only main() is compulsory; execution always begins there.
  • #include and #define are preprocessor directives — no semicolon.
  • return 0 reports success to the operating system.

Next — Page 14 — Character set, tokens and keywords

13 of 20

Page 14

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

14. Character Set, Tokens and Keywords

The six kinds of C token

Keywords

32 reserved words in C89: int, for, while, return …

Identifiers

Names you choose for variables and functions.

Constants

10, 3.14, 'A', "text".

Strings

Characters in double quotes, ending with '\'.

Operators

+ - * / % ++ -- && || etc.

Special symbols

{ } [ ] ( ) ; , #

Rules for identifiers

  • Start with a letter or underscore, never a digit.
  • Letters, digits and underscore only — no space, no hyphen.
  • Case sensitive: total, Total and TOTAL are three variables.
  • A keyword can never be used as an identifier.

Next — Page 15 — Constants, variables and declarations

14 of 20

Page 15

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

15. Constants, Variables and Declarations

A variable names a storage location whose value may change; a constant's value is fixed at compile time. Every variable must be declared before use — C will not guess a type.

Declaration and initialisation
int count;               /* declaration only, value is garbage */
int marks = 78;          /* declaration with initialisation   */
const float PI = 3.14f;  /* value cannot be changed later     */
#define MAX 100          /* preprocessor constant, no memory  */
char grade = 'A';        /* single quotes for a character     */

Next — Page 16 — Data types, sizes and qualifiers

15 of 20

Page 16

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

16. Data Types, Sizes and Qualifiers

Typical sizes on a 64-bit compiler
TypeSizeRange / precisionFormat
char1 byte−128 to 127%c
int4 bytes−2,147,483,648 to 2,147,483,647%d
long long8 bytesabout ±9.2 × 10^18%lld
float4 bytesabout 6 decimal digits%f
double8 bytesabout 15 decimal digits%lf
  • Qualifiers: short, long, signed, unsigned change range, not meaning.
  • unsigned int cannot hold a negative value; it wraps to a large positive one.
  • Sizes are implementation defined — quote sizeof(), not a memorised number, if asked to prove it.

Next — Page 17 — Operators in C

16 of 20

Page 17

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

17. Operators in C

Arithmetic

+ − * / % (% only for integers)

Relational

< > <= >= == != — result 1 or 0

Logical

&& || ! with short-circuit evaluation

Assignment

= += −= *= /= %=

Increment

++ and −−, prefix or postfix

Bitwise

& | ^ ~ << >>

Output prediction — the favourite question
int i = 5;
printf("%d ", i++);   /* prints 5, then i becomes 6 */
printf("%d ", ++i);   /* i becomes 7, prints 7      */
printf("%d", 7 / 2);  /* 3  — integer division      */
printf("%d", 7 % 2);  /* 1  — remainder             */

Next — Page 18 — Type conversion and precedence

17 of 20

Page 18

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

18. Type Conversion and Precedence

Implicit versus explicit conversion

  • Implicit (promotion): the compiler widens the smaller type — char → int → float → double.
  • Explicit (cast): you force it, e.g. (float) a / b.
  • 5 / 2 is 2, but (float) 5 / 2 is 2.5 — the cast applies before the division.
Precedence, highest first
LevelOperatorsAssociativity
1() [] ->Left to right
2! ~ ++ -- unary − (type)Right to left
3* / %Left to right
4+ −Left to right
5< <= > >=Left to right
6== !=Left to right
7&& then ||Left to right
8= += −=Right to left

Next — Page 19 — Input and output, first complete program

18 of 20

Page 19

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

19. Input, Output and a First Complete Program

  • Formatted: printf() and scanf() — need a format specifier per value.
  • Unformatted: getchar(), putchar(), gets() (unsafe, use fgets()), puts().
  • scanf() needs the address operator: scanf("%d", &n).
si.c — simple interest
#include <stdio.h>

int main(void) {
    float p, r, t, si;
    printf("Enter principal, rate, time: ");
    scanf("%f %f %f", &p, &r, &t);
    si = (p * r * t) / 100;
    printf("Simple interest = %.2f\n", si);
    return 0;
}

Compile with gcc si.c -o si and run ./si. For 5000 8 2 the output is 800.00. Declare the variables as int instead and 5000 7.5 2 silently loses the fractional rate — the whole point of the exercise.

Next — Page 20 — Errors, debugging and revision checklist

19 of 20

Page 20

Wink Notes

B.Tech CSE — 1st Semester

Programming for Problem Solving in C

Unit - 1

20. Errors, Debugging and Revision Checklist

Error typeFound whenExample
SyntaxCompilationMissing semicolon
SemanticCompilationUsing an undeclared variable
LinkerLinkingCalling a function that is never defined
RuntimeExecutionDivision by zero
LogicalNever automaticallyWrong formula — it runs, the answer is wrong
  • Can you list the stages of program development with one line each?
  • Can you write an algorithm and draw the matching flowchart for the same problem?
  • Can you state four differences between a compiler and an interpreter?
  • Can you predict output for a mixed-type expression with integer division?
  • Can you name the six sections of a C program in order?

Next — Unit 2 — Control structures, arrays and strings

20 of 20

Continue in this subject