C Programming - Unit 2 and 3
C Programming - Unit 2 and 3
| Year | Event |
|-------|------------------------------------------------------|
| 1969 | Ken Thompson at Bell Labs began developing B, a precursor to C. |
| 1972 | Dennis Ritchie at Bell Labs started working on C as an evolution of B. |
| 1973 | C was first implemented on the DEC PDP-11 computer. |
| 1978 | The first edition of "The C Programming Language" (K&R C) by Kernighan and
Ritchie was published, providing a standard reference for C. |
| 1983 | The American National Standards Institute (ANSI) formed a committee to standardize
the C language. |
| 1989 | The ANSI C standard (ANSI X3.159-1989) was published, which later became the
basis for the ISO C standard. |
| 1990 | The International Organization for Standardization (ISO) adopted ANSI C as the ISO
C standard (ISO/IEC 9899:1990). |
| 1999 | The C Standard (ISO/IEC 9899:1999), often referred to as C99, was released,
introducing many new features and improvements. |
| 2011 | The C Standard (ISO/IEC 9899:2011), often called C11, was published with further
enhancements to the language. |
| 2018 | The C Standard (ISO/IEC 9899:2018), commonly known as C18, was released,
providing clarifications and bug fixes. |
Features of c programming:
C programming is known for its simplicity, flexibility, and versatility. Here are some of the key
features of the C programming language:
2. Preprocessing:
- Before compilation, the C preprocessor processes the code. It handles directives that start
with `#`, such as `#include` (for including header files) and `#define` (for macros). The
preprocessor replaces macros and includes the contents of header files in your code.
3. Compilation:
- Use a C compiler (e.g., GCC, Clang, or Microsoft Visual C++) to compile the preprocessed
code into machine code. This step generates an object file with a `.o` (or `.obj` on Windows)
extension. The compiler checks for syntax errors and other issues during this phase.
4. Linking:
- If your program uses external functions or libraries, the linker links the object files and
resolves references to functions from these external libraries. It generates an executable file,
typically with no file extension (e.g., `a.out` on Unix-like systems).
5. Execution:
- Run the generated executable file. You can execute the program from the command line by
typing the program's name (e.g., `./a.out` on Unix-like systems) or by double-clicking it in a
graphical environment.
6. Runtime Execution:
- The C program starts executing from the `main` function (or any designated entry point)
and performs its tasks according to the code you've written.
7. Output:
- If your program includes output statements (e.g., `printf`), it will produce output to the
console or other output streams, depending on your code.
8. Termination:
- The program continues executing until it reaches the end or explicitly exits (using `return`
in the `main` function or `exit()` function). The operating system then reclaims any resources
allocated to the program.
9. Handling Errors:
- If there are runtime errors or exceptions in your program, you may need to handle them
using error-handling mechanisms like `if` statements or exception handling (if applicable).
10. Debugging (if necessary):
- If you encounter issues during execution, you can use debugging tools and techniques to
identify and fix errors in your code.
The process of executing a C program may vary slightly depending on the development
environment and operating system you are using. Additionally, you can use build automation
tools like Make to streamline the compilation and linking process, making it more efficient and
consistent.
Character set:
In a C program, several character sets are used to represent different types of characters, and
these character sets are important for various aspects of the program. Here are some of the key
character sets used in C programming:
It's important to note that the exact definition and support for character sets may vary depending
on the C compiler and the platform you are using. In practice, many C compilers use character
encodings like ASCII, UTF-8, or UTF-16 for representing characters, and they often support a
wide range of characters from different character sets. Understanding these character sets is
essential for handling character encoding, input/output operations, and string manipulation in
C programming.
C tokens:
In C programming, a "token" is the smallest unit of a program. Tokens are the building blocks
of a C program, and the C compiler recognizes and processes them. There are several types of
tokens in C, including:
1. Keywords: Keywords are reserved words that have special meanings in the C language.
Examples include `int`, `if`, `while`, `for`, and `return`.
2. Identifiers:Identifiers are used to name variables, functions, and other program elements.
They must start with a letter or an underscore and can be followed by letters, digits, or
underscores.
3. Constants: Constants are fixed values that do not change during program execution. There
are two main types of constants:
- Integer Constants: These include decimal integers (e.g., 42), octal integers (e.g., 052), and
hexadecimal integers (e.g., 0x2A).
- Floating-Point Constants: These represent real numbers and include both integer and
fractional parts (e.g., 3.14).
4. String Literals: String literals are sequences of characters enclosed in double quotes, such as
`"Hello, World!"`. They are used to represent strings in the program.
5. Operators: Operators are symbols that perform operations on operands. Examples include
`+`, `-`, `*`, `/`, `==`, and `&&`.
6. Punctuation: Punctuation tokens are symbols that serve various purposes in the program's
syntax. Examples include `{`, `}`, `;`, `,`, `(`, and `)`.
7. Separators: Separators are used to separate parts of a program. The most common separator
is the space character, but others include tabs, line breaks, and comments.
8. Comments: Comments are used for documentation and are not processed by the compiler. C
supports two types of comments:
- Single-Line Comments: These are created using `//` and continue until the end of the line.
- Multi-Line Comments: These are enclosed between `/*` and `*/` and can span multiple
lines.
9. Preprocessor Directives: Preprocessor directives start with `#` and are used to provide
instructions to the C preprocessor. Examples include `#include`, `#define`, and `#ifdef`.
These tokens collectively make up the C program and are processed by the C compiler during
compilation.
Data types:
Data types in C specify the type of data that a variable can hold. C provides a variety of data
types to accommodate different kinds of data, from integers and floating-point numbers to
characters and more. Here are some of the common data types in C:
1. int:
- Used for storing integer values (whole numbers).
- Variants include `int`, `short`, and `long`, which differ in the size of storage.
2. float:
- Used for representing single-precision floating-point numbers (real numbers with a
fractional part).
- Example: `float x = 3.14;`
3. double:
- Used for representing double-precision floating-point numbers (real numbers with greater
precision).
- Example: `double y = 2.71828;`
4. char:
- Used for storing single characters, which can represent characters, letters, or small integers.
- Example: `char grade = 'A';`
5. _Bool:
- Used for Boolean values, which can be either `true` or `false`.
- Example: `_Bool isTrue = 1;`
6. void:
- Represents the absence of a type or an empty data type. It's often used for functions that do
not return a value.
- Example: `void someFunction();`
7. Enums:
- Enums allow you to define a set of named integer constants.
- Example:
```c
enum Color { RED, GREEN, BLUE };
enum Color selectedColor = RED;
8. Arrays:
- Arrays are collections of elements of the same data type.
- Example: `int numbers[5] = {1, 2, 3, 4, 5};`
9. Structures (struct):
- Structures allow you to group variables of different data types together into a single data
type.
- Example:
```c
struct Person {
char name[50];
int age;
};
struct Person person1;
10. Pointers:
- Pointers store memory addresses, allowing you to work with the memory location of
variables.
- Example: `int *ptr;`
11. Union:
- Unions are similar to structures but share the same memory location for their members.
- Example:
```c
union Data {
int num;
float f;
char c;
};
union Data data1;
12. Typedef:
- `typedef` allows you to create custom type aliases.
- Example:
```c
typedef int Length;
Length distance = 100;
13.Long double:
- Represents extended-precision floating-point numbers for high precision.
- Example: `long double pi = 3.14159265358979323846L;`
Variables:
In C, variables are used to store and manipulate data. Variables have a data type that specifies
what kind of data they can hold, and they are given a name that allows you to refer to and
manipulate the data stored in the variable. Here's how variables work in C:
1. Declaring Variables:
- Before using a variable, you need to declare it. A variable declaration specifies the data type
and a name for the variable.
- Example:
```c
int age; // Declares an integer variable named 'age'
float salary; // Declares a floating-point variable named 'salary'
char initial; // Declares a character variable named 'initial'
2. Initializing Variables:
- You can also initialize a variable at the time of declaration, which sets its initial value.
- Example:
```c
int count = 10; // Initializes an integer variable 'count' with the value 10
float pi = 3.14159; // Initializes a float variable 'pi' with the value 3.14159
char grade = 'A'; // Initializes a character variable 'grade' with the value 'A'
3. Assigning Values:
- After declaring and optionally initializing a variable, you can assign new values to it using
the assignment operator (`=`).
- Example:
```c
age = 25; // Assigns the value 25 to the 'age' variable
salary = 50000.0; // Assigns the value 50000.0 to the 'salary' variable
initial = 'J'; // Assigns the character 'J' to the 'initial' variable
4. Using Variables:
- You can use variables in expressions and statements to perform operations or access their
values.
- Example:
```c
int total = count + 5; // Calculates the sum of 'count' and 5 and stores it in 'total'
printf("Age: %d\n", age); // Prints the value of 'age' using the 'printf' function
5. Scope of Variables:
- Variables can have different scopes. A variable declared within a block of code is usually
local to that block. Variables declared outside of any function (at the global scope) have file
scope and are accessible throughout the file.
- Example:
```c
int globalVar; // A variable with file scope
void someFunction() {
int localVar; // A variable with local scope
// ...
}
6. Lifetime of Variables:
- Variables have a lifetime that corresponds to their scope. Local variables typically exist only
within the block or function they are declared in. Global variables exist throughout the
program's execution.
7. Constants:
- In addition to variables, you can also declare constants in C using the `const` keyword.
Constants have fixed, unchangeable values.
- Example:
```c
const int days_in_week = 7; // Declares a constant 'days_in_week' with the value 7
Variables are a fundamental concept in C, and they play a crucial role in storing and
manipulating data in your programs. Understanding data types, scope, and the proper use of
variables is essential for writing correct and efficient C code.
Storage class:
In C, storage classes define the scope, visibility, and lifetime of variables. There are four
primary storage classes in C:
Data overflow:
Data overflow, also known as overflow or overflow error, occurs when a computer program or
system attempts to store data in a memory location or data type that cannot accommodate the
data's size or value. When data overflow occurs, the excess data is discarded or wrapped
around, leading to unexpected and potentially erroneous results. Data overflow can occur in
various contexts, including integer overflow and buffer overflow.
1. Integer Overflow:
- Integer overflow happens when an arithmetic operation on integer data types (e.g., int, long)
results in a value that is too large to be represented within the available number of bits.
- For example, if you add 1 to the maximum representable integer value, you may get a result
that wraps around to the minimum representable value (this is called two's complement
overflow).
- Integer overflow can lead to unexpected behavior, crashes, and security vulnerabilities in
software.
```c
int maxInt = INT_MAX; // Maximum representable integer value
int overflowed = maxInt + 1; // This may result in undefined behavior
```
2. Buffer Overflow:
- Buffer overflow is a type of data overflow that occurs when data is written beyond the
bounds of a fixed-size data buffer (e.g., an array) in memory.
- If unchecked, buffer overflow can lead to memory corruption and is a common security
vulnerability that can be exploited by attackers to gain unauthorized access or crash a program.
```c
char buffer[10]; // A buffer with space for 10 characters
strcpy(buffer, "This is a long string that overflows the buffer"); // Buffer overflow occurs
```
To prevent data overflow, it's essential to:
- Use appropriate data types: Choose data types that can accommodate the expected range of
values for your variables
- Check for overflows: Implement checks to detect potential overflows before they occur. This
may involve validating user input or using conditional statements to ensure that the results of
arithmetic operations are within acceptable bounds.
- Use safe functions: When working with strings and buffers, use safe library functions like
`strncpy`, `snprintf`, and bounds-checked functions to prevent buffer overflows.
- Handle exceptions and errors: Implement error handling mechanisms to gracefully handle
overflows when they occur, and avoid undefined behavior.
- Keep software and libraries up to date: Vulnerabilities related to buffer overflows are often
patched in software updates, so it's important to maintain a current and secure software
environment.
Preventing data overflow is essential for writing reliable and secure software. Failing to handle
data overflow can result in unpredictable behavior, crashes, or security vulnerabilities in your
programs.
Operators:
Operators in C are symbols that represent operations to be performed on variables and values.
C provides a wide range of operators that can be categorized into various types, including
arithmetic, relational, logical, assignment, bitwise, and more. Here's an overview of some of
the common operators in C:
1. Arithmetic Operators:
- These operators perform basic mathematical operations.
- Addition `+`
- Subtraction `-`
- Multiplication `*`
- Division `/`
- Modulus `%` (remainder after division)
- Increment `++` (adds 1 to a variable)
- Decrement `--` (subtracts 1 from a variable)
2. Relational Operators:
- These operators compare two values and return a Boolean result (`true` or `false`).
- Equal to `==`
- Not equal to `!=`
- Greater than `>`
- Less than `<`
- Greater than or equal to `>=`
- Less than or equal to `<=`
3. Logical Operators:
- Logical operators are used to combine or modify Boolean values.
- Logical AND `&&`
- Logical OR `||`
- Logical NOT `!`
4. Assignment Operators:
- These operators are used to assign values to variables.
- Assignment `=`
- Addition assignment `+=`
- Subtraction assignment `-=`
- Multiplication assignment `*=`
- Division assignment `/=`
- Modulus assignment `%=`
5. Bitwise Operators:
- Bitwise operators perform operations at the bit level.
- Bitwise AND `&`
- Bitwise OR `|`
- Bitwise XOR `^`
- Bitwise NOT `~`
- Left shift `<<`
- Right shift `>>`
6. Conditional (Ternary) Operator:
- The conditional operator is used for simple conditional expressions.
- Syntax: `condition ? expr1 : expr2`
- If the condition is `true`, `expr1` is evaluated; otherwise, `expr2` is evaluated.
7. Comma Operator:
- The comma operator is used to separate expressions in a statement. It evaluates each
expression from left to right and returns the result of the last expression.
- Example: `a = 5, b = 10, c = a + b;`
9. Pointer Operators:
- `*` is used for pointer declaration and dereferencing.
- `&` is used to get the address of a variable.
- Example: `int *ptr; ptr = &x;`
Operator Precedence:
Operators with higher precedence are evaluated before operators with lower precedence. For
example, multiplication (`*`) has higher precedence than addition (`+`), so `a * b + c` is
equivalent to `(a * b) + c`, not `a * (b + c)`.
Here is a general hierarchy of operator precedence in C from highest to lowest (with some
examples):
1. Postfix operators: `()`, `[]`, `->`, `.`, `++`, `--`
- Example: `array[i]`, `ptr->member`, `function()`
2. Unary operators: `+`, `-`, `!`, `~`, `*` (dereference), `&` (address-of), `sizeof`
- Example: `-x`, `!flag`, `&variable`
3. Multiplicative operators: `*`, `/`, `%`
- Example: `a * b`, `x / y`, `num % divisor`
4. Additive operators: `+`, `-`
- Example: `x + y`, `total - discount`
5. Shift operators: `<<`, `>>`
- Example: `value << 2`, `result >> 1`
6. Relational operators: `<`, `>`, `<=`, `>=`
- Example: `a < b`, `x >= y`
7. Equality operators: `==`, `!=`
- Example: `x == y`, `flag != true`
8. Bitwise AND operator: `&`
- Example: `a & b`
9. Bitwise XOR operator: `^`
- Example: `x ^ y`
10. Bitwise OR operator: `|`
- Example: `mask | value`
Associativity:
If operators have the same precedence, their associativity determines the order in which they
are evaluated.
- Left-to-right (left-associative): Operators are evaluated from left to right.
- Right-to-left (right-associative): Operators are evaluated from right to left.
For example, the assignment operator `=` is right-associative, so `a = b = c` is evaluated as `a
= (b = c)`.
It's important to understand operator precedence and associativity to write expressions that
produce the intended results and to avoid unexpected behavior in C programs. You can use
parentheses to override these rules and specify the order of evaluation explicitly.
I/O Functions:
C programming provides a set of standard input/output functions that allow you to perform
input and output operations. These functions are part of the standard library and are declared
in the `stdio.h` header file. Here are some of the commonly used I/O functions in C
programming:
Unit 3:
PLEASE REFER LIST OF PROGRAMS PERFORMED USING IF STATEMENT, IF-ELSE
STATEMENT AND SWITCH CONDITION