0% found this document useful (0 votes)
12 views36 pages

Control Statements and Loops in C Programming

The document covers various programming concepts including control statements, looping statements, conditional statements, and storage classes in C. It also explains functions, arrays, strings, pointers, structures, unions, and file handling. Additionally, it introduces cyber security concepts, the CIA triad, and types of cyber threats.
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)
12 views36 pages

Control Statements and Loops in C Programming

The document covers various programming concepts including control statements, looping statements, conditional statements, and storage classes in C. It also explains functions, arrays, strings, pointers, structures, unions, and file handling. Additionally, it introduces cyber security concepts, the CIA triad, and types of cyber threats.
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

UNIT 3

1. CONTROL STATEMENTS

1.1 Definition – Control Statements


Control statements are the instructions in a program that control the
flow of execution.
They decide which statements will execute, how many times, and
under what conditions.

They are of three types:

1. Conditional statements
2. Looping statements
3. Jumping statements

2. LOOPING STATEMENTS

2.1 While Loop

Definition:
The while loop repeats a block of code as long as a condition is true.

Syntax:
while(condition) {
// statements
}

Example:
int i = 1;
while(i <= 5) {
printf("%d ", i);
i++;
}

2.2 Do-While Loop

Definition:

do-while loop executes the block at least once, then checks condition.

Syntax:
do {
// code
} while(condition);

Example:

int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);

2.3 For Loop

Definition:

for loop is used when we know the number of iterations in advance.

Syntax:

for(initialization; condition; increment) {


// statements
}

Example:

for(int i = 1; i <= 5; i++) {


printf("%d ", i);
}
2.4 Nested Loops

Definition:

A loop inside another loop is called a nested loop.

Example: Print 3×3 matrix


for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
printf("%d ", j);
}
printf("\n");
}

3. CONDITIONAL STATEMENTS

3.1 If-Else Statement

Definition:

if-else executes one block if a condition is true and another block if


false.

Example:
int age = 18;
if(age >= 18)
printf("Adult");
else
printf("Minor");

3.2 Switch Statement

Definition:
Switch is used when we want to select one option from multiple
choices.

Syntax & Example:


switch(day) {
case 1: printf("Monday"); break;
case 2: printf("Tuesday"); break;
default: printf("Invalid");
}

4. JUMP STATEMENTS

4.1 Break Statement

Definition:

break is used to exit loop or switch immediately.

Example:
for(int i=1; i<=10; i++) {
if(i==5) break;
printf("%d ", i);
}

4.2 Continue Statement

Definition:
continue skips the current iteration and moves to next iteration.

Example:
for(int i=1; i<=5; i++) {
if(i==3) continue;
printf("%d ", i);
}
4.3 Goto Statement

Definition:

goto jumps the control to a labeled statement.

Example:

goto start;
printf("This will be skipped");

start:
printf("Goto executed");

4.4 Comma Operator

Definition:

Comma operator allows multiple expressions in one line.


The rightmost value is returned.

Example:

int a = (1, 2, 3);


// a = 3

5. STORAGE CLASSES
Storage classes define lifetime, scope, and default value of variables.

5.1 Automatic (auto)

Definition:

Local variables defined inside a function.

Characteristics:
 Scope: inside block
 Lifetime: till function ends
 Default value: garbage

Example:
void f() {
auto int x = 10;
}

5.2 External (extern)

Definition:
Used to access global variables from another file.

Example:

extern int count;

5.3 Register

Definition:
Stores variable in CPU register for fast access.

Example:

register int x = 5;

5.4 Static

Definition:

Static variable preserves value between function calls.

Example:
void test() {
static int x = 0;
x++;
printf("%d", x);
}

6. FUNCTIONS

6.1 Function Definition

Definition:

A function is a block of code written to perform a specific task.

Example:
int add(int a, int b) {
return a + b;
}

6.2 Accessing (Calling) Functions

Example:**

int result = add(5, 3);

6.3 Passing Arguments


Types:

1. Call by value
2. Call by reference

Example:
add(10, 20);
6.4 Function Prototypes

Definition:

Declaration of a function before use.

Example:

int add(int, int);

6.5 Recursion

Definition:
A function calling itself is recursion.

Example: Factorial
int fact(int n) {
if(n==1) return 1;
return n * fact(n-1);
}

6.6 Library Functions


Examples:

 printf()
 scanf()
 strlen()
 sqrt()

6.7 Static Functions

Definition:
Static functions have file-level scope.
static void hello() {
printf("Hello");
}

7. ARRAYS

7.1 Definition

An array is a collection of elements of same data type stored in


continuous memory.

Example:
int a[5] = {1,2,3,4,5};

7.2 Passing Array to a Function

Example:
void display(int a[]) {
for(int i=0;i<5;i++)
printf("%d ", a[i]);
}

7.3 Multidimensional Arrays

Definition:
Array of arrays.

Example:

int matrix[2][3] = {{1,2,3},{4,5,6}};

8. STRINGS

8.1 Definition:
String is a character array ending with '\0'.

Example:

char name[] = "Aman";

Operations on Strings
Strings in C are arrays of characters ending with a null
character ('\0').
To perform operations on strings, we use functions from the
header file:
#include <string.h>

✔ 1. strlen() – String Length


Definition:
strlen() is used to find the length of a string (number of
characters).
It does NOT count the null character '\0'.
Syntax:
int strlen(string);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char name[] = "Computer";
int len = strlen(name);
printf("Length = %d", len);
return 0;
}
Output:
Length = 8

✔ 2. strcpy() – Copy One String to Another


Definition:
strcpy() copies the contents of one string into another.
Syntax:
strcpy(destination, source);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char s1[] = "Hello";
char s2[20];

strcpy(s2, s1);

printf("Copied String = %s", s2);


return 0;
}
Output:
Copied String = Hello

✔ 3. strcmp() – Compare Two Strings


Definition:
strcmp() compares two strings character by character.
It returns:

Return Value Meaning


0 Both strings are equal
Positive value First string is greater
Negative value Second string is greater

Syntax:
strcmp(string1, string2);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char a[] = "Apple";
char b[] = "Banana";

int result = strcmp(a, b);

if(result == 0)
printf("Strings are equal");
else if(result < 0)
printf("Apple comes before Banana");
else
printf("Apple comes after Banana");

return 0;
}
Output:
Apple comes before Banana

✔ 4. strcat() – Concatenate (Join) Strings


Definition:
strcat() joins (appends) one string at the end of another.
Syntax:
strcat(destination, source);
Example:
#include <stdio.h>
#include <string.h>

int main() {
char text1[30] = "Hello ";
char text2[] = "World";

strcat(text1, text2);

printf("Joined String = %s", text1);


return 0;
}
Output:
Joined String = Hello World

⭐ Summary Table

Function Purpose Example


strlen(s) Finds length strlen("ABC") → 3
strcpy(d,s) Copy string "Hello" → "Hello"
strcmp(s1,s2) Compare strings "A" < "B"
strcat(d,s) Join strings "Hello " + "World"
UNIT 4

✅ 1. Definition of Pointer
A pointer is a special variable that stores the memory
address of another variable.
Example
int a = 10;
int *p;
p = &a;
Here:
 a → stores value 10
 &a → memory address of a
 p → stores that address
 *p → gives the value stored at that address (10)

✅ 2. Pointer Declaration
Syntax:
data_type *pointer_name;
Example
float *ptr;
char *name;
int *p;
✅ 3. Address (&) and Value (*) Operators
& Operator (Address Operator)
Returns the memory location of a variable.
* Operator (Value / Dereference Operator)
Returns the value stored at the address.

Example
int x = 20;
int *p = &x;

printf("%d", *p); // Output: 20

✅ 4. Pointer Operations
(a) Pointer Assignment
int *p, *q;
int a = 5;
p = &a;
q = p;
(b) Incrementing Pointer
Pointer increases according to data type size.
int *p;
p++ ; // increases by 2 or 4 bytes (depends on system)
(c) Pointer Comparison
if(p == q) { }

✅ 5. Pointers & Arrays


A pointer can access all array elements easily.
Example
int a[3] = {10,20,30};
int *p = a;

printf("%d", *p); // 10
printf("%d", *(p+1)); // 20
printf("%d", *(p+2)); // 30

✅ 6. Passing Pointer to a Function


Definition
Sending address of a variable to a function so function can
modify original value.
Example
void change(int *x){
*x = 50;
}

int main(){
int a = 10;
change(&a);
printf("%d", a); // Output: 50
}
⭐ PART 2 – STRUCTURES

✅ 1. Definition of Structure
A structure is a collection of different data types grouped
together under one name.
Used to represent a record.
Example
struct student {
int roll;
char name[20];
float marks;
};

✅ 2. Declaring Structure Variable


struct student s1, s2;

✅ 3. Accessing Structure Members


Use dot operator (.)
[Link] = 10;
[Link] = 88.5;

✅ 4. Taking Input in Structure


printf("Enter roll:");
scanf("%d", &[Link]);

printf("Enter marks:");
scanf("%f", &[Link]);

✅ 5. Displaying Structure Output


printf("Roll = %d", [Link]);

⭐ 6. Array of Structures
Definition
A structure array is a collection of multiple structure
variables.
Example
struct student s[3];
You can store 3 students data.

⭐ PART 3 – POINTER TO STRUCTURE

✔ Definition
A pointer that stores address of a structure variable.
Syntax
struct student *ptr;
ptr = &s1;
Access using -> operator
ptr->roll = 5;
ptr->marks = 90;

⭐ PART 4 – UNIONS

✔ Definition of Union
A union is similar to structure but all members share same
memory location.
Example
union item {
int x;
float y;
char z;
};
Only one member can store value at a time.
Difference Between Structure & Union

Structure Union
Each member has separate All members share same
memory memory
Can store only one value at a
Can store multiple values
time
Memory usage more Memory usage less

⭐ PART 5 – TYPEDEF

✔ Definition
Used to give new name (alias) to a data type.
Example
typedef unsigned long int uli;

uli x = 2000;
You created a short name.

⭐ PART 6 – FILE HANDLING IN C


✔ 1. Definition of File
A file is a collection of data stored permanently in the
computer.

✔ 2. File Operations in C
1. Creating a file
2. Opening a file
3. Reading from a file
4. Writing to a file
5. Closing a file

✔ 3. File Pointer
FILE *fp;

✔ 4. Opening a File
(a) Write Mode
fp = fopen("[Link]","w");
(b) Read Mode
fp = fopen("[Link]","r");
(c) Append Mode
fp = fopen("[Link]","a");
✔ 5. Writing to a File
fprintf(fp, "Hello Students");

✔ 6. Reading from a File


fscanf(fp, "%s", str);

✔ 7. Closing a File
fclose(fp);

Difference between Call by Value and Call by Reference

Call by Value Call by Reference

1. The actual address (reference)


1. A copy of the actual value
of the variable is passed to the
is passed to the function.
function.
2. Changes made inside the 2. Changes made inside the
function do NOT affect the function directly affect the
original variable. original variable.
3. Safe method – original data 3. Risky – original data may
remains unchanged. change unintentionally.
4. Uses more memory because 4. Uses less memory because no
copies are created. copies are created.
5. Syntax uses normal 5. Syntax uses pointers.
variables. Example: func(a); Example: func(&a);
📘 Example of Call by Value
void change(int x) {
x = 50;
}

int main() {
int a = 10;
change(a);
printf("%d", a); // Output: 10 (no change)
}

📘 Example of Call by Reference


void change(int *x) {
*x = 50;
}

int main() {
int a = 10;
change(&a);
printf("%d", a); // Output: 50 (value changed)
}
UNIT 5

🔵 1. Introduction to Cyber Security

⭐ Definition of Cyber Security


Cyber Security is the practice of protecting computers,
networks, data, and digital systems from attacks, damage,
unauthorized access, and misuse.
Detailed Explanation:
Cyber security protects all digital information from
cybercriminals.
It includes:
 Protecting computers
 Protecting mobiles
 Protecting networks (Wi-Fi, internet)
 Protecting websites
 Protecting personal data (passwords, bank details)
Cyber security ensures that our information remains safe,
accurate, and available.

🔵 2. Information Security Concepts (CIA Triad)


The CIA triad is the foundation of cyber security.

⭐ A) Confidentiality
Definition:
Confidentiality means only authorized people can access the
information.
Explanation:
Your personal data (passwords, bank details) must be kept
private.
Unauthorized users should not see or use it.
Examples:
 Using a password so no one can open your email
 Locking your phone
 Encrypting data

⭐ B) Integrity
Definition:
Integrity means the data must remain accurate, complete,
and unchanged.
Explanation:
Nobody should modify, delete, or update data without
permission.
Examples:
 Marks database must not be changed by students
 Bank balance must always remain correct
 Files should not be corrupted by viruses
⭐ C) Availability
Definition:
Information must be available at the right time for
authorized users.
Explanation:
If systems go down (server down, network failure), work
stops.
Availability ensures system works whenever needed.
Examples:
 Online banking 24/7
 Website working always
 Hospital system available in emergencies

🔵 3. Cyber Threats

⭐ Definition of Threat
Threat is any potential danger that can damage a computer,
network, or data.

⭐ Types of Cyber Threats

🔶 1. Malware
Definition:
Malware = Malicious (bad) + Software
It is harmful software designed to damage systems.
Types of Malware:
A) Virus
Replicates (copies itself) and attaches to other programs.
Example: File-infecting virus.
B) Worm
Spreads automatically using the network.
Faster and more dangerous than virus.
C) Trojan Horse
Looks like a normal file/app but contains a hidden virus.
D) Ransomware
Locks your data and asks for money to unlock it.
Example: WannaCry attack.
E) Spyware
Secretly monitors your activities.
Example: Keylogger.

🔶 2. Phishing
Definition:
Cybercriminals send fake emails/messages to steal personal
information.
Example:
 Fake bank email asking for OTP or password
 Fake job messages
 Fake lottery messages

🔶 3. Social Engineering
Definition:
Tricking people using psychology to steal information.
Examples:
 Fake phone call pretending to be a bank officer
 Fake customer care
 Asking OTP for “verification”

🔶 4. Denial of Service (DoS) Attack


Definition:
Making a server or website unavailable by sending too many
requests.
Example:
Website gets so much traffic that it crashes.

🔶 5. Man-in-the-Middle Attack (MITM)


Definition:
Attacker secretly intercepts communication between two
people.
Example:
Hacking public Wi-Fi and stealing data.

🔶 6. Password Attacks
 Brute force (trying all combinations)
 Dictionary attack (using common passwords)

🔵 4. Vulnerability

⭐ Definition:
A vulnerability is a weakness in software, system, or network
that attackers can exploit.

⭐ Types of Vulnerabilities

🔸 Weak Passwords
Example: 12345, password, admin

🔸 Outdated Software
Hackers exploit old versions.

🔸 Unsecured Wi-Fi
Public Wi-Fi can be hacked easily.
🔸 Poor Configuration
Incorrect settings allow attackers inside.

🔵 5. Cybercrimes

⭐ Definition:
Cybercrime is any illegal activity done using computers or the
internet.

⭐ Types of Cybercrimes

🔴 Hacking
Unauthorized access to a system.

🔴 Identity Theft
Stealing someone’s identity (Aadhaar, PAN, bank details).

🔴 Cyber Bullying
Harassing someone on social media.

🔴 Online Fraud
 Fake shopping websites
 UPI fraud
 KYC scam

🔴 Data Theft
Stealing private or organizational data.

🔵 6. Cyber Security Measures (How to Protect Yourself)


These are steps used to protect computers and data.

⭐ 1. Antivirus Software
Scans, detects, and removes viruses.
Examples:
 Quick Heal
 McAfee
 Kaspersky

⭐ 2. Firewall
Definition:
A firewall is a security system that monitors and controls
incoming/outgoing network traffic.
It acts like a security guard for your computer.

⭐ 3. Strong Passwords
Characteristics of Strong Password:
 Minimum 8–12 characters
 Contains A-Z, a-z, 0-9, symbols
 No personal info (DOB, name)
 Should change regularly

⭐ 4. Encryption
Definition:
Encryption converts data into unreadable form to protect it.
Example:
HELLO → @#$%&123
Only authorized users with decryption key can read the data.

⭐ 5. Regular Software Updates


Fix security weaknesses.

⭐ 6. Backup
Creating a copy of data to avoid loss.

⭐ 7. Secure Wi-Fi
Use strong router password and WPA2/WPA3 security.
🔵 7. Authentication & Authorization

⭐ Authentication – Definition
Process of verifying who you are.
Examples:
 Password
 PIN
 OTP
 Fingerprint

⭐ Authorization – Definition
Process of verifying what you are allowed to do.
Examples:
 Student login → can only see their marks
 Teacher login → can upload marks
 Admin login → can control system

🔵 8. Cryptography

⭐ Definition:
Cryptography is the science of securing information using
mathematical techniques.

⭐ Types of Cryptography
🔸 Symmetric Key Cryptography
 One single key is used for both encryption and
decryption
 Very fast
Example Algorithms:
AES, DES

🔸 Asymmetric Key Cryptography


 Uses two keys: Public Key + Private Key
Example Algorithms:
RSA, ECC

🔵 9. Cyber Laws (IT Act 2000)

⭐ Definition:
Cyber law deals with crimes related to computers and digital
devices.
Important Sections:
 Section 66C – Identity theft
 Section 66D – Online cheating
 Section 67 – Publishing obscene content
 Section 43 – Data theft
🔵 10. Computer Viruses, Spyware & Remedies

⭐ Computer Virus – Definition


A program that can replicate itself and infect other files.

⭐ Spyware – Definition
A program that secretly records your activities.

⭐ Remedies
 Install antivirus
 Avoid downloading pirated apps
 Don't open unknown email attachments
 Use firewall
 Do not click strange links

Common questions

Powered by AI

Pointers and arrays in C have distinct differences yet can be used effectively together. A pointer is a variable that stores the memory address of another variable, allowing direct access and manipulation of memory . An array, however, is a collection of elements of the same data type stored in contiguous memory locations . Pointers can be effectively used with arrays by accessing and iterating through array elements using pointer arithmetic. For example, a pointer initialized to the first element of an array can traverse the array using increment operations such as *(p+i) to access subsequent elements . This relationship enhances performance by directly accessing memory locations.

Structures and unions in C are both user-defined data types used to group different data types under a single name, but they differ significantly in memory usage and constraints. Structures allocate separate memory locations for each member, allowing simultaneous storage of multiple values . In contrast, unions share the same memory location among all members, meaning only one member can store a value at a time . As a result, unions are more memory-efficient but limited in storing multiple values concurrently, whereas structures incur higher memory use to maintain separate blocks for each member.

Strong passwords are integral to cybersecurity as they significantly reduce the risk of unauthorized access to sensitive information. Key characteristics defining a strong password include a minimum length of 8–12 characters, the inclusion of uppercase and lowercase letters, numbers, and symbols, and the avoidance of easily guessable information like birthdays or sequential numbers . Additionally, strong passwords should be changed regularly to mitigate potential breaches through data leaks or cyber attacks. Utilizing such passwords enhances security posture by providing a robust barrier against common attacks like brute force or dictionary attacks.

File handling in C programming is crucial for performing operations like reading and writing data to files, thus enabling data storage and retrieval beyond program execution. File operations typically follow a sequence: creating or opening a file using fopen with modes 'w', 'r', or 'a' for writing, reading, or appending respectively; reading from or writing to files using functions like fscanf for reading and fprintf for writing ; and closing files using fclose to release resources . This systematic approach is essential for effective data management and persistence in software applications.

Control statements in programming are categorized into three main types: Conditional statements, Looping statements, and Jumping statements. Conditional statements, such as if-else and switch, allow execution of different code paths based on certain conditions . Looping statements, like while, do-while, and for loops, enable repeated execution of a block of code as long as a condition is true or for a specific number of iterations . Jumping statements, including break, continue, and goto, alter the flow by exiting loops, skipping iterations, or jumping to labeled code sections . These statements collectively determine the program's flow control, ensuring specific sequences of operations under defined conditions.

The 'static' keyword in programming serves to preserve the state of a variable or restrict function scope across multiple calls. A static variable retains its value between function calls instead of being reinitialized each time , making it useful in scenarios needing lifetime extension beyond a single function execution, such as counting number of function invocations. In the context of functions, declaring a function as static restricts its scope to the file in which it is declared, enhancing encapsulation by preventing it from being accessed externally . Static variables and functions thus play crucial roles in managing state and encapsulation.

The CIA triad in cyber security stands for Confidentiality, Integrity, and Availability, serving as a foundational model for protecting digital information. Confidentiality ensures that only authorized users have access to sensitive information, safeguarding privacy . Integrity maintains data accuracy and completeness by preventing unauthorized modifications . Availability ensures that information and resources are accessible to authorized users when needed, preventing service interruptions . Together, these principles guide the implementation of security measures to protect sensitive data from cyber threats.

Cyber threats encompass various types that significantly impact digital security, each with distinct mechanisms and consequences. Malware, such as viruses, worms, and ransomware, infiltrates systems, causing data corruption and financial loss . Phishing involves deceptive emails or messages to steal personal information like passwords . Social engineering exploits human psychology to gain system access . Denial of Service (DoS) attacks overload servers, disrupting availability . Man-in-the-Middle attacks intercept communications, compromising data integrity . These threats challenge confidentiality, integrity, and availability, necessitating robust security measures to protect digital assets.

'While' loops execute a block of code as long as the condition remains true and are suitable for situations where the number of iterations is not predetermined . 'Do-while' loops execute the code block at least once before checking the condition, making them ideal for scenarios where the loop must run at least once . 'For' loops are best used when the number of iterations is known beforehand. They provide a concise way to initialize, condition-check, and increment within a single line of syntax . Each loop type serves different use cases based on whether pre-evaluation checks or guaranteed initial execution are needed.

Recursion in programming is a method where a function calls itself directly or indirectly in order to solve a problem by breaking it down into smaller, manageable sub-problems . It contrasts with iterative solutions like loops, which repeatedly execute a block of code without utilizing self-referencing calls. While recursion can lead to simpler and more readable code for problems like traversing tree structures or calculating factorials (e.g., n * fact(n-1)), it may involve higher memory usage due to function call stacks. Iterative solutions manage state explicitly through variables and are often more memory efficient, especially in languages that do not optimize tail-recursive calls.

You might also like