Introduction to C
By Notes Vandar
Introduction to C
2.1 History of C Programme
The C programming language has a rich history that is deeply intertwined with the development of modern computing. It was developed in the early 1970s and has since become one of the most influential and widely used programming languages in the world. Here’s an overview of its history:
. Origins (1960s)
Before C was developed, the computing world used various programming languages for different purposes. One of the most influential languages during this time was ALGOL, introduced in the late 1950s. ALGOL influenced the development of many later languages, including BCPL and B.
- BCPL (1967): Developed by Martin Richards, BCPL (Basic Combined Programming Language) was a typeless language designed for writing system software and compilers. It served as one of the predecessors to C.
- B (1970): Created by Ken Thompson at Bell Labs, B was a simplified version of BCPL. It was used on early systems like the DEC PDP-7, and while powerful, it lacked data types and was limited in certain aspects, which led to its evolution.
2. Development of C (1972)
C was developed by Dennis Ritchie at Bell Labs between 1969 and 1973. Ritchie’s goal was to create a language that was both high-level and efficient enough to replace assembly language for system programming.
- Birth of C (1972): Ritchie took features from B and added important concepts such as data types, structures, and other higher-level constructs. The first major implementation of C was on a DEC PDP-11 running the UNIX operating system.
- UNIX and C: One of the most important uses of C was in rewriting the UNIX operating system, which was originally written in assembly language. The rewrite in C allowed UNIX to be easily ported to different computer systems, greatly increasing its popularity.
3. Standardization and Growth (1970s-1980s)
After its initial development, C quickly became popular for both system programming and application development. It was highly portable across different hardware platforms, which was a key advantage at the time.
- 1978: “The C Programming Language” (K&R C): In 1978, Brian Kernighan and Dennis Ritchie published a book called “The C Programming Language”, which became known as the K&R C. This book was instrumental in popularizing C and laid out its syntax, style, and features. K&R C became the de facto standard for C for many years.
- 1980s: Growing Popularity: By the early 1980s, C had become the dominant language for system software, including operating systems, compilers, and embedded systems. It was also being used in commercial applications, with many developers embracing it for its power and flexibility.
4. ANSI C (1989)
As C grew in popularity, different versions of the language started to emerge, leading to incompatibility issues between compilers. To address this, the American National Standards Institute (ANSI) began the process of standardizing C in 1983.
- ANSI C (1989): The first standardized version of C was completed in 1989 and is known as ANSI C or C89. This standard helped unify the different dialects of C and ensured that code written for one system could run on another without significant modifications.
- ISO Standard (1990): Following ANSI C, the International Organization for Standardization (ISO) adopted the same standard as ISO C in 1990 (ISO/IEC 9899:1990). This version is also referred to as C90.
5. Further Developments (1990s-2000s)
After the ANSI and ISO standardizations, C continued to evolve to include new features, improvements, and updates to keep up with the changing needs of software development.
- C99 (1999): The next major revision of the C language standard came in 1999, known as C99. This version added several new features, including:
- Support for inline functions
- New data types like
long long int
- Variable-length arrays
- Improved support for floating-point arithmetic
- C11 (2011): Another update came in 2011, known as C11, which added:
- Improved support for multithreading
- Anonymous structures and unions
- Unicode support
- Enhanced security features in the standard library
- C17 (2017): This is the most recent version of the C standard. It made minor bug fixes and improvements to the language but didn’t introduce major new features.
6. Legacy and Influence
Over the years, C has had a profound impact on many other programming languages. Languages such as C++, Objective-C, Java, C#, PHP, and JavaScript owe many of their design principles and syntax to C.
- C++ (1980s): Developed by Bjarne Stroustrup, C++ was built as an extension of C with additional features like object-oriented programming.
- Other Influenced Languages: Many other modern languages, such as Go, Rust, and Swift, were influenced by C’s design, particularly in their emphasis on low-level programming with high efficiency.
7. Modern Usage of C
Despite being over 50 years old, C remains one of the most widely used programming languages in the world. It is still a key language in:
- Operating systems: Linux, UNIX, Windows, macOS.
- Embedded systems: Used in hardware and microcontroller programming.
- System software: Compilers, interpreters, and drivers.
- Games and graphics programming: Due to its performance and direct memory access capabilities.
Timeline of Major Events in C’s History:
- 1967: BCPL language is created by Martin Richards.
- 1970: Ken Thompson creates the B language.
- 1972: Dennis Ritchie develops the C programming language at Bell Labs.
- 1978: “The C Programming Language” (K&R C) is published.
- 1983: ANSI starts standardizing C.
- 1989: ANSI C (C89) is released.
- 1990: ISO adopts ANSI C (C90).
- 1999: C99 standard is released.
- 2011: C11 standard is released.
- 2017: C17 standard is released.
2.2 Basic Structure of C Programme
The basic structure of a C program consists of several key components that work together to perform a task. Understanding this structure is important for writing clear, maintainable, and functional C programs. Here’s an outline of the essential components of a C program:
1. Preprocessor Directives
- Preprocessor directives begin with the
#
symbol and are used to include files and define constants before the actual compilation starts. - Common directives include
#include
(for including header files) and#define
(for defining constants).
Example:
2. Main Function
- Every C program must have a
main()
function. This is where the program starts executing. - The
main()
function is the entry point, and its return type is typicallyint
.
Example:
// code
return 0; // Indicates successful program termination
}
3. Variable Declaration
- Before using variables, they must be declared with a data type (e.g.,
int
,float
,char
). - Variables are typically declared at the beginning of a function or block of code.
Example:
float result; // Declaration of a floating-point variable
4. Body of the main()
Function
- This is the part where the actual logic of the program is written. It contains statements like variable declarations, operations, function calls, and loops.
Example:
int a = 5, b = 10;
int sum = a + b; // Simple operation
printf(“Sum: %d\n”, sum); // Print result
return 0;
}
5. Input/Output Functions
- C programs commonly use functions like
printf()
for output andscanf()
for input. #include <stdio.h>
provides the necessary functions for standard input/output.
Example:
#include <stdio.h>
int main() {
int num;
printf(“Enter a number: “);
scanf(“%d”, &num); // Taking input from the user
printf(“You entered: %d\n”, num); // Displaying the input
return 0;
}
6. Return Statement
- The
return
statement in themain()
function returns an integer value to the operating system. Returning0
typically indicates that the program has successfully executed.
Example:
7. Comments
- Comments are used to explain code and improve readability. They are ignored by the compiler.
- Single-line comments use
//
, while multi-line comments are enclosed between/* */
.
Example:
Example of a Complete C Program
Here’s a simple example that calculates the sum of two numbers and prints the result:
#include <stdio.h> // Preprocessor directive to include standard input/output library
int main() { // Main function
// Variable declaration
int num1, num2, sum;
// Input: Prompt the user for two numbers
printf(“Enter first number: “);
scanf(“%d”, &num1); // Reads an integer from the user and stores it in num1
printf(“Enter second number: “);
scanf(“%d”, &num2); // Reads another integer and stores it in num2
// Logic: Calculate the sum of the two numbers
sum = num1 + num2;
// Output: Display the result
printf(“Sum of %d and %d is: %d\n”, num1, num2, sum);
// Return statement: Indicate that the program ended successfully
return 0;
}
Basic Structure Summary:
- Preprocessor Directives: Used to include header files (
#include <stdio.h>
). main()
Function: The starting point of the program.- Variable Declarations: Declare variables for use in the program.
- Body of
main()
: Contains the program logic (e.g., calculations, loops, function calls). - Input/Output Functions:
printf()
for output andscanf()
for input. - Return Statement: Used to return a value from
main()
. - Comments: Used for code explanation and documentation.
2.3 Character set, Token and Comments
In C programming, a program consists of various elements such as characters, tokens, and comments. Each plays an important role in defining the structure and functionality of the code. Let’s break them down:
1. Character Set
The character set in C refers to the valid characters that can be used in writing a C program. These characters are divided into several categories:
Categories of the Character Set:
- Letters:
- All uppercase and lowercase English alphabets.
- Example:
A, B, C, ... Z
anda, b, c, ... z
- Digits:
- Decimal digits (0 to 9).
- Example:
0, 1, 2, 3, ... 9
- Special Characters:
- These characters include symbols used for operators, punctuation, etc.
- Example:
~
,!
,@
,#
,%
,^
,&
,*
,+
,=
,{
,}
,|
,\
,:
,;
,“
,<
,>
,/
,?
,_
, etc.
- White Spaces:
- Spaces, tabs, and newlines are used for formatting.
- White space is ignored by the C compiler except where it’s used to separate tokens.
- Escape Sequences:
- These represent special characters and consist of a backslash (
\
) followed by one or more characters. - Example:
\n
(newline)\t
(tab)\\
(backslash)\'
(single quote)\"
(double quote)
- These represent special characters and consist of a backslash (
2. Tokens
A token is the smallest unit in a C program that the compiler recognizes. C programs are written using these tokens.
Types of Tokens:
- Keywords:
- Reserved words in C that have a specific meaning and purpose. Keywords cannot be used as variable names.
- Example:
int
,float
,if
,else
,return
,for
,while
,void
,char
, etc.
- Identifiers:
- Names given to variables, functions, arrays, etc. Identifiers must follow certain rules (e.g., they cannot start with a digit).
- Example:
main
,sum
,totalMarks
,counter
- Constants:
- Fixed values that do not change during program execution.
- Types of constants:
- Integer constants:
10
,20
,-100
- Floating-point constants:
3.14
,0.001
,-45.6
- Character constants:
'a'
,'1'
,'#'
- String constants:
"Hello"
,"123"
- Integer constants:
- Operators:
- Symbols that specify operations on variables and values.
- Types of operators:
- Arithmetic operators:
+
,-
,*
,/
,%
- Relational operators:
==
,!=
,>
,<
,>=
,<=
- Logical operators:
&&
,||
,!
- Assignment operator:
=
- Increment/decrement operators:
++
,--
- Arithmetic operators:
- Punctuators (Separators):
- Symbols that are used for various purposes such as ending a statement, separating elements, etc.
- Example:
;
,{}
,[]
,()
,,
- Strings:
- A sequence of characters enclosed in double quotes.
- Example:
"Hello, World!"
3. Comments
Comments in C are used to add explanations or notes within the code. These comments are ignored by the compiler during execution, making them useful for improving code readability and helping other programmers understand the logic.
Types of Comments in C:
- Single-line Comment:
- Starts with
//
and extends to the end of the line. - Example:
file://%20this%20is%20a%20single-line%20commentint%20a%20=%205;%20%20//%20Variable%20’a’%20is%20initialized%20to%205
- Starts with
- Multi-line Comment:
- Starts with
/*
and ends with*/
. Can span multiple lines. - Example:
/*
* This is a multi-line comment
* It can span multiple lines.
*/
int b = 10;
- Starts with
Importance of Comments:
- Improves readability: Comments make code easier to understand by providing explanations for the logic.
- Helps in debugging: Developers can temporarily “comment out” parts of the code during debugging.
- Documentation: Comments serve as inline documentation for functions, variables, and algorithms.
Example Program with Character Set, Tokens, and Comments:
#include <stdio.h> // Preprocessor directive
int main() {
// Variable declaration
int num1 = 10; // Integer variable ‘num1’
int num2 = 20; // Integer variable ‘num2’
// Calculation
int sum = num1 + num2; // Add two numbers
// Print the result
printf(“Sum: %d\n”, sum); // Output the sum
return 0; // Return success code
}
Breakdown:
- Character Set: The program contains letters (
int
,main
), digits (10
,20
), special characters (+
,;
,()
), and whitespace. - Tokens: The code has keywords (
int
,return
), identifiers (main
,num1
,num2
), constants (10
,20
), operators (+
,=
), and punctuators (;
,{}
,()
). - Comments: There are both single-line comments explaining the program flow
2.4 Variables and Constants
In C programming, variables and constants are essential for storing and manipulating data. They differ in their mutability: variables can change during program execution, while constants remain fixed.
1. Variables
A variable is a storage location in memory with a name (identifier) that can hold a value. The value of a variable can change during the execution of a program.
Syntax of Variable Declaration:
To declare a variable in C, you need to specify the data type followed by the variable name (identifier).
data_type variable_name;
Example of Variable Declaration:
int age; // Declaring an integer variable
float salary; // Declaring a floating-point variable
char grade; // Declaring a character variable
Assigning a Value to a Variable:
You can assign a value to a variable using the assignment operator =
.
salary = 45000.50; // Assigning value 45000.50 to ‘salary’
grade = ‘A’; // Assigning character ‘A’ to ‘grade’
Initializing a Variable:
You can declare and assign a value to a variable in a single statement. This is known as initialization
int age = 25; // Declare and initialize ‘age’
float salary = 45000.50; // Declare and initialize ‘salary’
char grade = ‘A’; // Declare and initialize ‘grade’
Types of Variables:
- Local Variables:
- Declared inside a function or a block (inside
{}
). - Accessible only within that function or block.
- Example:
int age = 25; // Declare and initialize ‘age’
float salary = 45000.50; // Declare and initialize ‘salary’
char grade = ‘A’; // Declare and initialize ‘grade’
- Declared inside a function or a block (inside
- Global Variables:
- Declared outside all functions.
- Accessible throughout the program.
- Example:
int globalVar = 100; // Global variable
void func() {
printf(“%d”, globalVar); // Accessing global variable inside a function
}
- Static Variables:
- Declared with the
static
keyword. - Retain their value even after the function exits.
- Example:
void func() {
static int count = 0; // ‘count’ retains its value between function calls
count++;
printf(“%d”, count);
}
- Declared with the
- Automatic Variables:
- Local variables that are automatically created when a function is called and destroyed when the function exits.
- Declared without using the
static
keyword. - Example:
void func() {
auto int num = 5; // ‘num’ is an automatic variable
}
Example Program:
#include <stdio.h>
int main() {
int a = 10; // Integer variable
float b = 20.5; // Floating-point variable
char c = ‘X’; // Character variable
printf(“a = %d\n”, a);
printf(“b = %.2f\n”, b);
printf(“c = %c\n”, c);
return 0;
}
Output:
b = 20.50
c = X
2. Constants
A constant is a value that remains fixed during the entire execution of a program. You cannot modify a constant once it is defined.
Types of Constants:
- Integer Constants:
- Whole numbers without fractional parts.
- Example:
10
,-200
,0
- Floating-point Constants:
- Numbers with fractional parts.
- Example:
3.14
,-0.001
- Character Constants:
- A single character enclosed in single quotes.
- Example:
'A'
,'9'
,'#'
- String Constants:
- A sequence of characters enclosed in double quotes.
- Example:
"Hello, World!"
,"12345"
- Symbolic Constants:
- Defined using the
#define
preprocessor directive or theconst
keyword. - Example:
#define PI 3.14159 // Defining PI as a symbolic constant
const int MAX = 100; // Defining MAX as a constant integer
- Defined using the
Defining Constants:
- Using
#define
: The#define
preprocessor directive is used to define a constant.#define constant_name valueExample:
#define PI 3.14159You can use
PI
in your program, but you cannot change its value. - Using
const
Keyword: Theconst
keyword can be used to define constant variables whose value cannot be changed.const data_type variable_name = value;Example:
const int MAX = 100; // Defining MAX as a constant integerYou cannot modify the value of
MAX
in the program.
Example Program:
#include <stdio.h>
#define PI 3.14159 // Defining PI as a symbolic constant
int main() {
const int MAX = 100; // Defining MAX as a constant using ‘const’
printf(“Value of PI: %.5f\n”, PI);
printf(“Value of MAX: %d\n”, MAX);
return 0;
}
Output:
Value of MAX: 100
Differences Between Variables and Constants
Feature | Variables | Constants |
---|---|---|
Mutability | Value can change during execution | Value cannot change after being defined |
Declaration | Declared using a data type | Defined using const or #define |
Examples | int age = 25; |
const int MAX = 100; or #define PI 3.14159 |
2.5 Data Types
In C programming, data types define the type and size of data that a variable can hold. Understanding data types is crucial for efficient memory management and proper handling of different types of data (e.g., numbers, characters). C provides several built-in data types that are broadly categorized into the following:
1. Basic Data Types (Primitive Data Types)
These are the fundamental data types provided by C and include integers, floating-point numbers, and characters.
a. Integer Data Types (int
)
- Used to store whole numbers (positive or negative) without decimals.
- Size: Typically 4 bytes (on most systems), which allows a range of
-2,147,483,648
to2,147,483,647
.
Variants of int
:
signed int
: Can store both positive and negative values.- Example:
int a = -100;
- Example:
unsigned int
: Can store only positive values (doubles the upper range).- Example:
unsigned int a = 100;
- Example:
short int
: Requires less memory (typically 2 bytes).- Example:
short int a = 100;
- Example:
long int
: Allows storing larger integers (typically 4 or 8 bytes).- Example:
long int a = 123456789;
- Example:
b. Floating-Point Data Types (float
, double
)
Used to store numbers with decimal points (real numbers).
float
:- Size: Typically 4 bytes.
- Precision: Up to 6 decimal places.
- Example:
float pi = 3.14159;
double
:- Size: Typically 8 bytes.
- Precision: Up to 15 decimal places.
- Example:
double largeValue = 1234567.123456789;
long double
:- Size: Typically 10 or 16 bytes (depending on the system).
- Precision: Higher precision than
double
. - Example:
long double preciseValue = 1.234567890123456789;
c. Character Data Type (char
)
- Used to store single characters (letters, digits, or symbols).
- Size: 1 byte.
- Range: 0 to 255 (for
unsigned char
),-128
to127
(forsigned char
). - Example:
char grade = ‘A’; // Single character
2. Derived Data Types
Derived data types are based on basic data types but offer more complex structures.
a. Arrays
- A collection of elements of the same type stored in contiguous memory locations.
- Example:
int numbers[5] = {1, 2, 3, 4, 5}; // Array of 5 integers
b. Pointers
- A variable that stores the memory address of another variable.
- Example:
int a = 10;
int *ptr = &a; // Pointer to integer variable ‘a’
c. Structures
- Used to group different types of variables under a single name.
- Example:
struct Person {
char name[50];
int age;
float height;
};
d. Unions
- Similar to structures but can store only one member at a time (sharing memory).
- Example:
union Data {
int i;
float f;
char str[20];
};
3. Enumeration (enum
)
An enumeration is a user-defined data type that consists of integral constants and assigns names to those constants for readability.
- Example:
enum week {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
enum week today = Wednesday; // today is assigned the value 3 (index of Wednesday)
4. Void Data Type
- The
void
data type indicates the absence of any type. It is typically used with functions. - Example:
void functionName(); // Function returning no value
5. Modifiers
Modifiers change the size or range of the basic data types. They include:
signed
: The variable can hold both positive and negative values.unsigned
: The variable can hold only non-negative values, thus extending the upper range.short
: Used to reduce the storage size of an integer.long
: Used to increase the storage size of an integer.
Example with Modifiers:
long double highPrecisionValue = 2.718281828459; // Larger precision for floating-point numbers
Summary of Data Types and Sizes (on a typical 32-bit system):
Data Type | Size (bytes) | Range |
---|---|---|
char |
1 | -128 to 127 (signed), 0 to 255 (unsigned) |
int |
4 | -2,147,483,648 to 2,147,483,647 (signed) |
float |
4 | Up to 6 decimal places |
double |
8 | Up to 15 decimal places |
long int |
4 or 8 | Larger range for integers |
long double |
10 or 16 | Higher precision for floating-point numbers |
short int |
2 | -32,768 to 32,767 (signed) |
void |
0 | No data |
Example Program Demonstrating Data Types:
#include <stdio.h>
int main() {
// Basic data types
int age = 25; // Integer variable
float pi = 3.14159; // Floating-point variable
char grade = ‘A’; // Character variable
// Derived data types
int numbers[5] = {1, 2, 3, 4, 5}; // Array of integers
int *ptr = &age; // Pointer to integer
// Print values
printf(“Age: %d\n”, age);
printf(“PI: %.2f\n”, pi);
printf(“Grade: %c\n”, grade);
printf(“Pointer to age: %p\n”, ptr);
return 0;
}
Output:
2.6 Type Conversion
In C programming, type conversion refers to changing the type of a variable from one data type to another. This can be done either automatically by the compiler (implicit conversion) or manually by the programmer (explicit conversion). Understanding type conversion is important to ensure the correct interpretation of data when performing operations involving different data types.
v
1. Implicit Type Conversion (Automatic Type Conversion)
- Implicit type conversion happens automatically when a smaller data type is converted into a larger data type without the programmer’s intervention.
- This is also called “type promotion”.
- It occurs when operands of different data types are used in an expression, and the compiler promotes the smaller type to the larger type to prevent data loss.
Rules of Implicit Type Conversion:
- If a variable of a smaller data type is assigned to a larger data type, it is automatically promoted.
- The promotion hierarchy generally follows this order:
char
→int
→float
→double
→long double
Example of Implicit Type Conversion:
#include <stdio.h>
int main() {
int a = 10;
float b = 5.5;
float result = a + b; // ‘a’ is implicitly converted to ‘float’
printf(“Result: %.2f\n”, result); // Output will be 15.50
return 0;
}
Explanation:
- In the above example, the integer variable
a
is promoted to a floating-point type before the addition takes place. This prevents the loss of decimal precision in the result.
2. Explicit Type Conversion (Type Casting)
- Explicit type conversion, also known as type casting, is when the programmer manually converts one data type into another.
- This is done using the cast operator
(type)
.
Syntax for Type Casting:
Example of Explicit Type Conversion:
#include <stdio.h>
int main() {
float a = 5.75;
int b;
b = (int) a; // Explicitly converting ‘float’ to ‘int’
printf(“Value of a (float): %.2f\n”, a); // Output will be 5.75
printf(“Value of b (int): %d\n”, b); // Output will be 5 (fractional part truncated)
return 0;
}
Explanation:
- In the above example, the floating-point number
a
is explicitly cast to an integer using(int)
, which results in the truncation of the fractional part. Hence,b
becomes5
.
Difference Between Implicit and Explicit Type Conversion
Feature | Implicit Type Conversion | Explicit Type Conversion |
---|---|---|
Performed By | Automatically by the compiler | Manually by the programmer using a cast |
Risk of Data Loss | Less likely (happens during promotion) | Possible, especially when converting larger types to smaller types |
Usage | Used when mixing smaller and larger types | Used when programmer needs more control over the conversion |
Example | int x = 10; float y = x; |
float x = 10.5; int y = (int)x; |
3. Type Conversion in Expressions
When performing arithmetic operations, C often converts operands to a common type, either implicitly or explicitly.
Implicit Conversion in Expressions:
When mixed data types are involved in an expression, C automatically converts the data types to a common type, which follows the type promotion hierarchy.
Example:
float b = 6.2;
float result = a + b; // ‘a’ (int) is converted to ‘float’
In the above example, a
is automatically promoted to a float to perform the addition with b
.
Explicit Conversion in Expressions:
You can manually convert data types to perform operations of your choice, controlling the precision and avoiding data loss.
Example:
int b = 2;
float result = a / b; // Result is 2.875
int int_result = (int) (a / b); // Casting result to int truncates to 2
float a = 5.75;
int b = 2;
float result = a / b; // Result is 2.875
int int_result = (int) (a / b); // Casting result to int truncates to 2
4. Type Conversion in Function Calls
C also performs automatic type conversion during function calls, promoting smaller data types to larger ones (type promotion).
Example:
#include <stdio.h>
void printSum(float x) {
printf(“Sum is: %.2f\n”, x);
}
int main() {
int a = 10;
printSum(a); // ‘a’ (int) is implicitly promoted to ‘float’ before passing to the function
return 0;
}
void printSum(float x) {
printf("Sum is: %.2f\n", x);
}
int main() {
int a = 10;
printSum(a); // 'a' (int) is implicitly promoted to 'float' before passing to the function
return 0;
}
Here, the integer a
is promoted to float
when passed to the printSum
function, as the function expects a float
argument.
5. Type Promotion Rules in C
The following rules apply when converting data types in an expression:
- All
char
andshort
values are promoted toint
. - If one operand is
float
and the other isint
, theint
is converted tofloat
. - If one operand is
double
, the other operand is promoted todouble
. - When mixing signed and unsigned types:
- If the unsigned type is larger, the signed type is converted to unsigned.
- If the signed type is larger, the unsigned type is converted to signed.
Example:
#include <stdio.h>
int main() {
char a = 10;
int b = 20;
int sum = a + b; // ‘a’ is promoted from ‘char’ to ‘int’
printf(“Sum: %d\n”, sum); // Output will be 30
return 0;
}
2.7 Input and Output
stdio.h
header file.1. Input Operations
a. Reading Input from the Keyboard
scanf
Function:- The
scanf
function is used to read formatted input from the standard input (usually the keyboard). - Syntax:
int scanf(const char *format, …);
- Example:
#include <stdio.h>
int main() {
int age;
float height;printf(“Enter your age: “);
scanf(“%d”, &age); // Reading an integer valueprintf(“Enter your height (in meters): “);
scanf(“%f”, &height); // Reading a float valueprintf(“Age: %d\n”, age);
printf(“Height: %.2f meters\n”, height);return 0;
} - Format Specifiers:
%d
forint
%f
forfloat
%lf
fordouble
%c
forchar
%s
for strings
- Note: The
&
operator is used to provide the address of the variable where the input will be stored.
- The
b. Reading Strings
scanf
for Strings:- The
scanf
function can be used to read strings. - Example:
char name[50];
printf(“Enter your name: “);
scanf(“%s”, name); // Reading a string (without spaces)fgets
Function:
- The
fgets
function is used to read a line of text including spaces. - Syntax:
char *fgets(char *str, int n, FILE *stream);
- Example:
#include <stdio.h>
int main() {
char name[50];printf(“Enter your name: “);
fgets(name, sizeof(name), stdin); // Reading a line including spacesprintf(“Hello, %s”, name);
return 0;
}2. Output Operations
a. Displaying Output to the Screen
printf
Function:- The
printf
function is used to print formatted output to the standard output (usually the screen). - Syntax:
int printf(const char *format, …);
- Example:
#include <stdio.h>
int main() {
int age = 25;
float height = 1.75;printf(“Age: %d\n”, age);
printf(“Height: %.2f meters\n”, height);return 0;
} - Format Specifiers:
%d
for integer values%f
for floating-point values%lf
for double values%c
for characters%s
for strings%%
for printing the percent sign
- The
b. Formatting Output
- Field Width and Precision:
- You can specify field width and precision in
printf
to control the appearance of numbers. - Example:
printf(“Number with width 10: %10d\n”, 123); // Right-aligned in a field of width 10
printf(“Number with 2 decimal places: %.2f\n”, 3.14159); // Precision of 2 decimal places
- You can specify field width and precision in
- Left Alignment:
- You can left-align output by using the minus sign (
-
) in the format specifier. - Example:
printf(“Left-aligned: %-10d\n”, 123); // Left-aligned in a field of width 10
- You can left-align output by using the minus sign (
c. Printing Special Characters
- Escape Sequences:
- Special characters can be printed using escape sequences in
printf
. - Common Escape Sequences:
\n
for newline\t
for tab\\
for backslash\"
for double quote\'
for single quote
- Example:
printf(“Line 1\nLine 2\n”); // Newline
printf(“Column1\tColumn2\n”); // Tab
printf(“Path: C:\\Program Files\n”); // Backslash
- Special characters can be printed using escape sequences in
3. File I/O
In addition to standard input and output, C provides functions to handle file input and output using file pointers.
a. Opening a File
fopen
Function:- Opens a file and returns a file pointer.
- Syntax:
FILE *fopen(const char *filename, const char *mode);
- Modes:
"r"
: Read"w"
: Write (creates a new file or truncates an existing one)"a"
: Append"r+"
: Read and write"w+"
: Read and write (creates a new file or truncates an existing one)"a+"
: Read and append
- Example:
FILE *file = fopen(“example.txt”, “w”);
if (file == NULL) {
printf(“Error opening file.\n”);
return 1;
}
b. Writing to a File
fprintf
Function:- Writes formatted output to a file.
- Syntax:
int fprintf(FILE *stream, const char *format, …);
Example: -
fprintf(file, “Hello, World!\n”);
c. Reading from a File
fscanf
Function:- Reads formatted input from a file.
- Syntax:
int fscanf(FILE *stream, const char *format, …);
Example: -
int number;
fscanf(file, “%d”, &number);
d. Closing a File
fclose
Function:- Closes an opened file.
- Syntax:
int fclose(FILE *stream);
- Example:
fclose(file);
e. File Error Handling
feof
,ferror
,clearerr
Functions:- Used to check end-of-file, errors, and to clear error indicators.
- Example:
if (feof(file)) {
printf(“End of file reached.\n”);
}
if (ferror(file)) {
printf(“Error reading file.\n”);
}
- The
2.8 Operators
In C programming, operators are special symbols that perform operations on variables and values. Operators are fundamental to building expressions and controlling the flow of a program. C provides a variety of operators that can be categorized into several types: