Sunday, July 27, 2025

Chapter 5: Programming Concepts & Logics

 

5.1 Programming Concept

5.1.1 Introduction to Programming Languages

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. Programming languages are used to create programs that control the behaviour of a machine, to express algorithms precisely, or as a mode of human-computer interaction.

They consist of a set of rules for combining symbols (syntax) and a set of meanings for those combinations (semantics). Different programming languages are suited for different types of tasks, from web development and data science to game development and operating systems.

 

5.1.2 Low-level, High-level, and 4GL Programming Languages

Programming languages are often categorized by their level of abstraction from machine code:

1) Low-Level Programming Languages: These languages are very close to the computer's native language (machine code) and provide little or no abstraction from the computer's architecture. They offer direct manipulation of memory and hardware registers, leading to highly optimized and fast programs, but they are difficult to write and understand.

a) Machine Language (First Generation Language - 1GL): Consists of binary code (0s and 1s) directly   
executable by the CPU. It's the most fundamental level, extremely difficult for humans to write.

b) Assembly Language (Second Generation Language - 2GL): Uses mnemonics (short, symbolic codes like ADD, MOV, JMP) to represent machine instructions. It's more readable than machine language but still processor-specific and requires an assembler to translate it into machine code.

2) High-Level Programming Languages (3GL): These languages are more abstract and human-readable, using keywords, syntax, and structures that are closer to natural language (e.g., English). They are machine-independent and require a compiler or interpreter to translate them into machine code. This abstraction makes them easier to learn, use, and debug, leading to faster development. Examples: C, C++, Java, Python, JavaScript, C#, Ruby, Fortran, Pascal.

3) Fourth-Generation Languages (4GL): These languages are even higher-level than 3GLs, designed to be closer to human language and focused on specific domains or tasks, often with powerful built-in functionalities. They typically aim to reduce programming effort and time by enabling users to specify what they want to achieve rather than how to achieve it. Examples: SQL (for database queries), MATLAB, etc.

 

Generation

Full Form

Type of Language

Example Languages

Features

Ease of Use

Translation Required

Speed

1GL

First Generation Language

Machine Language (Binary)

10110010 (binary codes)

Directly executed by CPU; hardware-specific

Very Low

Not needed (already binary)

Very High (fastest)

2GL

Second Generation Language

Assembly Language

MOV A, B

Uses mnemonics; requires assembler to convert to machine code

Low

Assembler

High

3GL

Third Generation Language

High-level Programming Language

C, C++, Java, Python

Closer to human language; portable and easier to understand

Moderate to High

Compiler or Interpreter

Moderate

4GL

Fourth Generation Language

Very High-level / Domain-specific

SQL, MATLAB, Oracle Reports

Designed for specific tasks; non-procedural; fast development

Very High

Usually interpreter/compiler

Slower than 1GL/2GL

5.1.3 Compiler, Interpreter, and Assembler

These are software tools that translate source code written in a programming language into a form that a computer can understand and execute:

1) Compiler: A compiler translates an entire program written in a high-level language (source code) into machine code (object code) or an intermediate code before the program is run. Once compiled, the program can be executed many times without recompilation (unless the source code changes).

Advantages: Faster execution, standalone executable files.

Disadvantages: Compilation time can be significant, difficult to debug during runtime.

Examples: C, C++, Java

2) Interpreter: An interpreter translates and executes a program line by line. It reads one statement, translates it into machine code, and executes it immediately before moving to the next statement.

Advantages: Easier debugging (errors are found as the program runs), platform independence (if the interpreter is available).

Disadvantages: Slower execution compared to compiled code, requires the interpreter to be present to run the program.

Examples: Python, JavaScript, Ruby, PHP.

3) Assembler: An assembler translates assembly language (low-level language) into machine code. Each assembly language instruction typically corresponds to one machine language instruction.

 

Feature

Compiler

Interpreter

Translation

Translates the entire program before execution

Translates and executes code line by line

Speed

Faster, since the entire code is pre-translated

Slower, due to continuous translation during execution

Use Case

Ideal for repeated execution of the same program

Best for interactive or dynamic coding sessions

Error Handling

Errors detected after compilation of the whole program

Errors detected as code is executed line by line

Development

Harder to debug due to delayed execution

Easier to debug with immediate feedback

Examples

C, C++, Java

Python, Ruby, JavaScript

5.1.4 Syntax, Semantic, and Runtime Errors

Errors are an inseparable part of programming. Understanding different types of errors helps in debugging:

1) Syntax Errors: These are errors that violate the grammatical rules of the programming language. The compiler or interpreter catches these errors before the program can run or during the initial parsing phase. They are like grammatical mistakes in a natural language sentence.

Examples: Missing semicolon, misspelled keyword, unmatched parentheses, incorrect variable declaration.

Detection: Detected by the compiler/interpreter during compilation/parsing.

 

2) Semantic Errors (Logic Errors): These errors occur when the program is syntactically correct but does not do what the programmer intended it to do. The program runs, but the output is incorrect or unexpected. These are the hardest errors to find because the computer doesn't report them.

Examples: Incorrect formula, wrong operator used (+ instead of −), infinite loop (if not detected as a runtime error), etc.

Detection: Requires careful testing and debugging by the programmer.

 

3) Runtime Errors: These errors occur while the program is executing. They are not detected by the compiler (for compiled languages) or during the initial parsing (for interpreted languages) because they depend on conditions that arise only during execution (e.g., user input, system resources). The program might crash or terminate abnormally.

Examples: Division by zero, accessing an array element out of bounds, trying to open a file that doesn't exist, insufficient memory.

Detection: Occur during program execution, often leading to a program crash or an error message.

 

Aspect

Syntax Error

Semantic Error

Runtime Error

Definition

Violation of language grammar or structure

Code is grammatically correct but does not do what was intended

Error occurs during execution despite syntactically and semantically correct code

Detection Phase

Compile-time (or interpretation phase)

Often compile-time, but may only be noticed at runtime

Runtime (during program execution)

Example

if (x > 5 → missing closing parenthesis

int x = "hello"; → type mismatch or incorrect logic

int a = 5/0; → division by zero

Impact

Prevents code from compiling or running

Code runs but produces incorrect or unintended results

Program crashes or throws exceptions

Ease of Detection

Easy; compiler/interpreter flags it

Hard; requires logical analysis or testing

Moderate; often flagged by runtime environment

Fix Strategy

Correct the syntax (e.g., punctuation, keywords)

Refactor logic or correct type usage

Add error handling (e.g., try-catch, input validation)

5.1.5 Control Structures: Sequence, Selection, and Iteration

Control structures dictate the flow of execution in a program:

1) Sequence: This is the most basic control structure, where instructions are executed one after another in the order they appear in the program. This is the default flow of execution.

2) Selection (Conditional/Decision): This structure allows the program to make decisions and execute different blocks of code based on whether a certain condition is true or false.

3) Iteration (Looping/Repetition): This structure allows a block of code to be executed repeatedly as long as a certain condition is met or for a specified number of times.

5.1.6 Program Design Tools – Algorithm, Flowchart, and Pseudocode

These tools are used to plan and design the logic of a program before writing the actual code:

1) Algorithm: A step-by-step, unambiguous, and finite set of instructions for solving a problem or accomplishing a task. Algorithms are language-independent and focus purely on the logic.

Ø  Characteristics: Unambiguous, input, output, finiteness, effectiveness.

Ø  Examples:

Q1. Write an algorithm to calculate simple interest.

Step 1: Start

Step 2: Read the value of P, T, R

Step 3: Calculate simple interest by using I =(P*T*R)/100

Step 4: Display simple interest(I)

Step 5: Stop

Q2. Write an algorithm to check greatest number among two number.

Step 1: Start

Step 2: Read any two-number a, b

Step 3: check if (a>b)

              If yes, Display the greatest number is “a” and go to step 4

              If no, Display the greatest number is “b” and go to step 4

Step 4: Stop

 

2) Flowchart: A graphical representation of an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting them with arrows. Each type of box represents a specific type of operation (e.g., input/output, processing, decision).

Standard symbols used in Flowchart:

Advantages: Visual representation, easy to understand logic.

Disadvantages: Can become complex for large programs, difficult to modify.

Examples:

Q1. Draw flowchart to calculate simple interest.

Q2. Draw flowchart to find greatest number among two numbers.

 

3) Pseudocode: A high-level, informal description of an algorithm's logic, using a mixture of natural language and programming-like constructs. It is not executable code but helps in planning the program's structure without worrying about the strict syntax of a specific programming language.

Example (Pseudocode for calculating the sum of two numbers):

BEGIN

    INPUT number1

    INPUT number2

    SET sum = number1 + number2

    PRINT sum

END

 

5.1.7 Absolute Binary, BCD, ASCII, and Unicode

These are different ways to represent data, especially characters and numbers, in computer systems:

1. Absolute Binary (Pure Binary)

Ø  Represents numbers in base-2 (only 0s and 1s).

Ø  Directly corresponds to the computer's hardware representation.

Ø  Used in low-level computing (machine code, CPU operations).

Ø  Example:

o   Decimal 5 → 0101 in 4-bit binary.

o   Decimal 13 → 1101 in 4-bit binary.

2. BCD (Binary-Coded Decimal)

Ø  Encodes each decimal digit (0–9) into a 4-bit binary.

Ø  Used in financial systems, calculators, and digital displays where exact decimal representation is crucial.

Ø  Example:

o   Decimal 25 → 0010 0101 (2 → 0010, 5 → 0101).

Ø  Advantage: Avoids rounding errors in decimal arithmetic.

3. ASCII (American Standard Code for Information Interchange)

Ø  7-bit character encoding standard representing 128 characters (letters, digits, symbols, control codes).

Ø  Extended ASCII uses 8 bits (256 characters).

Ø  Example:

o   'A' → 65 (decimal) → 01000001 (binary).

Ø  Limitation: Only supports English and basic symbols.

4. Unicode

Ø  A universal character encoding standard supporting over 140,000 characters (languages, emojis, symbols).

Ø  Uses variable-length encoding (UTF-8, UTF-16, UTF-32):

o   UTF-8: Backward-compatible with ASCII (1–4 bytes per character).

o   UTF-16: Uses 2 or 4 bytes per character.

o   UTF-32: Fixed 4 bytes per character.

Ø  Example:

o   'A' (ASCII-compatible) → U+0041 → 41 in UTF-8.

 

Key Differences

Feature

Absolute Binary

BCD

ASCII

Unicode

Purpose

Numeric (base-2)

Decimal digit encoding

Text encoding

Universal text encoding

Bits/Char

Variable (e.g., 8-bit)

4 bits per digit

7/8 bits per character

1–4 bytes (UTF-8)

Coverage

Numbers only

Numbers (0–9)

English + basic symbols

All languages + emojis

Example Use

CPU operations

Calculators, finance

Early computers

Modern web/text

When to Use Which?

  1. Absolute Binary: Low-level programming, hardware control.
  2. BCD: Financial systems requiring exact decimal precision.
  3. ASCII: Legacy systems, minimal English text.
  4. Unicode (UTF-8): Modern applications, multilingual support.

5.2 C Programming Language

5.2.1 Introduction and Features of C Language

Introduction:

Ø  C is a proceduralhigh-level, and general-purpose programming language developed by Dennis Ritchie in 1972 at Bell Labs.

Ø  It was designed for system programming (OS, compilers, drivers) but is also used in application development.

Ø  Influenced languages like C++, Java, Python, and C#.

 

Features of C:

  1. Simple & Portable: Easy syntax, machine-independent (compiled for different platforms).
  2. Fast & Efficient: Close to hardware (low-level memory access).
  3. Structured Language: Supports functions, loops, and modular programming.
  4. Rich Library Support: Built-in functions for I/O, math, string handling, etc.
  5. Pointers & Memory Management: Direct memory manipulation using pointers.
  6. Extensible: Supports user-defined functions and libraries.

 

5.2.2 Structure of a C Program

A basic C program has the following structure:

#include <stdio.h>   // Preprocessor directive (header file)

int main()   // Main function (entry point)

{       

    printf("Hello, World!");   // Statement

    return 0;        // Exit status

}

Components:

  1. Preprocessor Directives (#include):  Includes header files.
  2. Main Function (int main()):  Program execution starts here.
  3. Statements:  Instructions (e.g., printf).
  4. Return Statement (return 0):  Indicates successful execution.

 

5.2.3 C Preprocessor and Header Files

Preprocessor

Ø  Runs before compilation.

Ø  Processes directives starting with #.

Ø  Examples:

#include <stdio.h>  // Includes standard I/O functions

#define PI 3.14     // Macro definition


Header Files: 

Ø  Contain function declarations and macros.

Ø  Common headers:

a)       stdio.h:  Input/output functions (printf, scanf).

b)      math.h:  Math operations (sqrt, pow).

c)       string.h:  String handling (strcpy, strlen).


5.2.4 Character Set used in C

In C programming, the character set means all the letters, digits, and symbols that can be used to write a C program. These characters are used to form C tokens like keywords, identifiers, constants, and operators.

The character set in C mainly includes:

  1. Alphabets: 

    • Uppercase letters: A to Z

    • Lowercase letters: a to z

    • Both uppercase and lowercase are treated as different (case-sensitive).

  2. Digits: 0 to 9 (Used to form numbers but cannot be the first character of an identifier).

  3. Special Characters: Symbols used for operators, punctuation, and other purposes. Examples:

    • + - * / = < > % & | ^ ! ~ ? : ; , . # ( ) { } [ ]
  4. White Space Characters:

    • Space, tab (\t), new line (\n), etc.

    • Used to separate tokens and improve readability.


5.2.5 Use of Comments

In C programming, comments are notes written in the program to explain the code. The compiler ignores comments, so they do not affect program execution.
They help make the code easier to understand for yourself and others.

Types of comments in C:

  1. Single-line comment

    • Starts with // and goes till the end of the line.

    • Example:

      // This is a single-line comment
  2. Multi-line comment

    • Starts with /* and ends with */.

    • Can span across multiple lines.

    • Example:

      /* This is a multi-line comment */

5.2.6 Identifiers, Keywords, and Tokens

1. Identifiers:

Ø  Identifiers are names given to variables, functions, arrays, structures, etc. in a C program.

Ø  Rules for naming identifiers:

o   Must begin with a letter or underscore (_).

o   Can contain letters, digits, and underscores.

o   Cannot be a keyword.

o   Case-sensitive (e.g., total and Total are different).

Ø  Examples: sum, count_1, _totalMarks.

 

2. Keywords:

Ø  Keywords are pre-defined words that have special meaning in C and are reserved by the compiler.

Ø  Cannot be used as identifiers.

Ø  Examples: int, float, if, else, return, for, while.

 

3. Tokens:

Ø  Tokens are the smallest units in a C program that have meaning to the compiler.

Ø  Types of tokens in C:

    1. Keywords – e.g., if, return
    2. Identifiers – e.g., total, count
    3. Constants – e.g., 10, 3.14
    4. Strings – e.g., "Hello"
    5. Operators – e.g., +, -, *, /
    6. Punctuators/Special symbols – e.g., {, }, ;, ,

 

5.2.7 Basic Data Types in C /5.2.9 Type of Specifier

C supports the following fundamental data types:

Data Type

Size (bytes)

Range

Format Specifier

Example

int

2 or 4

-32,768 to 32,767 (16-bit)
or -2,147,483,648 to 2,147,483,647 (32-bit)

%d

int x = 10;

char

1

-128 to 127 (signed)
or 0 to 255 (unsigned)

%c

char ch = 'A';

float

4

1.2E-38 to 3.4E+38 (6-7 decimal digits)

%f

float f = 3.14;

double

8

2.3E-308 to 1.7E+308 (15-16 decimal digits)

%lf

double d = 3.14159;

void

-

No value (used for functions & pointers)

-

void 


5.2.8 Constants and Variables

Variables:

Ø  Variables are named storage locations in memory that can hold different values during the execution of a program.

Ø  The value stored in a variable can change anytime.

Ø  Before using a variable, it must be declared with a data type.

Ø  Example:

               int age = 20;  // 'age' is a variable that can change

               age = 25;      // value of 'age' changed to 25

Constants:

Ø  Constants are fixed values that do not change during the program execution.

Ø  Once a constant is assigned a value, it cannot be altered.

Ø  Constants are used when the value must remain the same throughout the program.

Ø  In C, constants can be declared using the const keyword or by using #define preprocessor directive.

Ø  Examples:

  1. Using const keyword:

               const int MAX_AGE = 100; 

  1. Using #define:

               #define PI 3.1416  


5.2.10 Simple and Compound Statements

1) Simple Statement:
A simple statement is a single instruction that ends with a semicolon (;). It tells the computer to perform one action.
Example:

int x = 10; 

x = x + 5; 

printf("%d", x); 

 

2) Compound Statement (Block):
A compound statement is a group of simple statements enclosed within braces { }. It is treated as a single statement by the compiler.
Compound statements are used when multiple instructions need to be executed together.
Example:

    int x = 10; 

    x = x + 5; 

    printf("%d", x); 

}  


5.2.11 Operators and Expressions

Operators are special symbols in C used to perform operations on variables and values.

An expression is a combination of variables, constants, and operators that produces a value.

Different types of operators are as follows:

1. Arithmetic Operators: Used for mathematical calculations.

Operator

Meaning

Example

Result

+

Addition

5 + 3

8

-

Subtraction

10 - 4

6

*

Multiplication

4 * 2

8

/

Division

10 / 2

5

%

Modulus (remainder)

10 % 3

1

 

2. Relational Operators

Used to compare two values; result is true (1) or false (0).

Operator

Meaning

Example

Result

==

Equal to

5 == 5

1 (true)

!=

Not equal to

5 != 3

1 (true)

> 

Greater than

7 > 3

1 (true)

< 

Less than

2 < 5

1 (true)

>=

Greater than or equal

5 >= 5

1 (true)

<=

Less than or equal

3 <= 4

1 (true)

 

3. Logical Operators: Used to combine multiple conditions.

Operator

Meaning

Example

Result

&&

Logical AND

(5 > 3) && (2 < 4)

1 (true)

`

`

Logical OR

!

Logical NOT (negation)

!(5 > 3)

0 (false)

 

4. Assignment Operators

Used to assign values to variables.

Operator

Meaning

Example

Explanation

=

Simple assignment

x = 5;

Assigns 5 to x

+=

Add and assign

x += 3;

Same as x = x + 3;

-=

Subtract and assign

x -= 2;

Same as x = x - 2;

*=

Multiply and assign

x *= 4;

Same as x = x * 4;

/=

Divide and assign

x /= 2;

Same as x = x / 2;

%=

Modulus and assign

x %= 3;

Same as x = x % 3;

 

5. Unary Operators: Operators with one operand.

Operator

Meaning

Example

Result

++

Increment by 1

x++ or ++x

Increases x by 1

--

Decrement by 1

x-- or --x

Decreases x by 1

+

Unary plus (positive)

+x

Returns value of x

-

Unary minus (negative)

-x

Returns negative of x

!

Logical NOT

!x

Returns opposite boolean

 

6. Conditional (Ternary) Operator: A shorthand for if-else with three operands:

condition ? expression_if_true : expression_if_false;

Example:

int max = (a > b) ? a : b;

Explanation: If a > b is true, max gets a; otherwise, max gets b.

No comments:

Post a Comment