100% found this document useful (1 vote)
14 views62 pages

C Programming Basics and Features

The document provides an overview of the C programming language, covering its history, features, structure, and essential concepts such as variables, data types, operators, and control structures. It includes detailed explanations of programming constructs like decision-making statements, loops, and functions, along with examples and syntax. The content serves as a foundational guide for students in a Cyber Security course focusing on C programming.

Uploaded by

sy5984099
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
100% found this document useful (1 vote)
14 views62 pages

C Programming Basics and Features

The document provides an overview of the C programming language, covering its history, features, structure, and essential concepts such as variables, data types, operators, and control structures. It includes detailed explanations of programming constructs like decision-making statements, loops, and functions, along with examples and syntax. The content serves as a foundational guide for students in a Cyber Security course focusing on C programming.

Uploaded by

sy5984099
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

Class – F.Y.B.

Sc(Cyber Security)
Subject – Foundations of C Programming

UNIT – 1 : BASICS OF C PROGRAMMING


1. Introduction to C Programming
1.1 History of the C Language

The C programming language has a rich history rooted in the development of operating
systems. Its evolution can be traced through several key stages:

 Ancestral Languages:

C emerged from a lineage of earlier programming languages. ALGOL 58 (1958) introduced


fundamental concepts, followed by CPL (Combined Programming Language) in 1960, which
brought high-level data types and control structures. BCPL (Basic Combined Programming
Language) in 1967 simplified CPL, and then Ken Thompson at Bell Labs developed B in
1970 as a further simplification of BCPL for the nascent Unix operating system.

 Birth of C:

In 1972, Dennis Ritchie, also at Bell Labs, developed C. He built upon the foundation of B,
adding crucial features like data types, structures, and a more powerful compiler. C was
initially designed to rewrite the Unix operating system, which was then largely written in
assembly language. This goal drove C's efficiency and low-level memory access capabilities.

 Standardization:

As C's popularity grew, a need for standardization arose to ensure portability across different
systems. In 1983, the American National Standards Institute (ANSI) formed the X3J11
committee to standardize C. This effort culminated in the ratification of ANSI C (also known
as C89) in 1989. The International Organization for Standardization (ISO) later adopted a
similar standard (C90) in 1990. Subsequent revisions, such as C99, C11, and C23, have
introduced modern features while maintaining C's core principles.

 Influence and Legacy:


C's efficiency, portability, and low-level capabilities made it a highly influential language. It
became the foundation for numerous other programming languages, including C++, Java, and
Python. C continues to be widely used today, particularly in system programming, embedded
systems, operating systems, and performance-critical applications.
1.2 Features of C Language
C language has several features that make it powerful:

1. Simplicity
C has a small number of keywords (32 in ANSI C). Its syntax is simple and easy to
understand.

2. Portability

Programs written in C can run on different machines with minimal or no modification


because the language is machine-independent.

3. Speed and Efficiency

C programs run extremely fast because the language is close to machine-level instructions.

4. Structured Programming

C supports modular programming using functions. This makes programs easy to organize,
debug, and maintain.

5. Low-Level Access

With pointers and bitwise operators, C provides direct access to memory and hardware –
useful for system programming.

6. Rich Library

C provides a wide range of built-in functions for input/output, string handling, mathematics,
etc.

7. Extensibility

Users can create their own functions and libraries.

8. Mid-Level Language

C supports both low-level operations (like assembly) and high-level constructs (like loops,
functions).
2. Structure of a C Program
A C program has a well-defined structure. The typical layout is:

Documentation Section
Link Section
Definition Section
Global Declaration Section
main() Function Section
{
Local Declarations
Executable Statements
}
User-defined function definitions

Explanation of Each Section

1. Documentation Section

Includes comments describing the program.

/* Program to add two numbers */

2. Link Section

Used to include header files.

#include <stdio.h>
#include <math.h>

3. Definition Section

Defines constants.

#define PI 3.14

4. Global Declaration Section

Declares global variables or functions.

int a = 10;

5. main( ) Function

The entry point of every C program.

int main( )
{
// code
}

6. User-defined Functions
Functions created by the programmer.

int sum(int x, int y) { return x + y; }

3. C Character Set
C supports:

1. Letters

 Uppercase: A–Z
 Lowercase: a–z

2. Digits

 0–9

3. Special Characters

Examples:
[ ] ( ) { } ; : , . # ' “ ” ? \ % + - * / & ^ ! | < > = _

4. White Spaces

Space, tab, newline ensure readability.

4. Identifiers and Keywords


4.1 Identifiers

Names given to variables, functions, arrays, etc.

Rules:

 Must start with a letter or underscore


 Cannot start with a digit
 Only letters, digits, underscore allowed
 Case-sensitive
 No keywords allowed

Examples:

Valid: total, _num1, studentName


Invalid: 1data, %value, float (keyword)
4.2 Keywords

Predefined reserved words with fixed meaning.

Some common C keywords (ANSI C – 32 keywords):

auto break case char const continue


default do double else enum extern
float for goto if int long
register return short signed sizeof static
struct switch typedef union unsigned void
volatile while

5. Variables and Constants


5.1 Variables

Variables store data that can change during program execution.

Syntax:

data_type variable_name;

Example:

int age;
float salary;

5.2 Constants

Fixed values that do not change.

Types:

1. Integer constants

Example: 10, -45, 0

2. Floating constants

Example: 23.45, -0.345

3. Character constants

Enclosed in single quotes: 'A', '5', '$'

4. String constants

Enclosed in double quotes: "Hello"


5. Symbolic constants

Defined using #define.

#define PI 3.14

6. Data Types in C
6.1 Basic Data Types

Data Type Size Example


int 2 or 4 bytes 10, -20
float 4 bytes 3.14
double 8 bytes 234.567
char 1 byte 'A'

6.2 Derived Data Types

 Arrays
 Pointers
 Structures
 Unions

6.3 Enumerated Data Type (enum)

Used to define custom integer constants.

enum week {Mon, Tue, Wed, Thu, Fri, Sat, Sun};

6.4 Type Casting

Converts one data type to another.

Implicit Casting:

Automatically done.

int a = 5;
float b = a; // implicit conversion

Explicit Casting:

Forced conversion.

float x = 10.5;
int y = (int)x;
7. Declarations and Expressions
7.1 Declaration

Specifies data type.

int a, b;
float salary;

7.2 Expressions

Combination of variables, constants, and operators that yield a value.

z = x + y;

8. Operators in C
C supports multiple types of operators.

8.1 Unary and Binary Arithmetic Operators


Unary Operators (single operand)

Operator Meaning
+ Unary plus
- Unary minus
++ Increment
-- Decrement

Example:

x = -y;

Binary Arithmetic Operators

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
8.2 Increment and Decrement Operators
Pre-increment
++a;

Post-increment
a++;

Same applies to decrement (--a, a--).

8.3 Relational Operators


Used for comparison.

Operator Meaning
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal
!= not equal

8.4 Logical Operators


Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT

8.5 Bitwise Operators


Perform operations on bits.

Operator Meaning
& AND
| OR
^ XOR
<< Left shift
>> Right shift
~ Bitwise NOT
8.6 Assignment Operators
Operator Meaning
= Simple assignment
+= Add and assign
-= Subtract and assign
*= Multiply and assign
/= Divide and assign
%= Modulus and assign

8.7 Comma Operator


Used to separate expressions.

a = (b = 5, b + 2); // a = 7

8.8 sizeof Operator


Returns the size (in bytes) of a data type.

printf("%d", sizeof(int));

8.9 Ternary Conditional Operator


Syntax:

condition ? expression1 : expression2;

Example:

int max = (a > b) ? a : b;

8.10 Precedence and Associativity


Operators have ranks.
Example:
* / % have higher precedence than + -.

Associativity decides direction of evaluation.


Most operators have left-to-right associativity.
9. Input and Output Functions in C
C uses standard I/O functions from <stdio.h>.

9.1 printf( ) Function


Used for formatted output.

Syntax:

printf("format string", arguments);

Example:

printf("Sum = %d", total);

9.2 scanf( ) Function


Used for input.

Syntax:

scanf("format string", &variable);

Example:

scanf("%d %f", &age, &salary);

Note: Address operator & is required for most variables.

9.3 getchar( ) and putchar( )


getchar( )

Reads a single character from keyboard.

ch = getchar();

putchar( )

Displays a single character.

putchar(ch);
9.4 getch( )
Reads a character without echo (primarily in <conio.h>).

ch = getch();

9.5 gets( ) and puts( )


gets( )

Reads a string including spaces (unsafe).

gets(name);

puts( )

Displays a string.

puts(name);

10. Escape Sequence Characters


These are special character combinations.

Escape Meaning
\n Newline
\t Tab
\\ Backslash
\' Single quote
\" Double quote
\b Backspace
\r Carriage return

11. Format Specifiers


Used with printf and scanf.

Specifier Meaning
%d Integer
%f Float
%c Character
%s String
Specifier Meaning
%lf Double
%u Unsigned int
%x Hexadecimal
%o Octal

Example:

printf("Value = %d", num);

Conclusion
Unit 1 covers the foundational concepts of C programming including history, basic structure,
variables, datatypes, operators, and the essential I/O handling functions. These topics form
the basis for more advanced concepts like control statements, functions, arrays, pointers, and
memory management.
UNIT – 2 : CONTROL AND ITERATIVE
STRUCTURES
(With Definitions, Syntax, Questions, Examples & Output)

1. Decision-Making Structures

1.1 The if Statement


Definition

Executes a block of statements only when the given condition is true.

Syntax
if(condition)
{
// statements
}

Example Question:

Q1: Write a C program to check whether a number is greater than 5 using an if


statement.

Program:
#include <stdio.h>

int main() {
int num = 10;

if(num > 5) {
printf("Number is greater than 5");
}
return 0;
}

Output
Number is greater than 5
1.2 The if-else Statement
Definition

Executes one block when condition is true, otherwise executes another block.

Syntax
if(condition) {
// true block
}
else {
// false block
}

Example Question:

Q2: Write a C program to check whether a person is eligible to vote using if-else.

Program:
#include <stdio.h>

int main() {
int age = 17;

if(age >= 18)


printf("Eligible to vote");
else
printf("Not eligible to vote");

return 0;
}

Output
Not eligible to vote

1.3 if-else-if Ladder


Definition

Used to check multiple conditions in sequence.

Syntax
if(cond1) { ... }
else if(cond2) { ... }
else { ... }
Example Question:

Q3: Write a C program to display grade based on marks using else-if ladder.

Program:
#include <stdio.h>

int main()
{
int marks = 82;

if(marks >= 90)


printf("Grade A");
else if(marks >= 75)
printf("Grade B");
else
printf("Grade C");

return 0;
}

Output
Grade B

1.4 The switch Statement


Definition

Used to select one option from many possible cases.

Syntax
switch(expression)
{
case value1: statements; break;
case value2: statements; break;
...
default: statements;
}

Example Question:

Q4: Write a C program to display the day of the week using a switch statement.

Program:
#include <stdio.h>

int main()
{
int day = 3;

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

Output
Wednesday

1.5 Conditional (Ternary) Operator


Definition

Short form of simple if-else.

Syntax
(condition) ? expression1 : expression2;

Example Question:

Q5: Write a C program to find the maximum of two numbers using the conditional
operator.

Program:
#include <stdio.h>

int main()
{
int a = 10, b = 20;
int max = (a > b) ? a : b;

printf("Maximum = %d", max);


return 0;
}

Output
Maximum = 20
2. Looping (Iterative) Structures
2.1 while Loop
Definition

A pre-test loop that checks condition before execution.

Syntax
while(condition)
{
// loop body
}

Example Question:

Q6: Write a C program to print numbers from 1 to 5 using a while loop.

Program:
#include <stdio.h>

void main()
{
int i = 1;

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

Output
1 2 3 4 5
2.2 do-while Loop
Definition

Post-test loop that executes at least once.

Syntax
do
{

// statements

} while(condition);

Example Question:

Q7: Write a C program to print numbers from 1 to 5 using a do-while loop.

Program:
#include <stdio.h>

void main()
{
int i = 1;

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

Output
1 2 3 4 5
2.3 for Loop
Definition

Used when the number of iterations is known.

Syntax
for(initialization; condition; increment)
{
// body
}

Example Question:

Q8: Write a C program to print numbers from 1 to 5 using a for loop.

Program:
#include <stdio.h>

void main()
{
for(int i = 1; i <= 5; i++)
{
printf("%d ", i);
}

Output
1 2 3 4 5
3. Jumping Statements

3.1 break Statement


Definition

Breaks/exits the loop immediately.

Example Question:

Q9: Write a C program that stops printing numbers when it reaches 3 using break.

Program:
#include <stdio.h>

int main()
{
for(int i = 1; i <= 5; i++)
{
if(i == 3)
break;
printf("%d ", i);
}
return 0;
}

Output
1 2

3.2 continue Statement


Definition

Skips the current iteration and continues the next.

Example Question:

Q10: Write a C program that prints numbers from 1 to 5 but skips 3 using continue.
Program:
#include <stdio.h>

int main()
{
for(int i = 1; i <= 5; i++)
{
if(i == 3)
continue;
printf("%d ", i);
}
return 0;
}

Output
1 2 4 5

4. Nested Structures

4.1 Nested if
Example Question:

Q11: Write a C program using nested if to check if a number is positive and even.

Program:
#include <stdio.h>

int main()
{
int num = 10;

if(num > 0)
{
if(num % 2 == 0)
{
printf("Positive and Even");
}
}
return 0;
}

Output
Positive and Even
4.2 Nested Loops
Example Question:

Q12: Write a C program to print pairs using nested for loops.

Program:
#include <stdio.h>

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

Output
1 1
1 2
2 1
2 2
3 1
3 2

5. Unconditional Branching (goto)

Definition

Transfers program control to a labeled statement within the same function.

Syntax
goto label;

label:
// statements

Example Question:

Q13: Write a C program to print numbers 1 to 5 using goto statement.


Program:
#include <stdio.h>

int main() {
int i = 1;

start:
printf("%d ", i);
i++;

if(i <= 5)
goto start;

return 0;
}

Output
1 2 3 4 5

Unit-2 Summary Table


Topic Description

if Executes block if condition true

if-else Either true block or false block

switch Multi-way branching

?: Shorthand for if-else

while Pre-test loop

do-while Post-test loop

for Fixed iteration loop

break Exit loop

continue Skip loop iteration

Nested Control inside another

goto Unconditional jump


UNIT – 3 : FUNCTIONS

1. Concept of Function
Definition

A function in C is a block of code that performs a specific task and can be reused multiple
times in a program.
It helps in breaking a large program into smaller modules.

General Syntax
return_type function_name(parameters)
{
// body of the function
}

Example Question:

Q1: Write a C program to display “Hello Function” using a function.

Program:
#include <stdio.h>

void display()
{ // function definition
printf("Hello Function");
}

void main()
{
display(); // function call

Output
Hello Function
2. Advantages of Modular Design
Modular programming means dividing a large program into smaller, manageable functions.

Advantages

1. Reusability – A function can be reused in different programs.


2. Easy Debugging – Errors can be located and fixed easily.
3. Better Readability – Code becomes organized and clean.
4. Easy Maintenance – Updating one module does not affect others.
5. Team Work – Different programmers can work on different modules.

3. Standard Library Functions


These are pre-defined functions in header files of C.

Examples

Function Header File Use


printf(), scanf() stdio.h Input/Output
sqrt(), pow() math.h Mathematical
strlen(), strcpy() string.h String operations
toupper(), tolower() ctype.h Character handling

Example Question:

Q2: Write a C program to find the square root of a number using the sqrt() standard
function.

Program:
#include <stdio.h>
#include <math.h>

int main()
{
double num = 25;
double result = sqrt(num);

printf("Square root = %lf", result);


return 0;
}

Output
Square root = 5.000000
4. User-Defined Functions
These are functions created by the programmer.

There are 3 important parts:

1. Function Declaration (Prototype)


2. Function Definition
3. Function Call

4.1 Function Declaration (Prototype)


Definition

Tells the compiler the name, return type, and parameters of the function.

Syntax
return_type function_name(parameter_list);

4.2 Function Definition


Definition

Actual body of the function that contains statements.

Syntax
return_type function_name(parameters)
{
// statements
}

4.3 Function Call


Definition

The process of invoking the function in the main().

Syntax
function_name(arguments);

Example Question:
Q3: Write a C program to add two numbers using a user-defined function.

Program:
#include <stdio.h>

int add(int a, int b); // function declaration

int main()
{
int x = 10, y = 20, result;

result = add(x, y); // function call


printf("Sum = %d", result);

return 0;
}

// function definition
int add(int a, int b)
{
return a + b;
}

Output
Sum = 30
5. Parameter Passing (Call by Value)
Definition

In Call by Value, a copy of the actual value is passed to the function.


Changes made inside the function do not affect the original variables.

Syntax
void function(int x)
{
// x is a copy
}

Example Question:

Q4: Write a C program to demonstrate call by value.

Program:
#include <stdio.h>

void change(int a)
{
a = 50; // modifies only local copy
}

int main()
{
int x = 10;

change(x);
printf("Value of x = %d", x);

return 0;
}

Output
Value of x = 10
6. Return Statement
Definition

The return statement sends a value back to the calling function.

Syntax
return expression;

Example Question:

Q5: Write a C program where a function returns the square of a number.

Program:
#include <stdio.h>

int square(int n)
{
return n * n;
}

int main()
{
int result = square(6);
printf("Square = %d", result);
return 0;
}

Output
Square = 36
7. Recursive Functions
Definition

A recursive function is a function that calls itself until a base condition is met.

General Syntax
return_type function_name(parameters)
{
if(base_condition)
return value;
else
return function_name(modified_parameters);
}

Example Question:

Q6: Write a C program to find factorial of a number using recursion.

Program:
#include <stdio.h>

int factorial(int n)
{
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}

void main()
{
int result = factorial(5);
printf("Factorial = %d", result);

Output
Factorial = 120
8. Scope of Variables
Scope determines the visibility or accessibility of variables.

Types of Scope

1. Local Scope
Declared inside a function/block → usable only inside that function.

Example Question:

Q7: Write a program to demonstrate a local variable.

#include <stdio.h>

void test()
{
int x = 10;
printf("Inside test, x = %d\n", x);
}

int main()
{
test();
// printf("%d", x); // error: x not accessible
return 0;
}

Output
Inside test, x = 10

2. Global Scope
Declared outside all functions → accessible from any function.

Example Question:

Q8: Write a program to demonstrate a global variable.

#include <stdio.h>

int x = 100; // global variable

void display()
{
printf("Inside display, x = %d\n", x);
}

int main()
{
printf("Inside main, x = %d\n", x);
display();
return 0;
}

Output
Inside main, x = 100
Inside display, x = 100

9. Storage Classes
Storage classes tell the compiler the lifetime, scope, and default value of a variable.

9.1 auto
Definition

Default storage class for local variables.

 Scope: Local
 Lifetime: Until function exits
 Default Value: Garbage

Example Question:

Q9: Write a program to demonstrate auto variable.

#include <stdio.h>

int main()
{
auto int x = 10;
printf("x = %d", x);
return 0;
}

Output
x = 10
9.2 static
Definition

Retains its value even after function exits.

 Scope: Local
 Lifetime: Entire program
 Default Value: 0

Example Question:

Q10: Write a program to show how a static variable retains value.

#include <stdio.h>

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

void main()
{
test();
test();
test();
}

Output
x = 1
x = 2
x = 3

9.3 extern
Definition

Used to declare a global variable defined elsewhere.

Example Question:

Q11: Write a program to demonstrate extern keyword.

#include <stdio.h>

int x = 100;

void display() {
extern int x;
printf("x = %d", x);
}

int main() {
display();
return 0;
}

Output
x = 100

9.4 register
Definition

Requests the compiler to store variable in CPU register for faster access.

 Scope: Local
 Lifetime: Till function ends
 Default Value: Garbage

Example Question:

Q12: Write a program to declare a register variable.

#include <stdio.h>

int main()
{
register int x = 5;
printf("x = %d", x);
return 0;
}
Output
x = 5

Unit 3 Summary Table


Feature Description
Function Reusable block of code
Declaration Prototype
Definition Body of function
Call Invoking function
Call by Value Sends a copy
Recursion Function calling itself
Scope Local / Global
Storage Classes auto, static, extern, register
UNIT – 4 : ARRAYS, STRINGS & POINTERS

1. Concept of Array
Definition

An array is a collection of elements of the same data type stored in contiguous memory
locations, accessed using a single name and index number.

Example

int marks[5]; → creates an array of 5 integers.

Why use Arrays?

 To store multiple values of same type


 Efficient data management
 Reduces code length
 Fast accessing using index

2. Types of Arrays
1. One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array (3D, 4D, etc.)

* One-Dimensional Array
3.1 Declaration
Syntax
data_type array_name[size];

Example
int num[10];

3.2 Initialization
Syntax
int arr[5] = {10, 20, 30, 40, 50};

3.3 Accessing Elements


Elements are accessed using index (0 to n-1).

arr[0] = 10;
printf("%d", arr[0]);

Example Question:

Q1: Write a program to store 5 numbers in an array and print them.

Program
#include <stdio.h>

int main()
{
int arr[5] = {10, 20, 30, 40, 50};

for(int i = 0; i < 5; i++)


{
printf("%d ", arr[i]);
}
return 0;
}

Output
10 20 30 40 50
* Two-Dimensional Array
Definition
A 2D array is a collection of rows and columns (matrix form).

Syntax
data_type array_name[row][column];

Example
int matrix[3][3];

4.1 Initialization
int a[2][2] = { {1, 2},{3, 4} };

4.2 Accessing Elements


printf("%d", a[1][1]); // prints 4

Example Question:

Q2: Write a program to read a 2x2 matrix and display it.

Program
#include <stdio.h>

int main()
{
int a[2][2] = {{1, 2}, {3, 4}};

for(int i = 0; i < 2; i++)


{
for(int j = 0; j < 2; j++)
{
printf("%d ", a[i][j]);
}
printf("\n");
}

return 0;
}

Output
1 2
3 4
* Multidimensional Array or Three
Dimensional Array (3D Array)
Definition

An array with more than two dimensions.

Example
int arr[2][3][4]; // 3D array

Used in scientific computing, graphics, etc.

6. Memory Representation of 2D Array


A 2D array is stored sequentially in memory either:

6.1 Row-Major Order (C language uses this)


All elements of row 1, then row 2, and so on.

Example:

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

Memory layout:

1 2 3 4 5 6

6.2 Column-Major Order


(Used in languages like Fortran)

Stores all elements of column 1, then column 2, etc.

Example:

1 4 2 5 3 6
7. Passing Arrays to Functions
Syntax
void display(int arr[], int size);

Example Question:

Q3: Write a program to pass an array to a function and print its elements.

Program
#include <stdio.h>

void display(int arr[], int n)


{
for(int i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}

int main()
{
int a[5] = {10, 20, 30, 40, 50};
display(a, 5);
return 0;
}

Output
10 20 30 40 50

8. Bound Checking
C does not check array boundaries.
Example:

arr[10] = 5; // illegal if array size is 5

This can cause unpredictable results or memory errors.


9. Strings in C
9.1 Definition
A string is a character array terminated by a null character ‘\0’.

Syntax
char name[10];

9.2 Initialization
char name[10] = "Hello";

Or

char name[] = {'H','e','l','l','o','\0'};

9.3 String Input/Output


Input
gets(str);

Output
puts(str);

Example Question:

Q4: Write a program to read and display a string.

Program
#include <stdio.h>

void main()
{
char name[20];

printf("Enter name: ");


gets(name);

printf("You entered: ");


puts(name);
}
Output -
Enter name: Raju
You entered: Raju
10. String Operations
Common string functions (in string.h):

Function Use
strlen(str) Length of string
strcpy(a,b) Copy string
strcat(a,b) Concatenate
strcmp(a,b) Compare strings

Example Question:

Q5: Write a program to find the length of a string using strlen().

Program
#include <stdio.h>
#include <string.h>

int main()
{
char str[20] = "Hello";
int len = strlen(str);
printf("Length = %d", len);
return 0;
}

Output
Length = 5

11. Introduction to Pointers


Definition
A pointer is a variable that stores the memory address of another variable.

11.1 Address of Operator (&)


Gives address of variable.

int a = 10;
printf("%p", &a);
11.2 Indirection Operator (*)
Used to access value stored at pointer address.

int *p = &a;
printf("%d", *p);

Example Question:

Q6: Write a program to demonstrate pointers.

Program
#include <stdio.h>

int main()
{
int a = 10;
int *p = &a;

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


printf("Address of a = %p\n", &a);
printf("Value using pointer = %d\n", *p);

return 0;
}

Output
Value of a = 10
Address of a = 0x7ffeefbff45c
Value using pointer = 10

12. Pointer Arithmetic


Allowed operations:

Operation Meaning
p++ moves to next element
p-- moves to previous element
p+n jumps n elements
p-n goes backwards n elements

Example:

int *p;
p++; // moves 4 bytes forward in memory (for int)
Example Question:

Q7: Write a program to demonstrate pointer arithmetic.

Program
#include <stdio.h>

int main()
{
int arr[3] = {10, 20, 30};
int *p = arr;

printf("%d\n", *p); // 10
p++;
printf("%d\n", *p); // 20
p++;
printf("%d\n", *p); // 30

return 0;
}

Output
10
20
30

13. Dynamic Memory Allocation (DMA)


Used to allocate memory at runtime in heap.

Functions (in stdlib.h):

Function Use
malloc() Allocates memory
calloc() Allocates & initializes to zero
realloc() Changes size of previous block
free() Frees memory
Example Question:
Q8: Write a program to allocate memory dynamically using malloc( ).

Program
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *p;

p = (int*)malloc(5 * sizeof(int));
for(int i = 0; i < 5; i++)
p[i] = i + 1;

for(int i = 0; i < 5; i++)


printf("%d ", p[i]);

free(p);

return 0;
}

Output
1 2 3 4 5

14. Functions and Pointers


A pointer can also store the address of a function.

Syntax
return_type (*ptr)(parameter_list);

Example Question:

Q9: Write a program to call a function using a function pointer.

Program
#include <stdio.h>

void display()
{
printf("Hello from function pointer!");
}

int main()
{
void (*fp)();
fp = display;
fp();
return 0;
}

Output
Hello from function pointer!
Unit 4 Summary
Topic Key Points
Arrays Contiguous memory, indexed access
1D, 2D, Multi-D Different structures of arrays
Row-major C stores rows sequentially
Strings Null-terminated char arrays
Pointer Stores memory address
DMA malloc, calloc, free
Function pointers Store address of functions
UNIT – 5 : STRUCTURE AND UNION
(Detailed Notes + Questions + Programs + Outputs)

1. Introduction to Structure
Definition

A structure in C is a user-defined data type that allows grouping variables of different


data types under one name.

Example: Storing student details (roll, name, marks, grade) together.

Why use Structures?

 To combine different types of data.


 Handles complex data more efficiently.
 Useful in databases, records, real-life applications.
 Forms the base for files, linked lists, trees, and other data structures.

2. Declaring a Structure
Syntax
struct structure_name
{
data_type member1;
data_type member2;
...
};

Example
struct Student
{
int roll;
char name[20];
float marks;
};
3. Creating Structure Variables
Syntax
struct structure_name variable_name;

Example
struct Student s1;

4. Accessing Structure Members


Use dot operator ( . )

Syntax
variable_name.member

Example
[Link] = 10;
scanf("%s", [Link]);
printf("%f", [Link]);

Example Question 1:
Q1: Write a C program to store and display student details using structure.

Program
#include <stdio.h>

struct Student
{
int roll;
char name[20];
float marks;
};

int main()
{
struct Student s;

printf("Enter roll, name and marks:\n");


scanf("%d %s %f", &[Link], [Link], &[Link]);

printf("\n--- Student Details ---\n");


printf("Roll = %d\n", [Link]);
printf("Name = %s\n", [Link]);
printf("Marks = %.2f\n", [Link]);

return 0;
}

Output
Enter roll, name and marks:
101 Raju 85.5

--- Student Details ---


Roll = 101
Name = Raju
Marks = 85.50

5. Structure Initialization
Syntax
struct Student s = {101, "Raju", 88.5};

6. Structure Operations
Allowed operations:
✔ Access members
✔ Assign values to variables of same structure
✔ Passing structure to function
✔ Returning structure from function

Not allowed:
✘ Direct comparison
✘ Direct assignment between different structure types

7. Array of Structures
Used when many records must be stored.

Syntax
struct Student s[50];

Example Question 2:
Q2: Write a program to store data of 3 students using an array of structures.

Program
#include <stdio.h>

struct Student
{
int roll;
char name[20];
float marks;
};

int main()
{
struct Student s[3];

for(int i=0; i<3; i++)


{
printf("Enter roll, name, marks of student %d: ", i+1);
scanf("%d %s %f", &s[i].roll, s[i].name, &s[i].marks);
}

printf("\n--- Student Details ---\n");


for(int i=0; i<3; i++)
{
printf("%d %s %.2f\n", s[i].roll, s[i].name, s[i].marks);
}
return 0;
}

Output
Enter roll, name, marks of student 1: 101 Raju 88.5
Enter roll, name, marks of student 2: 102 Sita 78
Enter roll, name, marks of student 3: 103 Ram 90

--- Student Details ---


101 Raju 88.50
102 Sita 78.00
103 Ram 90.00
8. Nested Structure
A structure inside another structure.
Syntax
struct Outer
{
int x;
struct Inner
{
int y;
} in;
};

Example Question 3:

Q3: Write a program using nested structure to store employee address.

Program
#include <stdio.h>

struct Address
{
char city[20];
int pincode;
};

struct Employee
{
int id;
char name[20];
struct Address addr; // nested structure
};

int main()
{
struct Employee e;

printf("Enter ID, Name, City, Pincode:\n");


scanf("%d %s %s %d", &[Link], [Link], [Link], &[Link]);

printf("\n--- Employee Details ---\n");


printf("ID = %d\n", [Link]);
printf("Name = %s\n", [Link]);
printf("City = %s\n", [Link]);
printf("Pincode = %d\n", [Link]);

return 0;
}

Output
Enter ID, Name, City, Pincode:
1 Ravi Mumbai 400001
--- Employee Details ---
ID = 1
Name = Ravi
City = Mumbai
Pincode = 400001

9. Introduction to Union
Definition

A union is a user-defined data type like structure, but all members share the same memory
location.

Only one member can store value at a time.

Key Differences (Structure vs Union)

Feature Structure Union


Memory Sum of all members Size of largest member
Access All members at once Only one member at a time
Use Multiple data storage Memory-saving multipurpose storage

10. Declaring a Union


Syntax
union union_name
{
data_type member1;
data_type member2;
};

Example
union Data
{
int i;
float f;
char ch;
};
11. Accessing Union Members
Syntax
[Link]

Example Question 4:

Q4: Write a program to demonstrate union behavior.

Program
#include <stdio.h>

union Data
{
int i;
float f;
char ch;
};

int main()
{
union Data d;

d.i = 10;
printf("Integer = %d\n", d.i);

d.f = 5.5;
printf("Float = %.2f\n", d.f);

[Link] = 'A';
printf("Char = %c\n", [Link]);

printf("\nNow checking previous values:\n");


printf("Integer = %d\n", d.i);
printf("Float = %.2f\n", d.f);

return 0;
}

Output
Integer = 10
Float = 5.50
Char = A

Now checking previous values:


Integer = 1090519040 (garbage)
Float = 0.00 (garbage)

Explanation

 Last assigned member → ch = 'A'


 Other members lose their values due to shared memory.
12. Nested Union
Unions can be nested inside structures and vice versa.

Syntax
struct A
{
int x;
union B
{
int i;
float f;
} u;
};
Example Question 5:

Q5: Write a program with union inside structure.

Program -
#include <stdio.h>

union Marks
{
int internal;
int external;
};

struct Student
{
int roll;
char name[20];
union Marks m;
};

int main()
{
struct Student s;

printf("Enter roll, name and internal marks: ");


scanf("%d %s %d", &[Link], [Link], &[Link]);

printf("\nRoll = %d\nName = %s\nInternal Marks = %d\n",


[Link], [Link], [Link]);

return 0;
}

Output
Enter roll, name and internal marks: 101 Raju 40

Roll = 101
Name = Raju
Internal Marks = 40
13. Structure vs Union Summary
Feature Structure Union
Memory Separate memory for all members One shared memory
Usage Complex records (student, employee) Memory saving (variations)
Size Sum of all fields Size of largest field
Access All members at same time Only one at a time

UNIT 5 Summary
✔ Structure = different data types stored together
✔ Nested Structures = structure inside structure
✔ Array of structures = multiple records
✔ Union = shared memory storage
✔ Union stores only one value at a time
✔ Structures support multiple operations
✔ Unions save memory
UNIT – 6 : FILE HANDLING

1. Introduction to File
Definition

A file is a collection of data stored permanently on a storage device (Hard disk, SSD, USB,
etc.).
In C, file handling allows the programmer to store data permanently, even after the
program ends.

Why do we use Files?

 Data remains saved even after program execution.


 Large data can be stored easily.
 Easy to transfer data between programs.
 Used in applications like billing, payroll, banking, databases, etc.

2. File Handling Concepts in C


C uses a special pointer called FILE pointer for manipulating files.

Syntax
FILE *fp;

Opening a File

Use the fopen() function.

fp = fopen("[Link]", "mode");

Closing a File

After using a file, close it using:

fclose(fp);
3. File Modes in C
Mode Meaning
"r" Open file for reading
"w" Open for writing (existing data erased)
"a" Open for appending (write at end)
"r+" Read + Write
"w+" Write + Read (erase previous data)
"a+" Append + Read

4. Basic File Operations


The main operations are:

1. Creating a file
2. Writing to a file
3. Reading from a file
4. Searching inside a file
5. Updating a file

5. Writing to a File
Using fprintf( ) or fputs( ) or fputc( ).

Example Question 1:

Q1: Write a program to write text into a file called "[Link]".

Program
#include <stdio.h>

void main()
{
FILE *fp;
fp = fopen("[Link]", "w");

if(fp == NULL) {
printf("File cannot be opened!");
return 0;
}

fprintf(fp, "Hello File Handling in C!\n");


fclose(fp);
printf("Data written to file successfully.");
}

Output
Data written to file successfully.

Contents of [Link]
Hello File Handling in C!

6. Reading from a File


Using fscanf( ), fgets( ), or fgetc( ).

Example Question 2:

Q2: Write a C program to read contents of "[Link]" and display them.

Program
#include <stdio.h>

int main() {
FILE *fp;
char ch;

fp = fopen("[Link]", "r");

if(fp == NULL) {
printf("File not found!");
return 0;
}

while((ch = fgetc(fp)) != EOF) {


putchar(ch);
}

fclose(fp);
return 0;
}

Output
Hello File Handling in C!
7. Appending Data to a File
Using mode "a".

Example Question 3:

Q3: Write a program to append text to an existing file.

Program
#include <stdio.h>

int main()
{
FILE *fp;
fp = fopen("[Link]", "a");

if(fp == NULL) {
printf("Unable to open file!");
return 0;
}

fputs("Appending new line.\n", fp);

fclose(fp);

printf("File updated successfully.");


return 0;
}

Output
File updated successfully.

Contents of [Link] Now


Hello File Handling in C!
Appending new line.
8. Reading a File Line-by-Line
Using fgets( ).

Example Question 4:

Q4: Read a file line by line and display it.

Program
#include <stdio.h>

int main()
{
FILE *fp;
char str[100];

fp = fopen("[Link]", "r");

if(fp == NULL) {
printf("File error!");
return 0;
}

while(fgets(str, 100, fp)) {


printf("%s", str);
}

fclose(fp);
return 0;
}

Output
Hello File Handling in C!
Appending new line.
9. Searching Inside a File
You can search for a word/number by reading file content and comparing.

Example Question 5:

Q5: Search for a word “Hello” inside a file.

Program
#include <stdio.h>
#include <string.h>

int main()
{
FILE *fp;
char word[50];
int found = 0;

fp = fopen("[Link]", "r");

if(fp == NULL)
{
printf("File error!");
return 0;
}

while(fscanf(fp, "%s", word) != EOF)


{
if(strcmp(word, "Hello") == 0)
{
found = 1;
break;
}
}

if(found)
printf("Word FOUND!");
else
printf("Word NOT FOUND!");

fclose(fp);
return 0;
}

Output
Word FOUND!
10. Updating Contents of a File
Updating a file can be done by:

1. Reading old data


2. Making modifications
3. Writing updated data to a new file or rewriting original file

Example Question 6:

Q6: Replace a word “Hello” with “Hi” inside a file.

Program
#include <stdio.h>
#include <string.h>

int main()
{
FILE *fp1, *fp2;
char word[50];

fp1 = fopen("[Link]", "r");


fp2 = fopen("[Link]", "w");

while(fscanf(fp1, "%s", word) != EOF)


{
if(strcmp(word, "Hello") == 0)
fprintf(fp2, "%s ", "Hi");
else
fprintf(fp2, "%s ", word);
}

fclose(fp1);
fclose(fp2);

remove("[Link]");
rename("[Link]", "[Link]");

printf("File updated successfully.");


return 0;
}

Output
File updated successfully.
11. Checking End of File (EOF)
EOF: End Of File indicator used by:

while(!feof(fp))

Or better:

while((ch = fgetc(fp)) != EOF)

12. File Handling Functions Summary


Function Purpose
fopen() Opens a file
fclose() Closes a file
fprintf() Print to file
fscanf() Read formatted data
fgetc() Read a character
fputc() Write a character
fgets() Read a string
fputs() Write a string
remove() Delete a file
rename() Rename a file

UNIT 6 SUMMARY
✔ File = permanent data storage
✔ FILE pointer (FILE *fp) used
✔ Modes: r, w, a, r+, w+, a+
✔ Read, Write, Append using file functions
✔ Searching by reading tokens and comparing
✔ Updating by creating a temp file

You might also like