Cse Full
Cse Full
a)C programming offers several benefits, making it a popular choice for system programming,
embedded systems, and performance-critical applications. Here are the key advantages:
2. Portability
● C programs can run on different platforms with minimal modifications.
● It follows ANSI and ISO standards, ensuring compatibility across systems.
3. Memory Management
● C allows direct memory manipulation using pointers, making it powerful for system-level
programming.
● It provides dynamic memory allocation (malloc, calloc, free), offering better memory
control.
7. Hardware-Level Programming
● Used in developing device drivers, embedded systems, and microcontroller-based
applications.
● Direct interaction with hardware makes it ideal for low-level system programming.
b)Variables and Keywords in C
1. Variables in C
A variable in C is a name assigned to a memory location that stores a value. It must follow
certain rules:
● Can contain letters (A-Z, a-z), digits (0-9), and underscore (_)
● Must begin with a letter or underscore
● Cannot be a keyword (reserved word in C)
● Cannot contain spaces or special characters (except underscore)
2. Keywords in C
A keyword is a reserved word that has a special meaning in C and cannot be used as a
2.
a)
○ x is initialized to 10.
■ Then increase x by 1.
○ So, y = 15 + 10 = 25.
○ So, z = 15 + 12 = 27.
4. Final Values
○ x = 12 ○ y = 25
○ z = 27
5. Output
12 25 27 b)
c)
Given Expression:
3.
a)#include <stdio.h>
int main() {
int year;
return 0;
}
b)#include <stdio.h>
int main() {
int day;
// Taking input from the user printf("Enter a numeric value for the weekday (1
for Sunday, 7 for Saturday): "); scanf("%d", &day);
return 0;
}
HISTORY
Origins in the 1970s:
C was developed in 1972 by Dennis Ritchie at Bell Labs as an evolution of the B programming
language. It was initially created to write the UNIX operating system.
Standardization:
In 1983, the American National Standards Institute (ANSI) standardized C, creating the ANSI
C standard, which became widely adopted.
Influence on Other Languages:
C has heavily influenced many modern programming languages, including C++, Java, and
Python. Its simple, efficient syntax serves as a foundation for many languages.
System Programming:
C is known for its use in system-level programming. It's widely used for operating systems,
embedded systems, and device drivers.
Portable & Efficient:
One of C's strengths is its portability—C code can be compiled and run on different systems
with minimal changes, making it ideal for cross-platform development.
Legacy and Continued Use:
Despite being over 50 years old, C remains one of the most popular and widely used
programming languages in software development, especially for performance-critical
applications.
IMPORTANCE
Chapter 1
1.11 Why and when do we use the #define directive?
● The #define directive is used to create macros, which are symbolic constants or code
snippets. It is used to improve code readability and maintainability by replacing magic
numbers or repeated code with meaningful names.
● void main(void) is a function declaration where void indicates that the function does
not return any value, and (void) indicates that it does not take any arguments.
However, the standard entry point in C is int main(void) or int main(int argc,
char *argv[]).
● (a) main() and void main(void): main() is a function declaration that does not specify
the return type or parameters, while void main(void) explicitly states that the
function returns nothing and takes no arguments.
● (b) int main() and void main(): int main() specifies that the function returns an
integer, typically used to indicate the program's exit status. void main() indicates that
the function does not return a value, which is non-standard and generally discouraged.
● Comments are used to explain the purpose and logic of the code, making it easier for
others (and yourself) to understand and maintain the code.
● The look of a program, including formatting and indentation, is important for readability and
maintainability. Well-structured code is easier to debug and extend.
● Blank spaces are permitted between tokens (like keywords, identifiers, and operators) and
in indentation. They are not permitted within tokens (e.g., variable names or keywords).
1.18 Describe the structure of a C program.
1.19 Describe the process of creating and executing a C program under UNIX system.
● To create and execute a C program under UNIX, you typically write the code in a .c file,
compile it using a compiler like gcc (e.g., gcc program.c -o program), and then
● Multiple source files can be implemented by compiling them separately and then linking
them together. For example, gcc file1.c file2.c -o program compiles and links
file1.c and file2.c into a single executable named program. Header files are often
used to declare functions and variables shared between source files.
2.4 Describe the four basic data types. How could we extend the range of
values they represent?
The four basic data types in C are:
1. int: Used to store integers. The range can be extended by using qualifiers like short,
2. float: Used to store single-precision floating-point numbers. The range can be extended
by using double or long double for higher precision.
3. char: Used to store single characters. The range can be extended by using unsigned
To extend the range of values, you can use qualifiers like unsigned, short, long, and long
● const: The const qualifier is used to declare a variable as constant, meaning its value
cannot be changed after initialization. This is useful for defining values that should
remain unchanged throughout the program, such as mathematical constants or
configuration settings.
● volatile: The volatile qualifier indicates that a variable's value may be changed at any
time by external factors, such as hardware or other threads. This prevents the compiler
from optimizing out accesses to the variable, ensuring that the program always reads the
current value from memory.
2.15 When dealing with very small or very large numbers, what steps would
you take to improve the accuracy of the calculations?
To improve the accuracy of calculations with very small or very large numbers:
1. Use Higher Precision Data Types: Use double or long double instead of float for
floating-point calculations to increase precision.
2. Avoid Accumulating Errors: Minimize the number of arithmetic operations that can
accumulate rounding errors. For example, use algorithms that reduce the number of
additions and subtractions.
3. Use Specialized Libraries: Utilize libraries designed for high-precision arithmetic, such
as GNU MP (GMP) for arbitrary-precision arithmetic.
4. Normalize Values: Scale numbers to a similar range before performing operations to
reduce the risk of overflow or underflow.
5. Error Analysis: Perform error analysis to understand and mitigate the impact of
rounding errors in your calculations.
2.17
Int x;
○ Error: The keyword should be int (lowercase), not Int.
2. float letter,DIGIT;
○ No error. This is a valid declaration of two float variables, letter and DIGIT.
3. double = p,q
○ Error: The = sign is incorrect. It should be double p, q;.
4. exponent alpha,beta;
○ Error: exponent is not a valid data type in C. It should be a valid data type like
5. m,n,z: INTEGER
○ Error: The syntax is incorrect. In C, the correct syntax is int m, n, z;.
The value of x would be 107. This is because the character 'a' has an ASCII value of 97.
Syntax Errors:
1. Incomplete comment: The comment on the line int R,C; is not properly closed.
● Global Variables:
○ Declared outside of all functions, typically at the top of the program.
○ Accessible from any function within the program.
○ Lifetime extends throughout the entire execution of the program. ○
Stored in a fixed memory location. ● Local Variables: ○ Declared within a
function or block.
○ Accessible only within the function or block where they are declared. ○ Lifetime
is limited to the execution of the function or block.
○ Stored in the stack memory.
○ Created when the block is entered and destroyed when the block is exited. ○
Default storage class for local variables.
○ Example: int x; or auto int x; ●
Static Variables:
○ Declared with the static keyword.
○ Retains its value between function calls.
○ If declared within a function, it is local to that function but retains its value. ○ If
declared outside of all functions, it is a global variable but limited to the file in
which it is declared.
○ Example: static int x;
True. The modulus operator % is used to find the remainder of a division and can only be applied to
integer operands.
(c) The operators <=, >= and != all enjoy the same level of priority.
● True. These relational operators have the same level of precedence.
(d) During modulo division, the sign of the result is positive, if both the operands are of
the same sign.
● True. The result of a modulo operation has the same sign as the dividend if both operands have the
same sign.
● False. The expression x≤yx≤y is true if xx is less than or equal to yy, whereas x>yx>y is true if xx is
greater than yy. They are not the same.
● False. A unary expression consists of one operand and one unary operator (e.g., -x, ++x).
● True. Associativity determines the order in which operators of the same precedence level are
evaluated.
● True. In mixed expressions, C automatically performs implicit type conversion (casting) to ensure
consistent types.
● True. An explicit cast can be used to convert one data type to another, changing the
expression's type.
● True. The statement is valid. The + is a unary plus operator, and a = +10; assigns the
value 10 to a.
○ 0 * 6 is 0.
○ 0 / 2 is 0.
○ a + 0 is 10.
○ 1 * 2 is 2.
○ 2 / 3 is 0.
○ b + 0 is 20.
remains 20.
● False. The statement ++a++; is invalid because it attempts to apply both the
assigned 0.
● False. The expression 1/3 + 1/3 + 1/3 performs integer division, so each 1/3 is 0,
○ 5 + 5 is 10.
○ 10 >= 10 is true.
○ !true is false.
Result: false
(b) 5 + 5 == 10 || 1 + 3 == 5
1. Evaluate 5 + 5 == 10:
○ 5 + 5 is 10.
○ 10 == 10 is true. 2.
Evaluate 1 + 3 == 5:
○ 1 + 3 is 4.
○ 4 == 5 is false.
Result: true
○ 5 > 10 is
false. 2. Evaluate
10 < 20:
○ 10 < 20 is true.
3. Evaluate 3 < 5:
●
○ 3 < 5 is true.
Result: true
1. Evaluate 10 != 15:
○ 10 != 15 is true.
○ 10 < 20 is true.
○ 15 > 30 is false.
Result: false
Summary of Results:
● (a) false
25/3%25/3% 2
1. Validity: Valid.
2. Evaluation: ○ 25/325/3 is 88 (integer division). ○ 8%28%2 is
00.
Result: 00
(b) +9/4+5+9/4+5
1. Validity: Valid.
2. Evaluation:
○ +9/4+9/4 is 22 (integer division). ○ 2+52+5 is 77.
Result: 77
(c) 7.5%7.5% 3
1. Validity: Invalid.
2. Reason: The modulus operator % can only be used with integer operands. 7.57.5 is a
floating-point number.
Result: Invalid
(d) 14%14% 3+7%3+7% 2
1. Validity: Valid.
2. Evaluation:
○ 7%27%2 is 11.
○ 3+13+1 is 44.
○ 14%414%4 is 22.
Result: 22
(e) −14%−14% 3
1. Validity: Valid.
2. Evaluation:
○ −14%3−14%3 is −2−2 (the result takes the sign of the dividend).
Result: −2−2
(f) 15.25+−5.015.25+−5.0
1. Validity: Valid.
2. Evaluation:
○ 15.25+−5.015.25+−5.0 is 10.2510.25.
Result: 10.2510.25
21%21% (int)4.5
1. Validity: Valid.
2. Evaluation:
○ (int)4.5(int)4.5 is 44 (casting to integer). ○ 21%421%4 is 11.
Result: 11
Summary of Results:
● (a) 00
● (b) 77
● (c) Invalid (modulus with non-integer)
● (d) 22
● (e) −2−2
● (f) 10.2510.25
● (g) Invalid (invalid operator)
● (h) 11
3.9
3.11
Explanation:
1. Variable Declarations and Assignments:
○ char x; declares x as a character variable.
○ int y; declares y as an integer variable.
○ x = 100; assigns the integer value 100 to x. In ASCII, 100 corresponds to the
character 'd'.
○ y = 125; assigns the integer value 125 to y. In ASCII, 125 corresponds to the
character '}'.
2. Print Statements:
○ printf("%c\n", x); prints the character representation of x. Since x is 100, it
prints 'd'.
prints '}'.
○ printf("%d\n", x); prints the integer value of x. Since x is 100, it prints 100.
Output:
d
}
100
3.12
3.15
3.17
a)
4.3
(a) getchar and scanf functions
● getchar:
○ Reads a single character from the standard input (usually the keyboard).
○ Does not require a format specifier.
○ Example: char c = getchar(); ● scanf:
● %s:
○ Reads a string (sequence of characters) from the input.
○ Stops reading at the first whitespace character (space, tab, newline).
○ Example: scanf("%s", str); ●
%c:
● %s:
○ Reads a string until the first whitespace character.
○ Example: scanf("%s", str); ● %[ ]: ○ Reads a string that matches a
set of specified characters within the brackets. ○ Can be used to read strings with
specific characters or to exclude certain characters.
○ Example: scanf("%[aeiou]", vowels); reads only vowels.
● %g:
○ Prints a floating-point number in either %f or %e format, whichever is more
compact.
○ Removes trailing zeros and the decimal point if not needed.
○ Example: printf("%g", 123.456); might print 123.456 or 1.23456e+02.
● %f:
○ Prints a floating-point number in decimal notation.
○ Example: printf("%f", 123.456); prints 123.456000.
● %f:
○ Prints a floating-point number in decimal notation.
○ Example: printf("%f", 123.456); prints 123.456000.
● %e:
○ Prints a floating-point number in scientific notation (exponential notation).
○ Example: printf("%e", 123.456); prints 1.234560e+02.
● Error: The format string should not include the commas and ampersands. It should
be "%f%d", &amount, &year.
● Error: The variable code should not be in quotes. It should be &code. Also, Root
should be &Root.
4.7 What will be the values stored in the variables year and code when the
data 1988, x is keyed in as a response to the following statements:
character and code an integer. year will be '1' (the first character of 1988) and
● Values: This will cause incorrect behavior because year is not a string. This will
likely lead to a runtime error or undefined behavior.
4.11 How can we use the getchar() function to read multicharacter strings?
● Answer: The getchar() function reads a single character from the standard input.
To read multicharacter strings, you can use getchar() in a loop to read each
character one by one and store them in an array until a specific delimiter (like a
newline or EOF) is encountered.
4.12 How can we use the putchar() function to output multicharacter strings?
● Answer: The putchar() function outputs a single character to the standard output.
To output multicharacter strings, you can use putchar() in a loop to print each
character of the string one by one.
● Answer: The scanf() function is used to read formatted input from the standard
input (usually the keyboard). It allows you to specify the format of the input data
and store it in variables.
4.14 Describe the purpose of commonly used conversion characters in a
scanf() function.
○ %s for strings.
● Answer: The printf() function is used to print formatted output to the standard
output (usually the screen). It allows you to specify the format of the output data.
4.17 Describe the purpose of commonly used conversion characters in a
printf() function.
○ %d for integers.
○ %s for strings.
● Answer: In printf(), the control string specifies the format of the output, including
literal text and conversion specifiers. In scanf(), the control string specifies the
(a) When if statements are nested, the last else gets associated with the nearest if without an
else. → True
(c) A switch statement can always be replaced by a series of if..else statements. → True
(f) Each expression in the else if must test the same variable.
→ True (To be replaced with switch.)
(j) The predicate !(x >= 10||(y <= 5)) is equivalent to (x < 10)&&(y > 5). → True (By De
Morgan's law.)
(a) The logical AND (&&) operator is true only when both the operands are true.
(b) Multiway selection can be accomplished using an else if statement or the switch statement.
(c) The break statement when executed in a switch statement causes immediate exit from the
structure.
(d) The ternary conditional expression using the operator ?: could be easily coded using if-else
statement.
(e) The expression !(x != y) can be replaced by the expression x == y.
5.3 Find errors in the following segments:
(b)
c
if (code > 1);
a = b + c;
else a =
0;
(c)
c
if (p < 0) || (q < 0)
printf("sign is negative");
Error: Extra parentheses around condition, and condition not grouped properly.
✅ Correct: if ((p < 0) || (q < 0))
• (a) n = 1:
→ x = 2, y = 0 •
(b) n = 0:
→ x = 1, y = 0
(b)
(c)
5.6 State whether the following logical expressions are true or false (assuming x = 10)
Explanation: x == 10 is true.
(a) switch(y);
→ Error: Semicolon ends the statement — no case block.
✅ Correct: Remove semicolon and add braces and case.
(c) switch (x + y)
→ Valid if followed by a valid case block.
(d)
→ Valid
(a)
c Copy code
if (x &&
y) x =
10; else
y = 10;
→ x = 5, y = 10, z = 1
(b)
c Copy code if
(x || y || z)
y = 10; else
z = 0;
→ x = 5, y = 10, z = 1
(c)
c Copy code if
(x) if (y)
z = 10;
else z
= 0;
→ x = 5, y = 0, z = 0
(d)
c Copy code if (x =
0 || x && y) if
(!y) z = 0;
else y = 1;
(a)
→ x = 0, y = 2
(b)
c Copy code
switch (y) {
case 0:
x = 0;
y = 0;
case 2:
x = 2;
z = 2;
default:
x = 1;
y = 2; }
(a)
c Copy code if (x
> 10) then
printf("\n");
(b)
c Copy code if x
>= 10
printf("OK");
Error: Missing parentheses. ✅ Correct: if (x >= 10)
(c)
c Copy code if (x =
10)
printf("Good");
(d)
✅ Correct
C
main ( ) { int m = 1; if
( m == 1 ) { printf ( "
Delhi " ); if ( m == 2 )
printf ( " Chennai " );
else
printf("Bangalore");
}
else
printf(" END"); }
Answer:
Output of 5.13:
Delhi Bangalore
C
main ( ) {
int m ;
for ( m = 1 ; m<5 ; m++ )
printf("%d\n", (m%2) ? m : m*2); }
Answer:
Output of 5.14:
1
4
3
8
C
main ( ) {
int m, n, p ;
for ( m = 0 ; m < 3 ; m++ )
for ( n = 0 ; n < 3 ; n++ )
for ( p = 0 ; p < 3 ; p++ )
if ( m + n + p == 2 )
goto print ; print:
printf("%d, %d, %d\n", m, n, p ) ; }
Answer:
• This program uses nested for loops to iterate through all possible combinations of m, n, and p
from 0 to 2.
• The if ( m + n + p == 2 ) condition checks if the sum of m, n, and p is equal to 2.
• The first time this condition is true, the goto print; statement jumps to the print: label.
• The printf statement then prints the current values of m, n, and p.
The loops execute in a specific order. The first combination of (m, n, p) for which m + n + p == 2 is
(0, 0, 2). At this point, the goto print; is executed, and the values are printed. Although other
combinations also satisfy the condition, the goto statement executes and prints the values only the first
time the condition is met.
Output of 5.15:
0, 0, 2
5.16 What will be the value of x when the following segment is executed?
C
int x = 10, y = 15 ; x = ( x > y ) ? (
x + y ) : ( y - x ) ; Answer:
• Initially, x is 10 and y is 15.
• The expression (x > y) evaluates to false (since 10 is not greater than 15).
• Therefore, the ternary operator assigns the value of the expression after the colon (:) to x.
• This expression is (y - x), which is 15 - 10 = 5.
• So, the value of x is updated to 5.
5.17 What will be the output when the following segment is executed?
C
int x = 0; if (
x = 0 ) if (
x == 0 )
printf("Number is zero");
else printf("Number is
positive"); Answer: • int x = 0;
initializes x to 0.
• The first if condition is (x = 0). This is an assignment operation, not a comparison. The value 0
is assigned to x (which it already is), and the result of the assignment (which is 0) is evaluated as a
boolean condition. In C, 0 is considered false.
• Since the first if condition evaluates to false, the code block directly following it is skipped.
• The else block associated with the first if statement is executed.
• printf("Number is positive"); prints "Number is positive".
Output of 5.17:
Number is positive
Okay, let's go through each question and determine the output or the value of x.
C
main ( ) { int m = 1; if
( m == 1 ) { printf ( "
Delhi " ); if ( m == 2 )
printf ( " Chennai " );
else
printf("Bangalore");
}
else
printf(" END");
}
Answer:
Output of 5.13:
Delhi Bangalore
C
main ( ) {
int m ;
for ( m = 1 ; m<5 ; m++ )
printf("%d\n", (m%2) ? m : m*2); }
Answer:
• m = 1: (1 % 2) is 1 (true), so it prints 1.
• m = 2: (2 % 2) is 0 (false), so it prints 2 * 2 = 4.
• m = 3: (3 % 2) is 1 (true), so it prints 3.
• m = 4: (4 % 2) is 0 (false), so it prints 4 * 2 = 8.
Output of 5.14:
1
4
3
8
C
main ( ) { int m, n, p ;
for ( m = 0 ; m < 3 ; m++ )
for ( n = 0 ; n < 3 ; n++ )
for ( p = 0 ; p < 3 ; p++ )
if ( m + n + p == 2 )
goto print ; print:
printf("%d, %d, %d\n", m, n, p ) ; }
Answer:
• This program uses nested for loops to iterate through all possible combinations of m, n, and p
from 0 to 2.
• The if ( m + n + p == 2 ) condition checks if the sum of m, n, and p is equal to 2.
• The first time this condition is true, the goto print; statement jumps to the print: label.
• The printf statement then prints the current values of m, n, and p.
The loops execute in a specific order. The first combination of (m, n, p) for which m + n + p == 2 is
(0, 0, 2). At this point, the goto print; is executed, and the values are printed. Although other
combinations also satisfy the condition, the goto statement executes and prints the values only the first
time the condition is met.
Output of 5.15:
0, 0, 2
5.16 What will be the value of x when the following segment is executed?
C
int x = 10, y = 15 ; x = ( x > y ) ? (
x + y ) : ( y - x ) ; Answer:
5.17 What will be the output when the following segment is executed?
C
int x = 0; if (
x = 0 ) if (
x == 0 )
printf("Number is zero"); else
printf("Number is positive");
Answer: • int x = 0; initializes x
to 0.
• The first if condition is (x = 0). This is an assignment operation, not a comparison. The value 0
is assigned to x (which it already is), and the result of the assignment (which is 0) is evaluated as a
boolean condition. In C, 0 is considered false.
• Since the first if condition evaluates to false, the code block directly following it is skipped.
• The else block associated with the first if statement is executed.
• printf("Number is positive"); prints "Number is positive".
Output of 5.17:
Number is positive
Chapter 6 :
(a) Explain the operation of each of the following for loops:
(a) for ( n = 1; n < 10; n = n + 2 ) Answer: This loop initializes n to 1. It continues to execute
as long as n is less than 10. After each iteration, the value of n is incremented by 2. The values of n will
be 1, 3, 5, 7, 9. The loop will execute 5 times.
(b) for ( sum = n; n < 5; n = n + 1 ) sum = sum + n; Answer: This loop initializes sum to
the current value of n (assuming n has been previously declared and possibly initialized). It continues as
long as n is less than 5. In each iteration, n is incremented by 1, and sum is updated by adding the current
value of n to it. The final value of sum will depend on the initial value of n. If n starts at, say, 0, the loop
will execute for n = 0, 1, 2, 3, 4, and sum will become 0 + 0 + 1 + 2 + 3 + 4 = 10.
(d) for ( n = 1; n <= n + 1 ) Answer: This loop initializes n to 1. The condition n <= n + 1
will always be true because any number is always less than or equal to itself plus 1. Therefore, this is an
infinite loop unless there is a break statement inside the loop body that terminates it.
6.9 What would be the output of each of the following code segments? (a)
C
int count = 5; while
(count < = 5)
printf("count");
count++;
Answer: This is an infinite loop. count is initialized to 5. The while condition (count <= 5) is initially
true. Inside the loop, "count" is printed, but count++ is outside the loop body (due to the missing curly
braces {}). Therefore, count will remain 5, and the condition will always be true, leading to continuous
printing of "count".
(b)
C
int count = 5; while
(count = 0)
printf("count");
count++;
Answer: This loop will not execute at all. Inside the while condition, count = 0 is an assignment.
count is assigned the value 0, and the result of the assignment (0) is evaluated as false. Since
the condition is immediately false, the loop body (printf("count");) is never executed.
(c)
C
int count = 0; while
(count < 7)
printf("count");
count++;
Answer: This is another infinite loop. count starts at 0, and the condition count < 7 is initially true.
Inside the loop, "count" is printed, but count++ is outside the loop body due to the missing curly braces.
Thus, count remains 0, and the condition count < 7 will always be true.
(d)
C
int count = 0;
while (count < 7)
{
printf("count");
count++; }
printf("\n");
(e)
C
for (int m = 10; m >= 0; m --)
printf("%d ", m); printf("\n");
Answer: This for loop initializes m to 10. It continues as long as m is greater than or equal to 0. In each
iteration, the current value of m is printed followed by a space, and then m is decremented by 1. Finally, a
newline is printed.
• while loop (pretest loop): The condition is evaluated before the loop body is executed. If the
condition is initially false, the loop body will not execute at all.
• do...while loop (posttest loop): The loop body is executed at least once, and then the condition
is evaluated. The loop continues as long as the condition is true.
Key Difference: A do...while loop guarantees at least one execution of its body, whereas a while loop
might not execute its body even once.
(b) while and for Comparison:
• while loop: Primarily used when the number of iterations is not known beforehand, and the loop
continues as long as a specific condition remains true. It focuses on the condition.
• for loop: Typically used when the number of iterations is known or can be easily controlled with
an initialization, condition, and update expression. It neatly combines loop control elements in its
header.
Key Difference: for loops are often more structured for count-controlled iterations, while while loops
are more general-purpose for condition-based iterations. However, any for loop can be rewritten as a
while loop, and vice versa.
(c) break and goto Comparison:
• break statement: Used to immediately terminate the innermost enclosing loop (for, while,
do...while) or the switch statement. Execution continues with the statement immediately
following the terminated construct.
• goto statement: Used to unconditionally transfer program control to a labeled statement within
the same function.
Key Difference: break has a more structured and limited scope of control transfer (exiting loops or
switches). goto allows for arbitrary jumps within a function, which can lead to less readable and
harderto-maintain "spaghetti code" if not used very carefully and sparingly.
• break statement: Terminates the entire loop (or switch statement) immediately.
• continue statement: Skips the rest of the current iteration of the loop. Control is transferred back
to the loop's condition evaluation (for while and do...while) or the update expression and then
the condition evaluation (for for).
Key Difference: break exits the loop entirely, while continue only skips the current iteration and
proceeds to the next one (if the loop condition is still true).
• continue statement: Transfers control to the beginning of the next iteration of the current loop.
• goto statement: Transfers control to a labeled statement anywhere within the same function.
Key Difference: continue has a specific and restricted control flow within loops. goto provides a more
general but potentially less structured way to transfer control.
(f) continue and break and goto Comparison (building on previous points):
6.11 Analyze each of the program segments that follow and determine how many times the body of
each loop will be executed.
(a)
C
x = 5; y = 50;
while (x <=
y)
{
x = y / x; }
Analysis:
(b)
C
m = 1;
do {
m = m + 2; }
while (m < 10);
Analysis:
1. Initially, m = 1.
2. Iteration 1: The body executes. m becomes 1 + 2 = [Link] condition m < 10 (3 < 10) is true.
3. Iteration 2: The body executes. m becomes 3 + 2 = 5. The condition m < 10 (5 < 10) is
true. 4. Iteration 3: The body executes. m becomes 5 + 2 = 7. The condition m < 10 (7 < 10)
is true.
[Link] 4: The body executes. m becomes 7 + 2 = 9. The condition m < 10 (9 < 10) is true.
[Link] 5: The body executes. m becomes 9 + 2 = 11. The condition m < 10 (11 < 10) is false.
The loop terminates. The body of the loop is executed 5 times. (c)
C int
i;
for
(i =
0; i
< 5;
i = i
+
2/3)
{
// Loop body }
Analysis:
1. i is initialized to 0.
2. The condition is i < 5.
3. In each iteration, i is updated by i = i + 2/3. Integer division 2/3 results in 0. So, i will remain
0 in each iteration.
4. Iteration 1: i < 5 (0 < 5) is true. i remains 0.
5. Iteration 2: i < 5 (0 < 5) is true. i remains 0. This will also be an infinite loop because the value
of i never changes. The body will be executed infinitely many times. (d)
C
int m = 10; int n
= 7; while (m % n
>= 0)
{ m = m +
1; n = n
+ 2; }
Analysis:
1. Initially, m = 10 and n = 7.
2. Iteration 1: m % n (10 % 7 = 3) >= 0 is true. m becomes 11, n becomes 9.
3. Iteration 2: m % n (11 % 9 = 2) >= 0 is true. m becomes 12, n becomes 11.
4. Iteration 3: m % n (12 % 11 = 1) >= 0 is true. m becomes 13, n becomes 13.
5. Iteration 4: m % n (13 % 13 = 0) >= 0 is true. m becomes 14, n becomes 15.
6. Iteration 5: m % n (14 % 15 = 14) >= 0 is true. m becomes 15, n becomes 17.
7. Iteration 6: m % n (15 % 17 = 15) >= 0 is true. m becomes 16, n becomes 19. The value of n
increases faster than m. Eventually, n will become larger than m. When n > m, the result of m % n
will be m itself (since m is non-negative), and the condition m % n >= 0 will remain true as long as
mis non-negative. Since m is always increasing, this will also lead to an infinite loop. The body
will be executed infinitely many times.
6.12 Find errors, if any, in each of the following looping segments. Assume that all the variables
have been declared and assigned values.
(a)
C
while ( count = 10 )
{
sum = sum + k;
}
Error: The condition in the while loop is an assignment (count = 10) instead of a comparison (count
== 10). The assignment will always evaluate to the assigned value (10), which is non-zero and thus
treated as true in C. This will result in an infinite loop unless there's a break statement inside the loop
(which is not present here).
C
while ( count == 10 )
{
sum = sum + k;
// Potentially modify 'count' inside the loop to avoid infinite loop
}
(b)
C
name = 1; do
name = name + 1; while (
1. The variable name is likely intended to be a string or character array, but it's being assigned integer
values. This might lead to type mismatch errors depending on how name is declared.
2. The condition in the while loop is an assignment (name = count + 1) instead of a comparison
(e.g., name < count + 1). The assignment will evaluate to the assigned value, which will likely
be non-zero, leading to an infinite loop.
Corrected (assuming name is an integer and the intent was to loop while name is less than or equal to
count + 1):
C
int name = 1; // Assuming 'name' is an integer do
{
name = name + 1;
} while ( name <= count + 1 );
1, 2, 4, 8, 16, 32
C
for (int i = 1; i <= 32; i *= 2) {
printf("%d ", i);
} printf("\n");
(b) 3, 9, 27, 81, 243
C
for (int i = 3; i <= 243; i *= 3) {
printf("%d ", i);
} printf("\n");
C
for (float i = 4.0; i >= 0.25; i /= -2.0) {
printf("%.2f ", i);
} printf("\n");
C
for (int i = -4; i <= 4; i += 2) {
printf("%d ", i);
} printf("\n");
C
for (int i = 20; i >= -10; i -= 6) {
printf("%d ", i);
} printf("\n");
C
for (int i = -10; i <= 30; i += 10) {
printf("%d ", i);
} printf("\n");
C
printf("Hi\n");
int i; // Assuming 'i' is declared before
while (i <= 5) { printf("%d\n", i);
i++;
printf("Hello\n"); }
C
int sum = 0;
int number; // Assuming 'number' is declared before
while (number != 0) { sum += number;
scanf("%d", &number); }
6.15 Change the following while loops in Exercise 6.14 to do...while loops.
C
int x = 1; do
{
printf("%d\n", x);
x++;
} while (x <= 10);
C
printf("Hi\n");
int i; // Assuming 'i' is declared before
if (i <= 5) { // To handle the case where the condition is initially false
do {
printf("%d\n", i);
i++;
printf("Hello\n");
} while (i <= 5);
}
(c) int sum = 0; int number; while (number != 0) { sum += number; scanf("%d",
&number); }
C
int sum = 0;
int number; // Assuming 'number' is declared before
do { sum += number; scanf("%d", &number); }
while (number != 0);
// Note: If 'number' is initially 0, the loop body will execute once.
C
int n = 0; while
(n <= 0)
{ if (n < 10)
m = n + 10;
} printf("m = %d\n", m); // 'm' might be uninitialized if the loop doesn't
execute Analysis:
1. n is initialized to 0.
2. The while condition (n <= 0) is true.
3. Inside the loop, the if condition (n < 10) (0 < 10) is true.
4. m is assigned the value n + 10, which is 0 + 10 = 10.
5. The loop condition (n <= 0) remains true, leading to an infinite loop. The value of m will be
continuously updated to 10.
6. The printf statement is outside the loop, so it will only be reached if the loop terminates (which
it won't in this case). If the program were to somehow exit the loop (e.g., with a break), the
output would be m = 10. However, as written, it's an infinite loop, and the printf might not
be reached.
Assuming the loop would eventually terminate (which it shouldn't): Output would be m = 10.
C
int n = 5;
do {
if (n == 10)
continue; n++;
} while (n < 7); printf("n
1. n is initialized to 5.
2. The do...while loop starts.
3. Iteration 1: n == 10 (5 == 10) is false. n becomes 6.
4. Iteration 2: n == 10 (6 == 10) is false. n becomes 7.
5. The while condition (n < 7) (7 < 7) is false. The loop terminates.
6. printf("n = %d\n", n); prints the final value of n.
Output:
n = 7
C
int n = 0, m = 1;
do {
printf("%d ", m);
m++;
} while (m == n);
printf("\n");
Analysis:
Output of 6.18:
1
C
int n = 0, m;
for (m = 1; m = n + 1; m++)
printf("%d ", m);
printf("\n"); Analysis:
Output of 6.19:
1 1 1 1 1 1 1 1 1 1 ... (infinitely)
C for ( ; ;
)
Answer: The statement for ( ; ; ) represents an infinite loop. We use it in situations where we want
a block of code to execute repeatedly without a predetermined number of iterations or a fixed termination
condition within the for loop header itself.
• Event-driven programs: Waiting for user input, network events, or sensor data. The loop
continues indefinitely until a specific event triggers a break or the program is terminated
externally.
• Real-time systems: Continuously monitoring and reacting to environmental changes.
• Background processes or services: Performing tasks in the background as long as the system is
running.
• When the loop termination is handled explicitly within the loop body using break statements
based on certain conditions. This allows for more complex or dynamic termination logic.
It's crucial to ensure that there is a mechanism (usually a break statement within the loop) to eventually
exit the loop under specific conditions to prevent the program from running indefinitely in unintended
ways.
Chapter 7
7.3 Identify errors, if any, in each of the following array declaration statements, assuming that ROW
and COLUMN are declared as symbolic constants.
(a) int score (); Error: This looks like a function declaration, not an array declaration. An array
declaration needs square brackets [] to specify the size.
Corrected: int score[]; (size can be defined later or during initialization) or int score[SIZE];
(where SIZE is a constant).
(b) float values [10,15]; Error: Multidimensional array declarations in C use separate square
brackets for each dimension. A comma inside a single pair of brackets is incorrect for declaring a 2D
array.
(c) float average[ROW + ][COLUMN]; Error: There's an extra ] after ROW +. The size of an array
dimension should be a single expression within the square brackets.
(d) char name[15]; Error: No apparent error in this declaration. It declares a character array
(string) that can hold up to 14 characters plus the null terminator.
(e) int sum []; Error: While this is valid in some contexts (like function parameters), if it's a
standalone declaration within a function, the size needs to be defined either explicitly or through
initialization.
Corrected (with initialization): int sum[] = {1, 2, 3}; or Corrected (with size): int sum[SIZE];
(f) double salary [, + ROW]; Error: Similar to (b) and (c), the syntax for multidimensional
arrays is incorrect. The comma and + inside the single pair of brackets are invalid.
(g) long int number [ROW]; Error: No apparent error in this declaration. It declares an array of
long int with a size determined by the symbolic constant ROW.
(h) int array = [COLUMN]; Error: The syntax for array declaration is incorrect. The variable name
should come before the square brackets. Also, using = with just the size in square brackets is not the
standard way to declare an array (it looks like an attempt at initialization, but the syntax is wrong).
(a) int number [ ] = { 0,0,0,0,0 }; Error: No apparent error. This correctly initializes an integer
array, and the size is automatically determined by the number of initializers (5).
1. The inner elements are enclosed in parentheses () instead of curly braces {}.
2. There are 6 initializers for an array of size 3x2 (which can hold only 6 elements), but the grouping
is incorrect. The outer curly braces should contain initializers for each row (which are themselves
enclosed in curly braces).
(c) char words [ ] = { 'R', 'A', 'I', 'N', 'Y' }; Error: No apparent error. This correctly
initializes a character array. The size will be 5.
(d) int set [2] [4] = { {0,0}, {1,1,1,1} }; Error: No apparent error, but there's a potential for
uninitialized elements. The array set has 2 rows and 4 columns (8 elements). The first row is
initialized with two 0s, and the remaining two elements will be 0 by default. The second row is fully
initialized with four 1s.
(e) float result [10] = 0; Error: This attempts to initialize the entire array with a single value using
an assignment-like syntax. To initialize all elements to 0, you should use curly braces.
Corrected: float result[10] = {0}; (This initializes the first element to 0, and the rest will be 0 by
default for numeric types). Or float result[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};.
C
int A[5][4]; float
B[4];
7.5 Assume that the arrays A and B are declared as follows: (a)
C
for (i=1; i<=5; i++)
for(j=1; j<=4; j++)
A[i][j] = 0;
Errors:
• Array A is declared as int A[5][4], which means the valid row indices are from 0 to 4, and the
valid column indices are from 0 to 3.
• The outer loop iterates i from 1 to 5 (inclusive), causing an out-of-bounds access when i is 5
(A[5] is invalid).
• The inner loop iterates j from 1 to 4 (inclusive), causing an out-of-bounds access when j is 4
(A[i][4] is invalid).
Corrected:
C
for (i=0; i<5; i++)
for(j=0; j<4; j++)
A[i][j] = 0;
(b)
C
for (i=1; i<4; i++)
• Array B is declared as float B[4], meaning the valid indices are from 0 to 3.
• The loop iterates i from 1 to 3 (inclusive), which is within the valid bounds. However, the element
B[0] is never initialized by this loop.
• If the intention was to initialize all elements of B, the loop should start from 0.
• If initializing only elements from index 1 to 3 was intentional, then there is no strict out-of-bounds
error in the loop itself. However, the element at index 0 will retain its uninitialized value.
C
for (i=0; i<4; i++)
scanf("%f", &B[i]);
(c)
C
for (i=0; i<=4; i++)
• Array B is declared as float B[4], meaning the valid indices are from 0 to 3.
• The loop iterates i from 0 to 4 (inclusive), causing an out-of-bounds access when i is 4 (B[4] is
invalid).
Corrected:
C
for (i=0; i<4; i++)
B[i] = B[i] + i;
Chapter 9
9.4 Describe the two ways of passing parameters to functions. When do you prefer to use each of them?
Answer:
• Call by value: Copies the value of the argument into the formal parameter. Use when the function should
not modify the original data.
• Call by reference: Passes the address of the argument, allowing modification of the original data. Use
when the function needs to change the original variable.
Answer: Prototyping is declaring a function (its name, return type, and parameters) before its use. It’s
necessary to allow the compiler to check for correct function usage (e.g., matching argument types) and
avoid errors during compilation.
9.7 Explain what is likely to happen when the following situations are encountered in a program:
(a) Actual arguments are less than the formal arguments in a function
Answer: The extra formal parameters will have undefined values, leading to potential runtime errors or
unexpected behavior.
(b) Data type of one of the actual arguments does not match with the type of the corresponding
formal argument
Answer: The compiler may perform implicit type conversion (if compatible) or throw a compilation error
(if incompatible).
(c) Data type of one of the arguments in a prototype does not match with the type of the
corresponding formal parameter in the header line
Answer: This causes a compilation error due to a mismatch between the prototype and the function
definition.
(a)
Copy
int (a, b)
return (a + b);
Answer: Invalid: Missing return type (int) and parameter types. Should be:
Copy
return (a + b);
}
(b)
Copy
int c = a + b;
return c;
Answer: Invalid: Missing function name, C doesn’t support &b (use pointers), and void functions can’t
return a value. Should be:
Copy
int c = a + *b;
(c)
Copy
double (c = a + b)
return (b);
Answer: Invalid: Missing function name, return type, and parameter list. Also, c = a + b isn’t a valid
header. Should be:
Copy
double sum(double a, double b) {
double c = a + b;
return c;
9.13 While calling the function calls if in change the header line:
Copy
#include <stdio.h>
int main()
fun(&x, &y);
return 0;
*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
Answer:
The function swaps the values of x and y using pointers:
10 20
20 10
Copy
#include <stdio.h>
return (a * b);
int main()
int x = 5, y = 4, z;
return 0;
Answer: Output: 20
Explanation: The function prod multiplies a and b, so prod(5, 4) returns 20, which is stored in z and
printed.
Copy
int n = 0;
if (n % 2 == 0)
else
number = number - 1;
n = n + 1;
return (n);
What will be the values of x and y when the following statements are executed?
Copy
int x = 50;
y = test (x);
Answer:
• x = 50 (remains unchanged).
• y=5
Explanation:
• test(50) iterates while number > 0:
o n = 0, number = 50 (even, number = 50 / 10 = 5), n = 1
o n = 1, number = 5 (odd, number = 5 - 1 = 4), n = 2
o n = 2, number = 4 (even, number = 4 / 10 = 0), n = 3
o Loop ends, returns n = 3.
• Correction: Rechecking the logic, the loop runs 5 times (n increments to 5 when number becomes 0), so y
= 5.
9.17 Enumerate the rules that apply to a function call.
Answer:
1. The number of actual arguments must match the number of formal parameters.
2. The data types of actual and formal arguments must be compatible (implicit conversion may occur).
3. The order of actual arguments must correspond to the order of formal parameters.
4. For call by reference, pointers must be used correctly with & and * operators.
5. The function must be prototyped or defined before its call to avoid undefined behavior.
9.18 Summarize the rules that apply to passing parameters to functions by pointers.
Answer:
1. Use the address-of operator (&) to pass the address of a variable to a pointer parameter.
2. The formal parameter must be a pointer type (e.g., int *p).
3. Dereference the pointer (*p) inside the function to modify the original variable.
4. Ensure the actual argument is a variable (not a constant or expression unless a pointer is explicitly
managed).
5. The pointer must point to a valid memory location to avoid segmentation faults.
9.19 What are the rules that govern the passing of arrays to functions?
Answer:
1. Arrays are passed by reference (the address of the first element is passed).
2. The formal parameter should be a pointer (e.g., int *arr) or an array notation (e.g., int arr[]).
3. The size of the array is not passed automatically; it must be passed as a separate parameter if needed.
4. Changes to the array elements inside the function affect the original array.
5. The array name acts as a constant pointer, so it cannot be reassigned within the function.
9.20 State the problems we are likely to encounter when we pass global variables as parameters to
functions.
Answer:
1. Unintended Modification: Global variables can be altered unintentionally, leading to side effects and
debugging challenges.
2. Scope Confusion: Passing a global variable as a parameter may confuse the function’s intent, as it can
access the global directly.
3. Name Conflicts: If a local variable has the same name as a global variable, it can overshadow the global,
causing unexpected behavior.
4. Maintainability Issues: Overuse of global variables reduces modularity and makes the code harder to
maintain or reuse.
5. Thread Safety: In multi-threaded programs, global variables passed as parameters can lead to race
conditions if not properly synchronized.