0% found this document useful (0 votes)
17 views21 pages

C Programming - Unit 2 and 3

This document provides an overview of the C programming language, including its history, key features, and the process of executing a C program. It discusses the evolution of the C language from 1969 to the present day through various standards. Some of the main features highlighted include C being a portable, middle-level language that provides efficiency and low-level access while also supporting high-level constructs. The document also outlines the typical steps involved in writing, compiling, linking and running a C program. It describes important character sets used in C like the source character set and execution character set. Finally, it defines what tokens are in C programming and lists some common token types.

Uploaded by

UTKARSH MISHRA
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)
17 views21 pages

C Programming - Unit 2 and 3

This document provides an overview of the C programming language, including its history, key features, and the process of executing a C program. It discusses the evolution of the C language from 1969 to the present day through various standards. Some of the main features highlighted include C being a portable, middle-level language that provides efficiency and low-level access while also supporting high-level constructs. The document also outlines the typical steps involved in writing, compiling, linking and running a C program. It describes important character sets used in C like the source character set and execution character set. Finally, it defines what tokens are in C programming and lists some common token types.

Uploaded by

UTKARSH MISHRA
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/ 21

Unit 2 and 3: C programming

| 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:

1. Procedural Language: C is a procedural programming language, which means it follows a


structured approach in which the program is divided into functions or procedures, making it
easy to understand and maintain.
2. Portable: C programs are highly portable, meaning they can be compiled and run on various
platforms with minimal or no modifications. This portability is due to the existence of
compilers for different systems.
3. Middle-Level Language: C combines low-level features like direct memory manipulation
with high-level features like functions and data structures, making it a middle-level language.
This allows for a high degree of control and efficiency.
4. Efficiency: C provides low-level access to memory and hardware, making it highly efficient.
This efficiency is particularly useful in system programming and embedded systems.
5. Structured Language: C supports structured programming with features like functions, loops,
and conditional statements, which promote code organization and readability.
6. Rich Standard Library: C includes a standard library that provides a wide range of functions
for input/output, string manipulation, memory management, and more. These libraries simplify
common tasks and save development time.
7. Pointers: C allows the use of pointers, which are variables that store memory addresses.
Pointers are crucial for tasks like dynamic memory allocation and can improve program
efficiency.
8. Dynamic Memory Allocation: C provides functions like `malloc` and `free` for dynamic
memory allocation and deallocation, giving programmers control over memory usage.
9. Modularity: C supports modular programming through the use of functions, which helps
break down complex programs into smaller, more manageable components.
10. Bit Manipulation: C provides bitwise operators for low-level bit manipulation, which is
essential in embedded systems and system-level programming.
11. Direct Memory Access: C allows direct memory access and manipulation, which is
necessary for tasks like hardware programming and operating system development.
12. Support for Structures and Unions: C supports structures and unions for creating custom
data types, allowing for the organization of related data elements.
13. Flexibility: C is a flexible language that does not impose many restrictions, giving
programmers a high degree of control over program behavior.
14. Extensibility: C can be extended by creating user-defined functions and libraries, allowing
for the development of custom modules and libraries.
15. Wide Usage: C has a long history and is widely used in various fields, including system
programming, application development, embedded systems, and more.
16. Compatibility: C code can often be integrated with code written in other languages, making
it compatible with a wide range of technologies and environments.

Process of executing a c program:


The execution of a C program involves several steps, from writing the code to running the
program. Here's an overview of the process:

1. Writing the C Code:


- Start by writing the C code in a text editor or integrated development environment (IDE).
Use a `.c` file extension for C source code files.

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.

11. Recompilation (if necessary):


- After making changes to your code, you may need to repeat the compilation and linking
steps before executing the updated program.

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:

1. Source Character Set (SCS):


- The source character set represents the set of characters that can be used in the source code
of a C program. It includes:
- The basic source character set, which typically includes the letters (both lowercase and
uppercase), digits, and a set of special characters like punctuation marks and operators.
- Trigraph sequences, which are used to represent certain characters not easily available on
all keyboards.
- Universal character names, used to represent characters from the universal character set.
2. Trigraph Sequences:
- Trigraph sequences are three-character combinations that begin with `??` and are used to
represent characters that might not be directly accessible on all keyboards. For example, `??(`
represents `[`, and `??/` represents `\`.
3. Universal Character Set (UCS):
- The universal character set is a superset of all characters in all character sets. It includes
characters from various languages and scripts, mathematical symbols, punctuation, and more.
Universal character names in C can be used to represent characters from the universal character
set.
4. Escape Sequences:
- Escape sequences are used to represent control characters and special characters in C strings
and character constants. For example, `\n` represents a newline character, and `\t` represents a
tab character.
5. Execution Character Set (ECS):
- The execution character set represents the set of characters that a C program can use for I/O
operations. It is typically a subset of the source character set and is used when reading and
writing characters in a C program.
6. Extended Character Set (XCS):
- The extended character set is an optional character set that includes additional characters
beyond those in the source character set. It may be used in extended character literals and string
literals.

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`.

Here's an example of a C code snippet broken down into tokens:


#include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
}
return 0;
}
In this code snippet, you can identify the following tokens:

- Keywords: `#include`, `int`, `if`, `return`.


- Identifiers: `main`, `x`.
- Constants: `10`, `5`, `0`.
- String Literal: `"x is greater than 5\n"`.
- Operators: `=`, `>`, `(`, `)`, `{`, `}`, `;`.
- Punctuation: `,`.
- Separators: Spaces, line breaks.
- Preprocessor Directives: `#include`.

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;`

14. Long long:


- Used for very large integer values, with greater storage than a regular `int`.
- Example: `long long bigNumber = 1234567890123456789LL;`
These are some of the common data types in C. The choice of data type depends on the kind of
data you need to work with and the specific requirements of your program. C also allows you
to create custom data types using structures and typedefs.

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

8. Dynamic Memory Allocation:


- In C, you can allocate memory dynamically using functions like `malloc`, which return a
pointer to a block of memory. The pointer can be stored in a variable for managing dynamic
data structures like arrays and linked lists.

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:

1. Automatic Storage Class (auto):


- Variables with the `auto` storage class are created and initialized each time their block or
function is entered.
- They have a local scope, meaning they are only accessible within the block or function
where they are declared.
- The default storage class for local variables if no storage class specifier is used.
- Example:
```c
void someFunction() {
auto int x = 10; // 'auto' storage class is optional, as it's the default
// 'x' is created and initialized each time 'someFunction' is called
}

2. Register Storage Class (register):


- Variables with the `register` storage class are stored in CPU registers for faster access.
- This storage class is rarely used in modern C, as modern compilers are optimized for
efficient variable storage.
- The `register` storage class is optional, and the compiler may choose to ignore it.
- Example (rarely used and not recommended):
```c
register int count = 0; // Suggests that 'count' be stored in a CPU register
3. Static Storage Class (static):
- Variables with the `static` storage class have a lifetime that extends throughout the program's
execution.
- They retain their values between function calls and are initialized only once.
- `static` variables can have local or global scope.
- Example:
```c
int globalVar; // 'globalVar' has static storage duration by default
void someFunction() {
static int localVar = 0; // 'localVar' is initialized once and retains its value
// ...
}
4. External (or Global) Storage Class (extern):
- The `extern` storage class is typically used to declare a global variable in one source file
that is defined in another source file.
- It is often used for creating global variables that can be accessed across multiple source files
in a program.
- Example:
In one source file (source1.c):
```c
int globalVar; // Declares a global variable
```
In another source file (source2.c):
```c
extern int globalVar; // Declares 'globalVar' as an external global variable
```
These storage classes determine where a variable is stored in memory, its visibility, and how
long it retains its value. The choice of storage class depends on the specific needs of your
program and how you want to manage variable lifetimes and scopes.

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;`

8. Member Selection Operator:


- The `.` operator is used to access members of a structure or union.
- Example: `struct Person person; person.age = 30;`

9. Pointer Operators:
- `*` is used for pointer declaration and dereferencing.
- `&` is used to get the address of a variable.
- Example: `int *ptr; ptr = &x;`

10. sizeof Operator:


- The `sizeof` operator returns the size, in bytes, of a data type or an expression.
- Example: `sizeof(int);`

11. Address-of Operator:


- The `&` operator is used to get the memory address of a variable.
- Example: `&variable;`

12. Indirection Operator:


- The `*` operator is used to access the value of the object pointed to by a pointer.
- Example: `*pointer;`
Operator precedence and associativity:
Operator precedence and associativity are rules that determine the order in which operators are
evaluated in an expression. These rules help ensure that expressions are evaluated correctly and
consistently. In C, operators have different levels of precedence, and operators with higher
precedence are evaluated before operators with lower precedence. Additionally, operators with
the same precedence are evaluated based on their associativity, which can be either left-to-right
or right-to-left.

Here's a summary of operator precedence and associativity in C:

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`

11. Logical AND operator: `&&`


- Example: `cond1 && cond2`
12. Logical OR operator: `||`
- Example: `flag1 || flag2`
13. Conditional (Ternary) operator: `? :`
- Example: `condition ? expr1 : expr2`
14. Assignment operators: `=`, `+=`, `-=`, `*=`, `/=`, `%=`, `&=`, `|=`, `^=`, `<<=`, `>>=`
- Example: `x = 5`, `total += amount`

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:

Standard Output Functions:


1. printf: Used for formatted output. It allows you to print data with specified formatting,
including placeholders for variables
int x = 10;
printf("The value of x is %d\n", x);

2. putchar: Outputs a single character to the console.


char ch = 'A';
putchar(ch);

3.puts: Outputs a string (a sequence of characters) followed by a newline character.


char message [] = "Hello, World!";
puts(message)
Standard Input Functions:
1. scanf: Used for formatted input. It reads data from the user according to a specified format
and stores the values in variables.
int age;
printf("Enter your age: ");
scanf("%d", &age);
2. getchar: Reads a single character from the console.
char ch;
printf("Enter a character: ");
ch getchar()
3. gets: Reads a line of text (a string) from the console.
char name[50];
printf("Enter your name: ");
gets(name);
4. fgets: Reads a line of text (a string) from a file or the console with a specified maximum
length
char buffer[50];
printf("Enter a string: ");
fgets(buffer, sizeof(buffer), stdin); // Reads from the console (stdin)
File I/O Functions:
C also provides functions for performing input and output operations on files. Some of the
commonly used file I/O functions include:
1. fopen: Opens a file for reading, writing, or appending.
FILE *file = fopen("example.txt", "r"); // Opens "example.txt" for reading
2. fclose: Closes a file that was previously opened.
fclose(file);
3. fprintf: Used for formatted output to a file.
FILE *file = fopen("output.txt", "w");
fprintf(file, "This is written to the file\n");
fclose(file)
4. fscanf: Used for formatted input from a file.
FILE *file = fopen("input.txt", "r");
int value;
fscanf(file, "%d", &value);
fclose(file);
5. **fgetc and fputc:** Read and write individual characters to/from a file.
FILE *file = fopen("text.txt", "w");
char ch = 'A';
fputc(ch, file);
fclose(file);
These are just a few of the standard input/output functions available in C. You can use these
functions to perform a wide range of input and output operations in your C programs, whether
you are working with console input/output or file input/output.

Unit 3:
PLEASE REFER LIST OF PROGRAMS PERFORMED USING IF STATEMENT, IF-ELSE
STATEMENT AND SWITCH CONDITION

You might also like