Programming Concepts and Logics

    Programming Concepts and Logics

    Reading Mode:

    Computer Science тАУ Grade XI

    Unit 5: Programming Concepts and Logics

    Topics covered: 5.1 Programming Concepts ┬╖ 5.2 C Programming Language


    5.1 Programming Concepts

    5.1.1 Program and Programmer

    A program is a set of instructions, written in a programming language, that tells the computer how to perform a task or solve a problem.

    Programming (coding) is the process of writing, testing and maintaining programs.

    A programmer is a person who designs, writes, tests, debugs and maintains computer programs. A programmer needs knowledge of programming languages, algorithms and problem solving.

    Features of a Good Program

    FeatureMeaning
    IntegrityGives correct and complete output for valid input; data is not corrupted
    ClarityEasy to read and understand; no confusing statements
    SimplicityUses the simplest logic that solves the problem
    EfficiencyRuns fast and uses little memory
    MaintainabilityEasy to modify, update and fix later
    ReliabilityWorks correctly every time under the expected conditions
    GeneralityWorks for a wide range of inputs and on different platforms
    ModularityDivided into small independent parts (modules/functions)
    RobustnessHandles wrong input and unexpected situations without crashing
    DocumentationHas comments and a user manual to help users and future programmers

    Difference between Program and Software

    ProgramSoftware
    A set of instructions to perform one specific taskA collection of programs, data and documentation
    Smaller in size and scopeLarger and more complex
    A component (part) of softwareMade up of many programs working together
    Usually written by one programmerUsually developed by a team
    Not usually sold with a licenceUsually distributed with a licence
    Example: a program to find simple interestExample: MS Word, Photoshop, Windows

    5.1.2 Programming Languages

    A programming language is an artificial language with a set of rules (syntax) and symbols used to write programs. A computer actually understands only machine language (0s and 1s), so programs written in other languages must be translated.

    A. Low-Level Languages

    Languages that are close to the hardware and depend on the computer's architecture (machine-dependent).

    1. Machine language (First generation, 1GL)

    • Written only in binary (0 and 1); the only language the CPU understands directly.
    • Advantages: fastest execution; no translator needed.
    • Disadvantages: very hard to write, read and debug; machine-dependent; time-consuming; high chance of errors.

    2. Assembly language (Second generation, 2GL)

    • Uses mnemonic (symbolic) codes such as ADD, SUB, MOV, CMP instead of 0s and 1s.
    • Needs an assembler to convert it into machine language.
    • Advantages: easier than machine language; easier to find and correct errors; fast and gives direct hardware control.
    • Disadvantages: machine-dependent; mnemonics must be remembered; needs a translator; harder than high-level languages.
    Machine LanguageAssembly Language
    Written in 0s and 1sWritten in mnemonic codes (ADD, SUB, MOV)
    Directly understood by the computerNeeds an assembler
    First-generation languageSecond-generation language
    Very difficult to write and debugEasier to write and debug
    Slightly faster executionSlightly slower (translation needed)

    B. High-Level Languages

    Languages that use English-like words and mathematical symbols. They are machine-independent (portable) and need a compiler or interpreter.

    • Advantages: easy to learn, write and debug; machine-independent; easier to maintain; better documentation; lower development cost.
    • Disadvantages: need translation, so execution is slower; use more memory; less direct control over hardware.
    GenerationTypeDescriptionExamples
    3GLProcedural languagesThe programmer writes how to solve the problem step by stepC, Pascal, FORTRAN, COBOL, BASIC
    4GLProblem-oriented languagesThe programmer states what is required; used for databases and reportsSQL, report generators (some textbooks also list Visual Basic, PHP)
    5GLNatural / AI languagesBased on constraints and logic, used for artificial intelligenceProlog, Lisp, Mercury
    LanguageFull form / Use
    FORTRANFormula Translation: first high-level language, for science and engineering
    COBOLCommon Business Oriented Language: business and data processing
    BASICBeginner's All-purpose Symbolic Instruction Code: for beginners
    PascalStructured programming; used for teaching
    C / C++System software, applications; C++ adds object-oriented features
    JavaObject-oriented; web and mobile applications
    PythonGeneral-purpose, easy to learn; data science and AI
    JavaScript, PHPWeb development (client side / server side)
    SQLDatabase queries

    5.1.3 Language Translators (Language Processors)

    A language translator converts a program written in one language (source program) into machine language (object program).

    TranslatorConvertsMethod
    AssemblerAssembly language тЖТ machine languageTranslates assembly code
    CompilerHigh-level language тЖТ machine languageTranslates the whole program at once
    InterpreterHigh-level language тЖТ machine languageTranslates and executes one statement at a time

    Difference between Compiler and Interpreter

    CompilerInterpreter
    Translates the whole program at onceTranslates one line at a time
    Creates a separate object (executable) fileDoes not create an object file
    Shows all errors after compiling the whole programStops and shows an error as soon as it finds one
    Execution is faster after compilationExecution is slower (translation every time)
    Debugging takes more effort (errors listed together)Easier to find the line with the error
    Needs more memory to store the object codeNeeds less memory
    Examples: C, C++, PascalExamples: BASIC, Python, Ruby

    Some languages, such as Java and Python, use both methods (first compile to an intermediate code, then interpret it).


    5.1.4 Errors, Testing and Debugging

    A bug (error) is a mistake in a program that causes wrong or unexpected behaviour.

    Types of Errors

    ErrorMeaningExample
    Syntax errorBreaking the grammar rules of the language. Detected by the compiler/interpreter before the program runsMissing semicolon, misspelled keyword (pritnf), unmatched bracket
    Logical (semantic) errorThe program runs but gives wrong output because of faulty logic. Not detected by the compilerUsing + instead of *; wrong formula for area
    Runtime errorOccurs while the program is running and stops it abnormallyDivision by zero, reading a missing file, using too much memory

    Difference between Syntax Error and Logical Error

    Syntax ErrorLogical Error
    Violation of the rules (grammar) of the languageMistake in the logic or formula of the program
    Detected by the compiler/interpreterNot detected by the compiler
    Program cannot run until it is fixedProgram runs but gives wrong results
    Easy to find (the compiler shows the line)Difficult to find; needs testing and tracing

    Syntax and semantics: Syntax is the set of rules for writing correct statements; semantics is the meaning of those statements. Example in English: "Aryan eats an apple." (correct syntax and meaning). "Aryan eats a house." (correct syntax, wrong meaning). "Aryan eat a house." (wrong syntax and meaning).

    Testing

    Testing is the process of running a program with different inputs to check whether it gives the expected output and to find errors.

    Testing stageMeaning
    Unit testingEach small part (module/function) is tested separately
    Integration testingModules are tested after they are joined together
    System testingThe complete program is tested as a whole
    User acceptance testingThe user checks whether the program meets the requirements

    Debugging

    Debugging is the process of finding and correcting errors (bugs) in a program. Testing finds that an error exists; debugging finds the cause and fixes it.


    5.1.5 Data Representation Codes

    Computers store everything in binary. Codes assign binary patterns to numbers and characters.

    CodeDescription
    Pure (absolute) binaryNumbers are stored directly in base 2. The leftmost bit can be used as a sign bit (0 = positive, 1 = negative)
    BCD (Binary Coded Decimal)Each decimal digit is written separately as 4 bits. Example: 59 тЖТ 0101 1001 (5 = 0101, 9 = 1001)
    ASCII (American Standard Code for Information Interchange)7-bit code with 128 characters (standard ASCII); 8-bit extended ASCII has 256 characters. Each character is stored in 1 byte
    EBCDIC (Extended Binary Coded Decimal Interchange Code)8-bit code (256 characters), used mainly in IBM mainframe computers
    UnicodeA universal standard that gives a unique number to the characters of all world languages (including Nepali/Devanagari) and symbols/emoji. Stored using encodings such as UTF-8, UTF-16 and UTF-32

    Useful ASCII values

    CharactersASCII code
    0 to 948 to 57
    A to Z65 to 90
    a to z97 to 122
    Space32

    Lowercase letter code = uppercase letter code + 32 ('a' = 97, 'A' = 65).

    #include <stdio.h>
    
    int main(void)
    {
        char ch = 'A';
        int code = 97;
    
        printf("Character %c has ASCII code %d\n", ch, ch);
        printf("ASCII code %d is the character %c\n", code, code);
        return 0;
    }
    

    Output

    Character A has ASCII code 65
    ASCII code 97 is the character a
    

    5.1.6 Programming Fundamentals

    Data types

    A data type tells the computer what kind of data a variable can store and how much memory it needs.

    Data typeMeaningExample
    IntegerWhole numbers (positive, negative, zero)25, тИТ7, 0
    Real / Floating pointNumbers with a fractional part3.14, тИТ0.5, 2.5e3
    CharacterA single letter, digit or symbol'A', '7', '#'
    StringA sequence of characters"Nepal"
    BooleanOnly two values: true or falseTRUE, FALSE

    Keyword, variable, constant

    TermMeaningExample
    KeywordA reserved word with a fixed meaning for the compiler; cannot be used as a nameint, float, if, while
    VariableA named memory location whose value can change during the programage = 16; then age = 17;
    ConstantA value that does not change during the program3.14, 100, 'A'

    Operation, operand, operator

    TermMeaningExample
    OperationAn action performed on dataaddition, comparison, input/output
    OperandThe data (value or variable) on which the operation is donea, b in a + b
    OperatorA symbol that performs the operation+, -, *, /, >, &&

    In c = a + b, the operands are a and b, the operator is + (and =), and the whole line is a statement.

    Programming statements

    StatementMeaningExample
    Simple statementA single instruction (assignment, calculation, or a test)L = 10; area = L * B;
    Compound statementA group of statements enclosed in { } and treated as one unit{ a = 5; b = 6; sum = a + b; }
    Control statementA statement that controls the order of execution (decision and repetition)if, switch, while, for

    5.1.7 Program Design Tools

    Before writing a program, the logic is planned using tools: algorithm, flowchart, pseudocode, decision tree and decision table.

    1. Algorithm

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

    Properties of a good algorithm

    • Input: zero or more inputs are given
    • Output: produces at least one output
    • Definiteness: each step is clear and unambiguous
    • Finiteness: ends after a finite number of steps
    • Effectiveness: each step is simple enough to be carried out
    • Language independent: can be written as a program in any language

    Example: algorithm to find simple interest

    1. Start
    2. Input P, T and R
    3. Calculate SI = (P ├Ч T ├Ч R) / 100
    4. Display SI
    5. End

    2. Flowchart

    A flowchart is a graphical (diagram) representation of an algorithm, using standard symbols joined by arrows.

    Flowchart symbols

    SymbolNameUse
    Oval (rounded)TerminalStart or End
    ParallelogramInput / OutputReading input or printing output
    RectangleProcessCalculation or assignment
    DiamondDecisionCondition with Yes/No (True/False) branches
    CircleConnectorJoins parts of a flowchart (on the same or another page)
    ArrowFlow lineShows the direction of flow

    Flowchart: simple interest

    Types of flowchart

    System FlowchartProgram Flowchart
    Shows the overall flow of data and operations in a whole systemShows the detailed logic of a single program
    Gives a general overviewGives step-by-step detail
    Used by system analystsUsed by programmers

    Advantages of flowcharts: easy communication, better analysis of the problem, proper documentation, easier coding, easier debugging, easier maintenance. Disadvantages: complex logic makes large and confusing charts; difficult to modify; time-consuming to draw; no standard way to show details of a program.

    3. Pseudocode

    Pseudocode is an informal description of a program's logic using English-like statements that resemble programming code. It is not a real program and cannot be run.

    Input Length, Breadth, Height
    Volume = Length * Breadth * Height
    Display Volume
    
    Input Marks
    IF Marks >= 40 THEN
        Display "Pass"
    ELSE
        Display "Fail"
    END IF
    

    4. Decision tree

    A decision tree is a tree-like diagram that shows the different possible decisions and their outcomes.

    Example: discount decision for a shop

    5. Decision table

    A decision table lists conditions and the actions to be taken for each combination of conditions.

    Conditions / ActionsRule 1Rule 2Rule 3Rule 4
    Member?YYNN
    Purchase тЙе 5000?YNYN
    Discount 20%тЬФ
    Discount 10%тЬФ
    Discount 5%тЬФ
    No discountтЬФ

    5.1.8 Control Structures

    A control structure (control statement) decides the order in which statements are executed. There are three basic structures.

    StructureMeaningC statements
    SequenceStatements run one after another in the order written(ordinary statements)
    Selection (decision / branching)Choose between actions depending on a conditionif, if-else, else-if ladder, nested if, switch
    Iteration (loop / repetition)Repeat statements while a condition is truewhile, do-while, for

    Selection structures: algorithm and flowchart

    (a) if (one condition, one action)

    Problem: check whether a number is positive.

    Algorithm: 1. Start 2. Input N 3. If N > 0, display "Positive" 4. End

    (b) if-else (one condition, two actions)

    Problem: find the greater of two numbers.

    Algorithm: 1. Start 2. Input X, Y 3. If X > Y display X is greater, else display Y is greater 4. End

    Problem: find the greatest of three numbers.

    Algorithm: 1. Start 2. Input P, Q, R 3. If P > Q and P > R, P is greatest; else if Q > R, Q is greatest; else R is greatest 4. End

    (d) Nested if (a condition inside another condition)

    Problem: find the greater of two numbers only if both are positive.

    Algorithm: 1. Start 2. Input X, Y 3. If X > 0 and Y > 0, then (if X > Y display X, else display Y); else display "not both positive" 4. End

    (e) switch-case (one value, many choices)

    Problem: input a number from 1 to 7 and display the day (1 = Sunday).

    Algorithm: 1. Start 2. Input day 3. Switch on day: case 1 Sunday, case 2 Monday, тАж case 7 Saturday, default "Out of range" 4. End

    Iteration structures: algorithm and flowchart

    (a) while loop (condition checked first)

    Problem: print the numbers 1 to 10.

    Algorithm: 1. Start 2. I = 1 3. While I тЙд 10: display I, then I = I + 1 4. Stop

    (b) do-while loop (condition checked after the body)

    Problem: print the numbers from 100 down to 1.

    Algorithm: 1. Start 2. A = 100 3. Do: display A, then A = A тИТ 1, while A тЙе 1 4. Stop

    (c) for loop (initialization, condition and counter in one line)

    Problem: print the multiplication table of 7.

    Algorithm: 1. Start 2. For i = 1 to 10: m = 7 ├Ч i, display m 3. Stop


    5.2 C Programming Language

    5.2.1 Introduction to C

    C is a general-purpose, structured (procedural) programming language developed by Dennis Ritchie at Bell Laboratories (AT&T), USA, around 1972 (developed between 1969 and 1973). It was first used to rewrite the UNIX operating system. It is called C because it came after the language B.

    Development of C

    • 1978: Brian Kernighan and Dennis Ritchie published the book The C Programming Language (called K&R C).
    • 1989: the ANSI C standard was approved (also called C89; adopted by ISO in 1990). Later versions are C99, C11 and C17.

    Features of C

    • Structured and procedural: programs are divided into functions
    • Middle-level language: has both high-level and low-level (bit and memory) features
    • Portable: the same program can run on different computers with little change
    • Fast and efficient programs
    • Small language: only 32 keywords (in ANSI C), with a rich library of functions
    • Extensible: users can add their own functions and libraries
    • Case sensitive: Sum and sum are different
    • Supports pointers and direct memory access

    Advantages and Disadvantages

    AdvantagesDisadvantages
    Fast, efficient and portableNo object-oriented features (unlike C++/Java)
    Easy to learn compared with other system languagesNo automatic checking of array limits
    Used on all kinds of machines, from microcontrollers to supercomputersPointers can cause hard-to-find errors
    Base for many other languages (C++, Java, C#)Weak error detection at run time
    Rich set of operators and library functionsLarge programs can become hard to manage

    Applications of C

    Operating systems (UNIX, Linux kernel, parts of Windows) ┬╖ embedded systems and microcontrollers ┬╖ compilers and interpreters ┬╖ database software ┬╖ device drivers ┬╖ games and graphics ┬╖ network software.


    5.2.2 Structure of a C Program

    Documentation section   тЖТ comments describing the program
    Link section            тЖТ #include header files
    Definition section      тЖТ #define constants
    Global declaration      тЖТ variables used by the whole program
    main() function         тЖТ the program starts here
        declarations
        statements
    
    #include <stdio.h>
    
    int main(void)
    {
        printf("Hello, World!\n");
        return 0;
    }
    

    Output

    Hello, World!
    
    LineExplanation
    #include <stdio.h>Includes the standard input/output header file (needed for printf and scanf)
    int main(void)The main function; execution of every C program starts here
    { }Braces mark the beginning and end of the function body
    printf("...");Displays output on the screen
    \nNew-line character
    return 0;Ends the program and returns 0 to the operating system, meaning success
    ;Every statement ends with a semicolon

    Comments are ignored by the compiler: // single line and /* multiple lines */.

    Compiling and running a C program


    5.2.3 Preprocessor Directives and Header Files

    Preprocessor directives are lines beginning with # that are processed before compilation.

    DirectiveUse
    #includeAdds the contents of a header file
    #defineDefines a constant or macro, e.g. #define PI 3.1416
    #ifdef, #ifndef, #endifConditional compilation

    A header file (extension .h) contains declarations of library functions, constants and data types. It is included at the top of the program.

    Header filePurposeCommon functions
    stdio.hStandard input/outputprintf(), scanf(), getchar(), putchar(), gets(), puts()
    conio.hConsole I/O (old Turbo C/DOS compilers only; not standard C)getch(), clrscr()
    math.hMathematical functionssqrt(), pow(), sin(), cos(), log(), ceil(), floor()
    string.hString handlingstrlen(), strcpy(), strcat(), strcmp()
    ctype.hCharacter testing/conversiontoupper(), tolower(), isalpha(), isdigit()
    stdlib.hGeneral utilitiesrand(), exit(), abs(), atoi()

    5.2.4 Character Set and Tokens

    The character set of C consists of: alphabets (AтАУZ, aтАУz), digits (0тАУ9), special symbols (+ - * / = ( ) { } [ ] < > ; , . " ' ! # % & _) and white-space characters (blank, tab, new line).

    Tokens are the smallest individual units of a C program.

    TokenMeaningExample
    KeywordReserved word with a fixed meaningint, if, while, return
    IdentifierName given to a variable, array or functionsum, marks, main
    ConstantFixed value100, 3.14, 'A'
    OperatorSymbol that performs an operation+, >, &&
    Special symbolPunctuation with special meaning;, { }, ( ), ,
    StringCharacters in double quotes"Nepal"

    Keywords (32 in ANSI C)

    auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while

    Rules for naming identifiers (variables)

    1. Must begin with a letter or underscore (_), not a digit
    2. May contain letters, digits and underscore only (no spaces or special symbols)
    3. Case sensitive (Age and age are different)
    4. A keyword cannot be used as a name
    5. Should have a meaningful name (total, not x1y2)

    Valid: sum, _count, total_marks, num1. Invalid: 1num, total marks, int, my-name.

    Constants and variables

    Type of constantExample
    Integer constant25, -8
    Real (floating) constant3.14, -0.5
    Character constant'A', '5' (single quotes)
    String constant"Hello" (double quotes)
    int age;              /* declaration */
    age = 16;             /* assignment  */
    float marks = 85.5;   /* declaration with initialization */
    const float PI = 3.14159;   /* constant variable */
    

    5.2.5 Data Types in C

    Data typeTypical sizeFormat specifierUse
    char1 byte%cA single character
    int4 bytes*%dWhole numbers
    float4 bytes%fReal numbers (about 6тАУ7 digits of precision)
    double8 bytes%lf (input), %f (output)Real numbers (about 15 digits of precision)
    voidnoneтАУNo value (function returns nothing)

    *int is 4 bytes on modern compilers (it was 2 bytes in old Turbo C).

    Modifiers: short, long, signed, unsigned change the size or range, e.g. unsigned int (only 0 and positive values), long int, long long.

    #include <stdio.h>
    
    int main(void)
    {
        printf("char   : %d byte(s)\n", (int) sizeof(char));
        printf("int    : %d byte(s)\n", (int) sizeof(int));
        printf("float  : %d byte(s)\n", (int) sizeof(float));
        printf("double : %d byte(s)\n", (int) sizeof(double));
        return 0;
    }
    

    Output

    char   : 1 byte(s)
    int    : 4 byte(s)
    float  : 4 byte(s)
    double : 8 byte(s)
    

    Type conversion: In an expression with mixed types, C converts automatically to the larger type (implicit). A programmer can force a conversion using a type cast, e.g. (float) sum / 5.


    5.2.6 Operators and Expressions

    An expression is a combination of operands and operators that gives a value.

    CategoryOperatorsExample
    Arithmetic+ - * / %17 % 5 gives 2
    Relational== != > < >= <=a > b gives 1 (true) or 0 (false)
    Logical&& (AND), || (OR), ! (NOT)(a > 5) && (b < 10)
    Assignment= += -= *= /= %=x += 5 means x = x + 5
    Increment / Decrement++ --x++, ++x, x--, --x
    Conditional (ternary)condition ? value1 : value2max = (a > b) ? a : b;
    Bitwise& | ^ ~ << >>12 & 10 gives 8
    Specialsizeof, , (comma)sizeof(int)

    Notes

    • Division of two integers gives an integer result: 17 / 5 is 3.
    • x++ (post-increment) uses the value first and then adds 1; ++x (pre-increment) adds 1 first and then uses the value.
    • = is assignment; == is comparison.
    #include <stdio.h>
    
    int main(void)
    {
        int a = 17, b = 5;
        int x = 5, y, z;
    
        printf("a + b = %d\n", a + b);
        printf("a - b = %d\n", a - b);
        printf("a * b = %d\n", a * b);
        printf("a / b = %d\n", a / b);
        printf("a %% b = %d\n", a % b);
    
        printf("a > b  : %d\n", a > b);
        printf("a == b : %d\n", a == b);
        printf("(a > 10) && (b > 10) : %d\n", (a > 10) && (b > 10));
        printf("(a > 10) || (b > 10) : %d\n", (a > 10) || (b > 10));
    
        y = x++;   /* y gets 5, then x becomes 6 */
        z = ++x;   /* x becomes 7, then z gets 7 */
        printf("x = %d, y = %d, z = %d\n", x, y, z);
    
        printf("Larger of a and b = %d\n", (a > b) ? a : b);
        return 0;
    }
    

    Output

    a + b = 22
    a - b = 12
    a * b = 85
    a / b = 3
    a % b = 2
    a > b  : 1
    a == b : 0
    (a > 10) && (b > 10) : 0
    (a > 10) || (b > 10) : 1
    x = 7, y = 5, z = 7
    Larger of a and b = 17
    

    Bitwise operators work on individual bits (12 = 1100, 10 = 1010).

    #include <stdio.h>
    
    int main(void)
    {
        int a = 12, b = 10;   /* 12 = 1100, 10 = 1010 */
    
        printf("a & b  = %d\n", a & b);
        printf("a | b  = %d\n", a | b);
        printf("a ^ b  = %d\n", a ^ b);
        printf("~a     = %d\n", ~a);
        printf("a << 1 = %d\n", a << 1);
        printf("a >> 1 = %d\n", a >> 1);
        return 0;
    }
    

    Output

    a & b  = 8
    a | b  = 14
    a ^ b  = 6
    ~a     = -13
    a << 1 = 24
    a >> 1 = 6
    

    Operator precedence (highest to lowest)

    OrderOperators
    1( ) brackets
    2! ++ -- (unary)
    3* / %
    4+ -
    5< <= > >=
    6== !=
    7&&
    8||
    9?:
    10= += -= etc.

    5.2.7 Input and Output in C

    Output: printf()

    printf("format string", variables);
    

    Input: scanf()

    scanf("format specifiers", &variable);
    

    The address-of operator & is required before the variable name (not for strings).

    SpecifierData
    %dint
    %ffloat
    %lfdouble (in scanf)
    %cchar
    %sstring
    Escape sequenceMeaning
    \nNew line
    \tTab (horizontal space)
    \\Backslash
    \"Double quote
    \0Null character (end of string)
    FunctionPurpose
    getchar() / putchar()Read / write a single character
    gets() / puts()Read / write a line of text. (gets() is unsafe and removed from newer C standards; fgets() is preferred.)
    getch() (conio.h)Read a character without showing it (Turbo C only)
    #include <stdio.h>
    
    int main(void)
    {
        int a, b, sum;
    
        printf("Enter two numbers: ");
        scanf("%d %d", &a, &b);
    
        sum = a + b;
        printf("Sum = %d\n", sum);
        return 0;
    }
    

    Output

    Enter two numbers: 10 20
    Sum = 30
    
    #include <stdio.h>
    
    int main(void)
    {
        float p, t, r, si;
    
        printf("Enter principal, time and rate: ");
        scanf("%f %f %f", &p, &t, &r);
    
        si = (p * t * r) / 100;
        printf("Simple Interest = %.2f\n", si);
        return 0;
    }
    

    Output

    Enter principal, time and rate: 5000 2 10
    Simple Interest = 1000.00
    
    #include <stdio.h>
    
    int main(void)
    {
        int a = 10, b = 20, temp;
    
        printf("Before swapping: a = %d, b = %d\n", a, b);
        temp = a;
        a = b;
        b = temp;
        printf("After swapping : a = %d, b = %d\n", a, b);
        return 0;
    }
    

    Output

    Before swapping: a = 10, b = 20
    After swapping : a = 20, b = 10
    

    5.2.8 Control Statements in C

    A. Selection (decision) statements

    Syntax of the forms of if

    if (condition)                    if (condition)                    if (condition1)
    {                                 {                                 {   statements 1;  }
        statements;                       statements 1;                 else if (condition2)
    }                                 }                                 {   statements 2;  }
                                      else                              else
                                      {                                 {   statements 3;  }
                                          statements 2;
                                      }
    

    1. if statement

    #include <stdio.h>
    
    int main(void)
    {
        int n;
    
        printf("Enter a number: ");
        scanf("%d", &n);
    
        if (n > 0)
        {
            printf("%d is positive.\n", n);
        }
        return 0;
    }
    

    Output

    Enter a number: 25
    25 is positive.
    

    2. if-else statement

    #include <stdio.h>
    
    int main(void)
    {
        int x, y;
    
        printf("Enter two numbers: ");
        scanf("%d %d", &x, &y);
    
        if (x > y)
            printf("%d is greater.\n", x);
        else
            printf("%d is greater.\n", y);
        return 0;
    }
    

    Output

    Enter two numbers: 12 25
    25 is greater.
    
    #include <stdio.h>
    
    int main(void)
    {
        int num;
    
        printf("Enter an integer: ");
        scanf("%d", &num);
    
        if (num % 2 == 0)
            printf("%d is an even number.\n", num);
        else
            printf("%d is an odd number.\n", num);
        return 0;
    }
    

    Output

    Enter an integer: 27
    27 is an odd number.
    

    3. else-if ladder

    #include <stdio.h>
    
    int main(void)
    {
        int p, q, r;
    
        printf("Enter three numbers: ");
        scanf("%d %d %d", &p, &q, &r);
    
        if (p > q && p > r)
            printf("%d is the greatest.\n", p);
        else if (q > r)
            printf("%d is the greatest.\n", q);
        else
            printf("%d is the greatest.\n", r);
        return 0;
    }
    

    Output

    Enter three numbers: 45 78 32
    78 is the greatest.
    

    4. Nested if

    #include <stdio.h>
    
    int main(void)
    {
        int x, y;
    
        printf("Enter two numbers: ");
        scanf("%d %d", &x, &y);
    
        if (x > 0 && y > 0)
        {
            if (x > y)
                printf("%d is greater.\n", x);
            else
                printf("%d is greater.\n", y);
        }
        else
        {
            printf("One or both numbers are not positive.\n");
        }
        return 0;
    }
    

    Output

    Enter two numbers: 15 9
    15 is greater.
    

    5. switch statement

    switch selects one of many blocks by matching the value of an expression with case labels. break is used to leave the switch after a match; default runs if no case matches.

    switch (expression)
    {
        case value1: statements; break;
        case value2: statements; break;
        default: statements;
    }
    
    #include <stdio.h>
    
    int main(void)
    {
        int day;
    
        printf("Enter a number (1-7): ");
        scanf("%d", &day);
    
        switch (day)
        {
            case 1: printf("Sunday\n");    break;
            case 2: printf("Monday\n");    break;
            case 3: printf("Tuesday\n");   break;
            case 4: printf("Wednesday\n"); break;
            case 5: printf("Thursday\n");  break;
            case 6: printf("Friday\n");    break;
            case 7: printf("Saturday\n");  break;
            default: printf("Out of range\n");
        }
        return 0;
    }
    

    Output

    Enter a number (1-7): 3
    Tuesday
    
    #include <stdio.h>
    
    int main(void)
    {
        float a, b;
        char op;
    
        printf("Enter number, operator (+ - * /), number: ");
        scanf("%f %c %f", &a, &op, &b);
    
        switch (op)
        {
            case '+': printf("Result = %.2f\n", a + b); break;
            case '-': printf("Result = %.2f\n", a - b); break;
            case '*': printf("Result = %.2f\n", a * b); break;
            case '/':
                if (b != 0)
                    printf("Result = %.2f\n", a / b);
                else
                    printf("Cannot divide by zero.\n");
                break;
            default:
                printf("Invalid operator.\n");
        }
        return 0;
    }
    

    Output

    Enter number, operator (+ - * /), number: 12 + 5
    Result = 17.00
    

    B. Iteration (looping) statements

    A loop repeats a block of statements while a condition is true.

    • Entry-controlled loops (while, for): the condition is checked before the body, so the body may run zero times.
    • Exit-controlled loop (do-while): the condition is checked after the body, so the body runs at least once.
    while (condition)            do                           for (initialization; condition; update)
    {                            {                            {
        statements;                  statements;                  statements;
        update;                  } while (condition);         }
    }
    
    LoopChecks conditionMinimum executionsSemicolon after condition
    whileBefore the body0No
    do-whileAfter the body1Yes (while (condition);)
    forBefore the body0No

    1. while loop

    #include <stdio.h>
    
    int main(void)
    {
        int i = 1;
    
        while (i <= 10)
        {
            printf("%d ", i);
            i++;
        }
        printf("\n");
        return 0;
    }
    

    Output

    1 2 3 4 5 6 7 8 9 10 
    

    2. do-while loop

    #include <stdio.h>
    
    int main(void)
    {
        int a = 100;
    
        do
        {
            printf("%d ", a);
            a--;
        } while (a >= 1);
    
        printf("\n");
        return 0;
    }
    

    Output

    100 99 98 97 96 95 ... 5 4 3 2 1
    

    3. for loop

    #include <stdio.h>
    
    int main(void)
    {
        int i, m;
    
        for (i = 1; i <= 10; i++)
        {
            m = 7 * i;
            printf("7 x %d = %d\n", i, m);
        }
        return 0;
    }
    

    Output

    7 x 1 = 7
    7 x 2 = 14
    7 x 3 = 21
    7 x 4 = 28
    7 x 5 = 35
    7 x 6 = 42
    7 x 7 = 49
    7 x 8 = 56
    7 x 9 = 63
    7 x 10 = 70
    

    Difference between while and do-while loops

    while loopdo-while loop
    Condition is tested before the loop bodyCondition is tested after the loop body
    Entry-controlled loopExit-controlled loop
    The body may never executeThe body executes at least once
    No semicolon after while (condition)Semicolon needed after while (condition);
    Example: while (i <= 5) { ... }Example: do { ... } while (i <= 5);

    4. Nested loops

    A loop inside another loop. For each pass of the outer loop, the inner loop runs completely.

    #include <stdio.h>
    
    int main(void)
    {
        int i, j;
    
        for (i = 1; i <= 4; i++)
        {
            for (j = 1; j <= i; j++)
                printf("* ");
            printf("\n");
        }
        return 0;
    }
    

    Output

    * 
    * * 
    * * * 
    * * * * 
    

    C. Jump statements

    StatementAction
    breakTerminates the loop (or switch) immediately and control goes to the statement after it
    continueSkips the rest of the current iteration and goes to the next iteration of the loop
    goto labelJumps to a labelled statement (should be avoided because it makes programs hard to follow)
    returnLeaves the function (ends main)
    #include <stdio.h>
    
    int main(void)
    {
        int i;
    
        for (i = 1; i <= 10; i++)
        {
            if (i == 6)
                break;
            printf("%d ", i);
        }
        printf("\nLoop ended at i = %d\n", i);
        return 0;
    }
    

    Output

    1 2 3 4 5 
    Loop ended at i = 6
    
    #include <stdio.h>
    
    int main(void)
    {
        int i;
    
        for (i = 1; i <= 10; i++)
        {
            if (i % 2 == 0)
                continue;
            printf("%d ", i);
        }
        printf("\n");
        return 0;
    }
    

    Output

    1 3 5 7 9 
    

    Difference between break and continue

    breakcontinue
    Ends the whole loop (or the switch)Skips only the current iteration
    Control moves outside the loopControl moves to the next iteration of the same loop
    Can be used in loops and switchUsed only in loops
    Example: stop searching when an item is foundExample: skip even numbers

    5.2.9 Common Programs (Practice)

    1. Reverse of a number

    #include <stdio.h>
    
    int main(void)
    {
        int n, rem, rev = 0;
    
        printf("Enter an integer: ");
        scanf("%d", &n);
    
        while (n != 0)
        {
            rem = n % 10;
            rev = rev * 10 + rem;
            n = n / 10;
        }
        printf("Reversed number = %d\n", rev);
        return 0;
    }
    

    Output

    Enter an integer: 1234
    Reversed number = 4321
    

    2. Factorial of a number (5! = 5 ├Ч 4 ├Ч 3 ├Ч 2 ├Ч 1)

    #include <stdio.h>
    
    int main(void)
    {
        int n, i;
        unsigned long long fact = 1;
    
        printf("Enter a positive integer: ");
        scanf("%d", &n);
    
        if (n < 0)
        {
            printf("Factorial of a negative number does not exist.\n");
        }
        else
        {
            for (i = 1; i <= n; i++)
                fact = fact * i;
            printf("Factorial of %d = %llu\n", n, fact);
        }
        return 0;
    }
    

    Output

    Enter a positive integer: 5
    Factorial of 5 = 120
    

    3. Fibonacci series (each term is the sum of the previous two)

    #include <stdio.h>
    
    int main(void)
    {
        int n, i, a = 0, b = 1, next;
    
        printf("Enter number of terms: ");
        scanf("%d", &n);
    
        printf("Fibonacci series: ");
        for (i = 1; i <= n; i++)
        {
            printf("%d ", a);
            next = a + b;
            a = b;
            b = next;
        }
        printf("\n");
        return 0;
    }
    

    Output

    Enter number of terms: 8
    Fibonacci series: 0 1 1 2 3 5 8 13 
    

    4. Armstrong number (a 3-digit number equal to the sum of the cubes of its digits: 153 = 1┬│ + 5┬│ + 3┬│)

    #include <stdio.h>
    
    int main(void)
    {
        int num, temp, rem, sum = 0;
    
        printf("Enter a three-digit number: ");
        scanf("%d", &num);
    
        temp = num;
        while (temp != 0)
        {
            rem = temp % 10;
            sum = sum + rem * rem * rem;
            temp = temp / 10;
        }
    
        if (sum == num)
            printf("%d is an Armstrong number.\n", num);
        else
            printf("%d is not an Armstrong number.\n", num);
        return 0;
    }
    

    Output

    Enter a three-digit number: 153
    153 is an Armstrong number.
    

    5. Prime number (divisible only by 1 and itself)

    #include <stdio.h>
    
    int main(void)
    {
        int n, i, flag = 0;
    
        printf("Enter a positive integer: ");
        scanf("%d", &n);
    
        if (n < 2)
            flag = 1;
    
        for (i = 2; i <= n / 2; i++)
        {
            if (n % i == 0)
            {
                flag = 1;
                break;
            }
        }
    
        if (flag == 0)
            printf("%d is a prime number.\n", n);
        else
            printf("%d is not a prime number.\n", n);
        return 0;
    }
    

    Output

    Enter a positive integer: 29
    29 is a prime number.
    

    6. Palindrome number (reads the same forwards and backwards)

    #include <stdio.h>
    
    int main(void)
    {
        int n, temp, rem, rev = 0;
    
        printf("Enter an integer: ");
        scanf("%d", &n);
    
        temp = n;
        while (temp != 0)
        {
            rem = temp % 10;
            rev = rev * 10 + rem;
            temp = temp / 10;
        }
    
        if (rev == n)
            printf("%d is a palindrome.\n", n);
        else
            printf("%d is not a palindrome.\n", n);
        return 0;
    }
    

    Output

    Enter an integer: 121
    121 is a palindrome.
    

    7. Sum of digits

    #include <stdio.h>
    
    int main(void)
    {
        int n, sum = 0;
    
        printf("Enter an integer: ");
        scanf("%d", &n);
    
        while (n != 0)
        {
            sum = sum + n % 10;
            n = n / 10;
        }
        printf("Sum of digits = %d\n", sum);
        return 0;
    }
    

    Output

    Enter an integer: 1234
    Sum of digits = 10
    

    5.2.10 Arrays

    An array is a collection of elements of the same data type stored in continuous memory locations under one name. Elements are accessed by an index (subscript), which starts from 0.

    data_type array_name[size];
    int marks[5];                          /* declaration */
    int marks[5] = {70, 85, 60, 90, 75};   /* declaration with initialization */
    
    Index01234
    marks7085609075

    marks[0] is 70 and the last element is marks[4]. If the array has n elements, the indexes run from 0 to n тИТ 1.

    One-dimensional array

    #include <stdio.h>
    
    int main(void)
    {
        int marks[5], i, sum = 0, max;
        float avg;
    
        printf("Enter 5 marks: ");
        for (i = 0; i < 5; i++)
            scanf("%d", &marks[i]);
    
        max = marks[0];
        for (i = 0; i < 5; i++)
        {
            sum = sum + marks[i];
            if (marks[i] > max)
                max = marks[i];
        }
        avg = (float) sum / 5;
    
        printf("Sum = %d\n", sum);
        printf("Average = %.2f\n", avg);
        printf("Largest = %d\n", max);
        return 0;
    }
    

    Output

    Enter 5 marks: 70 85 60 90 75
    Sum = 380
    Average = 76.00
    Largest = 90
    

    Two-dimensional array (matrix)

    A two-dimensional array has rows and columns: data_type name[rows][columns];

    int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
    
    Column 0Column 1Column 2
    Row 0a[0][0] = 1a[0][1] = 2a[0][2] = 3
    Row 1a[1][0] = 4a[1][1] = 5a[1][2] = 6
    #include <stdio.h>
    
    int main(void)
    {
        int a[2][3] = {{1, 2, 3}, {4, 5, 6}};
        int b[2][3] = {{1, 1, 1}, {2, 2, 2}};
        int c[2][3], i, j;
    
        for (i = 0; i < 2; i++)
            for (j = 0; j < 3; j++)
                c[i][j] = a[i][j] + b[i][j];
    
        printf("Sum of the matrices:\n");
        for (i = 0; i < 2; i++)
        {
            for (j = 0; j < 3; j++)
                printf("%d ", c[i][j]);
            printf("\n");
        }
        return 0;
    }
    

    Output

    Sum of the matrices:
    2 3 4 
    6 7 8 
    

    5.2.11 Strings

    A string is a sequence of characters. In C, a string is a character array that ends with the null character '\0'.

    char name[10] = "Nepal";   /* stored as N e p a l \0 */
    
    Index012345
    nameNepal\0
    • scanf("%s", name); reads one word (stops at a space).
    • fgets(name, size, stdin); reads a full line including spaces.
    • printf("%s", name); or puts(name); displays the string.

    String handling functions (<string.h>)

    FunctionPurposeExampleResult
    strlen(s)Length of the string (without \0)strlen("Hello")5
    strcpy(s1, s2)Copies s2 into s1strcpy(s1, "Hi")s1 = "Hi"
    strcat(s1, s2)Joins s2 to the end of s1strcat("Hello", "World")"HelloWorld"
    strcmp(s1, s2)Compares two stringsstrcmp("abc", "abc")0 (equal)
    strrev(s)Reverses the stringstrrev("abc")"cba"
    strupr(s) / strlwr(s)Converts to upper / lower casestrupr("abc")"ABC"

    strcmp() returns 0 if the strings are equal, a negative value if s1 is smaller than s2, and a positive value if s1 is larger.

    Note: strrev(), strupr() and strlwr() are not part of standard C; they exist in Turbo C and some old compilers. In standard C use a loop (or toupper() / tolower() from ctype.h), as shown below.

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char s1[20] = "Hello";
        char s2[20] = "World";
        char s3[20];
    
        printf("Length of s1      : %d\n", (int) strlen(s1));
    
        strcpy(s3, s1);
        printf("s3 after strcpy   : %s\n", s3);
    
        strcat(s1, s2);
        printf("s1 after strcat   : %s\n", s1);
    
        if (strcmp(s3, s2) == 0)
            printf("s3 and s2 are equal.\n");
        else
            printf("s3 and s2 are not equal.\n");
        return 0;
    }
    

    Output

    Length of s1      : 5
    s3 after strcpy   : Hello
    s1 after strcat   : HelloWorld
    s3 and s2 are not equal.
    

    Reverse a string without strrev()

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        char str[50], rev[50];
        int i, len;
    
        printf("Enter a string: ");
        scanf("%49s", str);
    
        len = (int) strlen(str);
        for (i = 0; i < len; i++)
            rev[i] = str[len - 1 - i];
        rev[len] = '\0';
    
        printf("Reversed string: %s\n", rev);
        return 0;
    }
    

    Output

    Enter a string: computer
    Reversed string: retupmoc
    

    Convert a string to uppercase using toupper()

    #include <stdio.h>
    #include <ctype.h>
    
    int main(void)
    {
        char str[] = "nepal";
        int i;
    
        for (i = 0; str[i] != '\0'; i++)
            str[i] = toupper(str[i]);
    
        printf("Uppercase: %s\n", str);
        return 0;
    }
    

    Output

    Uppercase: NEPAL
    

    Count the vowels in a string

    #include <stdio.h>
    #include <ctype.h>
    
    int main(void)
    {
        char str[] = "Education";
        int i, count = 0;
    
        for (i = 0; str[i] != '\0'; i++)
        {
            char ch = tolower(str[i]);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                count++;
        }
        printf("Number of vowels in %s = %d\n", str, count);
        return 0;
    }
    

    Output

    Number of vowels in Education = 5
    

    Quick Revision

    • Program = instructions; software = programs + data + documents.
    • Low-level: machine (0/1), assembly (mnemonics + assembler). High-level: 3GL, 4GL, 5GL (compiler/interpreter).
    • Compiler: whole program at once, creates object file. Interpreter: line by line, stops at first error.
    • Errors: syntax (grammar, found by compiler), logical (wrong output), runtime (during execution).
    • Algorithm = steps in words; flowchart = diagram; pseudocode = code-like English.
    • Control structures: sequence, selection (if, switch), iteration (while, do-while, for).
    • C: created by Dennis Ritchie (Bell Labs, 1972); ANSI standard 1989; case sensitive; 32 keywords.
    • Structure: #include, main(), { }, statements end with ;.
    • while / for may run 0 times; do-while runs at least once.
    • break leaves the loop; continue skips one iteration.
    • Array: same type, index from 0. String: char array ending with '\0'.
    • strlen, strcpy, strcat, strcmp are standard string functions.

    Practice Questions

    Short Answer

    1. What is a program? Differentiate between program and software.
    2. What is a programming language? Explain its types with merits and demerits.
    3. Differentiate between compiler and interpreter.
    4. What is an error? Briefly explain its types.
    5. Differentiate between syntax error and logical (semantic) error.
    6. Define algorithm and flowchart with suitable examples.
    7. What is a control structure? Differentiate between break and continue with examples.
    8. What is looping? Differentiate between while and do-while loops with examples.
    9. What is a data type? Explain the types of operators in C with examples.
    10. Define array. What is a string? Explain any four string handling functions with examples.
    11. Write short notes on: (a) pseudocode (b) decision table (c) ASCII and Unicode (d) preprocessor directive.

    Long Answer

    1. What is C? Write its features, advantages and applications.
    2. Explain the control structures with algorithms and flowcharts.

    Programming Practice Write a C program to: (a) check whether a number is even or odd; (b) find the factorial of a number; (c) display the Fibonacci series; (d) check Armstrong, prime and palindrome numbers; (e) find the sum and average of array elements; (f) reverse a string without using strrev().


    End of Unit 5 notes.