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

CSE Theoretical QS D.note by 2201121

This document is a compilation of important theoretical questions and concepts related to the C programming language, created for exam preparation. It covers topics such as middle-level languages, unary operators, decision-making, dynamic memory allocation, and the differences between various data types and functions in C. Additionally, it discusses the merits and demerits of arrays, file operations, and the structure of computer systems.

Uploaded by

sahadatmahi2021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views21 pages

CSE Theoretical QS D.note by 2201121

This document is a compilation of important theoretical questions and concepts related to the C programming language, created for exam preparation. It covers topics such as middle-level languages, unary operators, decision-making, dynamic memory allocation, and the differences between various data types and functions in C. Additionally, it discusses the merits and demerits of arrays, file operations, and the structure of computer systems.

Uploaded by

sahadatmahi2021
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
You are on page 1/ 21

Hey, its me again!!

This PDF contains all (or most) theoretical


questions I found important for our exam. I
made this in a rush during exam, so there
might quite a few mistakes

It is suggested that U add more questions


and revise it 2-3 times before your exam

Created by:
Mahathir Mohammad Siam
2201121

Caution : Most of these answers are AI generated. AI tool


used include Claude, Gemini, ChatGPT and Copilot. Other
sources: Web, slides, books.
C IS A MIDDLE LEVEL LANGUAGE
Middle level language generally refers to programming languages that exhibit
characteristics of both high-level and low-level languages. C is often classified as a
middle-level language due to its ability to perform low-level manipulation of
system components, such as memory addresses and hardware interfaces, while
also providing high-level abstractions like functions, data structures, and control
flow constructs.

High-level language features:


• Portable: C code can be easily adapted to run on different computer
systems with minimal changes. This is unlike low-level languages that are
specific to a particular machine's architecture.
• Structured: C has well-defined control flow structures like loops and
conditionals, making code easier to read and maintain compared to
machine code.
• Functions: C supports modular programming through functions, allowing
for code reuse and better organization.
Low-level language features:
• Memory access: C allows direct access to memory through pointers, giving
programmers finer control over data manipulation. This is similar to
assembly language, where memory addresses are explicitly used.
• Bit manipulation: C provides operators for working with individual
bits, essential for low-level hardware interaction and hardware-specific
optimizations.
• Inline assembly: Inline assembly in C lets us include assembly code within
our C code for tasks needing direct hardware control or machine-specific
commands.
UNARY OPERATOR
These are the type of operators that act upon just a single operand to produce a
new value. All the unary operators have equal precedence, and their associativity
is from right to left. When we combine the unary operator with an operand, we
get the unary expression.

There are following types of unary operators found in the C language:


• unary minus (-)
• unary plus (+)
• decrement (- -)
• increment (++)
• NOT (!)
• sizeof ()
• Address of operator (&)

DECISION MAKING IN C

In C programming, decision-making refers to the ability to control the flow of


program based on certain conditions. This is achieved through special statements
called conditional statements. They allow programs to choose different paths or
execute different blocks of code depending on whether a particular condition is
true or false.
If statement: Allow us to execute a block of code when a specified condition is
true. Optionally, we can use a else statement to execute a different block of code
if the condition is false.
if-else-if ladder: To check multiple conditions we can use if-else-if ladder.
Switch statement: The switch statement allows us to choose between multiple
code blocks based on the value of a single expression. It works like a series of if-
else statements but is often more concise and clearer. It is useful when we have
several possible cases to consider.
Ternary operators: Can be used as a replacement for if-else statement.
Goto-Statement: Go-To statements are jump statements that allow us to
unconditionally transfer control to a specific location.

DYNAMIC MEMORY ALLOCATION


1. Allows a program to request and use memory at runtime rather than at
compile time.
2. Rather than having a fixed size it helps to make code more versatile.
3. It is useful when the size of data structures is unknown during execution
time.
4. It helps to use memory more efficiently.
5. The key functions for Dynamic Memory Allocation in c are calloc(), malloc(),
realloc(), free.
6. Provides flexibility but needs to manage carefully to avoid issues like
memory leaks, accessing invalid memory.

VOID DATA TYPE


In C, the void keyword is used in various contexts to denote the absence of a
specific type or to indicate that a function does not return a value.

1.Function Return Type: When used as the return type of a function, void
indicates that the function does not return any value. It is commonly used for
functions that perform a task without producing a result.
2. Pointer Declaration: It is often used in situations where the type of data being
pointed to is not known at compile time.
3. Function Parameters: In a function declaration, using void as a parameter
indicates that the function takes no parameters.
FORMAL AND ACTUAL PARAMETER/ARGUMENT
1. Actual Parameters/Arguments:
• Actual parameters are the values or expressions supplied in a
function call.
• These are the arguments passed to a function when it is called.
• They are placed within the parentheses of the function call and
correspond to the formal parameters defined in the function
declaration or definition.
2. Formal Parameters/Parameter:
• Formal parameters are the variables declared in the function
declaration or definition.
• They act as placeholders for the values that will be passed to the
function when it is called.
• Formal parameters are used within the function to process the values
received from the actual parameters.

PURPOSE OF USING NULL CHARACTER IN STRING

In C, strings are represented as arrays of characters, and they are terminated by a


special character called the null character ('\0'). The null character serves several
important purposes in C strings:
String Termination: The null character marks the end of a string. When C
functions process strings, they rely on the presence of the null character to
determine the end of the string. This allows functions to operate on strings
without requiring additional length information.
String Functions: Standard C string manipulation functions, such as strlen, strcpy,
strcat, etc., use the null character to determine the length of a string and to
identify the end of the string when performing operations. These functions
continue processing characters until they encounter the null character.
String Initialization:
String Input and Output: Functions like printf and scanf use the null character to
determine the end of a string when printing or reading strings.
String Comparison: Functions like strcmp use the null character to compare
strings. The comparison stops when the null character is encountered.

MALLOC:
The malloc function allocates a block of memory of the specified size in bytes. It
does not initialize the allocated memory. The content of the memory block
allocated by malloc is indeterminate (contains garbage values) until explicitly set
by the program. It takes a single argument specifying the number of bytes to
allocate.

CALLOC:
The calloc function also allocates a block of memory, but it initializes the memory
to zero. It takes two arguments: the number of elements to allocate and the size
of each element in bytes. It initializes each element to zero. Because calloc
initializes the memory, it may be slightly slower than malloc for large memory
allocations, especially if the memory needs to be zero-initialized.

In summary, the key difference is that malloc allocates uninitialized memory, while
calloc allocates and initializes memory to zero. This difference may influence the
choice between the two functions depending on the specific requirements of your
program.
RECURSIVE VS NORMAL

• Recursion involves a function calling itself directly or indirectly, while


ordinary functions do not.
• Recursive functions can be used to solve problems that have a recursive
structure, while ordinary functions cannot.
• Recursive functions can be more concise and elegant than ordinary
functions, but they can also be more difficult to understand and debug.
• Recursive functions can be inefficient if they are not written carefully, while
ordinary functions are typically more efficient.

MERITS AND DEMERITS OF ARRAY IN C


Merits (Advantages) of Arrays in C:
1. Efficient Access: Arrays allow for direct access to elements using their index,
providing fast and efficient retrieval of data. This is particularly
advantageous in scenarios where quick access to elements is necessary.
2. Memory Efficiency: Arrays in C have a fixed size and store elements of the
same data type, leading to memory efficiency. Since elements are stored in
contiguous memory locations, there is minimal overhead, unlike some
other data structures.
3. Ease of Use: Arrays are straightforward to declare and manipulate in C. They
are supported by the language's syntax and built-in operations, making
them easy to work with for programmers.
4. Predictable Performance: Accessing elements in an array by its index takes
constant time because the compiler can directly calculate the memory
location of the element based on its index using pointer arithmetic.
5. Compatibility: Arrays are widely used and supported in C programming,
making them compatible with various libraries and frameworks.
6. Multidimensional Arrays: C supports multidimensional arrays, enabling the
representation of complex data structures like matrices and grids.

Demerits (Disadvantages) of Arrays in C:


1. Fixed Size: Arrays in C have a fixed size, which must be specified at compile
time. This limitation makes it challenging to handle situations where the
size of the data set may vary dynamically during runtime.
2. No Bounds Checking: C arrays do not perform bounds checking by default.
Accessing elements outside the bounds of the array can lead to buffer
overflows and other memory-related errors, potentially causing security
vulnerabilities or program crashes.
3. No Dynamic Resizing: C arrays cannot be resized dynamically. If more space
is needed than initially allocated, a new array must be created with a larger
size, and elements must be copied over. This process can be inefficient.
4. Homogeneous Data Types: Arrays in C require all elements to be of the
same data type. This restriction can be limiting in scenarios where
heterogeneous data needs to be stored or when working with complex data
structures.
5. No Built-in Methods: Unlike some higher-level languages, C does not
provide built-in methods or functions for common array operations such as
sorting, searching, or resizing. Programmers must implement these
functionalities manually or use external libraries.
Difference between 'a' and ''a'' ? Explain their size?
• 'a' (single quotes): This represents a single character literal of type char. Its
size is 1 byte in most encodings like ASCII or UTF-8. It holds the numerical
value corresponding to the character 'a' (usually 97).
• "a" (double quotes): This represents a string literal. It's an array of
characters, including the 'a' and a null terminator ('\0'). Its size is 2 bytes, 1
for the character and 1 for the null terminator.

FILE
• The operations using the C program are done on a prompt/terminal which
is not stored anywhere.
• The output is deleted when the program is closed.
• However, the output may require to be stored. That’s why File is needed in
C.
NECESSITY
Reusability: The data stored in the file can be accessed, updated, and deleted
anywhere and anytime providing high reusability.
Portability: Without losing any data, files can be transferred to another computer
system

Draw a block diagram of a computer and explain the function of each block
Explanation of each block:
1. Input Devices: These devices allow users to provide data and instructions to
the computer. Examples include
keyboards, mice, touchpads, scanners, webcams, microphones, etc. They
convert user input into digital signals that the computer can understand.
2. CPU (Central Processing Unit): This is considered the "brain" of the
computer responsible for processing data and instructions. It consists -of
three main components:
o Control Unit: Decodes instructions, manages the flow of data, and
controls other components.
o Arithmetic Logic Unit (ALU): Performs arithmetic and logical
operations on data.
o Registers: Temporary storage locations for data and instructions being
processed.
3. Memory: Stores data and instructions that the CPU needs to access
quickly. It has two main types:
o RAM (Random Access Memory): Volatile memory used for temporary
storage. Data is lost when the computer is turned off.
o ROM (Read-Only Memory): Non-volatile memory used for storing
permanent instructions and data (e.g., BIOS).
4. Output Devices: These devices display or output processed data and
information to the user. Examples include
monitors, printers, speakers, projectors, etc. They convert digital signals
from the computer into human-readable formats.
The storage unit of a computer refers to the components where data and
instructions are stored for processing by the computer's CPU (Central Processing
Unit). There are two main types of storage in a computer system: primary storage
and secondary storage.
1. Primary Storage:
• Definition: Primary storage, also known as main memory or RAM
(Random Access Memory)

2. Secondary Storage:
• Definition: Secondary storage refers to non-volatile memory devices used
for long-term storage of data, programs, and other files.

1. Volatility:
• Primary storage is volatile, meaning data is lost when the power is
turned off.
• Secondary storage is non-volatile, meaning data remains intact even
when the power is turned off.
2. Speed:
• Primary storage provides faster access times compared to secondary
storage, allowing for quick retrieval of data.
• Secondary storage typically has slower access times compared to
primary storage due to the nature of the storage medium.
3. Accessibility:
• Primary storage is directly accessible by the CPU and is used for
actively running programs and processing data.
• Secondary storage is used for long-term storage and is accessed as
needed to load data into primary storage for processing.
4. Capacity:
• Primary storage generally has limited capacity due to its high-speed,
expensive nature.
• Secondary storage devices typically offer larger storage capacities
compared to primary storage, making them suitable for storing large
amounts of data and files.

To increment the value of a, which statement a++ or a = a + 1 is preferable and

A++
• This is a post-increment operator. It increments the value of a by 1, but it
returns the original value of a before the increment.
• a++ is generally preferred when we want to increment the value of a and
also use its original value in an expression.
A=A+1
• This is an assignment statement. It explicitly assigns the value of a + 1 back
to a.
• a = a + 1 is more explicit and might be preferred when clarity or readability
is more important than brevity
In general, a++ is more concise and idiomatic, especially when you only need to
increment the value of a without using its original value in an expression.
However, if you need to use the original value of a in an expression or if you
prioritize clarity and readability, a = a + 1 might be preferred. Ultimately, the
choice between them depends on the specific context and coding style
preferences.
TOKENS
In C programming, a token is the smallest unit of a program that is meaningful to
the compiler. When the compiler processes a C program, it breaks it down into
individual tokens for further analysis and interpretation. Tokens are classified into
several categories based on their types and roles within the program. Here are the
main types of tokens in C programming:
1. Keywords: Keywords are reserved words that have special meanings in the
C language. They cannot be used as identifiers (variable names or function
names) and are used to define the syntax and structure of C programs.
Examples include int, char, if, else, for, while, return, etc.
2. Identifiers: Identifiers are names given to variables, functions, arrays, and
other user-defined entities in a C program. An identifier must begin with a
letter (either uppercase or lowercase) or an underscore (_) and can be
followed by letters, digits, or underscores. Identifiers are case-sensitive.
Examples include count, totalAmount, MAX_SIZE, etc.
3. Constants: Constants are fixed values that do not change during the
execution of a program. There are several types of constants in C
programming:
• Integer Constants: These are whole numbers without decimal points,
such as 10, -5, 0xFF (hexadecimal), etc.
• Floating-point Constants: These are real numbers with decimal
points, such as 3.14, -0.5, 1.0e6 (scientific notation), etc.
• Character Constants: These are single characters enclosed in single
quotes, such as 'a', '5', '\n' (newline), etc.
• String Constants: These are sequences of characters enclosed in
double quotes, such as "Hello", "C programming", "123", etc.
4. Operators: Operators are symbols used to perform operations on operands.
They include arithmetic operators (+, -, *, /, %), relational operators (==, !=,
<, >, <=, >=), logical operators (&&, ||, !), assignment operators (=, +=, -=,
*=, /=, %=), bitwise operators (&, |, ^, ~, <<, >>), etc.
5. Punctuators: Punctuators are special symbols used to structure and
punctuate C programs. They include braces {}, parentheses (), brackets [],
commas ,, semicolons ;, periods ., etc.
6. Preprocessor Directives: Preprocessor directives are special instructions
that begin with a hash (#) symbol and are processed by the preprocessor
before compilation. They are used to include header files (#include), define
macros (#define), perform conditional compilation (#ifdef, #ifndef, #if,
#else, #endif), etc.

LOOP CONTROL STATEMENTS


Break: In C programming, break is used to exit a loop prematurely. When
encountered, it immediately terminates the loop in which it is placed and
execution resumes at the next statement after the loop.
Continue: continue is also used in loops. When encountered, it skips the rest of
the loop's body for the current iteration and proceeds to the next iteration.
Goto: Go-To statements are jump statements that allow us to unconditionally
transfer control to a specific location. It is often discouraged because it makes
difficult to trace the flow of a program.

FUNCTION PROTOTYPE
Function prototypes in C programming serve as declarations that describe the
interface of a function before its actual implementation. They provide the
compiler with essential information about the function, including its name, return
type, and parameters. Function prototypes typically appear at the beginning of a C
source file or in a header file.
• Type checking: The compiler uses function prototypes to ensure that
function calls are made correctly, matching the expected parameter types
and return type. This helps prevent errors and makes code more accurate.
• Modular programming: Function prototypes allow you to define functions
in separate files, promoting modularity and reusability of code.
• Code organization: Prototypes act as documentation, clarifying what each
function does and how to use it. This improves code readability and
maintainability.

Difference between C and C++:


• C is a procedural programming language, while C++ is an object-oriented
programming language.
• C does not support classes and objects, whereas C++ does.
• C++ supports features like inheritance, polymorphism, encapsulation, and
abstraction, which are not present in C.
• C++ has additional features such as templates, exception handling, and
Standard Template Library (STL) compared to C.
• C++ allows function overloading and operator overloading, which are not
supported in C.
Advantages of C++ over C language:
• Object-oriented programming support, leading to better code organization
and reusability.
• Features like classes, inheritance, and polymorphism allow for more robust
and flexible code design.
• Support for function and operator overloading simplifies code and
enhances readability.
• C++ has additional features such as templates, exception handling which
improves productivity.
Features of C++ as an object-oriented programming language:
• Encapsulation
• Inheritance
• Polymorphism
• Abstraction
• Classes and objects
• Message passing

Classes and objects –


• A class is a blueprint or template for creating objects. It defines the
properties (attributes) and behaviors (methods) common to all objects of
that type.
• Any class type variable is called objects. An object is an instance of a class. It
represents a specific entity with its own state (data) and behavior
(methods), created based on the class definition.

✓ Encapsulation: Bundles data and methods, protecting data and promoting


modularity.
✓ Inheritance: Reuses code by creating new classes (subclasses) that inherit
from existing ones (base classes).
✓ Polymorphism: Objects respond differently to the same message, enabling
flexibility and dynamic behavior.
✓ Abstraction: Focuses on essential aspects, hiding implementation details for
easier use.
✓ Templates: Write generic code that works with various data types,
increasing reusability.

SCOPE
In C programming, scope refers to the region of a program where a particular
identifier (such as a variable or function) is visible and accessible.
Local Variables: Variables that are declared inside a function are called local
variables to that function. Don’t have effect outside of that function.
• Scope: Limited to the block in which they are declared
• Lifetime: Exists only during the execution of the block in which it is
declared. It's created when the block is entered and destroyed when the
block is exited.
Global Variables: Global variables are defined outside of a function, usually on
top of the program. Global variables can be accessed from any function after its
declaration.

• Scope: Accessible from any part of the program.


• Lifetime: Exists throughout the entire execution of the program.

Static Variables: Preserve their values even after they are out of their scope.
A static variable remains in memory while the program is running.

FUNCTION CALL
Call by Value:
• In call by value, a copy of the argument's value is passed to the function.
• Any changes made to the parameter inside the function are local to that
function and do not affect the original value of the argument outside the
function.
• Call by value is the default behavior in C for passing arguments to functions.

Call by Reference :
• In call by reference (simulated in C), a pointer to the memory location of the
argument is passed to the function.
• This allows the function to modify the original value of the argument
directly.
• It is needed to declare the function parameters as pointer types.

Function Declaration/Function prototype:


• A function declaration tells the compiler about a function's name, return
type, and parameters. It provides a prototype for the function. It typically
appears at the beginning of a program or in a header file.
• It doesn't provide the body of the function (the actual code
implementation). It only tells the compiler that the function exists and
describes its interface.
• A function declaration ends with a semicolon (;)

Function Definition:
• A function definition includes the actual implementation of the function. It
provides the body of the function, containing the statements that define
what the function does.
• It includes the function's return type, name, parameters, and the code
block enclosed within curly braces {}.
• Function definitions can appear either before or after their use in the
program.
• A function definition does not end with a semicolon.

One of the major issues with gets() is that it doesn't check the size of the buffer
into which it is reading. This can lead to buffer overflow vulnerabilities if the input
exceeds the size of the buffer.

• gets():
o Reads input until it encounters a newline character (\n) or end-of-file
(EOF).
o Includes whitespace in the input string.
o Only reads strings, not other data types.
• scanf():
o Reads input based on format specifiers (e.g., %d for integers, %s for
strings).
o Stops reading at whitespace, newline, or specific format specifier
limitations.
o Can read various data types (numbers, characters, strings).
An infinite loop is a loop in a computer program that continues indefinitely
because its terminating condition is never met. In other words, the loop keeps
executing its body repeatedly without ever stopping, leading to the program
becoming unresponsive or consuming excessive system resources.
Infinite loops are not inherently harmful for programming, as they can be
intentionally used in certain scenarios where continuous execution is desired,
such as:
1. Server applications: Servers often need to run continuously, waiting for
incoming requests. A server may use an infinite loop to continuously listen
for and process incoming requests.
2. Embedded systems
However, infinite loops can become problematic if they are unintentional or if
they consume excessive system resources without accomplishing anything useful.
They can lead to:
• Program freeze: If an infinite loop occurs unintentionally, it can cause the
program to become unresponsive, requiring the user to forcefully terminate
it.
• Resource consumption: Infinite loops can consume CPU resources
continuously, leading to high CPU usage and potentially slowing down the
entire system.

Structure:
• Each member of a structure has a separate memory location. This means
wecan store and access different values for each member independently.
• The size of a structure is equal to the sum of the sizes of its individual
members.
• Structures are well-suited for representing collections of related
data where each piece of data needs its own space.
Union:
• All members of a union share the same memory location. This means only
one member can hold a value at any given time.
• The size of a union is equal to the size of its largest member.
• Unions are primarily used for memory efficiency when we know we will
only need one of the member values at a time.

getch():
• This function is commonly used to read a single character from the console
without echoing it back to the screen.
getche():
• Similar to getch(), getche() reads a single character from the console, but it
echoes the character back to the screen.
Unlike getch() and getche(), getchar() waits for the user to press Enter before
reading the character.
fabs():
• It can be used to get the magnitude of a floating-point value irrespective of
its sign.
Constructors:
• Purpose: Initialize objects when created (set values, allocate memory).
• Key points: Same name as class, no return type, can be overloaded.
Destructors:
• Purpose: Clean up resources when objects are destroyed (release memory,
close files).
• Key points: Same name as class with tilde (~), no return type or arguments

You might also like