C Programming Basics and Features
C Programming Basics and Features
Sc(Cyber Security)
Subject – Foundations of C Programming
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:
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.
1. Simplicity
C has a small number of keywords (32 in ANSI C). Its syntax is simple and easy to
understand.
2. Portability
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
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
1. Documentation Section
2. Link Section
#include <stdio.h>
#include <math.h>
3. Definition Section
Defines constants.
#define PI 3.14
int a = 10;
5. main( ) Function
int main( )
{
// code
}
6. User-defined Functions
Functions created by the programmer.
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
Rules:
Examples:
Syntax:
data_type variable_name;
Example:
int age;
float salary;
5.2 Constants
Types:
1. Integer constants
2. Floating constants
3. Character constants
4. String constants
#define PI 3.14
6. Data Types in C
6.1 Basic Data Types
Arrays
Pointers
Structures
Unions
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
int a, b;
float salary;
7.2 Expressions
z = x + y;
8. Operators in C
C supports multiple types of operators.
Operator Meaning
+ Unary plus
- Unary minus
++ Increment
-- Decrement
Example:
x = -y;
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
8.2 Increment and Decrement Operators
Pre-increment
++a;
Post-increment
a++;
Operator Meaning
< less than
> greater than
<= less than or equal
>= greater than or equal
== equal
!= not equal
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
a = (b = 5, b + 2); // a = 7
printf("%d", sizeof(int));
Example:
Syntax:
Example:
Syntax:
Example:
ch = getchar();
putchar( )
putchar(ch);
9.4 getch( )
Reads a character without echo (primarily in <conio.h>).
ch = getch();
gets(name);
puts( )
Displays a string.
puts(name);
Escape Meaning
\n Newline
\t Tab
\\ Backslash
\' Single quote
\" Double quote
\b Backspace
\r Carriage return
Specifier Meaning
%d Integer
%f Float
%c Character
%s String
Specifier Meaning
%lf Double
%u Unsigned int
%x Hexadecimal
%o Octal
Example:
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
Syntax
if(condition)
{
// statements
}
Example Question:
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;
return 0;
}
Output
Not eligible to vote
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;
return 0;
}
Output
Grade B
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
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;
Output
Maximum = 20
2. Looping (Iterative) Structures
2.1 while Loop
Definition
Syntax
while(condition)
{
// loop body
}
Example Question:
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
Syntax
do
{
// statements
} while(condition);
Example Question:
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
Syntax
for(initialization; condition; increment)
{
// body
}
Example Question:
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
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
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:
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
Definition
Syntax
goto label;
label:
// statements
Example Question:
int main() {
int i = 1;
start:
printf("%d ", i);
i++;
if(i <= 5)
goto start;
return 0;
}
Output
1 2 3 4 5
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:
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
Examples
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);
Output
Square root = 5.000000
4. User-Defined Functions
These are functions created by the programmer.
Tells the compiler the name, return type, and parameters of the function.
Syntax
return_type function_name(parameter_list);
Syntax
return_type function_name(parameters)
{
// statements
}
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 main()
{
int x = 10, y = 20, result;
return 0;
}
// function definition
int add(int a, int b)
{
return a + b;
}
Output
Sum = 30
5. Parameter Passing (Call by Value)
Definition
Syntax
void function(int x)
{
// x is a copy
}
Example Question:
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
Syntax
return expression;
Example Question:
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:
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:
#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:
#include <stdio.h>
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
Scope: Local
Lifetime: Until function exits
Default Value: Garbage
Example Question:
#include <stdio.h>
int main()
{
auto int x = 10;
printf("x = %d", x);
return 0;
}
Output
x = 10
9.2 static
Definition
Scope: Local
Lifetime: Entire program
Default Value: 0
Example Question:
#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
Example Question:
#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:
#include <stdio.h>
int main()
{
register int x = 5;
printf("x = %d", x);
return 0;
}
Output
x = 5
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
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};
arr[0] = 10;
printf("%d", arr[0]);
Example Question:
Program
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
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} };
Example Question:
Program
#include <stdio.h>
int main()
{
int a[2][2] = {{1, 2}, {3, 4}};
return 0;
}
Output
1 2
3 4
* Multidimensional Array or Three
Dimensional Array (3D Array)
Definition
Example
int arr[2][3][4]; // 3D array
Example:
Memory layout:
1 2 3 4 5 6
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>
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:
Syntax
char name[10];
9.2 Initialization
char name[10] = "Hello";
Or
Output
puts(str);
Example Question:
Program
#include <stdio.h>
void main()
{
char name[20];
Function Use
strlen(str) Length of string
strcpy(a,b) Copy string
strcat(a,b) Concatenate
strcmp(a,b) Compare strings
Example Question:
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
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:
Program
#include <stdio.h>
int main()
{
int a = 10;
int *p = &a;
return 0;
}
Output
Value of a = 10
Address of a = 0x7ffeefbff45c
Value using pointer = 10
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:
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
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;
free(p);
return 0;
}
Output
1 2 3 4 5
Syntax
return_type (*ptr)(parameter_list);
Example Question:
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
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;
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;
return 0;
}
Output
Enter roll, name and marks:
101 Raju 85.5
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];
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
Example Question 3:
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;
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.
Example
union Data
{
int i;
float f;
char ch;
};
11. Accessing Union Members
Syntax
[Link]
Example Question 4:
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]);
return 0;
}
Output
Integer = 10
Float = 5.50
Char = A
Explanation
Syntax
struct A
{
int x;
union B
{
int i;
float f;
} u;
};
Example Question 5:
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;
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.
Syntax
FILE *fp;
Opening a File
fp = fopen("[Link]", "mode");
Closing a File
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
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:
Program
#include <stdio.h>
void main()
{
FILE *fp;
fp = fopen("[Link]", "w");
if(fp == NULL) {
printf("File cannot be opened!");
return 0;
}
Output
Data written to file successfully.
Contents of [Link]
Hello File Handling in C!
Example Question 2:
Program
#include <stdio.h>
int main() {
FILE *fp;
char ch;
fp = fopen("[Link]", "r");
if(fp == NULL) {
printf("File not found!");
return 0;
}
fclose(fp);
return 0;
}
Output
Hello File Handling in C!
7. Appending Data to a File
Using mode "a".
Example Question 3:
Program
#include <stdio.h>
int main()
{
FILE *fp;
fp = fopen("[Link]", "a");
if(fp == NULL) {
printf("Unable to open file!");
return 0;
}
fclose(fp);
Output
File updated successfully.
Example Question 4:
Program
#include <stdio.h>
int main()
{
FILE *fp;
char str[100];
fp = fopen("[Link]", "r");
if(fp == NULL) {
printf("File error!");
return 0;
}
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:
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;
}
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:
Example Question 6:
Program
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp1, *fp2;
char word[50];
fclose(fp1);
fclose(fp2);
remove("[Link]");
rename("[Link]", "[Link]");
Output
File updated successfully.
11. Checking End of File (EOF)
EOF: End Of File indicator used by:
while(!feof(fp))
Or better:
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