0% found this document useful (0 votes)
11 views

UNIT-1

Uploaded by

VIJAY
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

UNIT-1

Uploaded by

VIJAY
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIT - I

INTRODUCTION TO C:

C is a powerful and widely-used programming language, known for its efficiency,


flexibility, and portability is a general-purpose, procedural programming language
developed by Dennis Ritchie at Bell Labs in the early 1970s. It is widely used for
system programming, embedded systems, and developing operating systems,
compilers, and applications.

The C programming language, developed by Dennis Ritchie in the early 1970s at


Bell Labs, is known for its efficiency, control, and portability.

Features of C:

1. Simplicity: C has a simple set of keywords, making it easier to learn and use
compared to many other languages. Its syntax is straightforward, yet powerful.

2. Portability: C programs can be easily transferred from one machine to another with
minimal or no modification, making it a highly portable language.

3. Low-Level Access: C allows for direct manipulation of hardware and memory


through the use of pointers, making it suitable for system programming like operating
system development.

4. Rich Library Support: The C Standard Library provides a plethora of built-in


functions for handling input/output operations, string manipulations, memory
allocation, and various other functionalities.

5. Modularity: C supports modular programming through the use of functions. This


enables code reuse and better organization of programs.

6. Efficiency: C programs are generally very efficient in terms of execution speed and
memory usage. This efficiency is a result of its close-to-hardware operations and
minimal runtime overhead.

7. Structured Programming: C promotes structured programming paradigms, which


involve dividing the program into smaller, manageable functions or modules. This
helps in improving clarity, quality, and development time.
8. Extensibility: C can easily be extended by adding new functions and features,
allowing developers to build upon the existing framework.

9. Dynamic Memory Management: C provides dynamic memory allocation


functions such as `malloc()`, `calloc()`, `realloc()`, and `free()`, giving programmers
fine-grained control over memory usage.

10. Recursion: C supports recursion, where functions can call themselves. This is
useful for solving problems that can be broken down into smaller, similar sub-
problems.

11. Pointers: C includes extensive support for pointers, which are variables that store
memory addresses. Pointers are powerful for dynamic memory allocation, array
manipulation, and handling function arguments.

12. Bitwise Operations: C supports bitwise operators that enable manipulation of data
at the bit level, which is useful in systems programming, network programming, and
other low-level applications.

13. Fast Compilation and Execution: C compilers are generally very fast, and the
compiled code runs efficiently on most hardware, making it suitable for performance-
critical applications.

key aspects of the C language:

1. Syntax: C has a relatively simple syntax compared to some other languages,


making it easy to learn. It uses semicolons to terminate statements and curly
braces to define blocks of code.
2. Variables and Data Types: C supports various data types such as integers,
floats, characters, and pointers. Variables must be declared before they are used,
specifying their data type.
3. Functions: In C, programs are organized into functions. A function is a block of
code that performs a specific task. The `main()` function is where program
execution begins.
4. Control Structures: C provides various control structures such as if-else
statements, loops (like for, while, and do-while loops), and switch-case
statements for decision-making and iteration.
5. Arrays and Pointers: C supports arrays, which are collections of elements of
the same data type, and pointers, which are variables that store memory
addresses. Pointers are a powerful feature of C and are widely used for tasks
like dynamic memory allocation and working with arrays.
6. Memory Management: C gives the programmer direct control over memory
management through functions like `malloc()` and `free()`, allowing for
efficient memory allocation and de-allocation.
7. Preprocessor Directives: C uses preprocessor directives, which begin with a
hash (#) symbol, to include header files, define constants, and perform other
preprocessing tasks before compilation.
8. Standard Library: C comes with a standard library (stdlib.h, stdio.h, etc.) that
provides functions for tasks like input/output, string manipulation, mathematical
operations, and memory management.
9. Portability: C code is highly portable, meaning it can be compiled and run on
different platforms with minimal changes.
10.Compile and Link: C programs are typically compiled into machine code
using a compiler like GCC or Clang, and then linked with libraries to create an
executable file.

Example-1: Hello, World!

The classic "Hello, World!" program in C prints a message to the console.

#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}

Explanation:
- `#include <stdio.h>`: Includes the standard input-output library, providing functions
like `printf()`.
- `intmain()`: Entry point of the program, where execution begins.
- `printf("Hello, World!\n");`: Prints "Hello, World!" to the console.
- `return 0;`: Indicates successful program completion.

Example-2: Variables and Arithmetic Operations

C supports various data types and arithmetic operations.

#include <stdio.h>
int main() {
int num1 = 10, num2 = 5;
int sum, difference, product;
float quotient;

sum = num1 + num2;


difference = num1 - num2;
product = num1 * num2;
quotient = (float)num1 / num2;

printf("Sum: %d\n", sum);


printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %.2f\n", quotient);

return 0;
}

Explanation:
- `int num1 = 10, num2 = 5;`: Declares and initializes two integers.
- `int sum, difference, product; float quotient;`: Declares variables for storing results.
- Arithmetic operations (`+`, `-`, `*`, `/`) are performed.
- `(float)num1 / num2;`: Type casting ensures floating-point division.
- `%.2f`: Format specifier for printing floating-point numbers with two decimal places.

Example-3: Conditional Statements

C provides conditional statements for decision-making.

#include <stdio.h>

int main() {
intnum = 10;

if (num> 0) {
printf("Number is positive\n");
} else if (num< 0) {
printf("Number is negative\n");
} else {
printf("Number is zero\n");
}

return 0;
}

Explanation:
- `if`, `else if`, `else`: Used for conditional execution based on the value of `num`.
- `num> 0`: Condition for positive number.
- `num< 0`: Condition for negative number.
- `printf()`: Outputs the appropriate message based on the condition.

These examples provide a glimpse into the basics of C programming, including


outputting text, variable declaration, arithmetic operations, and conditional statements.
C offers much more in terms of functionality, control structures, and data handling,
making it a versatile and powerful language for various programming tasks.

DATATYPES IN C:

In C programming, data types specify the type of data that a variable can hold. Here
are the primary data types in C:

1. Basic Data Types:


a. int: Used to store integer values. Typically, it represents whole numbers,
both positive and negative.
b. char: Used to store single characters. It can hold any character from the
ASCII character set.
c. float: Used to store floating-point numbers, which include decimal
points.
d. double: Similar to float but can hold larger floating-point numbers with
double precision.

2. Derived Data Types:


a. Arrays: Collections of elements of the same data type. For example,
`intnumbers[5]` declares an array of 5 integers.
b. Structures (struct): User-defined data types that can hold different types
of data under a single name. They allow you to group variables of
different data types together.
c. Unions: Similar to structures, but union members share the same memory
location. Only one member can hold a value at a time.
d. Pointers: Variables that store memory addresses. They point to the
location of another variable in memory.

3. Enum Data Type (Enumeration):


Enums are used to define a set of named integer constants. This allows
you to create symbolic names for values, improving code readability.

4. Void Data Type:


The void data type is used to indicate that a function does not return any
value. It is also used to indicate a pointer that does not point to any
specific data type.

5. Qualified Data Types:


a. const: Used to declare constants, variables whose value cannot be
changed once assigned.
b. volatile: Indicates that a variable's value can be changed unexpectedly by
external factors (e.g., hardware).

These data types can be combined or used in combination with modifiers like `signed`,
`unsigned`, `short`, and `long` to specify the range and storage size of variables.

It's essential to choose the appropriate data type based on the requirements of your
program to efficiently use memory and ensure data integrity.

OPEARTORS AND EXPRESSIONS:

In C programming, operators are symbols that represent computations or actions to be


performed on operands. Expressions are combinations of operators and operands that
produce a value. Here are the main types of operators and expressions in C:

1. Arithmetic Operators:
- Addition `+`
- Subtraction `-`
- Multiplication `*`
- Division `/`
- Modulus `%` (remainder after division)

These operators perform basic arithmetic operations on numeric operands.

2. Relational Operators:
- Equal to `==`
- Not equal to `!=`
- Greater than `>`
- Less than `<`
- Greater than or equal to `>=`
- Less than or equal to `<=`
These operators compare two operands and return a Boolean value (`true` or `false`)
based on the comparison result.

3. Logical Operators:
- Logical AND `&&`
- Logical OR `||`
- Logical NOT `!`

These operators perform logical operations on Boolean operands and return Boolean
results.

4. Assignment Operators:
- Assignment `=`
- Compound assignment operators like `+=`, `-=`, `*=`, `/=`, `%=` etc.

These operators assign values to variables. Compound assignment operators combine


an arithmetic operation with assignment.

5. Increment and Decrement Operators:


- Increment `++`
- Decrement `--`
These operators are used to increase (`++`) or decrease (`--`) the value of a variable by
1.
6. Bitwise Operators:
- Bitwise AND `&`
- Bitwise OR `|`
- Bitwise XOR `^`
- Bitwise NOT `~`
- Left shift `<<`
- Right shift `>>`

These operators perform operations at the bit level on integer operands.

7. Conditional Operator (Ternary Operator):


- `? :`

This operator evaluates a condition and returns one of two expressions based on
whether the condition is true or false.

8. Comma Operator:
- `,`
This operator allows multiple expressions to be evaluated in a single statement, with
the value of the last expression being the result.

9. Member Access Operators:


- Dot `.` (used for accessing members of a structure)
- Arrow `->` (used for accessing members of a structure through a pointer)

10. Sizeof Operator:


- `sizeof`

This operator returns the size of a variable or data type in bytes.

These operators and expressions form the foundation of C programming and are used
extensively in writing logic and algorithms. Understanding them thoroughly is crucial
for effective programming.

Type of operator with examples:

1. Arithmetic Operators:

int a = 10, b = 5;
int sum = a + b; // Addition
int difference = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus
2. Relational Operators:

int x = 10, y = 5;
if (x > y) {
printf("x is greater than y\n");
}
if (x != y) {
printf("x is not equal to y\n");
}

3. Logical Operators:

int p = 1, q = 0;
if (p && q) {
printf("Both p and q are true\n");
}
if (p || q) {
printf("At least one of p or q is true\n");
}

4. Assignment Operators:

intnum = 10;
num += 5; // Equivalent to num = num + 5
num *= 2; // Equivalent to num = num * 2

5. Increment and Decrement Operators:

int count = 0;
count++; // Increment by 1
count--; // Decrement by 1

6. Bitwise Operators:

int x = 5, y = 3;
intbitwise_and = x & y; // Bitwise AND
intbitwise_or = x | y; // Bitwise OR
intbitwise_xor = x ^ y; // Bitwise XOR
intbitwise_not = ~x; // Bitwise NOT

7. Conditional Operator (Ternary Operator):

int a = 10, b = 5;
int max = (a > b) ? a : b; // Assigns the larger of a and b to max

8. Comma Operator:

int a = 1, b = 2, c = 3;
int sum = (a + b, b + c); // sum will be assigned the value of b + c

9. Member Access Operators:

struct Point {
int x;
int y;
};

struct Point p1;


p1.x = 10;
p1.y = 20;

10. Sizeof Operator:

intsize_int = sizeof(int);
intsize_char = sizeof(char);

These examples demonstrate how each type of operator is used in C programming.


Understanding their behavior and usage is crucial for writing efficient and correct
programs.

SCOPE AND LIFETIME OF VARIABLES:

In C programming, the scope and lifetime of variables determine where and for how
long a variable can be accessed and used within a program. Let's delve into each
concept with examples:

1. Scope: Scope refers to the region of the program where a variable is accessible.
There are three main scopes in C:

 Block Scope: Variables declared within a block of code (within curly braces
`{}`) have block scope. They are accessible only within that block.

#include <stdio.h>

int main() {
int x = 10; // x has block scope
{
int y = 20; // y also has block scope
printf("x = %d\n", x); // x is accessible
printf("y = %d\n", y); // y is accessible
}
// printf("y = %d\n", y); // Error: y is not accessible outside its block
return 0;
}

 Function Scope: Variables declared within a function have function scope.


They are accessible only within that function.

#include <stdio.h>

voidmyFunction() {
int a = 5; // a has function scope
printf("a = %d\n", a); // a is accessible
}

int main() {
// printf("a = %d\n", a); // Error: a is not accessible here
myFunction();
return 0;
}

 File Scope (Global Scope): Variables declared outside of all functions have file
scope. They are accessible from their declaration point until the end of the file.
#include <stdio.h>

intglobalVar = 100; // globalVar has file scope

voidmyFunction() {
printf("globalVar = %d\n", globalVar); // globalVar is accessible
}

int main() {
printf("globalVar = %d\n", globalVar); // globalVar is accessible
myFunction();
return 0;
}

2. Lifetime: Lifetime refers to the duration for which a variable exists in memory.
There are primarily three lifetimes in C.

i. Automatic Lifetime: Variables declared inside a function have automatic


lifetime. They are created when the function is called and destroyed when the
function exits.

#include <stdio.h>

voidmyFunction() {
int a = 5; // a has automatic lifetime
printf("a = %d\n", a); // a is accessible
}

int main() {
// printf("a = %d\n", a); // Error: a is not accessible here
myFunction();
return 0;
}

ii. Static Lifetime: Variables declared with the `static` keyword inside a function
have static lifetime. They are created when the program starts and destroyed
when the program terminates.

#include <stdio.h>

voidmyFunction() {
staticint b = 10; // b has static lifetime
printf("b = %d\n", b); // b is accessible
b++;
}

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

iii. Dynamic Lifetime: Variables created using dynamic memory allocation


functions like `malloc()` have dynamic lifetime. They are explicitly allocated
and de-allocated by the programmer and exist until explicitly de-allocated.

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr = (int *)malloc(sizeof(int)); // Dynamically allocated memory
*ptr = 100;
printf("*ptr = %d\n", *ptr); // *ptr is accessible
free(ptr); // Deallocate memory
// printf("*ptr = %d\n", *ptr); // Error: *ptr is not accessible after
deallocation
return 0;
}

Understanding the scope and lifetime of variables is crucial for writing efficient and
bug-free C programs. It helps in managing memory effectively and prevents issues
like memory leaks and undefined behavior.
CONSTANTS:

In C programming, constants are values that do not change during the execution of a
program. They are used to represent fixed values that remain constant throughout the
program's execution. Constants in C can be categorized into two main types:

1. Numeric Constants: Numeric constants represent fixed numerical values. They can
be integers, floating-point numbers, or characters. Numeric constants can be specified
in various formats:

 Integer Constants: These are whole numbers without any fractional part.
intnum = 10;

 Floating-point Constants: These are numbers with a fractional part or in


exponential notation.
float pi = 3.14;
double gravity = 9.81;

 Character Constants: These represent single characters enclosed in single


quotes.
char letter = 'A';

2. Symbolic Constants: Symbolic constants are identifiers that represent fixed values.
They are defined using the `#define` preprocessor directive or the `const` keyword.
Symbolic constants provide a way to give meaningful names to values, making the
code more readable and maintainable.

 Using `#define` directive:

#define PI 3.14
#define MAX_SIZE 100

 Using `const` keyword:

const float PI = 3.14;


constint MAX_SIZE = 100;

Constants offer several advantages in C programming:


 Readability: Using constants with meaningful names makes the code more
understandable and maintainable.
 Avoid Magic Numbers: Constants help avoid using "magic numbers" directly
in the code, which can be confusing and error-prone.
 Easy Maintenance: If a constant value needs to be changed, you only need to
modify it at one place in the code, rather than searching for and updating every
occurrence.
It's good practice to use constants whenever possible to make your code more robust
and easier to understand.

POINTERS:

Pointers in C are variables that store memory addresses. They are powerful features of
the language, allowing you to work directly with memory locations and manipulate
data efficiently. Here's an overview of pointers with examples:

1. Declaring Pointers:
Pointers are declared by adding an asterisk (*) before the variable name.

int *ptr; // Declares a pointer to an integer


char *chPtr; // Declares a pointer to a character

2. Assigning Pointers:
Pointers can be assigned the address of a variable using the address-of operator (&).

intnum = 10;
int *ptr = &num; // Assigns the address of num to ptr

3. Accessing Pointed Values:


The value pointed to by a pointer can be accessed using the dereference operator (*).

intnum = 10;
int *ptr = &num;
printf("Value of num: %d\n", *ptr); // Prints the value of num (10)

4. Pointer Arithmetic:
Pointers can be incremented or decremented to navigate through memory locations.
The size of the data type being pointed to determines the step size.

intarr[] = {10, 20, 30, 40};


int *ptr = arr; // Points to the first element of the array
printf("First element: %d\n", *ptr); // Prints 10
ptr++; // Move to the next element
printf("Second element: %d\n", *ptr); // Prints 20

5. Null Pointers:
Pointers can be explicitly set to NULL, indicating that they do not point to any valid
memory location.

int *ptr = NULL; // Pointer initialized to NULL

6. Pointer to Pointer (Double Pointer):


Pointers can also point to other pointers, forming a chain of indirection.

intnum = 10;
int *ptr = &num;
int ptrPtr = &ptr; // Pointer to a pointer

7. Dynamic Memory Allocation:


Pointers are commonly used with functions like `malloc()` and `free()` to dynamically
allocate and deallocate memory.

int *dynamicArray = (int *)malloc(5 * sizeof(int)); // Allocates memory for an


array of 5 integers

Pointers are extensively used in C for tasks like array manipulation, dynamic memory
allocation, and passing parameters to functions by reference. While powerful, they
require careful handling to avoid common pitfalls like dangling pointers and memory
leaks.

ARRAYS:

Arrays in C are collections of elements of the same data type stored in contiguous
memory locations. They provide a convenient way to store and manipulate a fixed-size
sequence of elements. Here's an overview of arrays in C with examples:

1. Declaring Arrays:
Arrays are declared by specifying the data type of the elements and the number of
elements enclosed in square brackets ([]).
int numbers[5]; // Declares an array of 5 integers
float prices[10]; // Declares an array of 10 floating-point numbers
char name[20]; // Declares an array of 20 characters

2. Initializing Arrays:
Arrays can be initialized at the time of declaration or later using assignment
statements.

int numbers[5] = {1, 2, 3, 4, 5}; // Initializes the array with values


float prices[3] = {1.99, 2.49, 3.99}; // Initializes the array with floating-point
values

3. Accessing Array Elements:


Array elements are accessed using zero-based indexing, where the index represents the
position of the element in the array.

int numbers[5] = {10, 20, 30, 40, 50};


intfirstElement = numbers[0]; // Accesses the first element (10)
intthirdElement = numbers[2]; // Accesses the third element (30)

4. Iterating Over Arrays:


Loops, such as `for` or `while`, are commonly used to iterate over array elements.

int numbers[5] = {10, 20, 30, 40, 50};


for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}

5. Multidimensional Arrays:
Arrays can have more than one dimension, allowing you to represent tables, matrices,
or other multi-dimensional data structures.

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

6. Strings as Arrays:
In C, strings are represented as arrays of characters, terminated by a null character (`'\
0'`).
char greeting[] = "Hello, World!";

7. Array Size:
The size of an array can be determined using the `sizeof` operator.
int numbers[5];
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculates the size of the
array

Arrays are fundamental data structures in C, offering a straightforward and efficient


way to work with collections of elements. Understanding arrays is essential for
programming tasks involving data manipulation and storage.

STRINGS:

In C programming, strings are sequences of characters stored in contiguous memory


locations, terminated by a null character (`'\0'`). They are represented as arrays of
characters. Here's an overview of strings in C with examples:

1. Declaring Strings:
Strings can be declared as character arrays, with enough space to store the characters
plus one additional character for the null terminator.
char greeting[20]; // Declares a string of 19 characters plus the null terminator

2. Initializing Strings:
Strings can be initialized at the time of declaration or later using assignment
statements.

char greeting[20] = "Hello, World!"; // Initializes the string with a value

3. Accessing String Elements:


Individual characters in a string can be accessed using zero-based indexing.

char greeting[] = "Hello, World!";


charfirstChar = greeting[0]; // Accesses the first character ('H')
4. Printing Strings:
Strings can be printed using the `printf()` function or the `%s` format specifier.

char greeting[] = "Hello, World!";


printf("%s\n", greeting); // Prints the string

5. String Input:
Strings can be read from the standard input using functions like `scanf()` or `fgets()`.

char name[50];
printf("Enter your name: ");
scanf("%s", name); // Reads a string from the user
printf("Hello, %s!\n", name);

6. String Functions:
C provides several string manipulation functions in the `<string.h>` header, such as
`strlen()`, `strcpy()`, `strcat()`, `strcmp()`, etc., for tasks like string length calculation,
copying, concatenation, and comparison.

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello";
char str2[] = "World";

printf("Length of str1: %d\n", strlen(str1)); // Prints the length of str1


strcat(str1, str2); // Concatenates str2 to str1
printf("Concatenated string: %s\n", str1);

return 0;
}

7. String Comparison:
Strings can be compared using the `strcmp()` function, which returns 0 if the strings
are equal, a negative value if the first string is lexicographically less than the second,
and a positive value otherwise.
char str1[] = "apple";
char str2[] = "banana";

int result = strcmp(str1, str2); // Compares str1 and str2


if (result == 0) {
printf("The strings are equal\n");
} else if (result < 0) {
printf("%s comes before %s\n", str1, str2);
} else {
printf("%s comes after %s\n", str1, str2);
}

Understanding strings and string manipulation functions is crucial for working with
text data in C programming. It allows you to perform tasks like input/output,
processing, and manipulation of textual data effectively.

CONTROL FLOW:

Control flow in C refers to the order in which statements are executed in a program. C
provides several control flow structures that allow you to alter the sequence of
execution based on conditions, loops, and function calls. Here's an overview of control
flow in C with examples:

1. Conditional Statements (if-else):


Conditional statements allow you to execute code based on a condition.

#include <stdio.h>

int main() {
intnum = 10;

if (num> 0) {
printf("Number is positive\n");
} else if (num< 0) {
printf("Number is negative\n");
} else {
printf("Number is zero\n");
}
return 0;
}

2. Switch Statement:
The switch statement allows you to select one of many blocks of code to execute.

#include <stdio.h>

int main() {
int choice = 2;

switch (choice) {
case 1:
printf("Choice is 1\n");
break;
case 2:
printf("Choice is 2\n");
break;
case 3:
printf("Choice is 3\n");
break;
default:
printf("Invalid choice\n");
}

return 0;
}

3. Loops:
Loops allow you to execute a block of code repeatedly.

- For Loop:

#include <stdio.h>

int main() {
for (int i = 0; i < 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}

- While Loop:
#include <stdio.h>

int main() {
int i = 0;
while (i < 5) {
printf("Iteration %d\n", i);
i++;
}
return 0;
}

- Do-While Loop:

#include <stdio.h>

int main() {
int i = 0;
do {
printf("Iteration %d\n", i);
i++;
} while (i < 5);
return 0;
}

4. Break and Continue Statements:


The break statement is used to exit a loop, and the continue statement is used to skip
the remaining code in the loop and continue with the next iteration.

#include <stdio.h>

int main() {
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d\n", i);
}
return 0;
}
These control flow structures in C allow you to write programs that can make
decisions, iterate over data, and handle various scenarios based on conditions.
Understanding and using them effectively is essential for writing efficient and robust
C programs.

FUNCTIONS AND PROGRAM STRUCTURE:

In C programming, functions are blocks of code that perform a specific task. They
allow you to organize code into manageable and reusable units. Here's an overview of
function and program structure in C:

1. Function Declaration and Definition:


Functions in C are declared before they are used. A function declaration specifies the
function's name, return type, and parameters (if any).

// Function declaration
int add(int a, int b);

int main() {
int result = add(10, 20); // Function call
printf("Result: %d\n", result);
return 0;
}

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

2. Function Parameters and Return Values:


Functions can accept parameters (inputs) and return values (outputs).

int add(int a, int b) {


return a + b;
}

int main() {
int result = add(10, 20); // Function call with parameters
printf("Result: %d\n", result);
return 0;
}

3. Function Prototypes:
Function prototypes declare the signature of a function before its actual
implementation. They are usually placed at the beginning of the file or in a header file.

// Function prototype
int add(int a, int b);

int main() {
int result = add(10, 20);
printf("Result: %d\n", result);
return 0;
}

int add(int a, int b) {


return a + b;
}

4. Function Scope:
Variables declared inside a function have function scope and are accessible only
within that function.

int add(int a, int b) {


int sum = a + b; // sum has function scope
return sum;
}

int main() {
// printf("%d\n", sum); // Error: sum is not accessible here
return 0;
}

5. Program Structure:
A C program typically consists of one or more functions. The `main()` function is the
entry point of the program, from where execution begins.

#include <stdio.h>

// Function declaration
int add(int a, int b);

int main() {
int result = add(10, 20);
printf("Result: %d\n", result);
return 0;
}

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

6. Header Files:
Header files contain function prototypes, constant declarations, and other preprocessor
directives. They are included in C programs using the `#include` directive.

// Example header file: math.h


int add(int a, int b);

// Example C program
#include <stdio.h>
#include "math.h" // Include user-defined header file

int main() {
int result = add(10, 20);
printf("Result: %d\n", result);
return 0;
}

int add(int a, int b) {


return a + b;
}
Understanding function and program structure in C is essential for writing modular,
maintainable, and efficient code. Functions help break down complex tasks into
smaller, manageable units, making code organization easier and promoting code reuse.

NAMESPACES:

In C, there is no direct concept of namespaces as in some other programming


languages like C++ or C#. However, C does provide mechanisms for organizing and
avoiding naming conflicts in large projects.

1. Prefixes: One common practice to simulate namespaces in C is by using prefixes


for functions, variables, and structures. For example, if you have a set of functions
related to math operations, you might prefix them with `math_`.

int math_add(int a, int b) {


return a + b;
}

intmath_subtract(int a, int b) {
return a - b;
}

2. Static Keyword: The `static` keyword can be used to limit the scope of functions
and variables to the file in which they are defined. This helps prevent name clashes
between files.
// math_operations.c
staticint add(int a, int b) {
return a + b;
}

// main.c
#include <stdio.h>

int main() {
printf("Result: %d\n", add(10, 20)); // Error: add is not accessible from main.c
return 0;
}

3. File Scope: Functions and variables declared outside of any function, at the top of a
file, have file scope. They are accessible only within that file by default.
// math_operations.c
staticint add(int a, int b) {
return a + b;
}

// subtract is only visible within math_operations.c


staticint subtract(int a, int b) {
return a - b;
}

4. Module or Object Files: You can also organize related functions and data
structures into separate module or object files, which are then linked together during
compilation. This helps compartmentalize code and reduce dependencies.

Namespaces, as a feature to encapsulate related entities, are more prevalent in


languages like C++, but in C, the concept is more informally implemented using
prefixes, static scope, and modularization.

ERROR HANDLING IN C:

Error handling in C involves managing unexpected situations that arise during


program execution, such as runtime errors, input validation failures, and resource
allocation failures. Here are some common techniques and best practices for error
handling in C:

1. Return Values: Functions can return error codes or special values to indicate
success or failure. Conventionally, a return value of 0 indicates success, while non-
zero values represent different error conditions.

int divide(int a, int b, int *result) {


if (b == 0) {
return -1; // Division by zero error
}
*result = a / b;
return 0; // Success
}

2. Global Variables: Global variables can be used to store error codes or status flags
that functions can check and update accordingly.

#include <stdio.h>
intlastError = 0;

int divide(int a, int b, int *result) {


if (b == 0) {
lastError = -1; // Division by zero error
return -1;
}
*result = a / b;
lastError = 0; // Success
return 0;
}

int main() {
int result;
if (divide(10, 0, &result) != 0) {
printf("Error: Division by zero\n");
printf("Last error code: %d\n", lastError);
}
return 0;
}

3. Error Codes: Define meaningful error codes or constants to represent different


error conditions. This improves code readability and maintainability.

#include <stdio.h>

#define ERROR_DIVISION_BY_ZERO -1

int divide(int a, int b, int *result) {


if (b == 0) {
return ERROR_DIVISION_BY_ZERO;
}
*result = a / b;
return 0;
}

int main() {
int result;
int error = divide(10, 0, &result);
if (error != 0) {
printf("Error: Division by zero\n");
printf("Error code: %d\n", error);
}
return 0;
}

4. Error Reporting Functions: Define functions or macros to handle and report


errors consistently throughout the program.

#include <stdio.h>

#define ERROR_DIVISION_BY_ZERO -1

voidreportError(interrorCode) {
switch (errorCode) {
case ERROR_DIVISION_BY_ZERO:
printf("Error: Division by zero\n");
break;
default:
printf("Unknown error\n");
}
}

int divide(int a, int b, int *result) {


if (b == 0) {
return ERROR_DIVISION_BY_ZERO;
}
*result = a / b;
return 0;
}

int main() {
int result;
int error = divide(10, 0, &result);
if (error != 0) {
reportError(error);
}
return 0;
}

5. Error Handling Libraries: Use existing error handling libraries or frameworks,


such as `errno.h`, to manage errors consistently across your project.
6. Resource Cleanup: Ensure proper cleanup of resources (e.g., memory, file
handles) in case of errors to prevent resource leaks.

Error handling is an essential aspect of writing robust and reliable C programs. By


implementing effective error handling mechanisms, you can improve program stability
and maintainability, and make it easier to debug and diagnose issues during
development and maintenance.

INPUT AND OUTPUT IN C:

Input and output (I/O) operations are essential for interacting with users and external
data sources in C programming. C provides several standard functions for performing
I/O operations. Here's an overview of input and output in C:

1. Standard Input and Output:


- `printf()`: Prints formatted output to the standard output stream (usually the
console).
- `scanf()`: Reads formatted input from the standard input stream (usually the
keyboard).

#include <stdio.h>

int main() {
intnum;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}

2. File Input and Output:


- `fopen()`: Opens a file.
- `fclose()`: Closes a file.
- `fprintf()`: Writes formatted output to a file.
- `fscanf()`: Reads formatted input from a file.

#include <stdio.h>

int main() {
FILE *fp;
intnum;

fp = fopen("data.txt", "w"); // Open file for writing


fprintf(fp, "Hello, World!\n");
fclose(fp);

fp = fopen("data.txt", "r"); // Open file for reading


fscanf(fp, "%d", &num);
printf("Number read from file: %d\n", num);
fclose(fp);

return 0;
}

3. Character I/O:
- `getchar()`: Reads a single character from the standard input.
- `putchar()`: Writes a single character to the standard output.

#include <stdio.h>
int main() {
char ch;
printf("Enter a character: ");
ch = getchar();
printf("You entered: ");
putchar(ch);
putchar('\n');
return 0;
}
output:

Enter a character: panimalar


You entered: p

4. String I/O:
- `gets()`: Reads a line of text from the standard input (deprecated due to security
vulnerabilities).
- `fgets()`: Reads a line of text from a file or the standard input.
- `puts()`: Writes a string to the standard output followed by a newline character.

#include <stdio.h>

int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: ");
puts(str);
return 0;
output:
Enter a string: pani malar
You entered: pani malar
}
5. Error Handling:
- Functions like `scanf()` and `fgets()` return a value indicating the number of items
successfully read. This can be used for error checking.
- `ferror()` and `feof()` can be used to check for file I/O errors and end-of-file
conditions.

Input and output operations are fundamental to most C programs. Understanding how
to use standard input and output functions, as well as file I/O functions, is essential for
writing practical and useful programs. Additionally, error handling is crucial to ensure
that I/O operations are performed safely and reliably.

LIBRARY FUNCTOINS IN C (string,math,stdlib):

1. string.h:
- strlen(): Calculates the length of a string.

#include <stdio.h>
#include <string.h>

int main() {
charstr[] = "Hello, World!";
int length = strlen(str);
printf("Length of the string: %d\n", length);
return 0;
}

- strcpy(): Copies one string to another.

#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello, World!";
char dest[20];
strcpy(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}

Output: Copied string: Hello, World!


2. math.h:
- sqrt(): Computes the square root of a number.

#include <stdio.h>
#include <math.h>

int main() {
double num = 25.0;
double squareRoot = sqrt(num);
printf("Square root of %lf: %lf\n", num, squareRoot);
return 0;
}
Output: Square root of 25.000000: 5.000000

- pow(): Computes the power of a number.

#include <stdio.h>
#include <math.h>

int main() {
double base = 2.0;
double exponent = 3.0;
double result = pow(base, exponent);
printf("%lf raised to the power %lf is %lf\n", base, exponent, result);
return 0;
}
Output:
2.000000 raised to the power 3.000000 is 8.000000

-malloc(): Allocates memory dynamically.

#include <stdio.h>
#include <stdlib.h>

int main() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 10;
printf("Value stored at dynamically allocated memory: %d\n", *ptr);
free(ptr); // Free dynamically allocated memory
return 0;
}

These are just a few examples of library functions from `string.h`, `math.h`, and
`stdlib.h` in C. These libraries offer a wide range of functions for string manipulation,
mathematical operations, memory allocation, and more, making them invaluable for
developing C programs.

COMMAND LINE ARGUMENT:

Command-line arguments allow users to provide inputs to a program when it is


executed from the command line. In C, the `main()` function can accept two
arguments: `argc` (argument count) and `argv` (argument vector). Here's how you can
use command-line arguments in a C program:

#include <stdio.h>

int main(intargc, char *argv[]) {


// argc: Number of command-line arguments
// argv: Array of pointers to strings containing the arguments

printf("Number of command-line arguments: %d\n", argc);

// Print each command-line argument


for (int i = 0; i <argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}

return 0;
}

Example usage:
$ ./program arg1 arg2 arg3
Number of command-line arguments: 4
Argument 0: ./program
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

How it works:

- `argc`: The number of command-line arguments passed to the program, including the
program name itself.
- `argv`: An array of pointers to strings (`char *`) representing the command-line
arguments. `argv[0]` holds the name of the program itself, and subsequent elements
contain the actual arguments.
- Each argument is separated by a space on the command line.

PREPROCESSOR DIRECTIVE:

Preprocessor directives are commands in C that are executed by the preprocessor


before the compilation process begins. They are preceded by the `#` symbol.
Preprocessor directives are used to perform tasks such as file inclusion, macro
definition, conditional compilation, and error control. Here are some commonly used
preprocessor directives in C:

1. Include Directive (`#include`):


- Used to include header files in the program.
- Syntax: `#include <header_file>` (for system header files) or `#include
"header_file"` (for user-defined header files).

#include <stdio.h> // Include the standard input-output header file

2. Define Directive (`#define`):


- Used to define macros, which are symbolic constants or short code snippets.
- Syntax: `#define macro_namereplacement_text`

#define PI 3.14159 // Define a macro for pi


3. Conditional Compilation Directives (`#ifdef`, `#ifndef`, `#if`, `#elif`, `#else`,
`#endif`):
- Used to conditionally compile code based on predefined macros or expressions.
- `#ifdef` and `#ifndef`: Check if a macro is defined or not defined.
- `#if`, `#elif`, `#else`: Evaluate expressions.
- `#endif`: Ends a conditional block.
# #include<stdio.h>

Example:
int main()
{
#ifdef DEBUG
printf("Debug mode enabled\n");
#else
printf("Debug mode disabled\n");
#endif
}
Output:
Debug mode disabled.

4. Undefine Directive (`#undef`):


- Used to undefine macros.
- Syntax: `#undefmacro_name`

#undef PI // Undefine the PI macro

5. Include Guard Directive:


- Used to prevent header files from being included multiple times.
- Syntax:
#include<stdio.h>
int main()
{
#ifndef HEADER_FILE_NAME_H
#define HEADER_FILE_NAME_H
// Contents of the header file
#endif
}
Output:
/tmp/1x5JUH5d1v.o

This ensures that the contents of the header file are included only once, even if the
header file is included multiple times in the program.

Preprocessor directives are processed before the actual compilation of the source code
begins. They are powerful tools for controlling the compilation process, including file
inclusion, conditional compilation, and macro definition, thus allowing for flexible
and efficient code development in C.

You might also like