//Find GCD and LCM of two numbers given by the Read & Write int value Dinamic Memory
Read & Write int value Dinamic Memory Allocation:
user using recursion #include <stdio.h>
#include<stdio.h> #include <stdlib.h>
int GCD(int, int); int main() {
int main() int n;
{ int *arr;
int num1, num2, result_gcd; printf("Enter the number of integers: ");
printf("Enter first number : "); scanf("%d", &n);
scanf("%d", &num1); arr = (int *)malloc(n * sizeof(int));
printf("Enter second number : "); if (arr == NULL) {
scanf("%d", &num2); printf("Memory allocation failed. Exiting...\n");
result_gcd = GCD(num1, num2); return 1;
printf("GCD of %d and %d is %d\n", num1, num2, }
result_gcd); printf("Enter %d integers:\n", n);
return 0; for (int i = 0; i < n; i++) {
} scanf("%d", &arr[i]);
}
int GCD(int x, int y) printf("Entered integers are:\n");
{ for (int i = 0; i < n; i++) {
int rem; printf("%d ", arr[i]);
rem = x % y; }
if(rem == 0) printf("\n");
{ free(arr);
return y; return 0;
} }
else
{ What is an array?
return(GCD(y, rem)); An array is a data structure that stores elements of
} the same type in contiguous memory locations. It
} has a fixed size, and each element is accessed using
an index or subscript. Arrays are commonly used for
Pointer Function :- organizing and managing collections of data in
A pointer to a function is a variable that holds the programming.
memory address of a function in computer
programming. Instead of storing data, it stores the Find Reverse of a String :-
location in memory where a function is stored. This #include <stdio.h>
allows for dynamic function invocation and enables #include <string.h>
the flexibility to choose and execute different int main() {
//Cheak the year leap year or not
functions during runtime. Pointers to functions are char inputString[100];
#include<stdio.h>
commonly used for implementing callbacks, function printf("Enter a string: ");
int main()
tables, and achieving polymorphic behavior in fgets(inputString, sizeof(inputString), stdin);
{
programming languages that support them. int length = strlen(inputString) - 1;
int year;
for (int i = 0; i < length / 2; i++) {
printf("Enter the year to cheak leap year or not :
One Dimentional array using pointer :- char temp = inputString[i];
");
#include <stdio.h> inputString[i] = inputString[length - 1 - i];
scanf("%d", &year);
int main() { inputString[length - 1 - i] = temp;
int arr[5] = {10, 20, 30, 40, 50}; }
if(((year % 4) == 0 && (year % 100) != 0) || ((year
int *ptr = arr; printf("Reversed string: %s\n", inputString);
% 400) == 0))
printf("Accessing array elements using return 0;
{
pointers:\n"); }
printf("The year is leap year");
for (int i = 0; i < 5; i++) {
}
printf("Value at arr[%d] = %d\n", i, *ptr); *State advantages of an array*
else
ptr++; 1. Sequential and Random Access: Arrays allow both
{
} sequential and direct access to elements.
printf("The year is not leap year");
return 0; 2. Memory Efficiency:Fixed-size allocation leads to
}
} predictable memory usage and avoids
return 0;
fragmentation.
}
Write a program in C to check whether a number is 3. Simplicity: Arrays are easy to declare, use, and
divisible by 5 and 11 or not: understand.
Difference between Compiler and Interpreter:
#include <stdio.h> 4. Ease of Manipulation: Facilitates various
### Interpreter:
int main() { operations like sorting and searching.
- *Translation:* Translates code line-by-line during
int number; 5. Compact Code: Enables concise and readable code
runtime.
printf("Enter a number: "); through loop iterations.
- *Execution:* Executes code immediately without
scanf("%d", &number); 6. Compatibility with Algorithms: Suited for
creating a separate executable file.
if (number % 5 == 0 && number % 11 == 0) { implementing algorithms, especially in numerical
- *Speed:* Generally slower due to interpreting code
printf("%d is divisible by both 5 and 11.\n", processing.
during runtime.
number); 7. Ease of Parameter Passing: Arrays can be
- *Debugging:* Provides informative error messages
} else { efficiently passed as parameters to functions.
during runtime.
printf("%d is not divisible by both 5 and 11.\n",
- *Portability:* More portable as it doesn't produce
number); Storage Class :-
machine-specific executables.
} 1. auto : Default storage class for local variables
- *Edit-Run Cycle:* Shorter since changes can be
return 0; inside functions. Limited to the block in which it's
executed without a separate compilation step.
} declared.
### Compiler:
2. register : Suggests storing variables in CPU
- *Translation:* Translates the entire code into
Differentiate between call by value and call by registers for faster access. Its usage is a hint to the
machine code or an intermediate form beforehand.
address.: compiler.
- *Execution:* Produces a separate executable file
Call by Value: 3. static : Persists throughout the program
that can be run independently.
- Passes actual values. execution, retains its value between function calls,
- *Speed:* Faster execution as code is already
- Changes don't affect the original. and retains storage even after the block ends.
translated into machine code.
- Requires additional memory. 4. extern : Declares variables or functions defined in
- *Debugging:* May provide less informative error
other files, enabling access to them from the current
messages compared to interpreters.
Call by Address (Reference): file.
- *Portability:* Might need recompilation for
- Passes memory addresses.
different platforms.
- Changes affect the original.
- Edit-Run Cycle: Longer as it requires a separate
- No additional memory overhead.
compilation step after code changes.
String Handaling Functions :- Write a program in C to add two numbers using Write a program in C to find all prime numbers
1. String Copying Functions: pointers and function. between given interval using functions:
- strcpy: Copies one string to another. #include <stdio.h> #include <stdio.h>
2. String Concatenation Functions: int add(int *a, int *b); #include <stdbool.h>
- strcat: Concatenates two strings. int main() bool isPrime(int num) {
3. String Comparison Functions: { if (num <= 1) return false;
- strcmp: Compares two strings. int x, y, sum; for (int i = 2; i * i <= num; i++)
- strncmp: Compares a specified number of printf("Enter two numbers: "); if (num % i == 0) return false;
characters of two strings. scanf("%d%d", &x, &y); return true;
4. String Length Functions: sum = add(&x, &y); }
- strlen: Returns the length of a string. printf("The sum is %d\n", sum); void displayPrimesInInterval(int start, int end) {
5. String Searching Functions: return 0; printf("Prime numbers between %d and %d:\n",
- strstr: Finds the first occurrence of a substring in a } start, end);
string. int add(int *a, int *b) for (int i = start; i <= end; i++)
- strchr: Finds the first occurrence of a character in a { if (isPrime(i)) printf("%d\n", i);
string. return *a + *b; }
6. Other String Functions: } int main() {
- strncpy: Copies a specified number of characters int start, end;
from one string to another. Looping: printf("Enter start and end of the interval: ");
- strncat: Concatenates a specified number of In C programming, looping refers to the process of scanf("%d %d", &start, &end);
characters from one string to another. repeatedly executing a block of code as long as a displayPrimesInInterval(start, end);
- strtok: Splits a string into tokens based on specified certain condition is true. It allows the program to return 0;
delimiters. execute a set of statements multiple times, making }
- strspn: Returns the length of the initial segment of the code more efficient and reducing redundancy.
a string consisting entirely of characters from # Key Points about Loops in C :- Types of User-Defined-Function :-
another string. -Loops help in executing a block of code repetitively 1. No Return Value, No Arguments:
based on a specified condition. - Function doesn't return any value and doesn't
Write a C program to convert lowercase string to -They aid in controlling the flow of the program and take any arguments.
uppercase and vice versa. Do Not use string.h avoiding redundant code. 2. Return Value, No Arguments:
#include <stdio.h> -It's crucial to ensure that the loop's condition - Function returns a value but doesn't take any
void convertToLowercase(char str[]) { eventually becomes false to prevent infinite loops. arguments.
int i = 0; 3. No Return Value, With Arguments:
while (str[i] != '\0') { State advantages of using pointer in C : - Function doesn't return a value but takes
if (str[i] >= 'A' && str[i] <= 'Z') { Efficient Memory Management: arguments.
str[i] += 32; // Convert uppercase to Pointers enable direct access to memory, optimizing 4. Return Value, With Arguments:
lowercase usage. - Function both returns a value and takes
} Dynamic Memory Allocation: arguments.
i++; Allows dynamic memory allocation for flexibility.
} Passing Addresses as Function Arguments: Explain malloc with example:
} Enables functions to modify caller's variables. malloc() is a C function for dynamic memory
void convertToUppercase(char str[]) { Efficient Array Manipulation: allocation, allowing you to request a specific number
int i = 0; Supports direct array manipulation using pointers. of bytes in the heap at runtime. It returns a void*
while (str[i] != '\0') { Enhanced String Handling: pointer, which can be cast to the desired type.
if (str[i] >= 'a' && str[i] <= 'z') { Facilitates efficient string manipulation. Example:
str[i] -= 32; // Convert lowercase to #include <stdio.h>
uppercase Types of Arrays :- #include <stdlib.h>
} #Based on Dimensions: int main() {
i++; 1. One-dimensional Array: Linear collection of int dynamicArray = (int)malloc(5 * sizeof(int));
} elements accessed using a single index. if (dynamicArray != NULL) {
} 2. Multi-dimensional Array: Arrays with multiple free(dynamicArray); }
int main() { dimensions accessed using multiple indices. return 0;
char inputString[100]; #Based on Declaration: }
printf("Enter a string: "); 1. Static Array: Fixed size determined at compile-
gets(inputString); time. Explain calloc with example:
convertToUppercase(inputString); 2. Dynamic Array: Size determined at runtime using calloc() is a C function for dynamic memory
printf("Uppercase: %s\n", inputString); memory allocation functions. allocation that initializes allocated memory to zero.
convertToLowercase(inputString); #Based on Element Type: It takes two arguments: the number of elements to
printf("Lowercase: %s\n", inputString); 1. Homogeneous Array: Elements of the same data allocate and the size of each element in bytes.
return 0; type. Example:
} 2. Heterogeneous Array: Elements of different data #include <stdio.h>
types or structures. #include <stdlib.h>
Source vs Object :- int main() {
1. Nature: Write a program in C to find ASCII value of a int dynamicArray = (int)calloc(5, sizeof(int));
- Source code: Human-readable, written by character: if (dynamicArray != NULL) {
programmers. #include <stdio.h> free(dynamicArray); }
- Object code: Machine-readable, generated from int main() { return 0;
source code by compilers/assemblers. char character; }
2. Format: printf("Enter a character: ");
- Source code: Written in a high-level programming scanf("%c", &character); Advantages of Structured Program :-
language. printf("ASCII value of '%c' is %d\n", character, 1. Clarity and Readability: Clear, understandable
- Object code: Consists of binary/hexadecimal character); code structure.
instructions. return 0; 2. Modularity and Reusability: Breaks problems into
3. Readability: } manageable modules, promoting code reuse.
- Source code: Understandable by humans. 3. Ease of Maintenance: Easier to maintain and
- Object code: Not directly readable by humans. Sizeof() Operator :- update.
4. Usage: - sizeof() returns the size in bytes. 4. Debugging and Testing: Facilitates systematic
- Source code: Used for programming and - The result of sizeof() may vary depending on the debugging and testing.
modifications. compiler and system architecture. 5. Structured Control Flow: Enhances program
- Object code: An intermediate stage before - It's particularly useful for dynamic memory control and logic.
generating the final executable. allocation and determining the size of data 6. Reduction of Complexity: Organized code reduces
5. Execution: structures overall complexity.
- Source code: Needs compilation before Example :- sizeof(Expression); 7. Portability and Maintainability: More portable and
execution. easier to maintain.
- Object code: Requires linking or further 8. Structured Design: Promotes a systematic
processing to become an executable. approach to problem-solving.
Header File :- = vs == :- Source File vs Object File vs Binary Executable File :-
A C header file contains declarations of functions, = (Assignment Operator) is used to assign a value to # Source File :-
constants, and data types used in multiple program a variable, whereas == (Equality Operator) is used to - Contains human-readable code written in a
files. It allows sharing these declarations across compare whether two values are equal in a programming language (e.g., C, C++).
different parts of the program for code reusability condition. - Has file extensions like .c (C), .cpp (C++), or others.
and consistency. They are included using #include - Contains the program's logic and is editable by
and have a .h extension. Token :-
programmers.
Tokens in C are the smallest units of code, including
#Object File :-
What is C? keywords, identifiers, constants, operators, special
C is a powerful, versatile, and efficient programming symbols, and comments. They form the fundamental - Generated by compiling the source code using a
language known for its portability, direct hardware elements parsed by the compiler to understand the compiler.
access, and wide applicability in system software, program's structure. - Contains machine code and is not directly
embedded systems, and applications due to its rich executable by the CPU.
standard library and structured nature. Syntax Error :- - Includes translated code from the source file,
Syntax errors violate programming language rules, symbol table information, and references to external
Explain realloc with example: found by the compiler during compilation, stopping functions.
realloc() resizes dynamically allocated memory in C. code execution. Examples: missing punctuation, - File extensions might be .o (Unix-based systems) or
It takes a pointer to the original block and the new incorrect syntax, must fix for successful compilation. .obj (Windows).
size in bytes. Returns a pointer to the resized block. #Binary Executable File :-
If unsuccessful, returns NULL.
- Created by linking one or more object files
Example: '\0' Character :-
together, along with necessary libraries.
#include <stdio.h> The '\0' character marks the end of a string in
- Contains machine code directly executable by the
#include <stdlib.h> programming languages like C and C++, signaling
int main() { CPU.
where the string ends in memory.
int arr = (int)malloc(3 * sizeof(int)); - The final form of the program that users run.
arr = (int*)realloc(arr, 5 * sizeof(int)); - File formats differ based on the operating system,
<> vs " " :-
free(arr); such as .exe on Windows, no extension on Unix-
1. < > : Used for system header files. Compiler
return 0; based systems, etc.
searches in system directories.
}
2. " " : Used for user-defined or local header files.
Break vs Continue :-
Macros :- Compiler searches in the current directory or
1. *Exit Behavior* :-
Macros in C are preprocessor directives created specified directories.
- break: Terminates the loop entirely.
using #define. They define symbolic constants or - continue: Skips the current iteration, proceeding
code snippets that get replaced throughout the code Debugging :-
to the next.
before compilation. They improve code readability, Debugging is finding and fixing errors in code. It
2. *Loop Control* :-
aid in defining constants, and create reusable code involves identifying issues, locating their source,
fragments. - break: Exits the innermost loop.
making corrections, and ensuring the code
- continue: Skips the current iteration's code.
functions as expected.
Explain free with example: 3. *Execution Flow* :-
free() is a C function used to deallocate memory - break: Jumps to the code following the loop after
Library Function :-
allocated by malloc(), calloc(), or realloc(). It takes a termination.
Library functions in C are pre-written functions
pointer to the allocated memory as an argument. - continue: Continues with the next
available in libraries like standard ('stdio.h', 'stdlib.h')
Example: iteration of the loop.
or third-party. They perform specific tasks, aiding in
#include <stdio.h>
#include <stdlib.h> code reusability and saving time by providing ready-
String Functions :-
int main() { made solutions for common programming tasks.
1. strlen :- Calculates the length of a string.
int arr = (int)malloc(5 * sizeof(int));
2. strcmp :- Compares two strings lexically.
free(arr); Prototype Declaration :-
3. strcat :- Concatenates (appends) one string to
return 0; Function prototype in C declares the function's
another.
} signature (return type, name, parameter types)
4. strcpy :- Copies one string to another.
without its body. It enables the compiler to check for
Assembler :- errors during compilation and allows calling
Assembler in C translates assembly code to machine Array vs Pointer :-
functions before their actual definitions.
code for the computer's hardware, creating object #Arrays:
files for linking into executable programs. Advantages :-
What is Keywords :-
- Indexed access
Keywords are reserved words in programming
Typecasting :- - Fixed size
Typecasting, or type conversion, is the process of languages with predefined roles, controlling program
- Compile-time error checking
converting one data type into another. In C, it can be flow, data types, and structures. Examples: if, int,
Disadvantages :-
implicit (automatic) or explicit (done by the return. They define syntax and are crucial for
- Fixed size limitation
programmer using (type)value). It's crucial for code functionality.
- Lack of dynamic memory allocation
ensuring compatibility between different data types
- Pass-by-value in function calls
but may result in loss of precision or information. Avoid & Disadvantages goto() :-
Avoid goto in modern programming. Its
What is local and global veriable in C : #Pointers:
disadvantages include complex and less readable
Local Variables: Advantages :-
code, hindered debugging, violation of structured
Declared within a block (e.g., a function). - Dynamic memory allocation
programming principles, and potential unintended
Limited scope to the block. - Flexibility in memory addressing
side effects. Using structured alternatives enhances
Memory is allocated upon entering the block and - Pass-by-reference in function calls
code readability, organization, and reduces errors.
released upon exit. Disadvantages :-
Accessible only within the block. - Manual memory management
Global Variables: Break vs Continue :-
- Potential for memory errors
Declared outside of functions. 1. *Exit Behavior* :-
- Indirection complexity
Program-wide scope. - break: Terminates the loop entirely.
Memory is allocated at program start and released - continue: Skips the current iteration, proceeding
#Differences :-
at program end. to the next.
- Arrays store elements of the same type; pointers
Accessible from any part of the program. 2. *Loop Control* :-
Local variables are specific to a block, while global store memory addresses.
- break: Exits the innermost loop.
variables have a broader scope across the entire - Arrays have a fixed size; pointers can change
- continue: Skips the current iteration's code.
program. dynamically.
3. *Execution Flow* :-
- Arrays allow direct element access; pointers need
- break: Jumps to the code following the loop after
to be dereferenced to access data.
termination.
- continue: Continues with the next
iteration of the loop.