Class 9 | Fundamentals of C Programming | C Programming Notes

C Programming Language – Complete Notes

Introduction to C Programming

C is a high-level, general-purpose programming language developed by Dennis Ritchie at AT&T Bell Laboratories in 1972.

The UNIX operating system was largely developed using the C programming language. C was developed to overcome many limitations of earlier programming languages and became one of the most widely used programming languages.

C is often described as a middle-level language because it provides features of both high-level and low-level programming languages.


Features of C Language

The major features of C programming language are:

  1. Simple: C is relatively simple and provides a structured approach to programming.
  2. Portable: A C program can be compiled and executed on different computer systems with little or no modification.
  3. Middle-Level Language: C supports both high-level programming features and low-level memory operations.
  4. Rich Library: C provides many standard library functions that make program development easier and faster.
  5. Fast Execution: C programs are generally efficient and execute quickly.
  6. Extensible: Programmers can create their own functions and extend the capabilities of a program.
  7. Structured Programming: Large programs can be divided into smaller functions or modules.
  8. Memory Management: C allows direct memory access through pointers and supports dynamic memory allocation.

Advantages of C Language

  1. C programs are portable across different computer platforms.
  2. C programs are relatively easy to test, debug, and maintain.
  3. Pointers make C powerful for memory manipulation.
  4. C has a relatively small set of keywords.
  5. Functions and program components can be reused.
  6. C compilers are widely available.
  7. C supports dynamic memory allocation at runtime.
  8. Users can create their own functions.
  9. C is suitable for both system programming and application development.

Limitations of C Language

  1. C does not provide automatic runtime checking for many programming errors.
  2. C is case-sensitive, so programmers must carefully distinguish between uppercase and lowercase letters.
  3. C provides relatively weak type checking compared with some modern programming languages.
  4. C does not directly support Object-Oriented Programming (OOP) concepts such as classes and inheritance.
  5. Manual memory management can lead to errors if it is not handled properly.

Basic Structure of a C Program

A C program can contain the following sections:

  1. Documentation Section
  2. Preprocessor / Link Section
  3. Definition Section
  4. Global Declaration Section
  5. main() Function Section
  6. Subprogram / User-Defined Function Section

1. Documentation Section

The documentation section contains information about the program.

It may include:

  • Program name
  • Purpose of the program
  • Author’s name
  • Date
  • Other relevant information

Comments are normally used for documentation.

Example

/* Program to calculate the sum of two numbers
   Author: ABC
*/

2. Preprocessor / Link Section

This section contains the header files required by the program.

Example

#include <stdio.h>

The #include directive tells the preprocessor to include the contents of the specified header file before compilation.


3. Definition Section

This section is optional.

Symbolic constants and macros can be defined using the #define directive.

Example

#define PI 3.14159

4. Global Declaration Section

Variables and functions that need to be accessed by multiple functions can be declared globally.

Example

int total;

5. Main Function Section

Every executable C program contains a main() function.

The execution of a C program begins from the main() function.

Example

int main(void)
{
    int a, b;

    a = 10;
    b = 20;

    return 0;
}

The main function generally contains:

A. Declaration Part

Variables required by the function are declared.

int a, b, sum;

B. Execution Part

Executable statements are written.

sum = a + b;
printf("%d", sum);

6. Subprogram Section

This section contains user-defined functions created by the programmer.

These functions can be called from main() or other functions.

Example

int add(int a, int b)
{
    return a + b;
}

Execution of a C Program

A C program generally passes through the following stages:

Create Program → Compile Program → Link Program → Execute Program


1. Creating the Program

A C program is written using a text editor or an Integrated Development Environment (IDE).

Examples include:

  • Visual Studio Code
  • Code::Blocks
  • Dev-C++
  • Turbo C
  • Notepad++

A C source file is normally saved using the:

.c

extension.

Example

program.c


2. Compiling the Program

The source code is processed by a compiler.

The compiler checks the program for syntax errors and translates the source code into object code.


3. Linking the Program

After compilation, the object code is linked with the necessary library files.

The linker combines the required object files and libraries to create an executable program.


4. Executing the Program

After successful compilation and linking, the executable program can be run.

The computer then executes the instructions and displays the required output.


C Program to Display “Hello World”

#include <stdio.h>

int main(void)
{
    printf("Hello World!");

    return 0;
}

Output

Hello World!

Preprocessor Directives

A preprocessor directive is an instruction processed before the actual compilation of a C program.

Preprocessor directives begin with the # symbol.

Example

#include <stdio.h>

Another example is:

#define PI 3.14

Preprocessor directives do not normally end with a semicolon.


Header Files in C

A header file contains declarations of functions, macros, constants, and data types that can be used by a C program.

Most standard C header files have the extension:

.h


Common Header Files

1. <stdio.h>

Standard Input/Output header file.

It contains functions such as:

  • printf()
  • scanf()
  • getchar()
  • putchar()

Example

#include <stdio.h>

2. <string.h>

Contains functions used to manipulate strings.

Examples:

  • strlen()
  • strcpy()
  • strcmp()
  • strcat()

3. <math.h>

Contains mathematical functions.

Examples:

  • sqrt()
  • pow()
  • sin()
  • cos()

4. <stdlib.h>

Contains general-purpose functions related to:

  • Dynamic memory allocation
  • Number conversion
  • Process control
  • Random numbers
  • Searching and sorting

Examples include:

  • malloc()
  • calloc()
  • free()
  • rand()
  • atoi()

5. <conio.h>

conio.h is used by some older compilers such as Turbo C for console-related functions.

Examples include:

  • getch()
  • putch()
  • clrscr()

Note: conio.h is not part of the standard C library and may not work with modern C compilers.


6. <graphics.h>

graphics.h was commonly used with older compilers for graphics programming.

Functions may include:

  • line()
  • circle()
  • rectangle()

Note: graphics.h is not part of standard C.


Tokens in C

Tokens are the smallest meaningful units of a C program that are recognized by the compiler.

Important C tokens include:

  1. Keywords
  2. Identifiers
  3. Constants
  4. Variables
  5. Strings
  6. Operators
  7. Special Symbols

Constants

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

Examples

10
25.5
'A'
"Hello"

Common types of constants include:

  • Integer constants
  • Floating-point constants
  • Character constants
  • String literals

Variables

A variable is a named memory location used to store a value that may change during program execution.

Example

int age = 20;

Here:

  • int = data type
  • age = variable name
  • 20 = value

Rules for Naming Variables

While naming variables in C:

  1. The first character must be a letter or underscore _.
  2. A variable name may contain:
    • Letters
    • Digits
    • Underscores
  3. A variable name cannot begin with a digit.
  4. Keywords cannot be used as variable names.
  5. Spaces are not allowed.
  6. Special symbols such as @, #, %, etc. cannot normally be used.
  7. C is case-sensitive.

Therefore:

age
Age
AGE

are three different identifiers.


Strings in C

A string in C is a sequence of characters terminated by a null character \0.

Strings are generally stored using character arrays.

Example

char name[] = "Nepal";

The string contains:

N e p a l \0

Keywords in C

Keywords are reserved words that have predefined meanings in the C programming language.

They cannot be used as names of variables, functions, or other identifiers.

Examples include:

int
float
char
if
else
for
while
return
switch
struct

The traditional ANSI C/C90 standard contains 32 keywords. Later versions of the C standard added additional keywords.


Identifiers

Identifiers are names given to program elements such as:

  • Variables
  • Functions
  • Arrays
  • Structures
  • Unions
  • Enumerations

Examples

total
studentName
calculateSum
marks

Rules for Naming Identifiers

  1. The first character must be a letter or underscore.
  2. An identifier may contain:
    • Letters
    • Digits
    • Underscores
  3. It must not be a C keyword.
  4. Spaces are not allowed.
  5. C identifiers are case-sensitive.

Operators in C

An operator is a special symbol used to perform an operation on one or more operands.

Example

c = a + b;

Here:

  • = is an assignment operator.
  • + is an arithmetic operator.
  • a and b are operands.

Operators can be classified according to the number of operands they require.


1. Unary Operators

A unary operator operates on one operand.

Examples include:

  • Increment ++
  • Decrement --
  • Logical NOT !
  • Unary minus -

Increment Operator

The increment operator ++ increases the value of an operand by 1.

Pre-Increment

++a;

Post-Increment

a++;

Decrement Operator

The decrement operator -- decreases the value by 1.

Pre-Decrement

--a;

Post-Decrement

a--;

2. Binary Operators

A binary operator requires two operands.

Important binary operators include:

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Assignment operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

OperatorMeaning
+Addition
-Subtraction
*Multiplication
/Division
%Modulus / Remainder

Example of Arithmetic Operators

#include <stdio.h>

int main(void)
{
    int a = 20;
    int b = 7;

    printf("Sum = %d\n", a + b);
    printf("Difference = %d\n", a - b);
    printf("Product = %d\n", a * b);
    printf("Division = %d\n", a / b);
    printf("Remainder = %d\n", a % b);

    return 0;
}

Logical Operators

Logical operators are commonly used to combine or reverse conditions.

OperatorMeaning
&&Logical AND
``Logical OR
!Logical NOT

Logical expressions usually evaluate as either:

  • True
  • False

In C, zero represents false and non-zero values represent true.


Assignment Operators

Assignment operators are used to assign values to variables.

Basic Assignment

a = 10;

Other assignment operators include:

OperatorExample
=a = 10
+=a += 5
-=a -= 5
*=a *= 5
/=a /= 5
%=a %= 5

Relational Operators

Relational operators compare two values.

The result of a relational expression is true or false.

OperatorMeaning
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
==Equal to
!=Not equal to

Example

#include <stdio.h>

int main(void)
{
    int a = 30;
    int b = 20;

    if (a > b)
    {
        printf("%d is greater than %d", a, b);
    }

    return 0;
}

Bitwise Operators

Bitwise operators perform operations directly on the individual bits of integer values.

OperatorMeaning
&Bitwise AND
``Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Left Shift
>>Right Shift

3. Ternary Operator

A ternary operator uses three operands.

The conditional operator ?: is the ternary operator in C.

Syntax

condition ? expression1 : expression2;

Example

int max;

max = (a > b) ? a : b;

If a > b is true, max receives the value of a. Otherwise, it receives the value of b.


Operator Precedence and Associativity

Operator precedence determines which operator is evaluated first in an expression.

Associativity determines the direction of evaluation when two operators have the same precedence.


Example

x = 4 * 5 + 10;

Multiplication has higher precedence than addition.

Therefore:

4 × 5 = 20
20 + 10 = 30

Hence:

x = 30

Operator Precedence Table

The following table shows commonly used C operators from higher to lower precedence.

OperatorsDescriptionAssociativity
() [] -> .Function call, array access, structure member accessLeft to Right
! ~ ++ -- unary + unary - & * sizeofUnary operatorsRight to Left
* / %Multiplication, division, remainderLeft to Right
+ -Addition, subtractionLeft to Right
<< >>Bitwise shiftsLeft to Right
< <= > >=Relational operatorsLeft to Right
== !=Equality operatorsLeft to Right
&Bitwise ANDLeft to Right
^Bitwise XORLeft to Right
``Bitwise ORLeft to Right
&&Logical ANDLeft to Right
``Logical ORLeft to Right
?:Conditional operatorRight to Left
= += -= *= /= %= <<= >>=Assignment operatorsRight to Left
,Comma operatorLeft to Right

Character Set in C

A character set is the collection of valid characters and symbols that can be used in a programming language.

The C character set contains several categories.


1. Alphabets

Both uppercase and lowercase English alphabets are used.

Uppercase

A B C ... Z

Lowercase

a b c ... z

2. Numeric Characters

Digits from:

0 1 2 3 4 5 6 7 8 9

3. Whitespace Characters

Whitespace characters are used to separate program elements and format code.

Examples include:

  • Space
  • Tab
  • Newline

4. Special Characters

C uses many special symbols.

Examples include:

+  -  *  /  %
=  <  >
{  }  [  ]
(  )
;  ,
#  &

Data Types in C

A data type specifies what kind of value a variable can store.

It also determines how much memory may be required and which operations can be performed on the data.

C data types can broadly be classified as:

  1. Basic / Primary Data Types
  2. Derived Data Types
  3. User-Defined Data Types

1. Basic / Primary Data Types

The fundamental C data types include:

Data TypePurpose
charStores a character or small integer value
intStores integers
floatStores single-precision floating-point values
doubleStores double-precision floating-point values
voidRepresents no value

Integer data types can also use modifiers such as:

  • short
  • long
  • signed
  • unsigned

Examples

int age;
float salary;
char grade;
double amount;

2. Derived Data Types

Derived data types are created from basic data types.

Common examples include:

Arrays

An array stores several elements of the same data type.

int marks[5];

Pointers

Pointers store memory addresses.

int *ptr;

Functions

Functions are also treated as derived types in C.

int add(int a, int b);

3. User-Defined Data Types

Programmers can create their own data types using C language features.

Important user-defined types include:

  • struct
  • union
  • enum
  • typedef

Structure

A structure groups different related data items under one name.

Example

struct Student
{
    int roll;
    char name[30];
};

Enumeration

An enumeration creates a set of named integer constants.

Example

enum Day
{
    SUNDAY,
    MONDAY,
    TUESDAY
};

typedef

typedef creates an alternative name for an existing data type.

Example

typedef unsigned int uint;

Format Specifiers

Format specifiers are used with formatted input/output functions such as:

  • printf()
  • scanf()

They begin with the % symbol.


Common Format Specifiers

Format SpecifierPurpose
%dInteger
%iInteger
%fFloating-point number
%cCharacter
%sString
%uUnsigned integer
%oOctal integer
%x / %XHexadecimal integer
%pPointer address
%lfDouble with scanf()

Program Using printf() and scanf()

#include <stdio.h>

int main(void)
{
    int emp_id;
    char name[20];
    float salary;

    printf("Enter employee ID, name and salary: ");
    scanf("%d %19s %f", &emp_id, name, &salary);

    printf("\nName: %s", name);
    printf("\nEmployee ID: %d", emp_id);
    printf("\nSalary: %.2f", salary);

    return 0;
}

Program Using Format Specifiers

#include <stdio.h>

int main(void)
{
    int a = 456;
    char b = 'y';
    float c = 12.458f;
    char name[] = "Rekha";

    printf("a = %d\n", a);
    printf("b = %c\n", b);
    printf("c = %.3f\n", c);
    printf("Name = %s\n", name);

    return 0;
}

Comments in C

A comment is descriptive text written inside a program to explain the code.

Comments are ignored by the compiler and are not executed.

C mainly supports two styles of comments.


1. Single-Line Comment

A single-line comment begins with:

//

Example

// This program calculates the sum.

2. Multi-Line / Block Comment

A block comment begins with:

/*

and ends with:

*/

Example

/*
This is a
multi-line comment.
*/

Escape Sequences

An escape sequence is a combination of characters beginning with a backslash \ that represents a special character.

Escape sequences are commonly used inside strings and character constants.


Common Escape Sequences

Escape SequenceMeaning
\nNew line
\tHorizontal tab
\rCarriage return
\bBackspace
\'Single quotation mark
\"Double quotation mark
\\Backslash
\vVertical tab
\?Question mark
\aAlert / Beep

Input and Output Functions in C

Any data supplied to a program is called input.

The result produced by a program after processing the input is called output.

C provides many input/output functions.

They can broadly be classified as:

  1. Formatted I/O Functions
  2. Unformatted / Character and String I/O Functions

Formatted I/O Functions

Formatted input/output functions use format specifiers such as:

%d
%f
%c
%s

The two most commonly used formatted I/O functions are:

  • printf()
  • scanf()

printf() Function

printf() is used to display formatted output on the screen.

Syntax

printf("format string", values);

Example

printf("Hello");

Another example:

int age = 20;

printf("Age = %d", age);

scanf() Function

scanf() is used to accept formatted input from the user.

Syntax

scanf("format specifier", &variable);

Example

int a;

scanf("%d", &a);

Character and String I/O Functions

Some common character and string input/output functions include:

  • getchar()
  • putchar()
  • puts()

Older non-standard environments may also provide:

  • getch()
  • putch()

getchar()

getchar() reads one character from standard input.

Example

char ch;

ch = getchar();

putchar()

putchar() displays one character.

Example

putchar(ch);

puts()

puts() displays a string followed by a newline.

Example

puts("Hello Nepal");

gets()

Older C programs commonly used gets() to read strings.

However, gets() is unsafe and has been removed from the modern C standard because it cannot prevent buffer overflow.

Modern programs should use:

fgets()

instead.


getch() and putch()

getch() and putch() are commonly found in older DOS/Turbo C environments through <conio.h>.

They are not standard C functions.


Program Using getchar() and putchar()

#include <stdio.h>

int main(void)
{
    char ch;

    printf("Enter a character: ");
    ch = getchar();

    printf("The character you entered is: ");
    putchar(ch);

    return 0;
}

Program Using puts() and fgets()

#include <stdio.h>

int main(void)
{
    char name[20];

    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);

    printf("Your name is: ");
    puts(name);

    return 0;
}

Important C Programs

Example 1: Program to Calculate Simple Interest

Question

Write a C program to calculate simple interest where Principal (P), Time (T), and Rate (R) are entered by the user.

Formula

Simple Interest = (P × T × R) / 100

Program

#include <stdio.h>

int main(void)
{
    float principal, time, rate, simpleInterest;

    printf("Enter principal amount: ");
    scanf("%f", &principal);

    printf("Enter time: ");
    scanf("%f", &time);

    printf("Enter rate: ");
    scanf("%f", &rate);

    simpleInterest = (principal * time * rate) / 100;

    printf("Simple Interest = %.2f\n", simpleInterest);

    return 0;
}

Example 2: Find the Smallest Number Among Three Numbers

Question

Write a C program to find the smallest number among three numbers.

Program

#include <stdio.h>

int main(void)
{
    int num1, num2, num3;
    int smallest;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &num1, &num2, &num3);

    smallest = num1;

    if (num2 < smallest)
    {
        smallest = num2;
    }

    if (num3 < smallest)
    {
        smallest = num3;
    }

    printf("The smallest number is: %d\n", smallest);

    return 0;
}

Example 3: Convert Seconds into Hours, Minutes and Seconds

Question

Write a C program to input time in seconds and convert it into hours, minutes, and seconds.

Program

#include <stdio.h>

int main(void)
{
    int totalSeconds;
    int hours;
    int minutes;
    int seconds;

    printf("Enter time in seconds: ");
    scanf("%d", &totalSeconds);

    hours = totalSeconds / 3600;

    totalSeconds = totalSeconds % 3600;

    minutes = totalSeconds / 60;

    seconds = totalSeconds % 60;

    printf(
        "Converted time: %d hour(s), %d minute(s), %d second(s)\n",
        hours,
        minutes,
        seconds
    );

    return 0;
}

Quick Revision

  • C was developed by Dennis Ritchie at Bell Laboratories.
  • C is a general-purpose and structured programming language.
  • C supports both high-level and low-level programming features.
  • The execution of a C program generally involves creation, compilation, linking, and execution.
  • #include is a preprocessor directive.
  • <stdio.h> provides standard input/output facilities.
  • Tokens are the smallest meaningful units of a C program.
  • Variables store values that can change during program execution.
  • Constants represent fixed values.
  • Keywords are reserved words.
  • Identifiers are programmer-defined names.
  • Operators perform operations on operands.
  • ++ and -- are unary increment and decrement operators.
  • +, -, *, /, and % are arithmetic operators.
  • &&, ||, and ! are logical operators.
  • >, <, >=, <=, ==, and != are relational operators.
  • ?: is the conditional or ternary operator.
  • C data types include basic, derived, and user-defined types.
  • printf() is used for formatted output.
  • scanf() is used for formatted input.
  • getchar() reads a character.
  • putchar() displays a character.
  • Comments are ignored by the compiler.
  • Escape sequences begin with a backslash \.

Discussion

Share a helpful question, idea, or explanation with other students.

Leave a Comment

Write a clear question, answer, or helpful explanation.
Your email will not be published.

Download Our Offline App

Study class-wise notes even when internet is not available. Get the app from Play Store.

Nepal eNotes offline app preview
Get it on Google Play