Programming in C

    Programming in C

    Reading Mode:

    Unit 4: Programming in C


    Class 12 ┬╖ Computer Science ┬╖ NEB Exam Preparation Guide

    How to use this chapter: Programming in C is split into five short parts so each page loads quickly and is easy to revise. Start here, because this page covers the fundamentals (data types, variables, operators, storage classes) that every later program depends on. Every program in this chapter was compiled and run, and the sample output shown is real. Type the programs yourself instead of only reading them.


    Chapter Map

    PartPageWhat it covers
    1Fundamentals (this page)Introduction to C, program structure, preprocessor, tokens, data types, variables, constants, operators, storage classes
    2Control Structures and Loopsif, switch, for, while, do...while, break, continue, goto, common number programs
    3Arrays and StringsOne- and two-dimensional arrays, matrices, string functions
    4Functions, Structures and UnionsUser-defined functions, recursion, call by value and reference, structures, unions
    5Pointers and File HandlingPointers, dynamic memory, text and binary files, fprintf and fscanf

    Where to find each NEB important question

    QuestionTopicPage
    1тАУ2What is C? Features, advantages and disadvantagesPart 1
    3Data typesPart 1
    4Variables and their typesPart 1
    5OperatorsPart 1
    11Storage classes: automatic vs externalPart 1
    6Control structures, break vs continuePart 2
    7Looping, while vs do...whilePart 2
    8Arrays, strings, string functionsPart 3
    9тАУ10Functions, features, types, recursionPart 4
    12тАУ14Structure, array vs structure, structure vs unionPart 4
    16Call by value and call by referencePart 4
    15, 17, 18Pointers, array vs pointer, structure vs pointerPart 5
    19тАУ20Sequential vs random access, fprintf vs fscanfPart 5

    Table of Contents

    1. Introduction to C
    2. Features, Advantages and Disadvantages
    3. Structure of a C Program
    4. How a C Program Is Developed and Run
    5. Preprocessor and Header Files
    6. Character Set, Identifiers, Keywords and Tokens
    7. Data Types
    8. Variables and Constants
    9. Format Specifiers and Escape Sequences
    10. Input and Output Functions
    11. Operators
    12. Storage Classes
    13. Turbo C and Modern Compilers
    14. Quick Revision Table
    15. Practice Questions

    1. Introduction to C

    What is C?

    C is a general-purpose, structured (procedural) programming language. It is a compiled language: a program called a compiler translates the whole source program into machine code before it runs.

    C is often called a middle-level language because it combines the readable, English-like statements of a high-level language with the low-level abilities of assembly language, such as working directly with memory addresses and individual bits.

    Correction to a common textbook line: C is a compiled language that uses a compiler. It is not "a compiler" itself.

    Development of C

    YearLanguage / eventDeveloped by
    1960ALGOL 60International committee
    1967BCPLMartin Richards
    1970BKen Thompson (Bell Labs)
    1972CDennis Ritchie (Bell Labs)
    1973UNIX operating system rewritten in CRitchie and Thompson
    1978Book The C Programming Language (known as K&R C)Kernighan and Ritchie
    1989ANSI C standard (C89), adopted by ISO in 1990ANSI / ISO
    1999 and laterC99, C11, C17ISO

    2. Features, Advantages and Disadvantages

    Features of C

    1. Simple and efficient: a small set of keywords (32) and a clear structure
    2. Structured: programs are divided into functions (modules)
    3. Portable: the same program can be compiled on different computers with little change
    4. Fast: compiled code runs close to the speed of the hardware
    5. Rich library: hundreds of ready-made functions (printf, sqrt, strlen)
    6. Pointers: direct access to memory addresses
    7. Low-level access: bitwise operators let you work with individual bits
    8. Extensible: programmers can create their own functions and header files
    9. Case sensitive: Total and total are different names

    Advantages

    AdvantageMeaning
    Machine independent (portable)Programs run on small devices up to mainframes after recompiling
    Easy to learnFew keywords and simple syntax compared with many languages
    EfficientFast execution and low memory use
    Foundation languageC++, Java, C# and many others borrow its syntax; operating systems such as UNIX and Linux are written in C
    Good for system programmingPointers and bit operations allow control of hardware

    Disadvantages

    DisadvantageMeaning
    No run-time checkingC does not check array limits, so an invalid index can silently corrupt data
    Weak error detectionMany mistakes are found only when the program misbehaves
    Hard to maintain large programsWithout objects, big programs become difficult to manage
    No object-oriented supportNo classes, inheritance or polymorphism (C++ adds these)
    Manual memory managementThe programmer must allocate and free memory
    No exception handlingThere is no try...catch

    3. Structure of a C Program

    A C program is built from these parts, in this order:

    1. Documentation section      /* comments: program name, author, purpose */
    2. Preprocessor directives    #include <stdio.h>   #define PI 3.14
    3. Global declarations        variables and functions used by the whole program
    4. main() function            execution always starts here
    5. User-defined functions     extra functions written by the programmer
    

    Your first program

    #include <stdio.h>
    
    int main(void)
    {
        printf("Hello, NEB Class 12!\n");
        return 0;
    }
    

    Output:

    Hello, NEB Class 12!
    

    A program with input, processing and output

    #include <stdio.h>                  /* preprocessor directive */
    
    int main(void)                      /* every C program starts from main() */
    {
        int a, b, sum;                  /* declaration of variables */
    
        printf("Enter two numbers: ");
        scanf("%d %d", &a, &b);         /* input */
        sum = a + b;                    /* processing */
        printf("Sum = %d\n", sum);      /* output */
        return 0;
    }
    

    Sample run:

    Enter two numbers: 12 8
    Sum = 20
    

    Line-by-line explanation

    LineMeaning
    #include <stdio.h>Adds the standard input/output library so printf and scanf can be used
    int main(void)The main function. The program starts here. int means it returns a number to the operating system
    { }Braces mark the start and end of a block of statements
    int a, b, sum;Declares three integer variables
    scanf("%d %d", &a, &b);Reads two integers from the keyboard. & gives the address where the value is stored
    printf(...)Prints text and values on the screen
    return 0;Tells the operating system that the program finished successfully

    Rules to remember

    • Every statement ends with a semicolon ;
    • C is case sensitive: main() works, Main() does not
    • Keywords are written in lowercase
    • Variables must be declared before use
    • Comments are written as /* ... */ or // ... and are ignored by the compiler

    4. How a C Program Is Developed and Run

    Writing a C program has four main stages:

    prog.c --> [Preprocessor] --> [Compiler] --> prog.obj --> [Linker + libraries] --> prog.exe --> RUN
     (edit)     handles # lines     checks syntax,   object        joins library          executable
                                    translates       code          code                   program
    
    StageWhat happens
    1. EditingThe programmer types the source code and saves it with the .c extension
    2. PreprocessingLines beginning with # are processed (header files are inserted, macros replaced)
    3. CompilingThe compiler checks the syntax and translates the code into object code (.obj or .o)
    4. LinkingThe linker joins the object code with library code to make the executable file
    5. ExecutingThe executable runs and produces output

    Types of errors

    ErrorWhen it appearsExample
    Syntax errorAt compile timeMissing semicolon, misspelled keyword
    Linker errorAt link timeCalling a function that does not exist
    Run-time errorWhile the program runsDividing by zero
    Logical errorProgram runs but gives wrong outputUsing + instead of *

    5. Preprocessor and Header Files

    Preprocessor

    The preprocessor is a program that runs before the compiler. Any line beginning with # is a preprocessor directive. It does not end with a semicolon.

    TypeDirectivePurpose
    File inclusion#includeInserts the contents of a header file
    Macro substitution#define, #undefReplaces a name with a value or expression
    Conditional compilation#if, #ifdef, #ifndef, #else, #endifCompiles parts of the code only when a condition is true
    Other#pragma, #errorCompiler-specific instructions and error messages

    #include <stdio.h> searches the compiler's standard folders. #include "myfile.h" searches the current folder first, so it is used for your own header files.

    #include <stdio.h>
    #define SQUARE(x) ((x) * (x))       /* macro with an argument */
    #define COLLEGE "StudyHub College"  /* object-like macro */
    #define DEBUG
    
    int main(void)
    {
        printf("College     : %s\n", COLLEGE);
        printf("Square of 5 : %d\n", SQUARE(5));
    #ifdef DEBUG
        printf("Debug mode is ON\n");
    #endif
    #ifndef VERSION
        printf("VERSION is not defined\n");
    #endif
        return 0;
    }
    

    Output:

    College     : StudyHub College
    Square of 5 : 25
    Debug mode is ON
    VERSION is not defined
    

    Header files

    A header file (extension .h) contains declarations of library functions, constants and macros. Including it tells the compiler what the library functions look like.

    Header filePurposeCommon functions
    stdio.hStandard input and outputprintf(), scanf(), getchar(), putchar(), puts(), fgets(), fopen(), fclose()
    conio.hConsole I/O (old Turbo C only, not standard)getch(), getche(), clrscr()
    math.hMathematical functionssqrt(), pow(), sin(), cos(), log(), ceil(), floor(), fabs()
    string.hString handlingstrlen(), strcpy(), strcmp(), strcat()
    ctype.hCharacter testing and conversiontoupper(), tolower(), isalpha(), isdigit(), isupper(), isspace(), isalnum()
    stdlib.hGeneral utilitiesmalloc(), calloc(), free(), rand(), exit(), abs(), atoi()
    complex.hComplex number arithmeticcabs(), csqrt(), cpow()

    A library function is a ready-made function supplied with the compiler, such as printf(), sqrt() or strlen(). A user-defined function is one you write yourself.


    6. Character Set, Identifiers, Keywords and Tokens

    Character set

    The character set is the group of characters a C program is allowed to use.

    GroupCharacters
    AlphabetsAтАУZ and aтАУz
    Digits0тАУ9
    Special symbols+ - * / = ( ) { } [ ] < > , ; : ' " ! # % & _ ~ \ ? .
    White spaceBlank space, tab, new line

    Identifiers

    An identifier is a name given by the programmer to a variable, function, array, structure, and so on.

    Rules:

    1. May contain letters, digits and the underscore _
    2. Must start with a letter or underscore, never a digit
    3. Case sensitive (Text and text are different)
    4. Cannot be a keyword
    5. Cannot contain spaces or special symbols such as @, #, -
    ValidInvalid
    total2marks (starts with a digit)
    _countmy name (contains a space)
    student_agefloat (keyword)
    Roll2net-pay (contains -)

    Keywords

    Keywords are reserved words with a fixed meaning in C. They cannot be used as identifiers. Standard C has 32 keywords, all in lowercase.

    GroupKeywords
    Data typeschar int float double void short long signed unsigned
    Storage classesauto extern register static
    Type qualifiersconst volatile
    Control flowif else switch case default for while do break continue goto return
    User-defined typesstruct union enum typedef
    Operatorsizeof

    near and far seen in some old notes are Turbo C extensions, not standard keywords.

    Tokens

    A token is the smallest meaningful unit in a C program. The compiler breaks the source code into tokens.

    Token typeExamples
    Keywordsint, float, if, for, return
    Identifiersmain, total, student_age
    Constants100, 3.14, 'A'
    String literals"Nepal", "Enter a number"
    Operators+, &&, !, ==
    Punctuators (special symbols); , { } ( ) [ ]

    7. Data Types

    A data type tells the compiler what kind of data a variable will hold, how much memory it needs and which operations are allowed.

    Classification

    CategoryTypes
    Primary (basic)int, char, float, double, void
    Derivedarray, pointer, function
    User-definedstruct, union, enum, typedef

    Primary data types

    Data typeStoresTypical sizeFormat specifierExample
    charOne character1 byte%c'A'
    intWhole number4 bytes (2 bytes in Turbo C)%d250
    floatDecimal number (about 6 digits of precision)4 bytes%f3.14f
    doubleDecimal number (about 15 digits)8 bytes%f in printf, %lf in scanf3.14159265
    long intLarger whole number4 or 8 bytes%ld29164578L
    long doubleVery large decimal number12 or 16 bytes%Lf1.5L
    voidNothing (used for functions with no return value)not applicablenot applicablevoid show()

    Correction: long is a whole-number type (long int), not a floating-point type. Sizes depend on the compiler and computer, so use sizeof to find them.

    Type modifiers: short, long, signed and unsigned change the size or range. For example, unsigned int stores only values from 0 upward, so it can hold larger positive numbers than int.

    Finding sizes with sizeof

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

    Output:

    char        : 1 byte
    short       : 2 bytes
    int         : 4 bytes
    long        : 8 bytes
    float       : 4 bytes
    double      : 8 bytes
    long double : 16 bytes
    

    (The sizes above are from a 64-bit computer. Older compilers such as Turbo C show int as 2 bytes.)

    Using the data types

    #include <stdio.h>
    
    int main(void)
    {
        char grade = 'A';
        int age = 17;
        float height = 5.8f;
        double pi = 3.14159265358979;
        long population = 29164578L;
    
        printf("Grade      : %c\n", grade);
        printf("Age        : %d\n", age);
        printf("Height     : %f\n", height);
        printf("Pi (2 dp)  : %.2f\n", pi);
        printf("Population : %ld\n", population);
        return 0;
    }
    

    Output:

    Grade      : A
    Age        : 17
    Height     : 5.800000
    Pi (2 dp)  : 3.14
    Population : 29164578
    

    8. Variables and Constants

    Variable

    A variable is a named memory location whose value can change while the program runs.

    Declaration syntax:

    data_type variable_name;                 /* declaration */
    data_type variable_name = value;         /* declaration with initialization */
    
    int age;
    float marks = 85.5f;
    char grade = 'A';
    

    Rules for variable names: the same as the identifier rules in section 6. In short, start with a letter or underscore, use only letters, digits and underscores, do not use a keyword, and remember that names are case sensitive.

    Types of variables

    1. Based on the data stored (NEB textbook classification)

    TypeStoresExamples
    Numeric variableWhole or decimal numbersint, float, double
    Character / string variableA single character, or a group of characterschar, character arrays

    C has no separate "string" data type. A string is stored in an array of char.

    2. Based on where they are declared

    TypeDeclaredWorks
    Local variableInside a function or blockOnly inside that function or block
    Global variableOutside all functionsIn every function of the program

    Constants

    A constant is a fixed value that does not change during the program.

    Constant typeExample
    Integer constant100, -25
    Floating-point constant3.14, 0.5
    Character constant'A', '7'
    String constant"Nepal"
    Symbolic constant#define PI 3.14159
    Escape sequence constant'\n', '\t'

    Two ways to create a named constant

    MethodExampleNote
    #define#define PI 3.14159Preprocessor replacement, no semicolon, no data type
    const keywordconst int DAYS = 7;A real variable that cannot be changed
    #include <stdio.h>
    #define PI 3.14159                  /* symbolic constant */
    
    int main(void)
    {
        const int DAYS = 7;             /* constant variable */
        float r = 5.0f;
        float area = PI * r * r;
    
        printf("Days in a week   : %d\n", DAYS);
        printf("Area of circle   : %.2f\n", area);
        printf("Integer constant : %d\n", 100);
        printf("Float constant   : %.1f\n", 3.5);
        printf("Character const  : %c\n", 'x');
        printf("String constant  : %s\n", "Nepal");
        return 0;
    }
    

    Output:

    Days in a week   : 7
    Area of circle   : 78.54
    Integer constant : 100
    Float constant   : 3.5
    Character const  : x
    String constant  : Nepal
    

    9. Format Specifiers and Escape Sequences

    Format specifiers

    A format specifier starts with % and tells printf() and scanf() what type of data to print or read.

    SpecifierData type
    %d or %iint (signed integer)
    %uunsigned int
    %ldlong int
    %ffloat (and double in printf)
    %lfdouble in scanf
    %cchar
    %sString
    %x / %oHexadecimal / octal integer
    %pPointer (memory address)
    %%Prints a % sign

    Controlling the output: %5d prints in a field 5 characters wide, %.2f prints two digits after the decimal point, and %-10s left-aligns a string in 10 characters.

    Escape sequences

    An escape sequence is a backslash \ followed by a character. It represents a special, non-printing character.

    EscapeNameEffect
    \nNew lineMoves to the next line
    \tHorizontal tabMoves to the next tab stop
    \\BackslashPrints \
    \'Single quotePrints '
    \"Double quotePrints "
    \aAlertMakes a beep
    \bBackspaceMoves back one character
    \0Null characterMarks the end of a string
    #include <stdio.h>
    
    int main(void)
    {
        printf("Name\tClass\tRoll\n");
        printf("Ram\t12\t5\n");
        printf("She said, \"C is fun!\"\n");
        printf("Backslash: \\\n");
        printf("Line one\nLine two\n");
        return 0;
    }
    

    Output:

    Name	Class	Roll
    Ram	12	5
    She said, "C is fun!"
    Backslash: \
    Line one
    Line two
    

    10. Input and Output Functions

    FunctionHeaderPurpose
    printf()stdio.hPrints formatted output
    scanf()stdio.hReads formatted input
    getchar()stdio.hReads one character
    putchar()stdio.hPrints one character
    puts()stdio.hPrints a string followed by a new line
    fgets()stdio.hReads a whole line safely, including spaces

    gets() appears in many old notes, but it was removed from the C standard because it can overflow memory. Use fgets() instead.

    #include <stdio.h>
    
    int main(void)
    {
        char ch;
        char name[30];
        int age;
    
        printf("Enter your name (one word) and age: ");
        scanf("%29s %d", name, &age);
        getchar();                      /* remove the newline left by scanf */
    
        printf("Enter one character: ");
        ch = getchar();                 /* read a single character */
    
        printf("The character is: ");
        putchar(ch);                    /* print a single character */
        putchar('\n');
    
        puts("Hello from puts()");      /* prints a string and a newline */
        printf("%s is %d years old.\n", name, age);
        return 0;
    }
    

    Sample run:

    Enter your name (one word) and age: Gita 17
    Enter one character: Z
    The character is: Z
    Hello from puts()
    Gita is 17 years old.
    

    Common scanf() mistakes

    • Forgetting & before the variable (scanf("%d", a) is wrong; use &a). The only exception is a character array, whose name is already an address.
    • scanf("%s", name) stops reading at the first space. Use fgets() to read a full line.
    • Passing several variables with only one format specifier. Each variable needs its own specifier.

    11. Operators

    An operator is a symbol that tells the compiler to perform an operation. The values it works on are operands. A combination of operands and operators is an expression. In a + b, + is the operator and a and b are operands.

    Types of operators

    #TypeOperatorsExample
    1Arithmetic+ - * / %a + b
    2Relational< > <= >= == !=a > b
    3Logical&& || !(a > b) && (a > c)
    4Assignment= += -= *= /= %=a += 5
    5Increment / decrement (unary)++ --a++, --a
    6Conditional (ternary)? :(a > b) ? a : b
    7Bitwise& | ^ ~ << >>a & b
    8Comma,a = 1, b = 2
    9sizeofsizeofsizeof(int)

    Key points about each type

    • Arithmetic: / on two integers gives an integer result (10 / 3 is 3). % gives the remainder and works only with integers. To get a decimal result, make one operand a float (10 / 3.0 or (float)10 / 3).
    • Relational: the result is 1 (true) or 0 (false).
    • Logical: && is true if both sides are true, || is true if at least one is true, ! reverses the result.
    • Increment / decrement: increase or decrease a variable by 1.
    FormNameMeaning
    ++aPre-incrementIncrease a first, then use it
    a++Post-incrementUse a first, then increase it
    --aPre-decrementDecrease first, then use
    a--Post-decrementUse first, then decrease
    • Conditional operator: expression1 ? expression2 : expression3. If expression1 is true (non-zero), the result is expression2, otherwise expression3. It is a short form of if...else.
    #include <stdio.h>
    
    int main(void)
    {
        int a = 10, b = 3, x;
    
        /* Arithmetic */
        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);          /* integer division */
        printf("a %% b = %d\n", a % b);         /* remainder */
    
        /* Relational: result is 1 (true) or 0 (false) */
        printf("a > b  : %d\n", a > b);
        printf("a == b : %d\n", a == b);
    
        /* Logical */
        printf("(a > 5) && (b > 5) : %d\n", (a > 5) && (b > 5));
        printf("(a > 5) || (b > 5) : %d\n", (a > 5) || (b > 5));
        printf("!(a > 5)           : %d\n", !(a > 5));
    
        /* Increment and decrement */
        x = a++;
        printf("x = a++  ->  x = %d, a = %d\n", x, a);
        x = ++a;
        printf("x = ++a  ->  x = %d, a = %d\n", x, a);
    
        /* Assignment */
        a += 5;
        printf("after a += 5 : a = %d\n", a);
    
        /* Conditional (ternary) */
        x = (a > b) ? a : b;
        printf("larger of a and b = %d\n", x);
    
        /* Bitwise */
        printf("6 & 3  = %d\n", 6 & 3);
        printf("6 | 3  = %d\n", 6 | 3);
        printf("6 ^ 3  = %d\n", 6 ^ 3);
        printf("1 << 3 = %d\n", 1 << 3);
    
        /* sizeof */
        printf("sizeof(int) = %zu\n", sizeof(int));
        return 0;
    }
    

    Output:

    a + b = 13
    a - b = 7
    a * b = 30
    a / b = 3
    a % b = 1
    a > b  : 1
    a == b : 0
    (a > 5) && (b > 5) : 0
    (a > 5) || (b > 5) : 1
    !(a > 5)           : 0
    x = a++  ->  x = 10, a = 11
    x = ++a  ->  x = 12, a = 12
    after a += 5 : a = 17
    larger of a and b = 17
    6 & 3  = 2
    6 | 3  = 7
    6 ^ 3  = 5
    1 << 3 = 8
    sizeof(int) = 4
    

    Type casting

    Converting one data type to another is type casting. Write the new type in brackets before the value.

    #include <stdio.h>
    
    int main(void)
    {
        int a = 7, b = 2;
    
        printf("a / b        = %d\n", a / b);          /* integer division */
        printf("(float)a / b = %.2f\n", (float)a / b); /* type casting */
        return 0;
    }
    

    Output:

    a / b        = 3
    (float)a / b = 3.50
    

    Operator precedence (highest to lowest)

    LevelOperatorsAssociativity
    1() []Left to right
    2! ~ ++ -- unary + - * & sizeof (type)Right to left
    3* / %Left to right
    4+ -Left to right
    5<< >>Left to right
    6< <= > >=Left to right
    7== !=Left to right
    8& then ^ then |Left to right
    9&& then ||Left to right
    10? :Right to left
    11= += -= *= /= %=Right to left
    12,Left to right

    Common operator mistakes

    • Writing = (assignment) instead of == (comparison) inside if
    • Expecting 5 / 2 to give 2.5; it gives 2
    • Writing a < b < c; it does not test whether b lies between a and c. Write a < b && b < c

    12. Storage Classes

    A storage class tells the compiler four things about a variable: where it is stored (memory or CPU register), its default (initial) value, its scope (where it can be used) and its lifetime (how long it exists).

    Storage classKeywordStored inDefault valueScopeLifetime
    Automaticauto (default for local variables)Memory (stack)Garbage (unpredictable)Inside the block or functionUntil the block ends
    RegisterregisterCPU register (if available)GarbageInside the block or functionUntil the block ends
    StaticstaticMemory (data area)0Inside the block (or file, if global)Whole program
    ExternalexternMemory (data area)0Whole program (all functions, even other files)Whole program
    #include <stdio.h>
    
    int total = 100;                    /* global (external) variable */
    
    void counter(void)
    {
        int a = 0;                      /* automatic: created again on every call */
        static int s = 0;               /* static: keeps its value between calls */
    
        a++;
        s++;
        printf("auto a = %d, static s = %d\n", a, s);
    }
    
    void show_total(void)
    {
        extern int total;               /* refers to the global variable above */
    
        total = total + 50;
        printf("total inside function = %d\n", total);
    }
    
    int main(void)
    {
        register int i;                 /* hint: keep i in a CPU register */
    
        for (i = 1; i <= 3; i++)
            counter();
        show_total();
        printf("total in main         = %d\n", total);
        return 0;
    }
    

    Output:

    auto a = 1, static s = 1
    auto a = 1, static s = 2
    auto a = 1, static s = 3
    total inside function = 150
    total in main         = 150
    

    What the output shows:

    • a is automatic, so it is created again as 0 on every call and always prints 1.
    • s is static, so it is created once and remembers its value: 1, 2, 3.
    • total is a global (external) variable, so every function sees the same variable and the change made in show_total() is also visible in main().

    Difference between automatic and external storage

    BasisAutomatic storageExternal storage
    Keywordauto (optional)extern
    DeclaredInside a function or blockOutside all functions (global)
    ScopeLocal to that blockGlobal: the whole program
    LifetimeExists only while the block runsExists until the program ends
    Default valueGarbage valueZero
    MemoryStackData area
    SharingCannot be shared between functionsShared by all functions and files

    13. Turbo C and Modern Compilers

    Many NEB notes and past answers use Turbo C, an old compiler. The programs in this chapter use standard C that works on current compilers such as GCC. Knowing the differences helps you read old answers.

    Old Turbo C styleStandard style used hereNote
    void main()int main(void) and return 0;Standard C requires main to return an int
    #include<conio.h> and getch()Not neededconio.h is not part of standard C
    clrscr()Not neededClears the screen in Turbo C only
    gets(s)fgets(s, size, stdin)gets() is unsafe and removed from the standard
    strrev(), strupr(), strlwr()A loop with toupper(), tolower()These three exist in Turbo C only (see Part 3)
    int is 2 bytesint is usually 4 bytesDepends on the compiler

    In an exam, follow the style your teacher and textbook use. The logic of the program is what earns the marks, and either style is normally understood.


    14. Quick Revision Table

    TopicKey point
    C languageStructured, compiled, middle-level; created by Dennis Ritchie, 1972
    FeaturesPortable, fast, pointers, rich library, 32 keywords
    PreprocessorRuns before compiling; lines start with #
    Header file.h file with library declarations (stdio.h, math.h)
    IdentifierProgrammer-chosen name; starts with letter or _
    KeywordReserved word; 32 in standard C
    TokenSmallest unit: keyword, identifier, constant, string, operator, punctuator
    Data typesPrimary (int, char, float, double, void), derived, user-defined
    %d %f %c %sint, float, char, string
    VariableNamed memory location whose value can change
    ConstantFixed value; #define or const
    / vs %Quotient vs remainder
    ++a vs a++Increase then use vs use then increase
    = vs ==Assign vs compare
    autoLocal, garbage default, block lifetime
    staticKeeps value between calls, default 0
    externGlobal, default 0, whole program
    registerStored in a CPU register if available

    15. Practice Questions

    Short-answer questions

    1. What is C? Write any four features of C.
    2. Write any three advantages and three disadvantages of C.
    3. What is a preprocessor? Name any three preprocessor directives.
    4. What is a header file? Write the purpose of stdio.h, math.h and string.h.
    5. Define identifier, keyword and token. Write the rules for naming identifiers.
    6. What is a data type? List the primary data types with their format specifiers.
    7. What is a variable? Differentiate between a variable and a constant.
    8. Write the difference between local and global variables.
    9. What is an operator? List the types of operators in C.
    10. Differentiate between ++a and a++ with an example.
    11. What is a storage class? Name the four storage classes.
    12. Differentiate between automatic and external storage classes.

    Long-answer questions

    1. What is C? Explain its features, advantages and disadvantages. (NEB Q1тАУ2)
    2. What is a data type? Explain the types of data with examples. (NEB Q3)
    3. What is a variable? Explain its types. (NEB Q4)
    4. What is an operator? Write its types and explain any four of them with examples. (NEB Q5)
    5. Explain the concept of storage classes. Differentiate between automatic and external storage. (NEB Q11)
    6. Explain the stages of developing and running a C program.

    Predict the output

    1. What is printed by printf("%d", 17 / 5); and printf("%d", 17 % 5);?
    2. If a = 5, what are a and b after b = a++; and after b = ++a;?
    3. What is the value of (10 > 5) && (3 > 8)?

    (Answers: 1) 3 and 2; 2) after b = a++; b is 5 and a is 6, and starting again from a = 5, b = ++a; gives b 6 and a 6; 3) 0.)

    Fill in the blanks

    1. C was developed by ______ at Bell Laboratories. (Dennis Ritchie)
    2. Standard C has ______ keywords. (32)
    3. The format specifier for a char is ______. (%c)
    4. A ______ variable keeps its value between function calls. (static)
    5. The ______ operator gives the size of a data type in bytes. (sizeof)

    Next тЖТ Part 2: Control Structures and Loops


    Prepared for NEB Class 12 Computer Science exam revision. Always cross-check key definitions with your prescribed textbook and your teacher's guidance.