Introduction to C
C is a general-purpose, procedural programming language developed by Dennis Ritchie in 1972. It is widely used for system programming, embedded systems, and developing operating systems. C is known for its efficiency and low-level memory manipulation capabilities.
Key Features of C:
- Procedural Language: C follows a step-by-step procedural approach.
- Portable: C programs can run on different platforms with minimal changes.
- Efficient: C provides direct access to memory and hardware.
- Rich Standard Library: C has a vast collection of built-in functions.
- Modularity: C supports modular programming using functions and libraries.
- Extensible: C allows integration with assembly language and other languages.
Why Learn C?
Learning C is essential for understanding the fundamentals of programming and computer science. It is the foundation for many modern programming languages like C++, Java, and Python. C is also widely used in:
- Operating Systems: Unix, Linux, and Windows are written in C.
- Embedded Systems: C is used in microcontrollers and IoT devices.
- Game Development: C is used in game engines and graphics programming.
- System Software: Compilers, interpreters, and device drivers are often written in C.
Basic Structure of a C Program
A C program typically consists of the following components:
// Preprocessor Directives
#include <stdio.h>
// Main Function
int main() {
// Program Statements
printf("Hello, World!\n");
return 0; // Return Statement
}
- Preprocessor Directives: Include header files like
stdio.h
for input/output functions. - Main Function: The
main()
function is the entry point of the program. - Program Statements: These are the instructions executed by the program.
- Return Statement: The
return 0;
statement indicates successful program execution.
Example: Hello World in C
// C Hello World Program
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
This program includes the standard input-output library (stdio.h
) and uses the
printf
function to print "Hello, World!" to the console.
Compiling and Running a C Program
To compile and run a C program, follow these steps:
- Write the program in a text editor and save it with a
.c
extension (e.g.,hello.c
). - Open a terminal or command prompt and navigate to the directory containing the program.
- Compile the program using a C compiler like
gcc
:gcc hello.c -o hello
- Run the compiled program:
./hello
Common C Libraries
C provides a rich set of standard libraries for various tasks. Some commonly used libraries include:
- stdio.h: Input/output functions like
printf
andscanf
. - stdlib.h: Memory allocation, random numbers, and other utility functions.
- math.h: Mathematical functions like
sqrt
,sin
, andcos
. - string.h: String manipulation functions like
strcpy
andstrlen
.