PPS Unit 2
09 June 2024 02:37
#include<stdio.h>
ANS-4---- void rotate_values(int *x, int *y, int *z) {
Simple Variables: // Rotate values: x <- y, y <- z, z <- x
• Definition: A simple variable (also known as a scalar) holds a single value of a specific data *x ^= *y;
type (e.g., int, float, char). *y ^= *z;
• Memory Allocation: A single memory location is allocated to store the value. *z ^= *x;
• Access: Accessed directly using the variable name. *x ^= *y; Explanation of a for loop: Program to check if a number is even or odd:
• Example: *y ^= *z; A for loop is a control flow statement that allows code to be executed #include <stdio.h>
int num = 5; *z ^= *x; repeatedly based on a condition. Typically, a for loop is used when the
float pi = 3.14; } number of iterations is known beforehand. The Syntax of a for loop in int main() {
char letter = 'A'; C is: int num;
int main() {
Arrays: int x, y, z; for (initialization; condition; increment/decrement) { printf("Enter an integer: ");
• Definition: An array is a collection of elements of the same data type stored in contiguous // Code to be executed scanf("%d", &num);
memory locations. printf("Enter the value of x, y, z\n"); }
• Memory Allocation: Multiple memory locations are allocated based on the size of the array scanf("%d %d %d", &x, &y, &z); • Initialization: Initializes the loop control variable. if (num % 2 == 0) {
(number of elements). • Condition: The loop continues as long as this condition is true. printf("%d is even.\n", num);
• Access: Accessed using an index. The index starts from 0 and goes up to n-1 where n is the rotate_values(&x, &y, &z); • Increment/Decrement: Updates the loop control variable after each } else {
size of the array. iteration. printf("%d is odd.\n", num);
• Example: printf("Rotated values: x = %d, y = %d, z = %d\n", x, y, z); Program to display numbers in increasing and decreasing order }
int numbers[5] = {1, 2, 3, 4, 5}; using infinite for loop:
float decimals[3] = {1.1, 2.2, 3.3}; return 0; Here’s a C program demonstrating an infinite for loop to display return 0;
char letters[4] = {'A', 'B', 'C', 'D'}; } numbers in increasing and decreasing order: }
This program uses the XOR swap trick to rotate the values of x, y, and z without using a #include <stdio.h>
In C, arrays are passed to functions by reference. This means that instead of passing a copy of the entire temporary variable. The rotate_values function takes pointers to x, y, and z as arguments and #include <stdlib.h> Precedence and associativity are fundamental concepts in programming and
array, you pass a pointer to the first element of the array. Consequently, any modifications made to the performs the rotation using bitwise XOR operations. #include <unistd.h> // For sleep function mathematics that dictate how expressions are evaluated. These rules ensure
array elements within the function will affect the original array. Note that this solution is not only more efficient but also more concise and elegant than the that expressions are interpreted correctly and consistently. Here’s an
Key Points: previous one. However, it's worth noting that this trick only works for integer types and may not int main() { illustration of their importance with examples:
1. Array Name as Pointer: be suitable for all types of variables. int i = 0; Precedence
○ The array name is treated as a pointer to the first element of the array. Precedence determines the order in which operators are evaluated in an
○ For example, if you have an array int arr[5];, the expression arr is equivalent to &arr[0]. // Infinite loop for increasing order expression. Operators with higher precedence are evaluated before those
2. Function Parameter: for (;;) { with lower precedence.
○ In the function declaration, the parameter can be specified as an array or a pointer. printf("Increasing: %d\n", i); Example:
○ Both int arr[] and int *arr are valid declarations for a function that takes an integer array as i++; Consider the expression: 3 + 4 * 2
an argument. sleep(1); // Pause for 1 second to slow down the output • Without Precedence Rules: If there were no precedence rules, the
if (i > 10) break; // Exit condition for demonstration
Example Program: }
expression could be evaluated from left to right, resulting in: (3+4)×2=7
Let's see an example program that demonstrates how to pass an array to a function and modify its ×2=14(3 + 4) \times 2 = 7 \times 2 = 14(3+4)×2=7×2=14
elements. • With Precedence Rules: Multiplication has a higher precedence than
i = 10; // Resetting i for decreasing order addition, so the expression is evaluated as: 3+(4×2)=3+8=113 + (4 \times
#include <stdio.h> 2) = 3 + 8 = 113+(4×2)=3+8=11
// Infinite loop for decreasing order
for (;;) { Associativity
// Function to print the elements of the array #include <stdio.h> Associativity determines the order in which operators of the same precedence
printf("Decreasing: %d\n", i);
void printArray(int arr[], int size) { #include <string.h> are evaluated. This can be either left-to-right (left associative) or right-to-left
i--;
for (int i = 0; i < size; i++) { (right associative).
sleep(1); // Pause for 1 second to slow down the output
printf("%d ", arr[i]); #define MAX_EMPLOYEES 100 if (i < 0) break; // Exit condition for demonstration Example:
} } Consider the expression: 4 - 2 - 1
printf("\n"); typedef struct { • Left-to-Right Associativity (Subtraction is left associative): The
} int id; expression is evaluated as: (4−2)−1=2−1=1(4 - 2) - 1 = 2 - 1 = 1(4−2)−1=2
return 0;
char category; } −1=1
// Function to modify elements of the array int num_loans; • Right-to-Left Associativity: If subtraction were right associative, the
void modifyArray(int arr[], int size) { float total_loan_amount; expression would be evaluated as: 4−(2−1)=4−1=34 - (2 - 1) = 4 - 1 = 34
Difference between while and do while loop:
for (int i = 0; i < size; i++) { } Employee; −(2−1)=4−1=3
1. Syntax:
arr[i] = arr[i] * 2;
} float getMaxLoanAmount(char category) {
○ while loop: Combined Importance
while (condition) { Precedence and associativity work together to provide a clear and
} switch (category) {
// Code to be executed unambiguous way to evaluate complex expressions.
case 'A': return 50000.0;
} Example:
int main() { case 'B': return 30000.0;
○ do while loop: Consider the expression: 5 + 3 * 2 ^ 2 - 1
int arr[5] = {1, 2, 3, 4, 5}; case 'C': return 20000.0;
do { • Step-by-Step Evaluation Using Precedence and Associativity:
int size = sizeof(arr) / sizeof(arr[0]); default: return 0.0;
// Code to be executed 1. Exponentiation (Highest Precedence): 22=42 ^ 2 = 422=4
}
} while (condition); 2. Multiplication (Next Highest Precedence): 3∗4=123 * 4 = 123∗4=
// Print original array }
• Execution: 12
printf("Original array: ");
• while loop: The condition is checked before the code is 3. Addition and Subtraction (Left-to-Right Associativity): 5+12−1=
printArray(arr, size); void processLoanApplication(Employee employees[], int num_employees, int emp_id, float
executed. If the condition is false initially, the code inside 17−1=165 + 12 - 1 = 17 - 1 = 165+12−1=17−1=16
loan_amount) {
the loop may never be executed.
// Modify array for (int i = 0; i < num_employees; i++) {
• do while loop: The code is executed at least once before
Practical Impact
modifyArray(arr, size); if (employees[i].id == emp_id) { • Programming: In programming languages, precedence and associativity
the condition is checked. Even if the condition is false
if (employees[i].num_loans >= 2) { rules are essential to correctly interpret and execute expressions. For
initially, the code inside the loop is executed at least
// Print modified array printf("Loan application denied for Employee %d: Already has two loans.\n", emp_id); example, in C, C++, Java, and Python, these rules ensure that
once.
printf("Modified array: "); return; expressions like a + b * c are consistently evaluated as a + (b * c).
• Use Case:
printArray(arr, size); } • Mathematics: In mathematical notation, these rules prevent ambiguity.
• while loop is generally used when the number of
float max_loan_amount = getMaxLoanAmount(employees[i].category); For example, in the absence of parentheses, the expression a + b * c is
iterations is not known and depends on a condition.
return 0; if (employees[i].total_loan_amount + loan_amount > max_loan_amount) { universally understood to mean a + (b * c) due to the higher precedence
• do while loop is used when the code block needs to be
} printf("Loan application denied for Employee %d: Exceeds maximum permissible total loan of multiplication.
executed at least once, regardless of the condition
Explanation: amount.\n", emp_id);
Explanation of a function: Conclusion
return;
1. Array Declaration: A function is a self-contained block of code that performs a specific Precedence and associativity are crucial for evaluating expressions correctly.
}
○ This declares an array arr of size 5 and initializes it with values 1, 2, 3, 4, and 5. task. Functions are used to modularize the code, improve readability, They provide a clear framework that avoids ambiguity and ensures consistent
employees[i].num_loans++;
Printing the Array: and enable reuse. In C, a function has a return type, a name, a results across different contexts, whether in programming languages or
employees[i].total_loan_amount += loan_amount;
○ The printArray function takes an array and its size as parameters and prints each element. parameter list, and a body. mathematical notation. Understanding these rules helps in writing correct and
printf("Loan application approved for Employee %d. Total loans: %d, Total loan amount: %.2f\n",
Modifying the Array: Example of a function: efficient code and in solving mathematical problems accurately.
emp_id, employees[i].num_loans, employees[i].total_loan_amount);
○ The modifyArray function takes an array and its size as parameters and doubles each int add(int a, int b) {
return;
element's value. return a + b; Call By Value
}
Main Function: }
} #include <stdio.h>
○ The main function declares and initializes the array, prints the original array, modifies it
printf("Employee %d not found.\n", emp_id); void swap(int , int); //prototype of the function
using modifyArray, and then prints the modified array.
} int main()
Detailed Steps: {
1. Array Initialization: int main() { int a = 10;
○ The array arr is initialized with values {1, 2, 3, 4, 5}. Employee employees[MAX_EMPLOYEES]; int b = 20;
2. Passing Array to Function: int num_employees = 0; printf("Before swapping the values in main a = %d, b = %d\n",a,b);
○ When printArray(arr, size) is called, the array arr is passed to the function. Here, arr is // printing the value of a and b in main
treated as a pointer to the first element of the array. // Sample data for testing swap(a,b);
○ Similarly, when modifyArray(arr, size) is called, the array arr is passed by reference. employees[num_employees++] = (Employee){101, 'A', 1, 20000.0}; printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of
3. Function Execution: employees[num_employees++] = (Employee){102, 'B', 0, 0.0}; actual parameters do not change by changing the formal parameters in call by
○ In printArray, the function iterates over the array using the size parameter and prints each employees[num_employees++] = (Employee){103, 'C', 2, 15000.0}; value, a = 10, b = 20
element. }
○ In modifyArray, the function iterates over the array and modifies each element by doubling int emp_id; void swap (int a, int b)
its value. float loan_amount; {
4. Effect on Original Array: int temp;
○ Because the array is passed by reference, the modifications made in modifyArray affect the // Example loan application process temp = a;
original array. When the modified array is printed in the main function, the changes are printf("Enter Employee ID and Loan Amount: "); a=b;
visible. scanf("%d %f", &emp_id, &loan_amount); b=temp;
This demonstrates how arrays are passed to functions in C and how functions can operate on the printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal
original array rather than a copy of it. processLoanApplication(employees, num_employees, emp_id, loan_amount); parameters, a = 20, b = 10
}
ANS-5---- return 0;
Call by Value: } Call By Reference
In call by value, the actual value is passed to the function. Modifications made to the parameter inside #include <stdio.h>
the function do not affect the original value. void swap(int *, int *); //prototype of the function
int main()
Call by Reference: {
In call by reference, a reference to the actual parameter is passed to the function. Modifications made int a = 10;
to the parameter inside the function affect the original value. int b = 20;
Here's the program: printf("Before swapping the values in main a = %d, b = %d\n",a,b); //
printing the value of a and b in main
#include <stdio.h> swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values
// Function prototypes of actual parameters do change in call by reference, a = 10, b = 20
void callByValue(int a); }
void callByReference(int *a); void swap (int *a, int *b)
{
int main() { int temp;
int x = 10; temp = *a;
int y = 20; *a=*b;
*b=temp;
printf("Initial values:\n"); printf("After swapping values in function a = %d, b = %d\n",*a,*b); //
printf("x = %d, y = %d\n", x, y); Formal parameters, a = 20, b = 10
}
// Call by value
callByValue(x);
printf("\nAfter callByValue function:\n");
printf("x = %d (unchanged)\n", x);
// Call by reference
callByReference(&y);
printf("\nAfter callByReference function:\n");
printf("y = %d (changed)\n", y);
return 0;
}
// Call by value function
void callByValue(int a) {
a = a + 10;
printf("Inside callByValue function:\n");
printf("a = %d\n", a);
}
// Call by reference function
void callByReference(int *a) {
*a = *a + 10;
printf("Inside callByReference function:\n");
printf("*a = %d\n", *a);
}
(explain the code one by one)
Output:
Initial values:
x = 10, y = 20
Inside callByValue function:
a = 20
After callByValue function:
x = 10 (unchanged)
Inside callByReference function:
*a = 30
After callByReference function:
y = 30 (changed)
• The value of x remains unchanged after the call by value function.
• The value of y is changed after the call by reference function.