0% found this document useful (0 votes)
18 views28 pages

Fundamentals of C

The document provides a comprehensive overview of the C programming language, covering its history, key features, structure of a program, compilation process, debugging techniques, data types, variable declaration, storage classes, enumerations, macros, and operators. It highlights the procedural nature of C, its applications in various domains, and essential programming concepts such as syntax, identifiers, and error handling. Additionally, it includes examples and explanations of different components and functionalities within C programming.

Uploaded by

sbarnwal704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views28 pages

Fundamentals of C

The document provides a comprehensive overview of the C programming language, covering its history, key features, structure of a program, compilation process, debugging techniques, data types, variable declaration, storage classes, enumerations, macros, and operators. It highlights the procedural nature of C, its applications in various domains, and essential programming concepts such as syntax, identifiers, and error handling. Additionally, it includes examples and explanations of different components and functionalities within C programming.

Uploaded by

sbarnwal704
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Fundamentals of C Programming Language

Introduction to C Programming Language


C is a general-purpose, procedural programming language that was developed in 1972
by Dennis Ritchie at Bell Labs. It was designed for system programming and has
influenced many modern languages like C++, Java, Python, and Rust.

Key Features of C

1. Procedural Language: Follows a step-by-step procedural approach.


2. Portability: Code written in C can be compiled and executed on various platforms
with minimal modifications.
3. Efficiency: Produces optimized machine code that runs fast.
4. Low-Level Access: Provides direct interaction with hardware via pointers and
memory management.
5. Modularity: Supports functions, making code reusable.
6. Rich Library Support: Has a robust standard library for various operations.

Applications of C

• Operating Systems (UNIX, Linux kernel, Windows components)


• Embedded Systems (Microcontrollers, IoT devices)
• Compilers and Interpreters (C is used to build other languages)
• Database Management Systems (MySQL)
• Graphics and Game Development

Structure of a C Program
A C program follows a well-defined structure:

Basic Structure of a C Program

#include <stdio.h> // Preprocessor Directive


// Function Declaration
void greet();

int main() { // Main Function - Entry Point


printf("Hello, World!\n"); // Statement
greet(); // Function Call
return 0; // Return Statement
}

// Function Definition
void greet() {
printf("Welcome to C Programming!\n");
}

Components of a C Program

1. Preprocessor Directives: #include <stdio.h> – Includes standard libraries.


2. Global Declarations: Constants or global variables can be declared.
3. main() Function: The starting point of execution.
4. Variable Declarations: Variables are declared before use.
5. Statements and Function Calls: Program logic is implemented here.
6. User-Defined Functions: Functions improve modularity and code reuse.

Compilation and Execution of C Programs


A C program goes through several steps before execution:

Steps of Compilation & Execution

1. Editing: Writing the source code (.c file).


2. Preprocessing (cpp): Handles #include and #define directives.
3. Compilation (cc): Translates the source code into assembly language.
4. Assembly (as): Converts assembly code to machine code.
5. Linking (ld): Links libraries and generates an executable file.
6. Execution: The OS loads and runs the program.
Debugging Techniques in C
Debugging is the process of identifying and fixing errors (bugs) in a program.

Types of Errors

1. Syntax Errors: Violations of C syntax rules.


Example:

int x = 10 // Missing semicolon (Syntax Error)

2. Logical Errors: Incorrect logic leading to wrong results.


Example:

int x = 10, y = 0;
int result = x / y; // Division by zero (Logical Error)

3. Runtime Errors: Errors occurring during execution (e.g., memory access violation).

Debugging Techniques

1. Using printf() Statements

printf("Value of x: %d\n", x);

2. Using Debuggers (GDB)

gdb ./program

3. Breakpoints: Stop execution at specific points for analysis.


4. Valgrind (Memory Debugging)
valgrind --leak-check=full ./program

5. Static Analysis Tools: Tools like clang-tidy, cppcheck.


Data Types and Sizes in C
C provides various data types for variable declaration.

Primary Data Types

Data Type Size (bytes) Range (Typical)


char 1 -128 to 127
unsigned char 1 0 to 255
int 2 or 4 -32,768 to 32,767 (2 bytes) / -2,147,483,648 to
2,147,483,647 (4 bytes)
unsigned int 2 or 4 0 to 65,535 (2 bytes) / 0 to 4,294,967,295 (4 bytes)
short 2 -32,768 to 32,767
long 4 or 8 -2,147,483,648 to 2,147,483,647 (4 bytes)
float 4 ~6 decimal places
double 8 ~15 decimal places
long double 10-16 Higher precision

Derived Data Types

1. Arrays: Collection of elements (int arr[5]).


2. Pointers: Store memory addresses (int *ptr).
3. Structures (struct): Group different data types.
4. Unions (union): Share memory among multiple variables.
5. Enumerations (enum): Define a set of named integer constants.

Declaration of Variables
A variable is a name assigned to a memory location.

Syntax for Declaring Variables

data_type variable_name;
Example

int age; // Declaration


float pi = 3.14; // Declaration with initialization

Rules for Variable Declaration

• Must start with a letter (a-z, A-Z) or underscore _


• Cannot be a keyword (e.g., int, float, return)
• Cannot have special characters (@, $, %)

Modifiers in C
C provides type modifiers to alter data type properties.

Modifier Effect
signed Default for int, allows positive & negative values
unsigned Allows only positive values (e.g., unsigned int)
short Uses less memory (e.g., short int)
long Increases memory size (e.g., long int)

Example

unsigned int a = 10;


long double b = 5.6789;

Identifiers and Keywords

Identifiers
Identifiers are the names of variables, functions, arrays, etc.
Rules for Identifiers

1. Can contain letters, digits, and underscores (_)


2. Cannot start with a digit
3. Case-sensitive (sum and SUM are different)
4. Cannot use C keywords

Example of Identifiers

int rollNumber;
float student_marks;

Keywords
C has 32 reserved keywords that cannot be used as identifiers.

List of Keywords in C

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

Storage Classes in C
Storage classes in C determine the scope, lifetime, default value, and storage location
of a variable. They define how and where a variable is stored, its visibility, and its
existence throughout program execution.

Types of Storage Classes in C


1. auto (Automatic Storage Class)
2. register (Register Storage Class)
3. static (Static Storage Class)
4. extern (External Storage Class)

1. Automatic Storage Class (auto)


• Scope: Local to the function/block where it is declared.
• Lifetime: Exists until the function/block execution ends.
• Default Initial Value: Garbage value (uninitialized memory).
• Storage Location: RAM (stack memory).
• Keyword: auto (optional, as local variables are auto by default).

Example

#include <stdio.h>

void function() {
auto int x = 10; // Auto storage class (local variable)
printf("Value of x: %d\n", x);
}

int main() {
function();
return 0;
}

Output:

Value of x: 10

Explanation:

• x is created when function() is called.


• x is destroyed after function() execution ends.
Key Points

Automatically created and destroyed.


Default for local variables.
Cannot retain values between function calls.

2. Register Storage Class (register)


• Scope: Local to the function/block where it is declared.
• Lifetime: Exists until the function execution ends.
• Default Initial Value: Garbage value.
• Storage Location: CPU registers (if available).
• Keyword: register.

Example

#include <stdio.h>

int main() {
register int count = 10; // Store variable in CPU register
printf("Count: %d\n", count);
return 0;
}

Output:

Count: 10

Key Points

Faster access as it may be stored in CPU registers.


Cannot use the & (address-of) operator as registers have no memory address.
Storage in registers is not guaranteed (depends on CPU availability).
3. Static Storage Class (static)
• Scope:
o Local static variables: Limited to the function/block where declared.
o Global static variables: Limited to the file (internal linkage).
• Lifetime: Exists throughout program execution.
• Default Initial Value: Zero (0) for numbers, NULL for pointers.
• Storage Location: Data segment (not stack).
• Keyword: static.

Example 1: Static Local Variable

#include <stdio.h>

void counter() {
static int count = 0; // Static variable retains value
count++;
printf("Count: %d\n", count);
}

int main() {
counter();
counter();
counter();
return 0;
}

Output:

Count: 1
Count: 2
Count: 3

Explanation:
• count retains its value between function calls.

Example 2: Static Global Variable

#include <stdio.h>

static int num = 100; // File scope (internal linkage)

void display() {
printf("num: %d\n", num);
}

int main() {
display();
return 0;
}

Key Points Local static variables retain values between function calls.
Global static variables are not accessible outside the file.
Uses memory for the entire program duration (not efficient for short-term variables).

4. External Storage Class (extern)


• Scope: Global, accessible from multiple files.
• Lifetime: Entire program execution.
• Default Initial Value: Zero (0) for numbers, NULL for pointers.
• Storage Location: Data segment.
• Keyword: extern.

Example: Using extern Across Multiple Files

File1.c

#include <stdio.h>
int num = 100; // Global variable

void display() {
printf("num: %d\n", num);
}

File2.c

#include <stdio.h>

extern int num; // Referencing num from File1.c

int main() {
printf("Accessing num in File2: %d\n", num);
return 0;
}

Explanation:

• extern declares the variable num (which is defined in File1.c).


• This allows access to num without re-declaring it.

Key Points

Used for global variable access across multiple files.


Reduces memory usage by avoiding redundant variable declarations.
Must not initialize an extern variable inside a function.

Comparison Table of Storage Classes


Storage Scope Lifetime Default Storage Location Keyword
Class Value
auto Local Function Garbage Stack auto
execution (optional)
register Local Function Garbage CPU registers (if register
execution available)
static Local Entire program 0 Data segment static
(local) execution
static File Entire program 0 Data segment static
(global) scope execution
extern Global Entire program 0 Data segment extern
execution

Enumerations (enum)
Enumerations provide a way to assign names to integer values.

Syntax

enum Color {RED, GREEN, BLUE};

Example

#include <stdio.h>
enum Color {RED, GREEN, BLUE};

int main() {
enum Color myColor = GREEN;
printf("Value of GREEN: %d\n", myColor);
return 0;
}

Output:
Value of GREEN: 1

Macros in C

A macro is a preprocessor directive that replaces code before compilation.


Example

#include <stdio.h>
#define SQUARE(x) (x * x)

int main() {
printf("Square of 5: %d\n", SQUARE(5));
return 0;
}

The C Preprocessor

The C preprocessor (cpp) modifies source code before compilation.

Common Preprocessor Directives

Directive Description
#include Includes header files (#include <stdio.h>)
#define Defines macros (#define PI 3.14)

Operators in C
Operators in C are symbols that perform operations on variables and values. They are
classified into different types based on their functionality.

1. Unary Operators
Unary operators operate on a single operand. Common unary operators in C include:

a. Unary Plus (+) and Unary Minus (-)

• +a: Returns the positive value of a.


• -a: Negates the value of a.

Example:
int a = 10;
int b = -a; // b becomes -10

b. Increment (++) and Decrement (--)

• ++a (Pre-increment): Increases a by 1 before using it.


• a++ (Post-increment): Uses a first, then increases it by 1.
• --a (Pre-decrement): Decreases a by 1 before using it.
• a-- (Post-decrement): Uses a first, then decreases it by 1.

Example:

int x = 5;
int y = ++x; // x becomes 6, y is assigned 6
int z = x--; // z is assigned 6, x becomes 5

c. Logical NOT (!)

• Negates a boolean value.


• !1 → 0, !0 → 1

Example:

int a = 0;
if (!a) {
printf("a is false");
}

d. Bitwise NOT (~)

• Flips all bits of a number.


• ~5 (00000101 → 11111010)

Example:
int a = 5;
int b = ~a; // b becomes -6 (Two’s complement representation)

e. Address-of (&)

• Returns the memory address of a variable.

Example:

int a = 10;
printf("%p", &a); // Prints address of a

f. Dereference (*)

• Used with pointers to access value at a memory location.

Example:

int a = 10;
int *ptr = &a;
printf("%d", *ptr); // Prints 10

g. Type Casting ((type))

• Converts a variable from one data type to another.

Example:

int a = 10;
float b = (float)a / 3; // b becomes 3.3333

2. Arithmetic and Logical Operators

a. Arithmetic Operators

These operators perform mathematical operations.


OPERATOR DESCRIPTION EXAMPLE
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (Remainder) a % b

Example:

int a = 10, b = 3;
printf("%d", a % b); // Prints 1 (Remainder of 10/3)

b. Logical Operators

Used in conditional statements.

OPERATOR DESCRIPTION EXAMPLE


&& Logical AND (a > 5 && b < 10)
` `
! Logical NOT !a

Example:

int a = 1, b = 0;
if (a && b) {
printf("Both are true");
} else {
printf("At least one is false"); // This will execute
}

3. Bitwise Operators
Bitwise operators perform bitwise manipulation.

Operator Description Example (a = 5, b = 3)


& AND a & b → 1 (0101 & 0011 = 0001)
` ` OR
^ XOR a ^ b → 6 (0101 ^ 0011 = 0110)
~ NOT ~a → -6 (~0101 = 1010 in two’s complement)
<< Left Shift a << 1 → 10 (0101 → 1010)
>> Right Shift a >> 1 → 2 (0101 → 0010)

Example:

int a = 5, b = 3;
printf("%d", a & b); // Prints 1

4. Assignment Operators
Used to assign values to variables.

Operator Example Equivalent To


= a = 5 a =5
+= a += 5 a =a + 5
-= a -= 5 a =a - 5
*= a *= 5 a =a * 5
/= a /= 5 a =a / 5
%= a %= 5 a =a % 5
&= a &= 5 a =a & 5
` =` `a
^= a ^= 5 a = a ^ 5
<<= a <<= 2 a = a << 2
>>= a >>= 2 a = a >> 2

Example:

int a = 10;
a += 5; // a becomes 15

5. Conditional (Ternary) Operator (?:)


The ternary operator provides a shorthand way to write if-else statements.

Syntax:
condition ? expression1 : expression2;

Example:

int a = 10, b = 5;
int min = (a < b) ? a : b; // min is 5

6. Operator Precedence and Order of Evaluation


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

a. Operator Precedence Table (Highest to Lowest)

Precedence Operators Associativity


1 () [] -> . Left to Right
2 ++ -- ! ~ + - * & (type) sizeof Right to Left
3 */% Left to Right
4 +- Left to Right
5 << >> Left to Right
6 < <= > >= Left to Right
7 == != Left to Right
8 & Left to Right
9 ^ Left to Right
10 ` `
11 && Left to Right
12 `
13 ?: Right to Left
14 = += -= *= /= %= <<= >>= &= ^= ` =`
15 , Left to Right

b. Order of Evaluation

• Operators with higher precedence are evaluated first.


• Operators with the same precedence follow their associativity.
• Parentheses () can be used to override precedence.

Example:
int a = 10, b = 5, c = 2;
int result = a + b * c; // Multiplication (*) happens first: 10 + (5 *
2) = 20

To enforce addition first:

int result = (a + b) * c; // (10 + 5) * 2 = 30

Control Statements in C
Control statements regulate the flow of execution in a program. The main control
statements in C are:

1. if-else Statement

The if-else statement is used to perform conditional execution.

Syntax:

if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}

Example:

int num = 10;


if (num > 0) {
printf("Positive number");
} else {
printf("Negative number");
}
if-else Variants

• if statement (without else)

if (condition) {
// Executes if condition is true
}

• if-else-if ladder

if (condition1) {
// Executes if condition1 is true
} else if (condition2) {
// Executes if condition2 is true
} else {
// Executes if all conditions are false
}

2. switch Statement

The switch statement is used when multiple conditions need to be checked.

Syntax:

switch (expression) {
case value1:
// Code to execute
break;
case value2:
// Code to execute
break;
default:
// Default case (if no match)
}

Example:
int day = 3;
switch (day) {
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
default:
printf("Invalid day");
}

3. break Statement

The break statement is used to exit loops or switch cases prematurely.

Example:

for (int i = 0; i < 10; i++) {


if (i == 5) {
break; // Exits the loop when i is 5
}
printf("%d ", i);
}

4. continue Statement

The continue statement skips the current iteration and moves to the next iteration in loops.

Example:

for (int i = 0; i < 10; i++) {


if (i == 5) {
continue; // Skips the iteration when i is 5
}
printf("%d ", i);
}

5. The Comma Operator (, )

The comma operator allows multiple expressions to be executed in a single statement.

Example:

int a, b, c;
a = (b = 5, c = 10, b + c); // a = 15
printf("%d", a);

6. goto Statement

The goto statement transfers control to a labeled statement.

Syntax:

goto label;
...
label:
statement;

Example:

int num = 10;


if (num > 0)
goto positive;
printf("This won't be printed");

positive:
printf("Number is positive");
Loops in C
Loops allow repeated execution of a block of code.

1. for Loop

Used when the number of iterations is known.

Syntax:

for (initialization; condition; increment/decrement) {


// Code to execute
}

Example:

for (int i = 0; i < 5; i++) {


printf("%d ", i);
}

2. while Loop

Used when the number of iterations is not known.

Syntax:

while (condition) {
// Code to execute
}

Example:

int i = 0;
while (i < 5) {
printf("%d ", i);
i++;
}
3. do-while Loop

Executes at least once, even if the condition is false.

Syntax:

do {
// Code to execute
} while (condition);

Example:

int i = 0;
do {
printf("%d ", i);
i++;
} while (i < 5);

Program: Check Even or Odd

#include <stdio.h>

int main() {
int num;

// Input from user


printf("Enter an integer: ");
scanf("%d", &num);

// Check even or odd


if (num % 2 == 0) {
printf("%d is Even.\n", num);
} else {
printf("%d is Odd.\n", num);
}
return 0;
}

Explanation

1. The program takes an integer input from the user.


2. It checks if the number is divisible by 2 using the modulus (%)
operator.
a. If num % 2 == 0, the number is even.
b. Otherwise, the number is odd.
3. The result is displayed accordingly.

Example Output

Enter an integer: 7
7 is Odd.

Functions in C
A function in C is a block of code designed to perform a specific task. It can be called
multiple times within a program to avoid redundancy and improve modularity.

1. Built-in Functions

Functions provided by C libraries, such as:

• printf(), scanf() (stdio.h)


• strlen(), strcpy() (string.h)
• pow(), sqrt() (math.h)

2. User-defined Functions

Functions created by the programmer.

Syntax:
return_type function_name(parameters) {
// Function body
return value;
}

Example:

int add(int a, int b) {


return a + b;
}

Function Declaration, Definition, and Call

• Declaration: int add(int, int);


• Definition: (Same as above)
• Function Call: int sum = add(5, 10);

3. Parameter Passing

Call by Value

Passes a copy of the variable; changes do not reflect.

Example:

void func(int x) {
x = 20;
}

Call by Reference

Passes address; changes reflect in original value.

Example:

void func(int *x) {


*x = 20;
}

4. Recursive Function

A function that calls itself.

Example (Factorial Calculation):

int factorial(int n) {
if (n == 0)
return 1;
return n * factorial(n - 1);
}

Arrays in C
An array is a collection of elements of the same data type stored in contiguous memory
locations. It allows storing multiple values under a single variable name and accessing
them using an index.

1. Linear (One-Dimensional) Array

Syntax:

data_type array_name[size];

Example:

int arr[5] = {1, 2, 3, 4, 5};

2. Multidimensional Arrays

Arrays with multiple dimensions.

Example (2D Array):


int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

3. Passing Arrays to Functions

Example:

void printArray(int arr[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}

4. Arrays and Strings

Strings are character arrays.

Example:

char str[] = "Hello";


printf("%s", str);

String Handling Functions

Requires #include <string.h>.

• strlen(str) – Length of string


• strcpy(dest, src) – Copy string
• strcmp(str1, str2) – Compare strings
• strcat(str1, str2) – Concatenate strings

You might also like