Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views93 pages

C Programming Language

Uploaded by

mamathabudarpu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views93 pages

C Programming Language

Uploaded by

mamathabudarpu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 93

C

Programmin
g Language
Introduction
What is C Language?

C is a high-level programming language developed in


1972 by Dennis Ritchie at Bell Labs. It is one of the
oldest and most widely used programming languages in
the world.
Why is C Important?

Foundation for Other Languages: Many modern programming


languages, like C++, Java, and Python, are influenced by C.
Portable: C programs can run on different machines with minimal
changes.
Efficient: C provides fast execution and is close to machine
language, which makes it powerful for system programming.
Features of C
Simple and Easy to Learn: The syntax of C is straightforward
and easy to understand.
Structured Language: Programs are divided into small modules
or functions, making them easier to manage.
Rich Library: C has a collection of built-in functions that make
programming easier.
Low-Level Access: It allows direct interaction with memory using
pointers, making it suitable for system-level tasks.
Extensibility: You can add new features or modify existing ones in
C programs.
Where is C Used?

Operating Systems: The Linux Kernel and other operating systems are
written in C.
Embedded Systems: C is used in programming microcontrollers for
devices like washing machines and microwaves.
Game Development: Some game engines use C for high-performance
tasks.
Database Development: Popular databases like MySQL are written in C.
Advantages
Foundation for Other Languages: Helps learn languages like C++,
Java, and Python.
Low-Level Understanding: Teaches how computers and memory
work.
Problem-Solving Skills. Improves logical thinking and coding.
Fast Execution: Programs run quickly and efficiently.
Versatile Usage: Used in operating systems, embedded systems, and
more.
Rich Libraries: Provides built-in functions for various tasks.
Portable: Programs can run on different machines with little change.
Limitations
No Object-Oriented Features: Lacks classes and
inheritance.
Manual Memory Management: Programmer must manage
memory carefully.
No Runtime Error Checking: Errors like memory access
issues aren’t caught during runtime.
No Exception Handling: Cannot handle errors automatically.
Verbose Code: Writing complex programs requires more
lines of code, making them harder to read and maintain.
History
Origins:
C was developed in 1972 by Dennis Ritchie at Bell Labs,
USA.
It was created to develop the UNIX operating system,
which needed a powerful and portable programming
language.
Predecessors:
C evolved from two earlier languages:
BCPL (Basic Combined Programming Language),
developed by Martin Richards in the 1960s.
B, developed by Ken Thompson in 1970, was simplified
from BCPL and used in early UNIX development.
Key Milestones:
1972: C was introduced to overcome the limitations of
B, providing more features and flexibility.
1978: The first book on C, The C Programming
Language by Brian Kernighan and Dennis Ritchie, was
published. This version is called K&R C.
1989: C was standardized by ANSI (American National
Standards Institute) as ANSI C or C89.
1990: The standard was adopted by ISO (International
Organization for Standardization) as ISO C.
1999: The standard was updated as C99, introducing
new features like inline functions and variable-length
arrays.
2011: Another update, C11, added support for
multithreading and safer standard functions.
Why C Became Popular?
It is simple, efficient, and close to hardware, making it suitable for
system programming.
C was widely used for developing operating systems, embedded
systems, and high-performance applications.
Algorithms
What is an Algorithm?
An algorithm is a step-by-step procedure or set of instructions
to solve a problem. It is a clear, logical sequence of actions to
achieve a specific goal or result.
Example:
Think of an algorithm like a recipe. The recipe gives you steps
to follow to make a dish. Similarly, an algorithm gives steps to
solve a problem.
Features of an Algorithm
Definiteness: Each step should be clearly defined.
Input: The algorithm must have inputs, which are the
data it works with.
Output: It produces an output after following the steps.
Finiteness: The algorithm must stop after a certain
number of steps.
Effectiveness: The steps must be basic enough to be
carried out.
Steps to Create an Algorithm
Understand the problem: Before making an algorithm, you
need to understand what the problem is and what result you
want to achieve.
Define inputs and outputs: Clearly mention what inputs are
needed and what output you expect.
Step-by-step instructions: Write clear, simple steps to solve
the problem. Each step should be easy to understand and
perform.
Test the algorithm: After writing it, test if it solves the
problem correctly.
Example of an Algorithm:
Problem: Find the sum of two numbers.
Step 1: Start.
Step 2: Take two numbers as input.
Step 3: Add the two numbers.
Step 4: Display the result.
Step 5: End.
Flowcharts
What is a Flowchart?
A flowchart is a visual representation of an algorithm. It
uses shapes like arrows, circles, and rectangles to show
the steps and the flow of the algorithm.
Example:
A flowchart is like a map that shows you how to get from
one place to another, but for a process or algorithm.
Common Symbols in a Flowchart:
Oval (Terminal): Represents the start or end of the
process.
Rectangle (Process): Represents an operation or action,
like calculations or assignments.
Parallelogram (I/O): Used to represent input or output.
Diamond (Decision): Represents a decision-making step,
where a condition is checked.
Arrow (Flow of Control): Indicates the direction in which
the steps of the algorithm flow.
Example:
Why Use Flowcharts?
Clarity: Flowcharts make complex algorithms easy to
understand by visually representing the flow of steps.
Error-Free: Helps detect problems early in the process
because you can clearly see the sequence of steps.
Documentation: Flowcharts can be a helpful reference
for future use or improvements.
When to Use Algorithms and Flowcharts:
Algorithm: Use when you need to describe a solution in
a detailed, step-by-step way.
Flowchart: Use when you need to visually explain the
process or make it easier to follow.
Token
A token is the smallest unit of a program that has meaning. In C, a
program is made up of many tokens, which are the building blocks of
the code.
There are six types of tokens in C:
1. Keywords
2. Identifiers
3. Constants
4. String literals
5. Operators
6. Punctuation – Semicolon, Comma, Period, Parentheses, Curly
Braces etc..
Identifier
An identifier is the name used to identify variables, functions, arrays,
or any other user-defined items in a program. Identifiers are created
by programmers to represent values and functions in the code.
Rules for naming an identifier in C:
It must start with a letter (a-z, A-Z) or an underscore (_).
After the first character, it can contain letters, digits (0-9), or
underscores.
Identifiers are case-sensitive.
It cannot be a keyword.
It cannot contain spaces or special characters.
Examples of valid identifiers:
age, total_amount, counter_1, _sum
Examples of invalid identifiers:
2count (cannot start with a number),
first-name (cannot contain hyphen),
int (cannot use C keywords).
Keyword
A keyword is a reserved word in C that has a special meaning to
the compiler. Keywords are part of the C language syntax, and you
cannot use them as identifiers.
Reserved Words: These are reserved by the C language and have
special meanings. They cannot be used as identifiers.
Case-sensitive: Keywords are case-sensitive, meaning int and INT
are different.
No redefinition: Keywords can’t be redefined by the programmer.
auto default float long sizeof unsign
ed
break do for registe static void
r
case double goto restric struct volatile
t
char else if return switch while

const enum inline short typede


f
continu extern int signed union
First Program

#include <stdio.h>
int main(){
printf(“Hello,
World!”);
return 0;
}
Structure
#include <stdio.h>
This is a preprocessor directive that tells the compiler to
include the Standard Input/Output library ( stdio.h ).
The printf() function, used for printing output, is defined
in this library.
Header File:
Header files in C are files with a .h extension that
contain declarations for functions, macros, constants,
and data types. They are used to share code between
different source files and organize the program.
 Provide function prototypes.
 Define macros and constants.
 Declare global variables.
 Enable code reuse and modularity.
Including Header Files: Use the #include directive to
include header files in your program.
Standard headers: Use angle brackets ( < > ).
#include <math.h>
Custom headers: Use double quotes (“ ”).
#include “myheader.h”
Int main()
This is the entry point of every C program. Execution
starts here.
Return Type ( int ): Specifies that the function returns
an integer value to the operating system. A return value
of 0 usually means successful execution.
Without main(), the program won’t execute.
Curly Braces:
Denote the block of code. All the instructions within
these braces are executed sequentially.
Groups multiple statements into a single block.
printf(“Hello, World!”);
Prints the text “Hello, World!” to the console.
printf Function: Outputs formatted data.

return 0;
Ends the main() function and returns the value 0 to the
operating system.
Indicates that the program executed successfully.
Execution Process
The execution process of a C program involves several steps,
from writing the source code to running the compiled program.
Writing the Source Code
The programmer writes the source code in a .c file
Preprocessing
The preprocessor handles all preprocessor directives in the
source code.
Steps in preprocessing:
Expands all #include directives by copying the contents
of the included headers files into the source file.
Resolves macros and constants defined using #define.
Removes comments from the code.
Produces an intermediate file .i with the expanded code.
Compilation:
The preprocessed code is converted into assembly
language (a low level human readable representation of
machine code).
Steps in compilation:
Checks the syntax and semantics of the code.
Converts high-level code into assembly instructions.
Produces an assembly file .s file.
Assembly:
The assembly code is translated into machine code by
an assembler.
Produces an object file containing machine readable
instructions but not yet executable because it’s missing
necessary library functions.
Linking:
The linker combines the object file with standard libraries and
other required object files to create the final executable file.
Steps in linking:
Resolves external function calls by linking them to their
definitions in libraries.
Combines multiple object files into a single executable.
Produces an executable file .exe file.
Loading:
The loader loads the executable file into memory for
execution.
Steps in loading:
Allocates memory for the program.
Loads the program’s instructions into memory.
Execution:
The operating system passes control to the program’s main()
function.
Steps in execution:
Instructions in main() are executed sequentially.
Output is sent to the console.
When the return 0; statement is reached, the program ends and
returns control to the operating system.
Source Code (.c) --> Preprocessor --> Preprocessed
Code (.i)
--> Compiler --> Assembly Code (.s)
--> Assembler --> Object File (.o)
--> Linker --> Executable File (a.out / .exe)
--> Loader --> Memory --> Execution
Comments
Comments in C are pieces of text in the source code that are
ignored by the compiler. They are used to improve code
readability and provide information or explanations about the
code for developers.
C supports two types of comments.
Single-Line Comments:
Starts with // and continues until the end of the line.
Commonly used for short explanations or notes.
Multi-Line Comments:
Enclosed within /* and */.
Can span multiple lines.
Useful for longer descriptions or disabling blocks of
code.
Data Types

A data type in C is a classification that specifies the type of data a


variable can hold and how much memory it requires. It tells the
compiler what kind of value will be stored and how operations will
be performed on that value.
Category Examples Purpose
Basic Int, float, Store simple
double, char data values
Derived Array, Pointer, Build from basic
Function types for
advanced use.
User-defined Struct, union, Create custom
enum, typedef and more
complex types.
Basic Data Types:
These are the fundamental types used to store simple data values.
int: For whole numbers.
float: For decimal numbers with less precision (6-7 after the decimal
point).
double: For decimal numbers with high precision (15-16 after the
decimal point).
char: For single characters.
Derived Data Types:
These are built from basic data types:
Array: A collection of elements of the same type.
Pointer: Stores the memory address of another
variable.
Function: Code blocks that return specific data types.
User-Defined Data Types:
These are custom types created by the programmer for more
complex data.
Structure (struct): Combines different data types.
Union: Like a structure, but all members share the same memory
space.
Enumeration (enum): Defines a set of named integer constants.
Typedef: Allows creating an alias for an existing data type.
Variable
A variable in C is like a storage container with a name. It is used to store
data that your program can change or use later. You give the variable a
name, a data type (to define the kind of value it can hold), and assign it
a value.

Declaring and Initializing Variables:


Declaration: Declaring a variable means telling the compiler its type
and name.
Example:
int age;
Initialization: Assigning a value to a variable when you
declare it or later.
Example:
int age = 25;
age = 30;
Constants:
Constants are values that don’t change during the program’s
execution.
Using const:
Declares a variable as constant.
You cannot modify its value after initialization.
Example:
const int MAX = 100;
MAX = 200; // Error: cannot modify a const
Using #define:
A preprocessor directive to define a constant.
No type is specified, and it’s replaced directly in the
code during compilation
Example:
#define PI 3.14
Type Scope Lifetime
Local Variable Inside Created when
function/block function starts,
destroyed when
it ends.
Global Variable Entire program Exists
throughout
program
execution.
Static Variable Inside Retains value
function/block across function
calls.
Operators

Operators are symbols that perform specific actions on


variables and values, like addition or comparison.
Arithmetic Operators:
Used for basic math operations.

Operator Descriptio Example Result


n
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplicati 5*3 15
on
/ Division 6/2 3
% Modulus 5%2 1
Assignment Operators:
Assigns a value to a variable.

Operator Description Example Result


= Assign Int x=4; 4
+= Add and x+=8; 12
Assign
-= Subtract and x-=6; 6
Assign
*= Multiply and x*=2 12
Assign
/= Divide and x/=2 6
Assign
%= Modulus and x%=2 0
Assign
Relational Operators:
Compare two values and return 1 (true) or 0 (false).

Operator Descriptio Example Result


n
== Equal to 5==3 0
!= Not Equal 5!=3 1
to
> Greater 5>3 1
than
< Less than 5<3 0
>= Greater 5>=5 1
than or
Logical Operators:
Used to combine conditions.

Operator Descriptio Example Result


n
&& Logical AND (5>3) && 1
(4>2)
|| Logical OR (2>1) || (1>2) 1

! Logical NOT !(5>3) 0


Bitwise Operators:
Work on binary data.

Operator Descriptio Example Result


n
& Bitwise 10 & 8 8
AND
| | 10 | 8 10
^ Bitwise 10^8 2
XOR
~ Bitwise ~10 -11
NOT
<< Left shift 5<<1 10
Conditional Operator:
A shorthand for if-else ( ? : ).
Example:
int x=(5>3)? 10:20;
Increment ( ++ ) :
Adds 1 to a variable.

Decrement ( -- ):
Subtracts 1 from a variable.
Control Structures
Control structures in C are tools that let you control the
flow of your program. They decided the other in which
instructions are executed based on conditions or loops.

 Decision Making Statements


 Looping Statements
 Jump Statements
Decision Making Statements:
These are used to make decisions based on conditions.
if statement:
Executes a block of code if a condition is true.
Syntax:
if ( condition ) {
// statements
}
if- else statement:
Chooses between two blocks of code based on a condition.
Syntax:
if ( condition ) {
// code if condition is true
}
else {
// code if condition is false
}
else if statement:
The else if statement is used when you want to
check multiple conditions in a decision making
process.
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if none of the above conditions are true
}
switch statement:
Checks a variable against multiple cases
and executes the matching block.
Syntax:
switch (variable) {
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
Looping Statements:
Used to repeat a block of code multiple times.
for statement:
Runs the code for a fixed number of times.
Syntax:
for ( initialization; condition; increment/decrement) {
// code to repeat
}
while statement:
Runs the code as long as the condition is true.
Syntax:
while ( condition ) {
// code to repeat
}
do while:
Runs the code at least once, then repeats while
the condition is true.
Syntax:
do {
// code to repeat
} while ( condition );
Control Flow Statements:
Used to alter the normal flow of a program.
break Statement:
Exists a loop or switch statement immediately.
continue statement:
Skips the current iteration of a loop and moves to
the next.
Functions
A function is a block of reusable code that performs a
specific task. Functions make programs modular, easier
to understand, and reusable.
Function Declaration:
Also called a prototype.
It tells the compiler about the function’s name, return
type, and parameters.
It appears before the main() function or in a header file.
Syntax:
return_type function_name( parameter_list );

Example:
int add ( int a, int b );
Parameters:
Parameters are the variables listed inside a
function’s parentheses. They are used to
pass values into the function.
Formal Parameters:
These are the variables that are declared inside
the function’s parentheses during function
declaration or definition.
They serve as placeholders or references for the
actual values ( arguments ) that will be passed to
the function when it is called.
They act as local variables within the function,
holding the values passed during the function call.
Actual Parameters:
These are the actual values or arguments passed
to the function when it is called.
The values of actual parameters are assigned to
the corresponding formal parameters when the
function is executed.
Function Definition:
Provides the actual implementation of the function.
Syntax:
return_type function_name( parameter_list ) {
// function body
return value;
}
Example:
int add( int a, int b ) {
return a+b;
}
Function Calling:
A function is called by using its name followed by
parentheses and arguments.
Example:
int main() {
int result = add ( 5, 3);
printf( “Result: %d\n”, result );
return 0;
}
Recursion:
Recursion is when a function calls itself directly
or indirectly.
It requires a base condition to stop the recursion,
otherwise, it leads to infinite recursion.
Example: Factorial Using Recursion
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1; // Base condition
return n * factorial(n - 1);
}
int main() {
printf("Factorial of 5: %d\n", factorial(5));
return 0;
}
Passing Arguments ( By Value and By
Reference ):
By Value:
 A copy of the variable is passed to the
function.
 Changes in the function do not affect the
original variable.
Example:
void byValue(int x) {
x = 10; // This change is local
}

int main() {
int num = 5;
byValue(num);
printf("num: %d\n", num); // Output: 5
return 0;
}
By Reference:
The function receives the variable’s
memory address.
Changes made in the function affect the
original variable.
Example:
void byReference(int *x) {
*x = 10; // Modifies the value at the address
}

int main() {
int num = 5;
byReference(&num); // Pass address of num
printf("num: %d\n", num); // Output: 10
return 0;
}
Arrays
An array is a collection of elements that are of the same
data type, stored in contiguous memory locations. It allows
you to store multiple values in a single variable, using an
index to access each value.
Single-Dimensional Arrays:
A single-dimensional array is a list of elements of the same
type, where each element is accessed using an index.
Syntax:
data_type array_name [ size ];
Multi-Dimensional Arrays:
A multi-dimensional array is an array of arrays. It
can have more than one dimension, such as 2D
arrays ( like matrices ), 3D arrays, and so on.
Syntax:
data_type array_name [ row_size ]
[ column_size ];
Array Manipulation:
Arrays in C allow various types of manipulation, such as
accessing, modifying, and copying elements.
Accessing Elements:
Access elements by using the index ( starting from 0 ).
Modifying Elements:
You can change elements by assigning new values to
specific indices.
Array Traversal:
You can loop through the array using a for loop.
Finding Array Length:
There is no built-in function to get the length of
an array in C, but you can calculate it using the
sizeof operator.
Example:
int arr[5] = {1, 2, 3, 4, 5};
int length = sizeof(arr) / sizeof(arr[0]); // Output:
5
Pointers
A pointer is a variable that holds the memory address of
another variable. Pointers are essential in C because they
allow you to work with memory directly, perform efficient
array manipulation, and implement dynamic memory
management.

Syntax:
data_type *pointer_name;
#include <stdio.h>
int main() {
int num = 10;
int *ptr = &num; // ptr holds the address of num
printf("Value of num: %d\n", num); // Output: 10
printf("Address of num: %p\n", &num); // Output: Address of
num
printf("Value pointed by ptr: %d\n", *ptr); // Output: 10
printf("Address stored in ptr: %p\n", ptr); // Output: Address of
num
return 0;
}

You might also like