Programming in C
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
| Part | Page | What it covers |
|---|---|---|
| 1 | Fundamentals (this page) | Introduction to C, program structure, preprocessor, tokens, data types, variables, constants, operators, storage classes |
| 2 | Control Structures and Loops | if, switch, for, while, do...while, break, continue, goto, common number programs |
| 3 | Arrays and Strings | One- and two-dimensional arrays, matrices, string functions |
| 4 | Functions, Structures and Unions | User-defined functions, recursion, call by value and reference, structures, unions |
| 5 | Pointers and File Handling | Pointers, dynamic memory, text and binary files, fprintf and fscanf |
Where to find each NEB important question
| Question | Topic | Page |
|---|---|---|
| 1тАУ2 | What is C? Features, advantages and disadvantages | Part 1 |
| 3 | Data types | Part 1 |
| 4 | Variables and their types | Part 1 |
| 5 | Operators | Part 1 |
| 11 | Storage classes: automatic vs external | Part 1 |
| 6 | Control structures, break vs continue | Part 2 |
| 7 | Looping, while vs do...while | Part 2 |
| 8 | Arrays, strings, string functions | Part 3 |
| 9тАУ10 | Functions, features, types, recursion | Part 4 |
| 12тАУ14 | Structure, array vs structure, structure vs union | Part 4 |
| 16 | Call by value and call by reference | Part 4 |
| 15, 17, 18 | Pointers, array vs pointer, structure vs pointer | Part 5 |
| 19тАУ20 | Sequential vs random access, fprintf vs fscanf | Part 5 |
Table of Contents
- Introduction to C
- Features, Advantages and Disadvantages
- Structure of a C Program
- How a C Program Is Developed and Run
- Preprocessor and Header Files
- Character Set, Identifiers, Keywords and Tokens
- Data Types
- Variables and Constants
- Format Specifiers and Escape Sequences
- Input and Output Functions
- Operators
- Storage Classes
- Turbo C and Modern Compilers
- Quick Revision Table
- 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
| Year | Language / event | Developed by |
|---|---|---|
| 1960 | ALGOL 60 | International committee |
| 1967 | BCPL | Martin Richards |
| 1970 | B | Ken Thompson (Bell Labs) |
| 1972 | C | Dennis Ritchie (Bell Labs) |
| 1973 | UNIX operating system rewritten in C | Ritchie and Thompson |
| 1978 | Book The C Programming Language (known as K&R C) | Kernighan and Ritchie |
| 1989 | ANSI C standard (C89), adopted by ISO in 1990 | ANSI / ISO |
| 1999 and later | C99, C11, C17 | ISO |
2. Features, Advantages and Disadvantages
Features of C
- Simple and efficient: a small set of keywords (32) and a clear structure
- Structured: programs are divided into functions (modules)
- Portable: the same program can be compiled on different computers with little change
- Fast: compiled code runs close to the speed of the hardware
- Rich library: hundreds of ready-made functions (
printf,sqrt,strlen) - Pointers: direct access to memory addresses
- Low-level access: bitwise operators let you work with individual bits
- Extensible: programmers can create their own functions and header files
- Case sensitive:
Totalandtotalare different names
Advantages
| Advantage | Meaning |
|---|---|
| Machine independent (portable) | Programs run on small devices up to mainframes after recompiling |
| Easy to learn | Few keywords and simple syntax compared with many languages |
| Efficient | Fast execution and low memory use |
| Foundation language | C++, Java, C# and many others borrow its syntax; operating systems such as UNIX and Linux are written in C |
| Good for system programming | Pointers and bit operations allow control of hardware |
Disadvantages
| Disadvantage | Meaning |
|---|---|
| No run-time checking | C does not check array limits, so an invalid index can silently corrupt data |
| Weak error detection | Many mistakes are found only when the program misbehaves |
| Hard to maintain large programs | Without objects, big programs become difficult to manage |
| No object-oriented support | No classes, inheritance or polymorphism (C++ adds these) |
| Manual memory management | The programmer must allocate and free memory |
| No exception handling | There 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
| Line | Meaning |
|---|---|
#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
| Stage | What happens |
|---|---|
| 1. Editing | The programmer types the source code and saves it with the .c extension |
| 2. Preprocessing | Lines beginning with # are processed (header files are inserted, macros replaced) |
| 3. Compiling | The compiler checks the syntax and translates the code into object code (.obj or .o) |
| 4. Linking | The linker joins the object code with library code to make the executable file |
| 5. Executing | The executable runs and produces output |
Types of errors
| Error | When it appears | Example |
|---|---|---|
| Syntax error | At compile time | Missing semicolon, misspelled keyword |
| Linker error | At link time | Calling a function that does not exist |
| Run-time error | While the program runs | Dividing by zero |
| Logical error | Program runs but gives wrong output | Using + 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.
| Type | Directive | Purpose |
|---|---|---|
| File inclusion | #include | Inserts the contents of a header file |
| Macro substitution | #define, #undef | Replaces a name with a value or expression |
| Conditional compilation | #if, #ifdef, #ifndef, #else, #endif | Compiles parts of the code only when a condition is true |
| Other | #pragma, #error | Compiler-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 file | Purpose | Common functions |
|---|---|---|
stdio.h | Standard input and output | printf(), scanf(), getchar(), putchar(), puts(), fgets(), fopen(), fclose() |
conio.h | Console I/O (old Turbo C only, not standard) | getch(), getche(), clrscr() |
math.h | Mathematical functions | sqrt(), pow(), sin(), cos(), log(), ceil(), floor(), fabs() |
string.h | String handling | strlen(), strcpy(), strcmp(), strcat() |
ctype.h | Character testing and conversion | toupper(), tolower(), isalpha(), isdigit(), isupper(), isspace(), isalnum() |
stdlib.h | General utilities | malloc(), calloc(), free(), rand(), exit(), abs(), atoi() |
complex.h | Complex number arithmetic | cabs(), csqrt(), cpow() |
A library function is a ready-made function supplied with the compiler, such as
printf(),sqrt()orstrlen(). 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.
| Group | Characters |
|---|---|
| Alphabets | AтАУZ and aтАУz |
| Digits | 0тАУ9 |
| Special symbols | + - * / = ( ) { } [ ] < > , ; : ' " ! # % & _ ~ \ ? . |
| White space | Blank space, tab, new line |
Identifiers
An identifier is a name given by the programmer to a variable, function, array, structure, and so on.
Rules:
- May contain letters, digits and the underscore
_ - Must start with a letter or underscore, never a digit
- Case sensitive (
Textandtextare different) - Cannot be a keyword
- Cannot contain spaces or special symbols such as
@,#,-
| Valid | Invalid |
|---|---|
total | 2marks (starts with a digit) |
_count | my name (contains a space) |
student_age | float (keyword) |
Roll2 | net-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.
| Group | Keywords |
|---|---|
| Data types | char int float double void short long signed unsigned |
| Storage classes | auto extern register static |
| Type qualifiers | const volatile |
| Control flow | if else switch case default for while do break continue goto return |
| User-defined types | struct union enum typedef |
| Operator | sizeof |
nearandfarseen 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 type | Examples |
|---|---|
| Keywords | int, float, if, for, return |
| Identifiers | main, total, student_age |
| Constants | 100, 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
| Category | Types |
|---|---|
| Primary (basic) | int, char, float, double, void |
| Derived | array, pointer, function |
| User-defined | struct, union, enum, typedef |
Primary data types
| Data type | Stores | Typical size | Format specifier | Example |
|---|---|---|---|---|
char | One character | 1 byte | %c | 'A' |
int | Whole number | 4 bytes (2 bytes in Turbo C) | %d | 250 |
float | Decimal number (about 6 digits of precision) | 4 bytes | %f | 3.14f |
double | Decimal number (about 15 digits) | 8 bytes | %f in printf, %lf in scanf | 3.14159265 |
long int | Larger whole number | 4 or 8 bytes | %ld | 29164578L |
long double | Very large decimal number | 12 or 16 bytes | %Lf | 1.5L |
void | Nothing (used for functions with no return value) | not applicable | not applicable | void show() |
Correction:
longis a whole-number type (long int), not a floating-point type. Sizes depend on the compiler and computer, so usesizeofto 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)
| Type | Stores | Examples |
|---|---|---|
| Numeric variable | Whole or decimal numbers | int, float, double |
| Character / string variable | A single character, or a group of characters | char, 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
| Type | Declared | Works |
|---|---|---|
| Local variable | Inside a function or block | Only inside that function or block |
| Global variable | Outside all functions | In every function of the program |
Constants
A constant is a fixed value that does not change during the program.
| Constant type | Example |
|---|---|
| Integer constant | 100, -25 |
| Floating-point constant | 3.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
| Method | Example | Note |
|---|---|---|
#define | #define PI 3.14159 | Preprocessor replacement, no semicolon, no data type |
const keyword | const 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.
| Specifier | Data type |
|---|---|
%d or %i | int (signed integer) |
%u | unsigned int |
%ld | long int |
%f | float (and double in printf) |
%lf | double in scanf |
%c | char |
%s | String |
%x / %o | Hexadecimal / octal integer |
%p | Pointer (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.
| Escape | Name | Effect |
|---|---|---|
\n | New line | Moves to the next line |
\t | Horizontal tab | Moves to the next tab stop |
\\ | Backslash | Prints \ |
\' | Single quote | Prints ' |
\" | Double quote | Prints " |
\a | Alert | Makes a beep |
\b | Backspace | Moves back one character |
\0 | Null character | Marks 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
| Function | Header | Purpose |
|---|---|---|
printf() | stdio.h | Prints formatted output |
scanf() | stdio.h | Reads formatted input |
getchar() | stdio.h | Reads one character |
putchar() | stdio.h | Prints one character |
puts() | stdio.h | Prints a string followed by a new line |
fgets() | stdio.h | Reads 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. Usefgets()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. Usefgets()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
| # | Type | Operators | Example |
|---|---|---|---|
| 1 | Arithmetic | + - * / % | a + b |
| 2 | Relational | < > <= >= == != | a > b |
| 3 | Logical | && || ! | (a > b) && (a > c) |
| 4 | Assignment | = += -= *= /= %= | a += 5 |
| 5 | Increment / decrement (unary) | ++ -- | a++, --a |
| 6 | Conditional (ternary) | ? : | (a > b) ? a : b |
| 7 | Bitwise | & | ^ ~ << >> | a & b |
| 8 | Comma | , | a = 1, b = 2 |
| 9 | sizeof | sizeof | sizeof(int) |
Key points about each type
- Arithmetic:
/on two integers gives an integer result (10 / 3is3).%gives the remainder and works only with integers. To get a decimal result, make one operand a float (10 / 3.0or(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.
| Form | Name | Meaning |
|---|---|---|
++a | Pre-increment | Increase a first, then use it |
a++ | Post-increment | Use a first, then increase it |
--a | Pre-decrement | Decrease first, then use |
a-- | Post-decrement | Use first, then decrease |
- Conditional operator:
expression1 ? expression2 : expression3. Ifexpression1is true (non-zero), the result isexpression2, otherwiseexpression3. It is a short form ofif...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)
| Level | Operators | Associativity |
|---|---|---|
| 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) insideif - Expecting
5 / 2to give2.5; it gives2 - Writing
a < b < c; it does not test whetherblies betweenaandc. Writea < 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 class | Keyword | Stored in | Default value | Scope | Lifetime |
|---|---|---|---|---|---|
| Automatic | auto (default for local variables) | Memory (stack) | Garbage (unpredictable) | Inside the block or function | Until the block ends |
| Register | register | CPU register (if available) | Garbage | Inside the block or function | Until the block ends |
| Static | static | Memory (data area) | 0 | Inside the block (or file, if global) | Whole program |
| External | extern | Memory (data area) | 0 | Whole 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:
ais automatic, so it is created again as0on every call and always prints1.sis static, so it is created once and remembers its value:1,2,3.totalis a global (external) variable, so every function sees the same variable and the change made inshow_total()is also visible inmain().
Difference between automatic and external storage
| Basis | Automatic storage | External storage |
|---|---|---|
| Keyword | auto (optional) | extern |
| Declared | Inside a function or block | Outside all functions (global) |
| Scope | Local to that block | Global: the whole program |
| Lifetime | Exists only while the block runs | Exists until the program ends |
| Default value | Garbage value | Zero |
| Memory | Stack | Data area |
| Sharing | Cannot be shared between functions | Shared 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 style | Standard style used here | Note |
|---|---|---|
void main() | int main(void) and return 0; | Standard C requires main to return an int |
#include<conio.h> and getch() | Not needed | conio.h is not part of standard C |
clrscr() | Not needed | Clears 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 bytes | int is usually 4 bytes | Depends 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
| Topic | Key point |
|---|---|
| C language | Structured, compiled, middle-level; created by Dennis Ritchie, 1972 |
| Features | Portable, fast, pointers, rich library, 32 keywords |
| Preprocessor | Runs before compiling; lines start with # |
| Header file | .h file with library declarations (stdio.h, math.h) |
| Identifier | Programmer-chosen name; starts with letter or _ |
| Keyword | Reserved word; 32 in standard C |
| Token | Smallest unit: keyword, identifier, constant, string, operator, punctuator |
| Data types | Primary (int, char, float, double, void), derived, user-defined |
%d %f %c %s | int, float, char, string |
| Variable | Named memory location whose value can change |
| Constant | Fixed value; #define or const |
/ vs % | Quotient vs remainder |
++a vs a++ | Increase then use vs use then increase |
= vs == | Assign vs compare |
auto | Local, garbage default, block lifetime |
static | Keeps value between calls, default 0 |
extern | Global, default 0, whole program |
register | Stored in a CPU register if available |
15. Practice Questions
Short-answer questions
- What is C? Write any four features of C.
- Write any three advantages and three disadvantages of C.
- What is a preprocessor? Name any three preprocessor directives.
- What is a header file? Write the purpose of
stdio.h,math.handstring.h. - Define identifier, keyword and token. Write the rules for naming identifiers.
- What is a data type? List the primary data types with their format specifiers.
- What is a variable? Differentiate between a variable and a constant.
- Write the difference between local and global variables.
- What is an operator? List the types of operators in C.
- Differentiate between
++aanda++with an example. - What is a storage class? Name the four storage classes.
- Differentiate between automatic and external storage classes.
Long-answer questions
- What is C? Explain its features, advantages and disadvantages. (NEB Q1тАУ2)
- What is a data type? Explain the types of data with examples. (NEB Q3)
- What is a variable? Explain its types. (NEB Q4)
- What is an operator? Write its types and explain any four of them with examples. (NEB Q5)
- Explain the concept of storage classes. Differentiate between automatic and external storage. (NEB Q11)
- Explain the stages of developing and running a C program.
Predict the output
- What is printed by
printf("%d", 17 / 5);andprintf("%d", 17 % 5);? - If
a = 5, what areaandbafterb = a++;and afterb = ++a;? - 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
- C was developed by ______ at Bell Laboratories. (Dennis Ritchie)
- Standard C has ______ keywords. (32)
- The format specifier for a
charis ______. (%c) - A ______ variable keeps its value between function calls. (static)
- 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.