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

C Programming

The document provides an overview of the C programming language, including its history, features, and structure. It explains the role of programming in data analytics, detailing data manipulation, statistical analysis, and automation. Additionally, it covers fundamental concepts such as data types, variables, and the differences between compilers and interpreters.

Uploaded by

ARJUNA.R
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)
3 views123 pages

C Programming

The document provides an overview of the C programming language, including its history, features, and structure. It explains the role of programming in data analytics, detailing data manipulation, statistical analysis, and automation. Additionally, it covers fundamental concepts such as data types, variables, and the differences between compilers and interpreters.

Uploaded by

ARJUNA.R
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

C PROGRAMMING

PROGRAMMING
Thynk Unlimited Home About Content Others

C Programming
Language

C language is a general-purpose, procedure


oriented programming language, developed by
Dennis Ritchie in 1972 at AT & T’S Bell
Telephone Laboratories, US. Dennis Ritchie
created it to developed Unix Operating
System.
History of C
Before becoming of C Language, in 1966, a person named Martin Richard created a
Programming Language named BCPL (Basic Combined Programming Language). It was created
at AT & T’S Bell Telephone Laboratories, US, by the combining of basic features of all
programming languages. BCPL was not suitable for making large software, as well as coding in
low-level style. Ken Thompson, who worked at AT & T’S Bell Telephone Laboratories along
with Martin Richard, created the B language in 1969 by improving BCPL. Actually, Ken
Thompson wanted to create an operating system that needed a good programming language
to build and that language was B Language. After creating B language, he created Unix
Operating System. Dennis Ritchie also worked at AT & T’S Bell Telephone Laboratories, which
created C Language in 1972, and told Ken Thompson, if we build the Unix Operating System
with the help of C Language, then e an add more features to it. The biggest feature was the
operating system being portable.
Features of C Home About Content Others

C is a simple and easyprogramminglanguage.


There are commands/instructions like English in C language which are very easy for a programmer
to read, understand, and code.
C is a Procedure Oriented Programming Language.
C is a very powerful and case sensitive programming language.
C Language is a Compiler based dynamic programming language.
C language is a middle level language due to which both low level and high level programming
can be done.
The C language is the most commonly used programming language in developing operating
systems and embedded systems.
C language is a very portable and powerful programming language.
C language is a Syntax Based Language.
C is a general purpose programming language that covers basic features of all other languages.
Role of programming in
data analytics
Programmingplaysa crucialandmultifaceted roleindata analytics, enabling analysts to efficiently
and effectively extract insights from data. Its key contributions include:
Data Manipulation and Cleaning: Programming languages like Python (with libraries such as Pandas)
and R provide robust tools for data acquisition, cleaning, transformation, and preparation. This
involves handling missing values, filtering, aggregating, merging datasets, and reformatting data for
analysis.
Statistical Analysis and Modeling: Programming facilitates the application of various statistical
methods and machine learning algorithms. R and Python offer extensive libraries (e.g., scikit-learn in
Python, various packages in R) for tasks like regression, classification, clustering, time-series
analysis, and more complex predictive modeling.
Automation of Tasks: Repetitive and time-consuming data analysis tasks can be automated through
scripting, significantly improving efficiency and reducing the potential for human error.
Data Visualization: Programming allows for the creation of dynamic and interactive data
visualizations, moving beyond static charts. Libraries like Matplotlib, Seaborn, and Plotly in Python,
and ggplot2 in R, enable the creation of insightful and customizable plots to communicate findings
effectively.
Scalability and Big Data Handling: Programming skills are essential for
working with large and complex datasets, as manual methods become
impractical. Languages like Python and frameworks like Apache Spark
enable the processing and analysis of big data.

Collaboration and Version Control: Programming promotes collaborative


work in data analysis projects by enabling standardized coding practices
and the use of version control systems (e.g., Git). This ensures organized
project management and facilitates teamwork.

Customization and Flexibility: Programming offers the flexibility to develop


custom solutions and algorithms tailored to specific analytical needs that
might not be met by off-the-shelf software.
Compiler
The Compiler is a translator that takes input i.e., High-
Level Language, and produces an output of low-level
language i.e. machine or assembly language. The work
of a Compiler is to transform the codes written in the
programming language into machine code (format of 0s
and 1s) so that computers can understand
Interpreter
An Interpreter is a program that translates a programming language into a
comprehensible language. The interpreter converts high-level language to an
intermediate language. It contains pre-compiled code, source code, etc.
It translates only one statement of the program at a time.
Interpreters, more often than not are smaller than compilers.
Difference between Compiler and Interpreter
Agenda Compiler Interpreter

The program is interpreted/translated one


Program scanning Compilers scan the entire program in one go.
line at a time.

As and when scanning is performed, all the


One line of code is scanned , and errors
Error Detection errors are shown in the end together , not line
encountered are shown
by line

Compilers convert the source code to object Interpreters do not convert the source
Object Code
code code to object code

The execution time of compiler is less ,


Execution Time It is not prefered due to its slow speed.
hence it is prefered

Programming Programming languages that use compilers Programming languages that use
Languages are C, C++ ,C# interpreter are python , ruby, perl

Types of error Compilers can check syntactic and semantic Interpreters checks the syntactic errors
detected errors in the program simultaneously only

Compiler are large in size Interpreters are small in size


Size

Interpreters are relatively flexible but are


Flexibility and Compilers are not flexible but are more
less efficient
Efficiency efficient
Structure of C
1) The Include Directive

#include is a preprocessor directive. It tells the C


compiler to include the content of the standard
input/output library ( stdio.h). This library contains
functions like printf that are essential for input and output
operations in your program
2)The main()
Function Every C program must have a main() function. This is
the entry point of your program 3 execution always begins
here. The () indicates that main does not receive any argument
values from the operating system when it starts.
3)Function Body

The statements that make up the main() function (or any


other function) are enclosed within curly braces {}. This
block of code defines what the function does
Input / Output (I/O) Functions : In C language, two types of Input/Output
functions are available, and all input and output operations are carried out
through function calls.
Several functions are available for input / output operations in C.
These functions are collectively known as the standard i/o library.

Input: In any programming language input means to feed some data into
program. This can be given in the form of file or from command line.

Output: In any programming language output means to display some data on


screen, printer or in any file.
The Standard Files
C programming treats all the devices as files. So devices
such as the display are addressed in the same way as files
and the following three files are automatically opened when
a program executes to provide access to the keyboard and
screen.
Formated I/O Functions: formatted I/O functions operates on various types of
data.

1 : printf() : output data or result of an operation can be displayed from the


computer to a standard output device using the library function printf(). This
function is used to print any combination of data.
Syntax : printf(“format String” ,list of variables);

Ex : printf(“%d”,3977); // Output: 3977


printf() statement another syntax :
Syntax : printf(“fomating string”);

Formating string : it prints all the character given in doublequotes


(“ “) except formattingspecifier.
<format string>: The CPU performs IO operations with input and output
devices in a streaming manner. The data read from a standard input device
(for example, a keyboard) through the standard input stream is called stdin.
Similarly the data sent to the standard output, which is the computer display
screen, through the standard output device is called stdout. The computer
receives data from the stream in a text form, however you may want to
parse it in variables of different data types such as int, float or a string.
Similarly, the data stored in int, float or char variables has to be sent to the
output stream in a text format. Format specifier symbols are used exactly
for this purpose.

%f: for printing float values.


%d: for printing integer values.
%c:for printing character values
The(&)symbolgivesthemeaning“addressof “ thevariable.
scanf() : input data can be entered into the computer using the standard
input C library function called scanf().

This function is used to enter any combination of input.

Syntax : scanf(“control string “,&var1, &var2,----, &varn);

The scanf() function is used to read information from the standard input
device (keyboard).

Ex : scanf(“ %d “,&a);-> hello Each variable name (argument) must be


preceeded by an ampersand (&).
The use of ampersand(&) before the variables is a must .
The & is the “Address of Operator”.
It gives the location number(address) used by the variable in
memory.
When the & is used , it indicates the scanf() at which memory
location should it store the value given by the user from the
keyboard.
#include <stdio.h>

int main()
{
printf("Hello World");

return 0;

}
UNIT 2
TOPICS

1. Data Types
2. Variables and constants
3. Scope and lifetime
4. Operators
DATA TYPES
Each variable in C has an associated
data type. It specifies the type of
data that the variable can store like
integer, character, floating, double,
etc.
DIAGRAM
INTEGER
Each variable in C has an
associated data type. It specifies
the type of data that the variable
can store like integer, character,
floating, double, etc.
On a 16-bit system, typically
ranges from -32,768 to +32,767.
On a 32-bit system, typically
ranges from -2,147,483,648 to
+2,147,483,647
FLOAT
The float data type is used to store
numbers that can have a fractional part,
also known as real numbers or floating-
point numbers. They are represented with
single-precision floating point format.

Typically a 32-bit quantity. Provides at


least six significant decimal digits of
precision. Magnitude generally ranges
between approximately 10-38 and
1038.
CHAR
Used to store a single character (e.g., 'A', 'b',
'5'). It typically occupies one byte of
memory. Can also be used to store small
integer values.
SHORT
A short integer. It's typically smaller
than an int and is used when you need to
conserve memory and the range of
integer values is known to be small.
LONG
A long integer. It's typically larger than
an int and is used for larger integer
values when the standard int range is
insufficient. long long is also available for
even larger values.
DOUBLE
Double-precision floating-point number.
Provides higher precision than float,
typically occupying 64 bits and offering
about 15 decimal digits of precision.
Used for more accurate calculations.
EXAMPLES
INT AND SHORT
FLOAT AND DOUBLE
CHAR
FORMAT STRING
A format specifier is a special placeholder used in formatted input/output
functions like printf() and scanf() in the C programming language
Always starts with a %, Instructs the compiler on how to interpret and
present the corresponding data—whether it's an integer, character, string,
etc...
FORMAT STRING
DERIVED DATA
TYPES
Arrays
Structures
Pointers
Unions
Array: In C, an array is a collection of
elements of the same data type stored in
contiguous memory locations. To declare an
array, you must specify the data type, the
array name, and the size (number of
elements the array can hold).
Declaring an array
data_type array_name[array_size]
Initializing the array:
int marks[30];
Structure
A structure in C is a user-defined, composite data type that
allows grouping together variables of different types under
a single name. Defined using the struct keyword, each
variable inside a structure is referred to as a member
Syntax: struct struct_name {
data_type member1;
data_type member2;
// ...
};
Unions
A union in C is a user-defined, composite data type that
allows multiple members of different types to share the
same memory location. Only one member can hold a valid
value at any given time, and the union’s overall size equals
the size of its largest member
Syntax: union union_name {
type1 member1;
type2 member2;
type3 member3;
};
Pointers
A pointer in C is a variable that stores the memory address
of another variable instead of the value itself. Using
operators such as the asterisk (*) for dereferencing and
address-of (&) for assigning addresses, pointers enable
direct memory manipulation, dynamic memory allocation,
and complex data structures
Syntax:// Declaration
data_type *pointer_name;
// Example
int var = 10;
int *ptr = &var; // ptr holds the address of var
VARIABLES
A variable is a name of memory location. It is used to store data.
Variables are changeable, we can change value of a variable
during execution of a program. . It can be reused many times.

Syntax to declare a variable: data_type Variable_name;


Example: int num;

Note: In C, every variable must be declared before it is used. We can also


declare multiple variables of same data type in a single statement by
separating them using comma

Example: int num1 , num2, num3;


VARIABLES
Initialising a variable :C Variable Initialization
Once the variable is declared, we can store useful values in it. The first
value we store is called initial value and the process is called Initialization. It
is done using assignment operator (=).

Syntax: data_type variable_name = value;


example: int num;
num = 3;
or
int num=3;
VARIABLES
Rules for naming a variable:
A variable name is any combination of 1 to 31 alphabets , digits
or underscores.

The first character in the variable name must be an alphabet or


underscore(_). It should not begin with digits.

No commas or blanks are allowed within a variable name.

No special symbol other than an underscore can be used in a


variable.
VARIABLES
Example
#include <stdio.h>

int main{
// Declaration + Initialization of variables
int a = 10; // Integer type variable
float pi = 3.14f; // Floating-point number
char ch = 'A'; // Character variable

// Performing operations and printing the values


printf("Value of a: %d\n", a);
printf("Value of pi: %.2f\n", pi);
printf("Character is: %c\n", ch);

return 0; // Indicate successful program termination


}
VARIABLES
Example
#include <stdio.h>

int main{
// Declaration + Initialization of variables
int a = 10; // Integer type variable
float pi = 3.14f; // Floating-point number
char ch = 'A'; // Character variable

// Performing operations and printing the values


printf("Value of a: %d\n", a);
printf("Value of pi: %.2f\n", pi);
printf("Character is: %c\n", ch);

return 0; // Indicate successful program termination


}
SCOPE AND LIFETIME OF VARIABLES
Scope of a Variable
Scope refers to the region of a program where a variable can be accessed or
referenced. In C programming, the scope of a variable determines its
visibility within various parts of the code.

1. Block Scope (Local Scope):


Variables declared inside a block, such as within a function or between curly
braces {}, are said to have block or local scope.
They are accessible only within that block and not outside it.
These variables are called as local variables.
example :void num()
{
int x = 10; // x is visible only inside num()
}
SCOPE AND LIFETIME OF VARIABLES
[Link] Scope (Global Scope):
Variables declared outside any function, usually at the top of a file, have file
scope.
They are accessible from their point of declaration to the end of the file, and
in all functions within that file (unless shadowed by a local variable).
These variables are called as global variable.
They are declared using global keyword.
example:
int globalVar = 5; // Visible throughout all functions in the file
SCOPE AND LIFETIME OF VARIABLES
Lifetime of a variable:
Lifetime refers to the duration for which a variable exists in
memory during program execution.
[Link] Variables:
Variables declared inside functions or blocks are
automatic by default.
Their lifetime begins when the block is entered and
ends when the block is exited
void num() {
int y = 20; // y exists only while num() is running
}
SCOPE AND LIFETIME OF VARIABLES
Static Variables:

Variables declared with the static keyword have a lifetime


that extends throughout the entire execution of the
program, even though their scope may be local to the block
in which they are declared.
void num() {
static int counter = 0; // counter persists for the entire program
}
SCOPE AND LIFETIME OF VARIABLES
Global Variables:
Variables declared outside functions (global variables) also
have a lifetime extending across the entire duration of the
program.

Dynamic Variables:
Memory allocated using functions like malloc persists until
it is freed explicitly using free.
Their lifetime begins when the memory is allocated, and
ends when it is freed.
CONSTANTS

The constants are those variables or values in the C which cannot be


modified once they are defined in the [Link] can be any type of
constant like integer, float, octal, hexadecimal, character constants, etc.

Syntax: const datatype constant_name;

Example: const float floatVal = 5.8;


OPERATORS

Operators are the basic components of C programming.


They are symbols that represent some kind of operation, such as mathematical,
relational, bitwise, conditional, or logical computations, which are to be performed
on values or variables. The values and variables used with operators are called
operands.
ARITHMETIC OPERATOR
The arithmetic operators are used to perform arithmetic/mathematical operations on
operands. There are 9 arithmetic operators in C language
ASSIGNMENT OPERATOR
Assignment operators are used to assign value to a variable. The left side operand of the assignment operator
is a variable and the right side operand of the assignment operator is a value. The value on the right side must
be of the same data type as the variable on the left side otherwise the compiler will raise an error
Relational operator
The relational operator n C are used for the comparison of the two operands.
All these operators are binary operators that return true or false values as the result of
comparison.
Logical operator
are used to combine two or more conditions/constraints or to complement the evaluation of the
original condition in consideration. The result of the operation of a logical operator is a boolean
value either TRUE or FALSE
.
Bitwise operator
Bitwise Operator are used to perform bit-level operations on the operands. The operators are
first converted to bit-level and then the calculation is performed on the operands.
Note: Mathematical operations such as addition, subtraction, multiplication
etc. can be performed at the bit level for faster processing.
Program to demonstrate arithemtic operators
#include <stdio.h>

int main(void) {
int a = 10, b = 4;
int add, sub, mul ,div,mod, res1,res2,res3,res4;

printf("a = %d, b = %d\n\n", a, b);

// Binary arithmetic operators


add = a + b;
printf("a + b = %d\n", add);

sub= a - b;
printf("a - b = %d\n", sub);

mul = a * b;
printf("a * b = %d\n", mul);

div= a / b;
printf("a / b = %d\n", div);

mod = a % b;
printf("a %% b = %d\n\n", mod);
Program to demonstrate arithemtic operators
// Unary operators
res1 = +a;
printf("+a = %d\n", res1);

res2 = -a;
printf("-a = %d\n", res2);

res3 = a++;
printf("a++ %d (now a = %d)\n", res3, a);

res4= a--;
printf("a-- (post-decrement) = %d (now a = %d)\n", result, a);
return 0;
Output
a = 10, b = 4
a + b = 14
a-b=6
a * b = 40
a/b=2
a%b=2
+a = 10
-a = -10
a++ (post-increment) = 10 (now a = 11)
a-- (post-decrement) = 11 (now a = 10)
Program to swap 2 numbers using 3rd variable
#include <stdio.h>
int main() {
int a, b, temp;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
temp = a;
a = b;
b = temp;
printf("After swapping (using third variable): a = %d, b = %d\n", a, b);
return 0;
}
Program to swap 2 numbers without using 3rd
variable
#include <stdio.h>
int main() {
int a, b;
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
a = a+b;
b = a-b;
b = a-b;
printf("After swapping (using third variable): a = %d, b = %d\n", a, b);
return 0;
}
THANK YOU
Introduction
Decision Making
if , if-else ,if-else ladder
Programs
Iterative
statements(looping control)
Example programs
Jump Statements
Functions
IN C PROGRAMMING, CONTROL STRUCTURES ARE THE BUILDING BLOCKS THAT ALLOW YOU TO
CONTROL THE FLOW OF EXECUTION IN A PROGRAM. UNLIKE SEQUENTIAL EXECUTION (WHERE
STATEMENTS RUN ONE AFTER ANOTHER FROM TOP TO BOTTOM), CONTROL STRUCTURES
ENABLE THE PROGRAM TO MAKE DECISIONS, REPEAT ACTIONS, OR JUMP TO DIFFERENT
PARTS OF THE CODE BASED ON CONDITIONS.
Decision making is a key part of selection
control, where the program evaluates a
condition (usually a boolean expression that
results in true or false) and executes code
accordingly. Let's dive into the details with
examples. All examples assume you're using
a basic C setup with and a function.
01 02 03 04
If if-else If-else ladder Switch Case.
The statement SYNTAX:
SYNTAX:
checks a
IF (CONDITION)
IF (CONDITION) {
condition. If the
// CODE
// CODE TO
TO EXECUTE
EXECUTE IF CONDITION IS
condition is true
(non-zero in C), }
it executes the
code inside the
block. If false
(zero), it skips
the block.
EXAMPLE PROGRAM
#include <stdio.h>
int main() {
int num = 10;
if (num > 0) {
printf("The number %d is positive.\n", num);
}
printf("This prints regardless.\n"); // Sequential flow continues here
return 0;
}
}
IF-ELSE STATEMENT: HANDLING TWO PATHS

THIS EXTENDS IF BY PROVIDING AN ALTERNATIVE BLOCK FOR WHEN THE CONDITION IS FALSE.
USE THE STATEMENT TO SPECIFY A BLOCK OF CODE TO BE EXECUTED IF THE CONDITION IS FALSE.

Syntax: if(condition) {
// Code if true
}else {
// Code if false
}
#include <stdio.h>
int main() {
int num = 7;
if (num % 2 == 0) {
printf("The number %d is even.\n", num);
} else {
printf("The number %d is odd.\n", num);
}
return 0;
}
If -else-if ladder
In C, if else if ladder is an extension of if else statement used to test a series of conditions
sequentially, executing the code for the first true condition. A condition is checked only if all previous
ones are false. Once a condition is true, its code block executes, and the ladder ends

Syntax: if (condition1) {
// Statements 1
}
else if (condition2) {
// Statements 2
}
else {
// Else body
}
#include <stdio.h>
EXAMPLE PROGRAM
int main() {
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else if (score >= 60) {
printf("Grade: D\n");
} else {
printf("Grade: F\n");
}
return 0;
}
SWITCH STATEMENTS
The switch case is an alternative to the if else if ladder that can be used to execute the conditional code based on the value of
the variable specified in the switch statement. The switch block consists of cases to be executed based on the value of the switch
variable.
Syntax: switch (expression) {
case constant1:
// Code for constant1
break; // Exit switch; without break, it "falls through" to next case
case constant2:
// Code for constant2
break;
// ... more cases
default:
// Code if no case matches (optional)
break;
}
LOOPING CONDITIONS
THE LOOP IS A CONDITIONAL ITERATION STATEMENT THAT REPEATEDLY EXECUTES A BLOCK
OF CODE AS LONG AS A SPECIFIED CONDITION REMAINS TRUE. IT FIRST EVALUATES THE
CONDITION; IF TRUE, THE LOOP BODY EXECUTES, AND THE CONDITION IS RE-EVALUATED.
IF THE CONDITION IS INITIALLY FALSE, THE LOOP BODY IS SKIPPED ENTIRELY. THIS
MAKES IT SUITABLE FOR SCENARIOS WHERE THE NUMBER OF ITERATIONS IS UNKNOWN IN
ADVANCE
SYNTAX:
WHILE (CONDITION) {
// LOOP BODY: STATEMENTS TO EXECUTE
// UPDATE STATEMENTS (E.G., INCREMENT/DECREMENT) TYPICALLY INSIDE
}
KEY FEATURES
• ENTRY-CONTROLLED LOOP: THE CONDITION IS CHECKED BEFORE THE FIRST EXECUTION OF THE BODY.

• POTENTIAL FOR ZERO ITERATIONS: IF THE CONDITION IS FALSE AT THE START, THE LOOP DOES NOT RUN.

• INFINITE LOOP RISK: OCCURS IF THE CONDITION NEVER BECOMES FALSE (E.G., FORGETTING TO UPDATE A
COUNTER); ALWAYS INCLUDE LOGIC TO MODIFY THE CONDITION.

• USAGE: IDEAL FOR PROCESSING DATA UNTIL A SENTINEL VALUE IS REACHED (E.G., READING INPUT UNTIL EOF)
OR WHEN ITERATIONS DEPEND ON A DYNAMIC CONDITION.
Example :
int i = 1;
while (i <= 5) {
printf("%d ", i);
i++; // Update to prevent infinite loop
Do-While
The loop is a post-test iteration statement that executes a block of
code at least once and then repeats the execution as long as a
specified condition is true. The condition is evaluated after the loop
body, allowing the body to run even if the condition would otherwise
be false initially. This structure ensures minimum one iteration,
making it appropriate for situations requiring guaranteed execution
before checking.
Do-While
Syntax:
do {
// Loop body: Statements to execute
// Update statements (e.g., increment/decrement) typically inside
} while (condition);
Key Features.

Exit-Controlled Loop: The condition is checked after each execution of the body.

Guaranteed One Iteration: The body always runs at least once, regardless of the
initial condition value.

Infinite Loop Risk: Similar to , if the condition remains true indefinitely.

Usage: Best for menu-driven programs or validation loops where user input must be
prompted at least once (e.g., "Enter a valid number" until correct).
Example.
int i = 1;
do {
printf("%d ", i);
i++;
} while (i <= 5);
For Loop.
The loop is a pre-test iteration statement that provides a
compact way to execute a block of code a fixed or predetermined
number of times. It combines initialization, condition testing,
and update into a single statement, making it efficient for
counted loops. The loop initializes a counter, checks a condition
before each iteration, executes the body if true, and updates the
counter afterward.
Syntax:
for (initialization; condition; increment/decrement) {
// Loop body: Statements to execute
Example.
for (int i = 1; i <= 5; i++) {
printf("%d ", i);
}
Jump Statements
In C, jump statements alter the normal sequential flow of
execution by transferring control to another part of the program.
They are primarily used within loops, switches, or functions to
exit, skip, or redirect execution.
The three main jump statements are.
Break
Continue
Goto
Break
The break statement is an unconditional jump that terminates the
nearest enclosing loop or switch statement immediately,
transferring control to the statement following the terminated
structure. It is used to exit early from repetitive or multi-way
selection constructs when a specific condition is met, preventing
unnecessary further execution.
Syntax: loop{
statements;
break;}
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit loop when i reaches 5
}
printf("%d ", i);
}
printf("\nExited loop.\n");
return 0;
Continue:
The statement is an unconditional jump that skips the remaining statements
in the current iteration of the nearest enclosing loop and immediately
proceeds to the next iteration by re-evaluating the loop's condition. It
does not terminate the loop but bypasses code for specific cases, allowing
selective execution within iterations.
Usage: Useful for filtering iterations (e.g., skipping even numbers in a
sum) without using complex nested statements. It simplifies code for
conditional skips in repetitive tasks.
goto:

The goto statement is an unconditional jump that transfers control directly to a


labeled statement within the same function, identified by a label. It enables
arbitrary branching to any point in the code, bypassing normal flow. Labels are
user-defined identifiers followed by a colon, and goto can jump forward or
backward, but it is generally avoided in favor of structured alternatives like loops
or functions.
syntax: goto label; // Jump to the statement labeled 'label'

// Elsewhere in the same function:


label: statement; // Label definition (ends with colon)
Functions:
In C, functions are fundamental building blocks that promote modularity,
reusability, and structured programming. They encapsulate a set of
statements to perform a specific task, allowing code to be organized into
logical units. Every C program must contain at least one function, , which
serves as the entry point for execution. Functions enable the division of
complex problems into simpler, manageable parts, reducing redundancy and
improving maintainability.
Functions follow a declarative paradigm: they are declared (prototyped), defined
(implemented), and invoked (called).
Functions:
Definition : A function is a self-contained block of code that performs a
well-defined operation and can be invoked from other parts of the program.
It has a name, a return type, optional parameters, and a body. Functions
promote the principle of "divide and conquer" by abstracting details—
callers need only know the interface (inputs/outputs), not the
implementation.
Functions:

Purpose: To reuse code, simplify debugging, and enhance readability. For example, a
function to compute the square root can be called multiple times without rewriting
the algorithm.
Execution Flow: When called, control transfers to the function; upon completion (via
or end of body), control returns to the caller.
Overloading: Not supported in standard C (unlike C++); functions must have unique
names or use prefixes.
Functions:
Function Declaration (Prototype):Informs the compiler about the function's name,
return type, and parameters without the body. Placed before or in header files if
the definition follows.
Syntax: return_type function_name(parameter_type1 param1, parameter_type2 param2,
...);
Functions:Function Definition: Provides the actual implementation, including
the body. Includes the prototype plus the code block.\
Syntax: return_type function_name(parameter_type1 param1, parameter_type2
param2...) {
// Local declarations
// Statements (body)
return expression; // Optional for void functions
}//The body is enclosed in curly braces and may contain variables, loops,
conditionals, or other functions.
Functions:
Function Call (Invocation):
Transfers control to the function by specifying its name and arguments. Can
occur anywhere after declaration.
Syntax: function_name(actual_arg1, actual_arg2, ...);
UNIT 3
DATA STRUCTURES IN C
Arrays
Types of array- Single and
multi-dimensional
Operations on array
Strings
String Operation
Pointers
Structures and union
IN C PROGRAMMING, AN ARRAY IS A FIXED-SIZE COLLECTION OF ELEMENTS OF THE SAME DATA TYPE STORED IN
CONTIGUOUS (ADJACENT) MEMORY LOCATIONS. IT ALLOWS YOU TO STORE MULTIPLE VALUES UNDER A SINGLE VARIABLE
NAME, MAKING IT EFFICIENT FOR HANDLING LISTS OF DATA LIKE NUMBERS, CHARACTERS, OR OTHER TYPES.
Fixed Size: The size must be specified at declaration (or
compile-time for static arrays) and cannot be changed
dynamically without using pointers or dynamic allocation.
Indexed Access: Elements are accessed using an index
(starting from 0 for the first element, up to for the last).
Homogeneous: All elements must be of the same type (e.g.,
all , all ).
Memory Layout: Elements are stored sequentially in
memory, enabling fast access via direct indexing (O(1) time
complexity).
ADATA_TYPE ARRAY_NAME[SIZE];
data_type: Type of elements ([Link], float, char ).
array_name: Name of the array (follows variable
naming rules).
size: Number of elements (must be a positive
integer constant or expression evaluable at compile-
time for static arrays).
// PARTIAL OR FULL INITIALIZATION
INT ARR[5] = {1, 2, 3};// FIRST 3 ELEMENTS SET, REST ARE 0
INT ARR[5] = {0}; // ALL ELEMENTS INITIALIZED TO 0
INT ARR[] = {1, 2, 3, 4}; // SIZE INFERRED AS 4
SINGLE DIMENSIONAL ARRAY
MULTI-DIMENSIONAL ARRAY
SINGLE-DIMENSIONAL ARRAYS
A SINGLE-DIMENSIONAL ARRAY IS A LINEAR COLLECTION OF
ELEMENTS, SIMILAR TO A ROW OF BOXES. IT'S THE SIMPLEST
FORM OF ARRAY.
DECLARATION: DATA_TYPE ARRAY_NAME[SIZE];
SINGLE-DIMENSIONAL ARRAYS
// DECLARATION AND INITIALIZATION
INT NUMBERS[5] = {10, 20, 30, 40, 50}; // INITIALIZES FIRST 5 ELEMENTS
// PARTIAL INITIALIZATION (REST ARE ZEROED)
INT SCORES[10] = {90, 85}; // SCORES[0]=90, SCORES[1]=85, OTHERS=0
// DECLARATION WITHOUT INITIALIZATION (ALL ELEMENTS ARE
GARBAGE/UNINITIALIZED)
FLOAT PRICES[3];
MULTIDIMENSIONAL ARRAYS
A MULTIDIMENSIONAL ARRAY ORGANIZES DATA IN MULTIPLE DIMENSIONS, LIKE
ROWS AND COLUMNS IN A TABLE (2D) OR A CUBE (3D). IN C, THESE ARE
ESSENTIALLY ARRAYS OF ARRAYS.
DECLARATION (FOR 2D, THE MOST COMMON):
DATA_TYPE ARRAY_NAME[ROWS][COLUMNS];
STRINGS
IN THE C PROGRAMMING LANGUAGE, A STRING IS A SEQUENCE OF CHARACTERS TREATED
AS A SINGLE DATA UNIT. UNLIKE HIGHER-LEVEL LANGUAGES (E.G., JAVA OR PYTHON),
C DOES NOT HAVE A BUILT-IN STRING DATA TYPE.

STRINGS ARE FUNDAMENTAL FOR HANDLING TEXTUAL DATA, SUCH AS NAMES, MESSAGES, FILE PATHS, AND USER
INPUT. THEY ARE STORED IN CONTIGUOUS MEMORY LOCATIONS, JUST LIKE OTHER ARRAYS, BUT THE NULL TERMINATOR
DISTINGUISHES THEM FROM PLAIN CHARACTER ARRAYS.
KEY CHARACTERISTICS OF STRINGS IN C:
IMMUTABLE LENGTH: ONCE DECLARED (FOR STATIC ARRAYS), THE SIZE IS FIXED.
DYNAMIC RESIZING REQUIRES POINTERS AND MEMORY ALLOCATION (E.G., VIA MALLOC).
NULL-TERMINATED: EVERY VALID STRING MUST END WITH '\0'. OMITTING IT CAN LEAD
TO BUFFER OVERFLOWS OR UNDEFINED BEHAVIOR.
CASE SENSITIVITY: C TREATS UPPERCASE AND LOWERCASE LETTERS AS DISTINCT (E.G.,
'A' ≠ 'A').
ENCODING: BY DEFAULT, C USES ASCII (7-BIT) OR EXTENDED ASCII (8-BIT) FOR
CHARACTERS, BUT MODERN SYSTEMS OFTEN SUPPORT UTF-8 VIA LIBRARIES.
DECLARATION: CHAR STRING_NAME[SIZE];

INITIALISATION: CHAR GREETING[20] = "HELLO, WORLD!";


+--------------------+-----------------------------------------------------------------+
| OPERATION | DESCRIPTION |
+--------------------+-----------------------------------------------------------------+
| **STRLEN()** | THE STRLEN() FUNCTION IS USED TO FIND THE LENGTH OF A STRING. |
| | IT RETURNS THE NUMBER OF CHARACTERS IN A STRING, EXCLUDING THE |
| | NULL TERMINATOR ('\0'). |
+--------------------+-----------------------------------------------------------------+
| **STRCPY()** | THE STRCPY() FUNCTION COPIES A STRING FROM THE SOURCE TO THE |
| | DESTINATION. IT COPIES THE ENTIRE STRING, INCLUDING THE NULL |
| | TERMINATOR. |
+--------------------+-----------------------------------------------------------------+
| **STRCAT()** | THE STRCAT() FUNCTION IS USED TO CONCATENATE (APPEND) ONE |
| | STRING TO THE END OF ANOTHER. IT APPENDS THE SOURCE STRING TO |
| | THE DESTINATION STRING, REPLACING THE NULL TERMINATOR OF THE |
| | DESTINATION WITH THE SOURCE STRING’S CONTENT. |
+--------------------+-----------------------------------------------------------------+
| **STRCMP()** | THE STRCMP() IS A BUILT-IN LIBRARY FUNCTION IN C. THIS FUNCTION |
| | TAKES TWO STRINGS AS ARGUMENTS, COMPARES THESE TWO STRINGS |
| | LEXICOGRAPHICALLY AND RETURNS AN INTEGER VALUE AS A RESULT OF |
| | COMPARISON. |
POINTER
A POINTER IS A VARIABLE THAT STORES THE MEMORY ADDRESS OF ANOTHER
VARIABLE, RATHER THAN ITS VALUE. POINTERS ALLOW INDIRECT ACCESS TO
DATA, MAKING C EFFICIENT FOR LOW-LEVEL OPERATIONS LIKE HARDWARE
INTERACTION OR PERFORMANCE-CRITICAL CODE. THEY ARE DECLARED USING THE *
OPERATOR AND USE & TO GET AN ADDRESS.
POINTER ARITHMETIC
POINTER ARITHMETIC ALLOWS ADDING/SUBTRACTING INTEGERS TO/FROM POINTERS,
SCALING AUTOMATICALLY BY THE SIZE OF THE POINTED-TO TYPE. THIS IS
CRUCIAL FOR TRAVERSING ARRAYS OR MEMORY BLOCKS EFFICIENTLY. OPERATIONS:
+, -, ++, -- (NO * OR /).
BASIC RULES
IF PTR POINTS TO TYPE T (SIZE SIZEOF(T) BYTES), PTR + 1 ADVANCES
BY SIZEOF(T) BYTES TO THE NEXT ELEMENT.
VALID OPERATIONS: PTR + N, PTR - N, PTR1 - PTR2 (RETURNS INT
OFFSET, SAME TYPE).
NO SCALING NEEDED: C HANDLES IT—E.G., FOR INT* (4 BYTES), PTR + 2
SKIPS 8 BYTES.
POINTERS WITH ARRAYS
ARRAYS AND POINTERS ARE CLOSELY RELATED IN C: AN ARRAY NAME IS A
CONSTANT POINTER TO ITS FIRST ELEMENT. THIS "ARRAY-TO-POINTER DECAY"
SIMPLIFIES PASSING ARRAYS TO FUNCTIONS.
ARRAY NAME AS POINTER
INT ARR[5]; : ARR IS EQUIVALENT TO &ARR[0] (A INT*).
INDEXING: ARR[I] IS *(ARR + I)—POINTER ARITHMETIC UNDER THE HOOD
POINTERS WITH FUNCTIONS
POINTERS ENABLE FUNCTIONS TO RETURN ADDRESSES, ACCEPT ADDRESSES AS
PARAMETERS, AND SIMULATE PASS-BY-REFERENCE.
STRUCTURES

A structure in C is a user-defined data type that allows storing different types of data in a
single unit. It's like a collection of variables under a single name.
Syntax:
struct structure_tag {
data_type member1;
data_type member2 ; // ... more members
} variable_name; // Optional: You can declare variables here
STRUCTURES
struct: Keyword to define a structure.

structure_tag: A name (identifier) for the structure, which can be used later to declare variables.

data_type member: Declarations of the members (variables) inside the structure. These can be of any data
type (e.g., int, float, char, arrays, etc.).

variable_name: Optional; you can declare one or more structure variables immediately after the definition.
UNION
A union in C is a user-defined, composite data type that allows multiple members of
different types to share the same memory location. Only one member can hold a valid
value at any given time, and the union’s overall size equals the size of its largest member.

Syntax: union union_name {


type1 member1;
type2 member2;
type3 member3;
};

You might also like