1 Fundamentals Of C Programming

C Programming · Unit 1

Fundamentals of C Programming

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

Fundamentals of C Programming in short

This chapter introduces the building blocks of every C program. You learn how a program is laid out, how it becomes a running file, and which words and names C allows.

Fundamentals of C Programming: notes

Basic structure of C program

A C program is a set of functions. Execution always starts from the main() function. A typical program has these parts in order:

  • Documentation section: comments about the program.
  • Link section: #include lines that bring in header files.
  • Definition section: macros and constants made with #define.
  • Global declaration section: variables and functions used by the whole file.
  • The main() function with its declarations and statements.
  • User-defined functions placed after or before main().
#include <stdio.h>
#define PI 3.14159

int main(void)
{
    float r = 2.0f, area;
    area = PI * r * r;
    printf("Area = %.2f\n", area);
    return 0;
}

The return 0; statement tells the operating system that the program ended without error. Every statement ends with a semicolon, and a block of statements is enclosed in braces { }.

Compilation and execution process

C is a compiled language. The source file (.c) must be changed into machine code before it can run. This happens in four stages:

  • Preprocessing: the preprocessor removes comments, expands macros and copies the header files into the code.
  • Compilation: the compiler checks the syntax and converts the code to assembly language, then to an object file (.o or .obj).
  • Linking: the linker joins the object file with library code, such as the code for printf, to make one executable file.
  • Execution: the loader places the executable in memory and the CPU runs it.

With the GCC compiler, the commands look like this:

gcc hello.c -o hello
./hello

Syntax errors are found at compile time. Errors such as a missing library function are found at link time. Errors such as division by zero appear only at run time.

What this unit covers

  • Basic structure of C program
  • Compilation and execution process
  • Comments and escape sequences
  • Tokens and statements
  • Identifiers and keywords
  • Rules for naming valid identifiers

Rules for naming valid identifiers

2078 · 10 marks

What is an Identifier and Keyword? Explain the rules for naming valid Identifiers in C with example.Write a program to convert a given string to lowercase without using any library functions.[5+5]

Show solved answer

Identifiers and Keywords in C

Identifiers

An identifier is a name given to various program elements such as variables, functions, arrays, structures, and user-defined types. Identifiers are used to uniquely identify a program element within its scope.

Example:

int age;          // 'age' is an identifier
float salary;     // 'salary' is an identifier
void display();   // 'display' is an identifier

Keywords

A keyword is a reserved word that has a predefined meaning in the C language. Keywords cannot be used as identifiers. C has 32 keywords.

Examples of Keywords:

intfloatcharif
elsewhileforreturn
voidstructswitchbreak

Rules for Naming Valid Identifiers in C

  1. Letters, digits, and underscore only: An identifier can only contain alphabets (A-Z, a-z), digits (0-9), and underscore ( _ ).

  2. Must begin with a letter or underscore: An identifier cannot start with a digit.

  3. No spaces allowed: Spaces are not permitted inside an identifier.

  4. Keywords not allowed: Reserved keywords cannot be used as identifiers.

  5. Case sensitive: Age and age are treated as different identifiers.

  6. No special characters: Characters like @, #, $, !, etc. are not allowed.

  7. Length: Typically, the first 31 characters are significant (as per ANSI C standard).

Examples:

IdentifierValid/InvalidReason
ageValidStarts with letter
_salaryValidStarts with underscore
total_marksValidLetters and underscore
var1ValidLetter followed by digit
1varInvalidStarts with digit
my varInvalidContains space
intInvalidReserved keyword
my@nameInvalidSpecial character @

Program to Convert a String to Lowercase Without Library Functions

#include <stdio.h>

int main() {
    char str[100];
    int i;

    printf("Enter a string: ");
    gets(str);   /* read the string */

    /* Convert each character to lowercase */
    for (i = 0; str[i] != '\0'; i++) {
        /* Check if character is uppercase (A=65, Z=90 in ASCII) */
        if (str[i] >= 'A' && str[i] <= 'Z') {
            /* Add 32 to convert uppercase to lowercase */
            str[i] = str[i] + 32;
        }
    }

    printf("Lowercase string: %s\n", str);

    return 0;
}

Sample Output:

Enter a string: Hello WORLD
Lowercase string: hello world

Logic Explanation:

  • In ASCII, uppercase letters range from 65 ('A') to 90 ('Z').
  • Lowercase letters range from 97 ('a') to 122 ('z').
  • The difference between any uppercase letter and its lowercase equivalent is 32.
  • So, adding 32 to an uppercase character converts it to lowercase.
  • For example: 'A' (65) + 32 = 97 = 'a'
  • Characters that are already lowercase or non-alphabetic are left unchanged.
Open this answer on its own page →

Basic structure of C program

2078 · 5 marks

What is the basic structure of a C program? Explain each part. [5]

Show solved answer

Basic Structure of a C Program


Basic Structure of a C Program

A C program is organized into several distinct sections. Below is the general template:

/* Documentation Section */
// Program description, author, date

/* Link Section (Header Files) */
#include <stdio.h>
#include <conio.h>

/* Definition Section (Macros/Constants) */
#define PI 3.14159

/* Global Declaration Section */
int globalVar;

/* Main Function */
int main()
{
    /* Local Declaration */
    int a, b;

    /* Executable Statements */
    printf("Hello, World!\n");

    return 0;
}

/* User-Defined Functions */
void myFunction()
{
    // function body
}

Explanation of Each Part

1. Documentation Section

  • Contains comments about the program such as program name, author, date, and purpose.
  • Written using /* ... */ (multi-line) or // (single-line).
  • Ignored by the compiler; meant for human readability.
  • Contains preprocessor directives that include standard library header files.
  • Syntax: #include <filename.h>
  • Example: #include <stdio.h> includes standard input/output functions like printf() and scanf().
  • These are processed before compilation.

3. Definition Section

  • Used to define symbolic constants or macros using #define.
  • Example: #define PI 3.14159
  • The preprocessor replaces every occurrence of PI with 3.14159 before compilation.

4. Global Declaration Section

  • Variables declared here are global variables, accessible throughout the entire program.
  • Declared outside all functions.
  • They retain their value for the entire lifetime of the program.

5. Main Function main()

  • Every C program must have exactly one main() function -- it is the entry point of execution.
  • Contains two parts:
    • Local Declaration: Variables declared inside main(), accessible only within it.
    • Executable Statements: The actual logic -- assignments, function calls, loops, etc.
  • Returns an integer value to the operating system (return 0 indicates successful execution).

6. User-Defined Functions

  • Functions written by the programmer to perform specific tasks.
  • Defined after (or before) main().
  • Promotes modularity and code reusability.

Summary Table

SectionPurpose
DocumentationComments and program description
Link SectionIncludes header/library files
Definition SectionDefines constants and macros
Global DeclarationDeclares global variables
main() FunctionEntry point; contains program logic
User-Defined FunctionsCustom functions for specific tasks
Open this answer on its own page →

2077 · 5 marks

What is the basic structure of a C program? Explain each part. [5]

Show solved answer

Basic Structure of a C Program


Basic Structure of a C Program

A C program is organized into several distinct sections. Below is the general template:

/* Documentation Section */
// Program description, author, date

/* Link Section */
#include <stdio.h>
#include <stdlib.h>

/* Definition Section */
#define PI 3.14159

/* Global Declaration Section */
int globalVar = 10;

/* Main Function */
int main()
{
    /* Local Declaration */
    int a, b;

    /* Executable Statements */
    printf("Hello, World!\n");

    return 0;
}

/* User-Defined Functions */
void myFunction()
{
    // function body
}

Explanation of Each Part

1. Documentation Section

  • Contains comments about the program such as program name, author, date, and purpose.
  • Written using /* ... */ (multi-line) or // (single-line).
  • Ignored by the compiler; meant for human readability.
  • Contains header file inclusions using #include.
  • Tells the compiler to include standard library files before compilation.
  • Example: #include <stdio.h> includes standard input/output functions like printf() and scanf().

3. Definition Section

  • Contains macro definitions using #define.
  • Defines symbolic constants or macros used throughout the program.
  • Example: #define PI 3.14159

4. Global Declaration Section

  • Declares global variables and function prototypes.
  • Global variables are accessible by all functions in the program.
  • Example: int count = 0;

5. Main Function (main())

  • The entry point of every C program; execution always begins here.
  • Contains two parts:
    • Local Declaration: Variables declared inside main().
    • Executable Statements: The actual logic, calculations, input/output operations.
  • Returns an integer value (typically 0 to indicate successful execution).

6. User-Defined Functions

  • Functions written by the programmer to perform specific tasks.
  • Defined after main() (or declared before using prototypes).
  • Promotes modularity and code reusability.

Summary Table

SectionPurpose
DocumentationComments and description
LinkInclude header files
DefinitionDefine constants/macros
Global DeclarationDeclare global variables
main()Program execution starts here
User-Defined FunctionsCustom reusable functions
Open this answer on its own page →

0 · 5 marks

Define the basic structure of C program. Explain the Compilation and Execution of a C program? [5]

--- A C program is organized into several distinct sections. The basic structure is as follows: Section Description ------ Documentation Comments describing the program Link / Header include directives to include library files Definition define for symbolic constants/macros Global Declaration Var...

Open this answer on its own page →

Comments and escape sequences

2078 · 5 marks

Write Short Notes on: a) Escape Sequence Write Short Notes on: b) Null Pointer [2.5+2.5]

--- An escape sequence is a combination of characters that begins with a backslash () followed by one or more characters. It is used to represent certain special, non-printable, or reserved characters within a string or character literal in C (and other programming languages). Escape sequences a...

Open this answer on its own page →

0 · 5 marks

What are the uses of comments and escape sequences in a C program, explain with example? [5]

--- Comments are non-executable statements used to explain and document the code. The compiler ignores comments completely during compilation. - To explain the purpose of code for better readability - To document functions, variables, and logic - To temporarily disable a block of code during debu...

Open this answer on its own page →

Identifiers and keywords

2077 · 10 marks

What is an Identifier and keyword? Explain the rules for naming valid identifiers in C with example.Write a C program to find sum of digits of a 'n' digit number.[5+5]

An identifier is a name given to various program elements such as variables, functions, arrays, structures, and other user-defined items. Identifiers are used to uniquely identify a program element during execution. Example: --- A keyword is a reserved word that has a predefined meaning in the C ...

Open this answer on its own page →

Compilation and execution process

2077 · 5 marks

Find errors (If any) in the following program and rewrite it.

#define (studio,h)
float main < >
int m [ ] [ ] = 1,2,3,4;
for (i = 4, I>=0 ; i--)
for (j=0, j <4; j++);
m[i] [j] = a[i][j] + b[i][j];
return 0. 0;
}

[5]

--- Erroneous Code Error Description ------------------------------------- 1 define (studio,h) Wrong preprocessor directive; should be include <stdio.h 2 float main < main must return int, not float; < should be () 3 int m[][] 2D array declaration is incomplete; must specify at least the column s...

Open this answer on its own page →

Tokens and statements

2081.2 · 5 marks

Define token. Describe any three types of statements. [5]

A token is the smallest meaningful unit in a programming language that the lexical analyzer (scanner) recognizes during the compilation process. Tokens are the basic building blocks of a program, produced by breaking the source code into categorized lexical units. Examples of token categories: - ...

Open this answer on its own page →