2 Elements Of C

C Programming · Unit 2 · 4 hrs

Elements of C

Exam-focused notes for Elements of C (C Programming, CSC115): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.

Elements of C in short

This chapter looks at the basic building blocks of a C program: the character set and tokens it is built from, how variables, constants and data types are declared, and how individual statements and comments are written.

Elements of C: notes

C Standards (ANSI C and C99)

C has evolved through a series of formal standards since Dennis Ritchie's original design. The version described in Kernighan and Ritchie's 1978 book is informally called K&R C. In 1989, the American National Standards Institute standardized the language as ANSI C, also called C89; it fixed the syntax and the standard library so that a program written for one ANSI-compliant compiler behaves the same way on another. C99, the next major revision, added the // single-line comment (previously only /* */ was standard), variable declarations anywhere in a block rather than only at its start, variable-length arrays, long long int, and a _Bool boolean type through stdbool.h. Later standards, C11 and C18, added further library features while keeping the core of the language unchanged. Following a recognized standard is what makes a C program portable across compilers and operating systems.

C Character Set

The character set of C is the complete set of characters the compiler recognizes when reading a program: the uppercase and lowercase letters A to Z and a to z, the digits 0 to 9, special characters such as + - * / = ( ) { } [ ] , . ; : ' " # % & ^ ! ~ | \ < > _ $, and white space (blank, tab, newline, carriage return, form feed). Every token in a program is built out of characters from this set.

C Tokens

A token is the smallest individual unit of a C program that the compiler recognizes as meaningful, in the way a word is the smallest meaningful unit of a sentence. C recognizes six categories of token: keywords (reserved words with a predefined meaning, such as int or while), identifiers (programmer-chosen names), constants (fixed values such as 10 or 'A'), string literals, operators (symbols such as + and ==), and special symbols, or punctuators ({ }, ( ), ,, ;). The compiler's first job, lexical analysis, is to split the source text into this stream of tokens before checking the grammar of the program.

There are only 32 reserved keywords in C, always written in lowercase:

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

An identifier is any name the programmer chooses for a variable, array, function or structure. It must start with a letter or an underscore, contain only letters, digits and underscores, must not be a keyword, and must contain no space; since C is case sensitive, Code, code and CODE count as three distinct identifiers, and names such as 8ab (starts with a digit) or sopan# (contains an illegal character) are invalid.

What this unit covers

  • C Standards (ANSI C and C99)
  • C Character Set
  • C Tokens
  • Escape sequence
  • Delimiters
  • Variables
  • Data types (Basic, Derived, and User Defined)
  • Structure of a C program
  • Executing a C program
  • Constants/ Literals
  • Expressions
  • Statements and Comments

Constants/ Literals

2079 · 5 marks

Differentiate between constant and literals. Why do we need to define the type of data? [5]

--- Basis Constant Literal --------- Definition A constant is a named memory location whose value cannot be changed during program execution. A literal is a fixed, raw value that appears directly in the source code. Has a Name? Yes, it has an identifier/name. No, it has no name; it is the value i...

Open this answer on its own page →

Structure of a C program

2078 · 5 marks

Explain structure of a C program with suitable example. [5]

Every C program follows a standard, well-defined structure. Understanding this structure is essential before writing any C program. --- A C program is divided into the following sections: Section Description ------ 1. Documentation Comments describing the program (purpose, author, date) 2. Prepro...

Open this answer on its own page →

2075 · 5 marks

What is preprocessor directive? Discuss #define derivative with example. [1.5+3.5]

Show solved answer

Preprocessor Directive and #define Directive


What is a Preprocessor Directive? [1.5 marks]

A preprocessor directive is an instruction given to the C preprocessor -- a program that processes the source code before actual compilation begins. Preprocessor directives tell the preprocessor to perform specific operations such as file inclusion, macro substitution, or conditional compilation.

Key characteristics:

  • All preprocessor directives begin with the # (hash) symbol.
  • They are not C statements, so they do not end with a semicolon (;).
  • They are processed before the compiler translates the source code into object code.
  • They appear at the top of the program, in the preprocessor directives section of the C program structure.

Common preprocessor directives:

DirectivePurpose
#includeIncludes a header file
#defineDefines a macro or symbolic constant
#undefUndefines a macro
#ifdef / #ifndefConditional compilation

The #define Directive [3.5 marks]

The #define directive is used to define macros in C. A macro is a name (identifier) that is replaced by a value or expression throughout the program by the preprocessor before compilation.

Syntax:

#define MACRO_NAME replacement_text

The preprocessor replaces every occurrence of MACRO_NAME in the source code with replacement_text before the compiler processes the file.


Types of #define Usage:


1. Symbolic Constants (Object-like Macros)

Used to define constant values. This improves readability and maintainability of the program -- if the value needs to change, it only needs to be changed in one place.

Example:

#include <stdio.h>
#define PI 3.14159
#define MAX 100

int main() {
    float radius, area;
    printf("Enter radius: ");
    scanf("%f", &radius);
    area = PI * radius * radius;
    printf("Area of circle = %.2f\n", area);
    return 0;
}

Output (for radius = 5):

Area of circle = 78.54

Here, every occurrence of PI is replaced by 3.14159 before compilation.


2. Function-like Macros (Macros with Parameters)

#define can also define macros that accept arguments, similar to functions but handled by the preprocessor.

Syntax:

#define MACRO_NAME(parameter) expression

Example:

#include <stdio.h>
#define SQUARE(x)   ((x) * (x))
#define MAX(a, b)   ((a) > (b) ? (a) : (b))

int main() {
    int num = 5;
    printf("Square of %d = %d\n", num, SQUARE(num));
    printf("Maximum of 10 and 20 = %d\n", MAX(10, 20));
    return 0;
}

Output:

Square of 5 = 25
Maximum of 10 and 20 = 20

Note: Parentheses around parameters in macros are important to avoid operator precedence errors. For example, SQUARE(2+3) without parentheses would give 2+3*2+3 = 11 (wrong), but with parentheses ((2+3)*(2+3)) = 25 (correct).


Important Points about #define:

PointDetail
No memory allocationMacros are just text substitution; no variable is created
No type checkingUnlike variables or functions, the preprocessor does not check data types
No semicolon#define PI 3.14; would include the semicolon in the replacement, causing errors
ScopeA macro defined with #define is valid from the point of definition to the end of the file (or until #undef)

Summary

The #define directive is a powerful preprocessor tool in C that allows programmers to define symbolic constants and function-like macros. It makes programs more readable, portable, and easy to maintain by avoiding the use of hard-coded values throughout the code.

Open this answer on its own page →

Variables

2078 · 5 marks

What is variable? How is it different from constant? How do you write comments in C? [1+2+2]

--- Definition (from notes): "Variable is a name that can be used to store values. Variables can take different values but one at a time. These values can be changed during the execution of the program. A data type is associated with each variable." In simple terms, a variable is a named memory l...

Open this answer on its own page →

Data types

2077 · 5 marks

What is data type? Why do we need it in programming? Explain any three basic data types with example. [1+1+3]

Show solved answer

Data Types in C Programming

What is a Data Type? [1 mark]

A data type defines the type of data that a variable can store, the amount of memory it occupies, and the range of values it can hold. In C, there are four fundamental data types: int, char, float, and double. The storage representation of these data types is different in memory.


Why Do We Need Data Types in Programming? [1 mark]

Data types are needed in programming for the following reasons:

  • Memory allocation: Different data types occupy different amounts of memory (e.g., char takes 1 byte, int takes 2 bytes). Specifying a data type tells the compiler how much memory to reserve.
  • Data validity: They ensure that only appropriate values are stored in a variable (e.g., an int variable cannot store a decimal value accurately).
  • Operations: They determine what operations are valid on a variable (e.g., arithmetic on int and float, character operations on char).
  • Type safety: They help the compiler detect errors when incompatible data is used.

Three Basic Data Types with Examples [3 marks]

1. int (Integer Data Type)

  • Used to store whole numbers (positive, negative, or zero).
  • On a 16-bit machine, it occupies 2 bytes of memory.
  • Range: -32768 to 32767 (for signed int).

Example:

#include <stdio.h>
int main() {
    int age = 20;
    printf("Age = %d", age);
    return 0;
}

Output:

Age = 20

2. float (Floating Point Data Type)

  • Used to store single precision floating point numbers (numbers with decimal points).
  • Occupies 4 bytes of memory.
  • Range: 3.4E-38 to 3.4E+38.

Example:

#include <stdio.h>
int main() {
    float price = 99.50;
    printf("Price = %.2f", price);
    return 0;
}

Output:

Price = 99.50

3. char (Character Data Type)

  • Used to store a single character (letter, digit, or symbol).
  • Occupies 1 byte of memory.
  • Range: -128 to 127 (for signed char), or 0 to 255 (for unsigned char).
  • Characters are stored internally as their ASCII values.

Example:

#include <stdio.h>
int main() {
    char grade = 'A';
    printf("Grade = %c", grade);
    return 0;
}

Output:

Grade = A

Summary Table

Data TypeSize (bytes)RangeUse
int2-32768 to 32767Whole numbers
float43.4E-38 to 3.4E+38Decimal numbers
char1-128 to 127Single characters

Note: The size and range shown above are for a 16-bit machine. Values may vary on machines with different word sizes.

Open this answer on its own page →

2074 · 5 marks

What is type conversion? Discuss type casting with suitable example. [5]

Type conversion is the process of converting a value from one data type to another data type. In C, since different variables have different data types (int, float, char, double, etc.), it is sometimes necessary to convert a value of one type into another type for proper computation or assignment...

Open this answer on its own page →