0% found this document useful (0 votes)
12 views

Reduced

The document provides an overview of the C programming language, including its history, characteristics, and evolution since its development in 1972 by Dennis Ritchie. It discusses key features such as portability, speed, efficiency, and structured programming, along with comparisons to other languages like Python and Java. Additionally, it covers fundamental concepts like variables, identifiers, tokens, constants, and pointers, highlighting their roles and usage in C programming.

Uploaded by

aqsanaveed2310
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Reduced

The document provides an overview of the C programming language, including its history, characteristics, and evolution since its development in 1972 by Dennis Ritchie. It discusses key features such as portability, speed, efficiency, and structured programming, along with comparisons to other languages like Python and Java. Additionally, it covers fundamental concepts like variables, identifiers, tokens, constants, and pointers, highlighting their roles and usage in C programming.

Uploaded by

aqsanaveed2310
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Written by Aqsa Naveed

Ph: 03172031442
Computer
Solved topics according to reduced syllabus (2025)

Topic 1: Introduction and history of C language:


Introduction to C Language
C is one of the most powerful and widely used programming languages. It is known as a general-purpose,
structured, and procedural language that is mainly used for system programming, developing operating systems,
and creating applications.

What is a Programming Language?


A programming language is a set of instructions that tells a computer what to do. Different programming languages
exist, such as Python, Java, C++, and C, each with its own advantages.

Why Was C Developed?


Before C, there were other programming languages like B and BCPL, but they had many limitations. These
languages were not efficient for system programming and could not handle complex tasks. Therefore, in 1972,
Dennis Ritchie developed the C language at Bell Laboratories (Bell Labs) to create the UNIX operating system.

Characteristics of C Language
The C language became popular because of its powerful features. Some important characteristics of C are:
1. Simple and Structured
• C follows a structured programming approach, which means a program is divided into small functions,
making it easy to read and modify.
2. Portable (Machine-Independent)
• A program written in C can run on different computer systems with minimal changes. This feature makes C
highly portable and useful for developing software that works on multiple platforms.
3. Fast and Efficient
• C is a low-level language, meaning it interacts closely with the computer hardware. This makes it faster than
other high-level languages like Python or Java.
4. Supports Low-Level Programming
• Unlike many modern programming languages, C allows direct memory access and hardware control, which
is why it is used for system programming.
5. Rich Set of Operators and Functions
• C has a variety of built-in operators (arithmetic, logical, relational, etc.) and library functions, making
programming easier.
6. Extensible
• New features and libraries can be added to C to extend its capabilities.

History of C Language
The development of the C language can be traced back to the 1960s and 1970s. It evolved over time and became
the foundation of many modern programming languages.

Languages Before C
Before C, there were two main programming languages:
BCPL (Basic Combined Programming Language) – Developed in 1966 by Martin Richards, it was used for writing
system software.
B Language – Developed by Ken Thompson in 1970, this was a simpler version of BCPL but lacked some
important features.
Since these languages were not very powerful, a better language was needed. This led to the development of C in
1972 by Dennis Ritchie.

Timeline of C Language Evolution


Year Version Features
1972 C (Original) Created by Dennis Ritchie to develop UNIX.
1978 K&R C The first official book on C, written by Kernighan & Ritchie.
1989 ANSI C (C89) Standardized by ANSI (American National Standards Institute) to ensure compatibility.
Introduced new features like inline functions, variable-length arrays, and better memory
1999 C99
handling.
2011 C11 Added multithreading support and security improvements.
2018 C17 Minor updates for performance improvements.

Why is C Still Used Today?


Even though many modern languages like Python, Java, and C++ exist, C is still widely used because:
1. C is the base of many modern languages – C++ is an extension of C, and languages like Java and Python have
concepts inspired by C.
2. It is used for system programming – Many operating systems, including Windows, Linux, and macOS, have
parts written in C.
3. Embedded Systems – C is commonly used in microcontrollers and embedded devices (washing machines,
smart TVs, etc.).
4. Game Development – Many game engines use C because of its speed.
5. Database Development – Popular databases like MySQL and PostgreSQL are built using C.

Comparison of C with Other Languages


Feature C Python Java

Speed Faster Slower Medium

Memory Control Manual Automatic Automatic

System programming, OS Web development, Enterprise applications, Android


Used For
development AI development

Syntax
Medium Simple Medium
Complexity

Types of Questions That Can Be Asked in the Exam


3. Long Answer Questions (5-8 Marks)
• Write a detailed note on the history of the C language.
Explain who developed it, why it was created, and how it evolved.
• Discuss the main features of the C language with examples.
Explain portability, speed, efficiency, and structured programming.
• Compare C with other modern languages like Python and Java.
Mention C's speed, efficiency, and system-level access vs. Python/Java's high-level features.

Solutions:
Q1: Write a detailed note on the history of the C language.
Introduction
C is a general-purpose, structured, and procedural programming language that was developed in 1972. It
became one of the most widely used programming languages and served as the foundation for many
modern languages like C++, Java, and Python.
Who Developed C?
C was developed by Dennis Ritchie at Bell Laboratories (Bell Labs) in 1972. It was created to overcome the
limitations of previous languages like B and BCPL and to develop the UNIX operating system.
Why Was C Created?
Before C, programmers used languages like Assembly, BCPL, and B, but these languages had limitations:
1. Assembly language was difficult to use – Programs were written in machine-level instructions,
making them complex.
2. BCPL and B had fewer features – They lacked data types and other important programming tools.
3. Needed a powerful system programming language – UNIX was being developed at Bell Labs, and a
better language was required for writing it.
To solve these issues, Dennis Ritchie developed C, which was more efficient, structured, and easy to use.

Evolution of C Language
Year Version Features
1972 C (Original) Created by Dennis Ritchie for UNIX.
1978 K&R C First book on C published by Kernighan & Ritchie.
1989 ANSI C (C89) Standardized version for compatibility.
1999 C99 Introduced inline functions, variable-length arrays.
2011 C11 Added multithreading and security improvements.
2018 C17 Minor updates and performance improvements.

Conclusion
C is one of the most influential programming languages in history. It revolutionized system programming
and software development and is still used today in various applications, including operating systems,
embedded systems, and database management systems.

Q2: Discuss the main features of the C language with examples.


1. Simplicity
C uses a simple syntax and keywords that make it easy to understand and use.
Example:
c
printf("Hello, World!");
This prints "Hello, World!" on the screen.
2. Structured Programming
C allows programs to be divided into functions, making them more organized and reusable.
Example:
c
void greet() {
printf("Hello!");
}
int main() {
greet();
return 0;
}
Here, greet() is a separate function that prints "Hello!"
3. Speed and Efficiency
C is faster than most high-level languages because it is close to machine language.
Example:
Sorting numbers in C is much faster than in Python because C uses direct memory manipulation.
4. Portability (Machine Independent)
A C program can run on different computers without major changes.
Example:
A C program compiled on Windows can also run on Linux with minor modifications.
5. Low-Level Access (System Programming)
C allows direct interaction with hardware, making it useful for writing operating systems and drivers.
Example:
c
int *ptr;
ptr = (int*)malloc(sizeof(int) * 10);
This allocates memory manually using pointers.
Conclusion
The C language is fast, structured, and versatile, making it ideal for both system and application
programming.

Q3: Explain portability, speed, efficiency, and structured programming in C.


1. Portability (Machine Independent)
• A program written in C can run on different operating systems with minimal changes.
• This makes C highly portable and useful for developing cross-platform software.
Example:
A program compiled on Windows can also work on Linux with a compatible compiler.
2. Speed
• C is faster than most high-level languages because it compiles directly into machine code.
• Unlike Python or Java, C does not require an interpreter or virtual machine, making execution
quicker.
Example:
Sorting a large number of elements in C takes less time than in Python because of its efficient memory
handling.
3. Efficiency
• C uses pointers, memory management functions (malloc, free), and direct memory access, making
it highly efficient.
• This is why C is used in operating systems, database management systems, and embedded
programming.
Example:
c
int *ptr;
ptr = (int*)malloc(10 * sizeof(int));
Here, malloc allocates memory dynamically, improving performance.
4. Structured Programming
• C follows a modular approach, dividing programs into functions for better readability and
maintenance.
Example:
c
void addNumbers(int a, int b) {
printf("Sum: %d", a + b);
}
int main() {
addNumbers(5, 3);
return 0;
}
This approach makes debugging easier.
Conclusion
The C language is portable, fast, efficient, and structured, making it one of the most widely used
programming languages today.

Topic 2: Explain (Variable, Identifiers, Token, Constant)

1) Identifiers:
Identifiers are name given to various program elements, such as variables, functions and arrays. Following
rule must be observed while constructing identifiers.
1: An identifier must start with a letter or (rarely) an underscore (_).
2: An identifier can contain letters, digits, or underscore. (_).
3: An identifier cannot contain blanks, commas or any other special characters.
4: An identifier cannot consist of more than 31 characters.
5: An identifier must confirm to case sensitivity (C differentiates between uppercase and lowercase
alphabetical characters). For example, the identifier MAX is not same as the identifier max.

2) Variables:
A variable is a programming- defined identifier whose value can change during the execution of the
program. All variables must have a name and a data type. C supports most of the common data types for
variables – integer, float (real), and character.
Rules For constructing Variable Names:
1: The first character in the variable name must be an alphabet.
2: No commas or blanks are allowed within a variable name.
3: No special symbol other than an underscore (as in tax_rate) can be used in a variable name.

Declaration of variable:
A declaration associates a group of variables with a specific data type. A declaration consists of a data type,
followed by one or more variable names, ending with a semicolon.
Example:
{
Int num;
float tax_rate;
This creates an int variable name num, and a float variable called tax_rate.

Initialization of variable:
Variable initialization in C means assigning an initial value to a variable at the time of declaration. This
prevents the variable from holding a garbage value.
Example:
int num = 10;
float tax_rate = 5.5;
char grade = 'A';
double price = 99.99;
long population = 8000000;
Each variable is declared and initialized with a value at the same time.

Difference Between Local and Global Variables:


Local Variables Global Variables
Define inside the body of function. Defined outside the body o function.
Only has specific access. Can be used across different function.
It can be used during specific part of program. Ut remains available throughout execution.
It is is not initialized a garbage value is stored. It it is not initialized zero is stored as default.
3) Token:
A token in C is the smallest unit of a program that the compiler recognizes. Tokens help in building C
statements and expressions.
Types of Tokens in C:
1. Keywords (e.g., int, float, return)
2. Identifiers (e.g., variable and function names)
3. Constants (e.g., 10, 3.14, 'A')
4. Strings (e.g., "Hello")
5. Operators (e.g., +, -, *, /)
6. Special Symbols (e.g., {}, (), [], ;)
4) Constant:
A constant in C is a fixed value that does not change during the program execution. Constants can be
numbers, characters, or strings, and they are stored in memory just like variables, but their values cannot
be modified after initialization.
Types of constant:
i) Integer constant:
An integer constant in C is a whole number (without decimal points) that remains fixed throughout the
program. It represents numeric values and cannot be changed during execution. Integer constant include
decimal, Octal and Hexadecimal constants.
Rules for Integer Constants:
1: An integer constant must have at least one digit.
2: It must not have a decimal point.
3: It could be either positive or negative.
4: If no sign precedes an integer constant it is assumed to be positive.
5: No commas or blanks are allowed within an integer constant.
6: The value of a constant cannot exceed specified minimum and maximum bonds. The allowable range for
integer constants is -32768 to + 32767

ii) Floating- point Constant:


Integers are inadequate for representing very large or very small numbers and fractions. For this you need
floating-point types. Floating-point constants are also called real constant.
Example: 0. 1. -0.5, 0.0001, 3E-7

iii) Character Constant:


A character constant is a single character, enclosed in apostrophes (i.e., single quotation marks). They
include the letters of alphabet (lowercase and uppercase). The numerals 0 to 9, punctuation marks such as
;, ; and ?, special characters such as &, +, -, # and $.
Example: ‘B’, ‘5’, ‘+’, ‘?’, ‘m’

iv) String constant:


A sequence of zero or more characters enclosed by double quotes is called a string constant. This can also
be called as an array of character constant. Some examples of valid character constants are:
Example: “The quick brown fox jumps over the lazy dog.”, “12-Qasim Rd.”, “516-86-112109”

v) Symbolic Constant:
A symbolic constant is a programmer-defined identifier that is replaced with a sequence of characters
called text. The replacement text may represent a numeric constant, a character constant or a string
constant.
Example: const float PI=3.14159; , const int YEAR_LENGTH = 12;, const char ANSWER = ‘Y’;

Difference between Constant and Variable:


Constant Variable
Constant is a quantity whose value does not It is a symbolic name that represents a value that
change during program execution. can change during execution of a program.
Constant have already known face-value. Variables value are mostly unknown.
It is used in mathematical expressions. It is used to represent alphabets and letters.
Cannot be modified after declaration. Can be modified anytime in the program.

Topic 3: Pointers (Initialization, Declaration with example).


Pointers:
A pointer in C is a special type of variable that stores the memory address of another variable rather than
storing a direct value. Pointers are powerful tools that allow programmers to efficiently manage memory,
pass function arguments by reference, and handle data structures like arrays, linked lists, and trees.
In simpler terms, if a normal variable is like a "locker" that stores a value, a pointer is like a "locker key"
that tells us where the value is stored in memory.

Initialization Of pointers:
Pointer initialization is the process of assigning a valid memory address to a pointer variable. A pointer
must be initialized before it is used to avoid storing garbage values, which can lead to unexpected program
behavior or crashes. The memory address assigned to a pointer comes from a normal variable using the
address-of (&) operator.
Example: #include <stdio.h>
int main() {
int num = 25; // Normal integer variable
int *ptr = &num; // Pointer storing address of num

printf("Value of num: %d\n", num);


printf("Address of num: %p\n", &num);
printf("Pointer ptr stores: %p\n", ptr);
printf("Value at pointer ptr: %d\n", *ptr); // Dereferencing

return 0;
}
Explanation:
• ptr is a pointer that stores the address of num.
• The dereferencing operator (*ptr) is used to access the value stored at that memory location.
• Proper initialization ensures the pointer does not hold a random or invalid memory address,
preventing errors.
This concept is crucial for efficient memory management and dynamic programming in C.

Deceleration of Pointers:
Pointer declaration in C means creating a pointer variable that can store the memory address of another
variable. A pointer is declared using the * (asterisk) symbol before the pointer name, along with its data
type, which specifies the type of variable the pointer will point to.
data_type specifies the type of variable the pointer will point to (int, float, char, etc.).
*pointer_name declares the variable as a pointer.
Example: #include <stdio.h>
int main() {
int *ptr; // Pointer declaration (stores address of an int variable)
float *fptr; // Pointer declaration (stores address of a float variable)

printf("Pointer variables declared successfully.");

return 0;
}
Explanation:
• int *ptr; declares a pointer ptr that can store the address of an integer variable.
• float *fptr; declares a pointer fptr that can store the address of a float variable.
• The asterisk (*) does not mean multiplication here; it signifies that the variable is a pointer.
Declaring pointers is essential for dynamic memory allocation, efficient memory handling, and advanced
programming techniques in C.

Topic 4: Operators and its usage:


Operators:
An operator is a special symbol or keyword that performs an operation on one or more operands. It is used
to manipulate values of variable.

Classification of Operator:
Basically C language has 45 types of different operators and here are some of most common types include:
1: Arithmetic Operator
2: Assignment Operator
3: Relational Operator
4: Increment Operator
5: Conditional Operator
6: Increment Operator
7: Decrement Operator
8: Address Operator
9: Logical/ Boolean Operator

i) Arithmetic Operators:
Arithmetic operators are used to perform mathematical calculation. An arithmetic expression is made up
of variable, constant, a combination of both or a function call, connected by arithmetic operators.
Following list provide the detail about arithmetic operators.
Operator Operation Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
% Remainder after integer division a%b

ii) Assignment Operators:


The basic assignment operator is =. This is used to assign value of an expression to an identifier. It has the
general form identifier= expression, where identifier generally represents a variable, and expression
represent a constant, a variable or a more complex expression. In addition to =, there are a number of
assignment operators in C. Some of them are.
Operators Operation Example
+= Add-assign a+=b
-= Subtract-assign a-=b
*= Multiply-assign a*=b
/= Divide-assign a/=b
%= Remainder-assign a%-=b

iii) Relational Operators:


Relational operators are used to compare two numeric operands. The operands can be variables, constant
or expressions that ultimately get evaluated to a numerical value. Since characters can be represented as
integers using ASCII code. The relational operators are summarized as:
Operators Operation Example
< Less than a<b
> Greater than a>b
<= Less than or equal to a<=b
>= Grater than or equal to a>=b
== Equal to a==b
!= Not equal to a=b

iv) Logical Operators/Boolean Operators:


A logical operator also called Boolean operator combines the results of one or more expressions and the
resultant expression is called the logical expression. After testing the conditions, they return either true
(non-zero value) or false (0) as net results. The logical operators are binary operators. The operands may
be constants, variables or expressions, The basic logical operators are:
Operator Operation Example
&& Logical AND 1 if a=b && c=d; else 0
|| Logical OR 1 if a=b|| c>d; else 0
! Logical NOT 1 if !a; else 0

v) Increment and Decrement Operators:


The increment operator ++ and decrement operator – are very useful operators and are not found in other
languages. If a variable a is incremented by 1, the increment operator ++ can be used rather than
expression a=a+1 or a+=1. The increment operator causes its operand to be increase by 1, where as the
decrement operator causes its operand to be decreases by 1.
Operator Operation Example
++ Increment by 1 a++ (post-increment) or ++a (pre-increment)
-- Decrement by 1 a-- (post-decrement) or --a (pre-decrement)

vi) Conditional Operators:


The conditional operator (? :) in C is a ternary operator, meaning it works with three operands. It is used as
a shorter alternative to if-else statements, allowing a condition to be evaluated in a single line. The syntax
follows:
condition ? expression_if_true : expression_if_false;

vii) Address Operators:


The address operator (&) is used to get the memory address of a variable. It returns the location in
memory where the variable is stored. This operator is commonly used in pointer operations. The syntax
follows:
condition? expression_if_true: expression_if_false;

Advantages/ Importance, Usage of Operators:


Enhances Code Efficiency – Operators allow quick execution of mathematical, logical, and bitwise
operations.
Reduces Code Complexity – Simplifies expressions, making programs easier to read and write.
Increases Readability – Helps write concise and clear code for better understanding.
Fast Execution – Improves program performance, especially in bitwise and arithmetic operations.
Supports Memory Management – Pointers and address operators allow direct access to memory.
Aids in Decision-Making & Looping – Logical and relational operators improve control flow.
Provides System-Level Access – Useful for low-level programming and hardware interactions.

Topic 5: Data Type with sizes:

C offers a standard, minimal set of basic types. Sometimes these are called “primitive” type. A lot of
complex data structures can be developed from these basic data types. In C, data types define the type of
data a variable can store. The size of each data type depends on the compiler and system architecture
(usually 32-bit or 64-bit). The C language defines 4 fundamental data types.
*Character (char)
*Integer (int)
*Floating-point (float)
*Double floating-point (double)
These data types are declared using keywords char, int, float and double respectively. Typical memory
requirements of the basic data types are given below.

Int (Integer) data type:


An integer is a whole number 9a number without a fractional part). It can be positive or negative numbers
like 1, -2, 3 etc., or zero.
The sizes of the integer variable depend on the hardware and opening system of the computer. On a
typical 15-bits system, the sizes of the integer types are as follows.
TYPE Bytes Possible values le values
Int 2 or 4 -32, 767 to 32 to 767
Unsigned unit 2 or 4 0 to 65,535
Signed unit 2 or 4 -32, 767 to 32,767
Long unit 4 -2,147,483,647 to 2,146, 483,647
Syntax to declaration variable: inta, b;

Float Data type:


Floating point numbers are numbers with a decimal point. The float type can take large floating-point
number with a small degree of precision (Precision is simply the number of decimal places to which a
number can be calculated with accuracy. If a number can be calculated to three decimal places, it is said to
have three significant digits).
Memory sizes: 4 bytes.
Minimal range: IE-38 to IE+38 with six digit of precision
Syntax to declaration variable floatc, d;

Double Float data type:


Double-precision floating point numbers are also numbers with a decimal point. We know that the float
type can take large floating- point numbers with a small degree of precision but the double-precision
double float type can hold even larger number with a higher degree precision. The sizes of the double
types are as follows.
TYPE Bytes Minimal range
Double precision 8 IE-38 to IE+38 with 10 digit of precision
Long double 8 IE-38 to IE+38 with 10 digit of precision
Syntax to declaration variable: doublec, d;

Char (character) data type:


Char designed for storing single characters. The integer value of a char corresponds to an ASCII character.
The char type is signed by default on some computers, but unsigned on others the sizes of the char types
are as follows.
TYPE Bytes Minimal range
Char 1 -127 to 127
Unsigned char 1 0 to 255
Signed char 1 -127 to 127
Syntax to declaration variable: chara, b;
Topic 6: Functions:
(System define/ predefine function with syntax, User define functions (declaration,
calling and definition), Four methods of user define function.

Functions:
A function is a block of instructions that together perform a specific task. Every C program has at least one
function, main (). You can also write your own functions and use them just as you use functions in a C
library. When your program starts, main () is called automatically and it is always executed first.

Advantages/ Usage/ Importance of functions:


The following are some advantages of using functions:
1)The complexity of the entire program can be divided into simple subtasks and function subprograms can
be written for each subtask.
2)Functions help us to avoid unnecessary repetition of code, using functions a single section of code can be
used many times in the same program.
3)Functions can have input and outputs and can process information.
4)The functions or subprograms are short, easier to write, understand and debug.
5) A function can be shared by other programs by compiling it separately and loading them together.
6) Functions are mostly independent of each other, just as one program id independent of another
program. Most of the activities in a function are hidden from the rest of the program.
7) In turbo C++ a function can call itself again and again. It is called recursiveness. Many calculations can be
done easily using recursive process such as calculation of factorial of a number etc.

Classification of functions:
Functions are of two types, these are:
1)Built-in-function/ Library function/ Predefine function/ System define functions.
2) User defined function

1)Built-in-function/ Library function/ Predefine function/ System define functions.


Many of the operations, like taking the square root of a number, sine value of a number etc., will be
frequently used by many programmers in their programs. Writing a program to find the square root of a
number or sine value of a number every time in each program is an unnecessary and lengthy job. Such
operations are programmed and stored in Turbo C++ library, so that they can be called through any
program in the form of functions. These are called library functions or built-in-functions.
Syntax: printf("Hello, World!");
2) User-Defined function:
Apart from the library functions that are built in Turbo C++ users can also define functions to do a task
relevant to their programs. Such functions are called user-defined functions. These functions should be
codified by the user, so that any call to the function can refer to it.
Syntax: return_ type function _ name (parameters) {
Return value 0;
}

General form of function:


The overall structure of the functions looks almost like that of the main () unction in a program. That is
because main () is also a function. The only difference is that main is a special name. Use of the function in
a program requires three things:
1)Function declaration, which is also called function prototype.
2) Function definition
3) Function calling

1) Function Declaration/ Function Prototype:


Using functions in your program requires that you first declare the function and then you define the
function. No function can e called from any other function that has not first been deleted. The declaration
of a function is called its prototype. It is a line writer before the main () function. The prototype tells the
compiler in advance about some characteristics of a function used in the program.
The general structure of the function prototype is:
Syntax: type function _ name (type argument -1, type argument -2, …);
It has three main components. These are:
1) Data type of the function 2) Name of the function 3) Arguments.

i) Data type of the Function:


The data type of the function is the type of the returned value. If the function does not return a value, the
type is defined as void.
ii) Name of the Function:
The name of the function is any legal identifier followed by the parentheses without any spaces in
between.
iii) Arguments:
The arguments come inside the parentheses, preceded by their types and separated by commas. If the
function does not use any arguments, the word void is used inside the parentheses.

2) Function Definition:
A function definition in C provides the actual implementation of a function that was declared earlier. It
includes the function header and body, where the logic is written. The function definition is the function
itself. The general structure of the function definition is:
Syntax: type function _ name (type argument -1, type argument -2, …)
{
Body of function
}
The function definition has two parts:
1) Function Header 2) Body of Functions

i) Function Header:
The function begins with a header which is exactly same as the function prototype except it must not be
terminated with semicolon (;). Header specifies the name of the function.

ii) Body of Function:


It is the main body of the function. All statements are written is this part of program. The statement in the
body of the function is written to perform a specific task.

3) Function Calling:
A user defined function is called from the main program simple by using its name, including the
parentheses which follow the name. The parentheses are necessary so the compiler knows you are
referring to a function and not a variable that you forgot to declare.

Four methods of user define function:


In C, user-defined functions can be used in different ways based on how they accept arguments and return
values. Functions can be used in four variations:
1) Functions that does not need any argument and also returns no value.
2) Functions that does not need any argument but returns a value.
3) Functions that needs one or more arguments but returns no value.
4) Functions that needs one or more arguments and also return a value.

1) Function with No Arguments and No Return Value:


The first function neither returns nor accept any arguments. Such type of function is called simple function.
OR
Takes no parameters and does not return a value.
Used when a function only performs a task without needing input or output.
Example:
#include <stdio.h>

void greet() {
printf("Hello, Welcome!\n");
}

int main() {
greet(); // Function call
return 0;
}
2) Function with No Arguments but Returns a Value:
The second function returns and integer value and does not accept any arguments. OR
Takes no parameters but returns a value.
Useful when a function generates or retrieves a value without external input.
Example:
#include <stdio.h>

int getNumber() {
return 25;
}

int main() {
int num = getNumber();
printf("Returned Number: %d\n", num);
return 0;
}
3) Function with Arguments but No Return Value:
The third function return no value but it accepts an argument x of the type integer. OR
Accepts parameters but does not return a value.
Used when a function performs an operation based on given input but doesn’t need to return anything.
Example:
#include <stdio.h>

void display(int num) {


printf("The number is: %d\n", num);
}
int main() {
display(10); // Function call with argument
return 0;
}
4) Function with Arguments and Returns a Value:
The fourth function accepts two double arguments (the value of x and the value of y) and returns a value
of the type float. OR
Takes parameters and returns a value.
Used when a function needs input to process and return an output.
Example:
#include <stdio.h>

int add(int a, int b) {


return a + b;
}

int main() {
int sum = add(5, 7);
printf("Sum: %d\n", sum);
return 0;
}

Topic 7: Basic structure/ Block structures of C program (Explain all three


stages, preprocessor directives, main () function, opening and ending
delimiters or braces and source code.

Difference between source code and object code:


Source Code/ Program Object Code/ Program
A collection of computer instruction written using A sequence of statement in binary that is
a human readable programming language. generated after compiling the source program.
It contains English words according to the syntax of It contains binaries
the programming language.
Source program is the input of the compiler. Object program is the output of the compiler.
Source code is another name for source program. Object code is another name for object program.

Basic structures / Block structures of C program:


The basic structure of C program comprises of three components.
1) Preprocessor directives 2) Main function header 3) Body of the program

#include<…> (Header files)


#include<…>
void main(void) (Function name)
{ (Start of function)
statement 1; (Function body)
statement 1;
………….
} (End of function)

Example:
#include <stdio.h> // Header files

// Global Declaration
int globalVar = 10;

// Function Prototype (Declaration)


void display();

// Main Function
int main() {
int localVar = 5; // Variable declaration
printf("Hello, World!\n");
display(); // Function call
return 0;
}

// User-defined Function
void display() {
printf("This is a user-defined function.\n");
}

Block of a C program:
Block Description
1. Preprocessor Directives #include<stdio.h> – Includes libraries for built-in functions.
2. Global Declarations Global variables/constants declared before main().
3. Function Declaration Declares user-defined functions before defining them.
4. main () Function The starting point of execution.
5. Variable Declaration Declares variables inside main() or functions.
6. Statements & Expressions Logical and arithmetic operations inside functions.
7. User-Defined Functions Functions created by the user for modular programming.

Explanation of Each Block


1. Preprocessor Directives (#include<stdio.h>)
o These include header files for input/output functions like printf () and scanf ().
2. Global Declarations
o Variables or constants declared outside functions, accessible throughout the program.
3. Function Declaration
o Function prototypes are declared before their actual definition.
4. Main () Function
o The execution of a C program begins from main ().
5. Variable Declaration
o Variables are declared before use inside main () or functions.
6. Statements & Expressions
o The actual logic of the program is written inside functions.
7. User-Defined Functions
o Functions created to divide the program into smaller, reusable parts.

Why C is case sensitive language:


C is called case-sensitive language because it treats uppercase and lowercase letters as different. This
means that identifiers keywords, and variable names must be used with consistent capitalization.
Example:
#include <stdio.h)
Int main ()
{
Int num=10
Print (“%d”, num);
Print f (“%d”, NUM);
Return 0;
}
Here, num and NUM are treated as different identifiers.

C preprocessor directives:
Preprocessor directives ate actually the instructions to the compiler itself. They are not translated but are
operated directly by the compiler. Note that preprocessor statements begin with a #symbol, and are not
terminated by a semicolon. Traditionally preprocessor statements are listed at the beginning of the source
file. They are also termed as macros.
The most common preprocessor directives are:
1) Include directives 2) Define directives

1) Include directives:
The include directive is used to include files. Like as we include header files in the beginning of the program
using #include directive e.g.
#include<stdio.h> #include<conio.h>

i)include<stdio.h>:
The #include<stdio.h> directive in C library is used to include the standard output library. Which provides
function like printf () and scanf () for input and output operations.

ii)#include<conio.h>:
The #include <conio.h> header file in C (short for Console Input/Output) is used to handle console-related
functions like clearing the screen, getting character input without pressing Enter, and more.

2) Define directives:
It is used to assign names to different constants or statements which are to be used repeatedly in a
program. These defined values or statement can be used by main or in the user defined functions as well.

i) Defining a constant:
For example,
#define PI3.1415687
#define g9.8

i) Defining a statement:
For example,
#define TRUE 1
i) Defining a mathematical expression:
For example,
#define floatingpointno float

Main () function in C program:


The main () function is the entry point of a C program where execution starts. It controls the program flow
and return value to the operating system.
Example:
#include <stdio.h>
Int main () {
Printf (“Hello, world!”);
Return 0;
}

Opening and ending delimiter or braces and source code:

1. Opening and Ending Delimiters (Braces {}) in C


In C programming, curly braces {} are used to define the beginning and end of a block of code. They are
used in functions, loops, conditional statements, and structures.
Opening Brace: {→ Marks the start of a code block.
Closing Brace: } → Marks the end of a code block.
Example:
#include <stdio.h>

int main() { // Opening brace


printf("Hello, World!\n");
return 0;
} // Closing brace
Here, the {} define the boundaries of the main() function.

2. Source Code in C
Source Code is the set of instructions written by the programmer in a file with a .c extension before
compilation.
It is written in human-readable form using C syntax.
It needs to be compiled into machine code using a C compiler (e.g., GCC, Turbo C).
Example:
#include <stdio.h>

void greet () {
printf ("Hello, Welcome! \n");
}

int main () {
greet (); // Calling user-defined function
return 0;
}
Here, the source code contains:
• A preprocessor directive (#include <stdio.h>)
• A function definition (greet ())
• The main function (main ())
• Curly braces {} to define function bodies.

Topic 8: Control Structures


Selection/Decision making structures (If, If-else, else-if, and switch -case with
syntax. Iterative structures (For, While, Do-while with syntax)

Iterative control structures:


Iteration is often referred to as a loop, because the program will keep repeating the activity until the
condition becomes false. Loops simplify programming because they enable the programmer to specify
certain instructions only once to have the computer execute them many times. C provides following three
types of iteration structures.
1) For loop 2) While loop 3) Do-while loop

1) The For loop:


A “For” loop is used to repeat a specific block of code a known number of times. OR
A for loop in C is a control structure that allows repeating a block of code multiple times based on a
condition. It is commonly used when the number of iterations is known in advance.
Syntax of for Loop:
for(initialization; condition; update) {
// Code to be executed
}
Initialization → Initializes a loop control variable.
Condition → The loop runs as long as this condition is true.
Update → Changes the loop variable after each iteration.

Advantages of for Loop:


Compact & Easy to Read – Combines initialization, condition, and update in one line.
Efficient Execution – Used when the number of iterations is known.
Less Error-Prone – Reduces the chances of missing an update statement.

Flowchart of for loop:

Initialization

Test No
Condition
?

Yes

Statement(s)
Increment/
Decrement
Flowchart format of for loop
2) The While loop:
The while loop is used to repeat a section of code an unknown number of times until a specific condition is
met. OR
A while loop in C is a pre-tested loop that allows a block of code to execute repeatedly as long as the given
condition remains true.
Syntax of while loop:
while(condition) {
// Code to be executed
}
Condition → The loop runs as long as this condition is true.
Body → The block of code inside {} executes repeatedly.
Update Statement → The loop variable must be updated inside the loop; otherwise, it may become an
infinite loop.

Advantages of while Loop:


Used when the number of iterations is unknown before execution.
More flexible than for loop – can use multiple conditions.
Avoids unnecessary iterations, as the condition is checked before execution.

Flowchart of while loop:

Test No
Condition
?

Yes

Statement(s)

Flowchart format of while loop

3) The Do while loop:


A do- while loop is a control flow statement that executes a block of code at least once, and then either
repeatedly executes the block, or stops executing it, depending on a given Boolean and condition at the
end of the block. Do-while loop verifies the condition after the execution of the statements inside the loop.
OR A do-while loop in C is an exit-controlled loop, meaning that the loop body executes at least once,
even if the condition is false. Unlike the while loop, which checks the condition before execution, the do-
while loop checks the condition after execution.

Syntax for the do-while loop:


do {
// Code to be executed
} while(condition);

do Block → Executes the code at least once.


Condition → If true, the loop continues; if false, the loop stops.

Advantages of do-while Loop:


Ensures execution at least once, even if the condition is false.
Useful when the first iteration does not depend on a condition.
Often used in menu-driven programs and input validation.

Flowchart of do-while loop:

Statement(s)

Test Yes
Condition
?

No

Flowchart format of do-while loop

Difference between while and do while loop:


While loop Do-while loop
No semi-colon is used. Semi-colon is used.
It is also known as an entry -controlled loop. It is also known as an exit-controlled loop.
In “while” loop the controlling condition appears at In “do-while” loop the controlling condition
the start of the loop. appears at the end of the loop.
While (condition) {statements; // body of loop}. Do {statements; // body of loop.} while (condition);

Difference between for loop and while loop:


For loop While loop
Iterates for a preset number of times. Iterates till a condition is met.
Used to obtain the result only when the number of Used to obtain the result only when the number of
iterations is known. iterations is known.
Structure of for loop is – for (initial condition; Structure of while loop is while (condition)
number of iterations) {// body of the loop}. {statements; // body}

Selection/Decision making structures (If, If-else, else-if, and switch -case with syntax):
In C programming, selection (or decision-making) statements allow the program to execute different code
blocks based on certain conditions. These statements control the flow of execution and decide which
statements should be executed.
There are three types of decision-making structures in C:
“If statement, “If-else” statement, “else-if” statement “switch case” statement

1) If Statement:
The if statement test a particular condition. Whenever that condition evaluates as true, an action is
performed-but if it is not true. Then the action is skipped and control transfer to the next step of the
program.
Syntax:
if(condition) {
statements; // Code to execute if the condition is true
}

Flowchart:

Test No
Condition
?

Yes

Statement(s)

If statement Flowchart

2) If-else statement:
The if selection structures perform an indicated action only when the condition is true, otherwise the
action is skipped. Whereas, if-else selection structure performs certain action when the condition is true
and some different action when the condition is false.
Syntax:
if(condition) {
statements;// Code to execute if the condition is true
} else {
Statements; // Code to execute if the condition is false
}
Flowchart:

Test No
Condition
?

Yes
Statement 2

Statement 1

If-else statement Flowchart

3) else-if statement:
When multiple conditions need to be checked one by one, we use the else if ladder.
Syntax:
if(condition1) {
Statement 1; // Code to execute if condition1 is true
} else if(condition2) {
Statement 2; // Code to execute if condition2 is true
} else if(condition3) {
Statement 3; // Code to execute if condition3 is true
} else {
Statement 4; // Code to execute if none of the conditions are true
}
4) Switch Case statement:
The switch-case statement is used when a variable needs to be compared with multiple values. Instead of
using multiple if-else conditions, we can use switch-case, which makes the code more readable.
Syntax:
switch(expression) {
case value1:
statement; // Code to execute if expression == value1
break;
case value2:
statement; // Code to execute if expression == value2
break;
case value3:
statement; // Code to execute if expression == value3
break;
default:
statement; // Code to execute if none of the cases match
}
Flowchart:

Yes
Case Case 1 statement break
1

Yes
Case Case 2 statement break
2

Yes
Case Case n statement break
n

Default statement

Difference between if and if-else statement:


If statement If-else statement
Executes a block of code only if the condition is Executes one block if the condition is true, and
true. another if it is false.
No alternative; if the condition is false, nothing Provides an alternative execution path when the
happens. condition is false.
Simple and direct. Slightly more complex due to the else block.

Difference between if else and switch statement:


If-else statement Switch statement
Becomes complex when there are many else-if More readable and structured for multiple
conditions. conditions.
Best for range-based or logical conditions. Best for menu-based or fixed value comparisons.
Works with all data types (int, float, char, string, Works only with integer and character values.
etc.).

Topic 9: Arrays and string


Array declaration, Initialization, 2D array string and few of strings like gets(),
getc(), puts(), putc(), strlen(), strey(), stremp(), streat(), (with syntax)

Arrays:
An array is a collection of variables of the same type that are collectively referred to by the common name.
In C all arrays are stores respectively in successive or memory locations. We can manipulate array data
type collectively or individually depending on the requirements of each particular application. An individua
variable in the array is called an array element. OR
In C, arrays are fundamental data structures used to store and manipulate collections of elements.

Types of arrays:
One-Dimensional Arrays (Linear array)
Two-Dimensional Arrays (Matrix) (2D arrays)
Multi-Dimensional Arrays (Higher-order arrays) (3D or 4D array)

1) One dimensional Arrays:


A one-dimensional array stores a sequence of elements of the same type.
Syntax:
data_type array_ name[size];

2) Two dimensional Arrays: (2D Arrays)


A two-dimensional array is an array of arrays, useful for storing tables or matrices.
Syntax:
data_type array_ name[rows][columns];

3) Multi-Dimensional Arrays: (3D or 4D array)


A multi-dimensional array is an extension of a two-dimensional array that can store data in multiple
dimensions (3D, 4D, etc.).
Syntax:
data_type array_ name[size1][size2][size3]...[sizeN];

Uses of 2D arrays:
Used in mathematical matrices and graphs.
Helpful in storing tables, spreadsheets, and images (pixels).
Widely used in games for grids (chessboard, tic-tac-toe).

Declaration of variable:
Declaration of more than one array can be made in one statement as given below. OR
An array in C is a collection of elements of the same data type, stored in contiguous memory locations.
Int temps [5], index [7];
Float fact, m, total;
Syntax:
data_type array_ name[size];

data_type → Type of data (int, float, char, etc.).


array_ name → Name of the array.
size → Number of elements in the array

Array initialisation:
Array initialization means assigning values to an array at the time of declaration or later in the program.
We can initialize a simple variable when we declare it as:
Int total =0;
Like this we can also initialise an array at the time of its declaration. Let temps is one-dimensional int array
having 5 elements, can be declared and initialized as:
Int temps [5] = {53, 85,29,19,63};
Syntax:
data_type array_ name[size] = {value1, value2, value3, ...};

data_type → Type of elements (int, float, char, etc.)


array_name → Name of the array
size → Number of elements
Values are enclosed in {} brackets

Definition of String in C
A string in C is a sequence of characters stored in a character array, ending with a null character (\0) to
indicate the end of the string. Unlike other programming languages, C does not have a built-in string data
type, so strings are managed using character arrays. The null character (\0) helps differentiate a string from
a regular character array. Strings are commonly used for storing and manipulating text in C programs.

2D arrays for string:


In C, a two-dimensional character array (2D array) is used to store multiple strings (an array of strings).
Each row stores a single string, and columns store the characters of that string.
Syntax:
char array_ name[rows][columns];

Strings gets(), getc(), puts(), putc(), strlen(), strcpy(), strmcp(), strcat(), (with
syntax) :

Gets ():
Reads a full string (including spaces) from standard input, but it's unsafe due to buffer overflow risks.
Syntax:
gets(str);

Puts ():
Prints a string to standard output and automatically adds a newline (\n).
Syntax:
puts(str);

Putc ():
Prints a single character to output (useful for file handling).
Syntax:
putc(ch, stdout);

Strlen ():
Returns the length of a string, excluding the null terminator \0.
Syntax:
strlen(str);
Strcpy ():
Copies the contents of one string (src) to another (dest).
Syntax:
strcpy(dest, src;

Strcmp ():
Compares two strings and returns 0 if equal, <0 if str1 is smaller, and >0 if str1 is greater.
Syntax:
strcmp(str1, str2);

Strcat ():
Appends (concatenates) src to the end of dest, modifying dest.
Syntax:
strcat(dest, src);

Getc ():
Reads a single character from input (can be used for file handling).
Syntax:
getc(stdin);

You might also like