0% found this document useful (0 votes)
104 views74 pages

Cse Full

The document outlines the advantages of C programming, including efficiency, portability, and memory management, making it ideal for system programming and embedded systems. It also discusses the basic data types, variable rules, and the importance of comments and structure in C programs. Additionally, it covers the history of C, its influence on other languages, and the significance of using qualifiers and proper syntax in programming.
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)
104 views74 pages

Cse Full

The document outlines the advantages of C programming, including efficiency, portability, and memory management, making it ideal for system programming and embedded systems. It also discusses the basic data types, variable rules, and the importance of comments and structure in C programs. Additionally, it covers the history of C, its influence on other languages, and the significance of using qualifiers and proper syntax in programming.
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

1.

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:

1. Efficiency & Performance


● C provides low-level memory access and minimal runtime overhead, making it extremely
fast and efficient.
● It is widely used for developing operating systems, embedded systems, and real-time
applications.

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.

4. Flexibility & Modularity


● Supports modular programming with functions, making code reusable and easy to
maintain.
● Large programs can be divided into multiple functions to improve readability.

5. Rich Library Support


● C provides a vast set of built-in libraries and functions for file handling, string
manipulation, and mathematical operations.

6. Foundation for Other Languages


● Many modern languages (C++, Java, Python) are influenced by C.
● Learning C builds a strong foundation for understanding programming concepts.

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

variable name (e.g., int, char, return, etc.).

Sure! Let's break it down in a simple way:

2.

a)

○ x is initialized to 10.

2. First Assignment (y = 15 + x++) ○ x++ means:

■ Use x first (which is 10).

■ Then increase x by 1.

○ So, y = 15 + 10 = 25.

○ Now, x becomes 11.

3. Second Assignment (z = 15 + ++x) ○ ++x means:

■ Increase x first (11 becomes 12).


■ Then use x.

○ 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;

// Taking input from the user


printf("Enter a year: ");
scanf("%d", &year);

// Checking leap year conditions if ((year % 4 == 0 && year


% 100 != 0) || (year % 400 == 0)) { printf("%d is a Leap Year.\n",
year);
} else {
printf("%d is NOT a Leap Year.\n", 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);

// Using switch statement to display the corresponding weekday name


switch(day) { case 1:
printf("Sunday\n"); break;
case 2:
printf("Monday\n"); break;
case 3:
printf("Tuesday\n"); break;
case 4:
printf("Wednesday\n"); break;
case 5:
printf("Thursday\n"); break;
case 6:
printf("Friday\n"); break;
case 7:
printf("Saturday\n");
break;
default:
printf("Invalid input! Please enter a number between 1 and 7.\n");
}

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

Foundation for Other Languages:


C is the base for many other programming languages like C++, Java, and Python. Learning C
helps you understand how other languages work.
System Programming:
C is used to write operating systems and other low-level programs. It allows you to interact
directly with the hardware of a computer, making it powerful for system programming.
Efficiency:
C is very fast and efficient because it gives the programmer control over system resources like
memory. This makes it ideal for programs that need to run quickly, like video games or device
drivers.
Portability:
C programs can be easily transferred from one type of computer to another. This means you can
write a program on one system and run it on different systems with minimal changes. Widely
Used in Embedded Systems:
C is used in devices like phones, microwaves, and cars. It’s important for programming devices
with limited resources like memory and processing power.
Strong Community and Libraries:
C has been around for a long time, so there are a lot of resources, tutorials, and libraries that
make programming in C easier.

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.

1.12 Why and when do we use the #include directive?


● The #include directive is used to include the contents of a file, typically header files, in
the source code. This is necessary to use functions, variables, and macros defined in
other files or libraries.
1.13 What does void main(void) mean?

● 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[]).

1.14 Distinguish between the following pairs:

● (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.

1.15 Why do we need to use comments in programs?

● 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.

1.16 Why is the look of a program important?

● The look of a program, including formatting and indentation, is important for readability and
maintainability. Well-structured code is easier to debug and extend.

1.17 Where are blank spaces permitted in a C program?

● 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.

● A typical C program includes preprocessor directives (like #include), global declarations,


the main() function, and other user-defined functions. The main() function is the entry
point of the 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

execute the resulting binary (e.g., ./program).

1.20 How do we implement multiple source program files?

● 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,

long, or long long.

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

char to store larger positive values.

4. double: Used to store double-precision floating-point numbers. The range can be


extended by using long double.

To extend the range of values, you can use qualifiers like unsigned, short, long, and long

long for integers, and long double for floating-point numbers.

2.7 What is a variable and what is meant by the “value” of a variable?


A variable is a named storage location in memory that holds data which can be changed during
program execution. The value of a variable is the actual data stored in that memory location.
For example, in the statement int x = 5;, x is the variable, and 5 is its value.

2.13 Describe the purpose of the qualifiers const and volatile.

● 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.15 Which of the following are invalid constants and why?


● 0.0001: Valid. It is a floating-point constant.
● 5 × 1.5: Invalid. The multiplication symbol (×) is not allowed in constants.
● 99999: Valid. It is an integer constant.
● +100: Valid. It is a positive integer constant.
● 75.45 E-2: Valid. It is a floating-point constant in scientific notation.
● “15.75”: Invalid. It is a string, not a numeric constant.
● –45.6: Valid. It is a negative floating-point constant.
● –1.79 e + 4: Valid. It is a floating-point constant in scientific notation. ● 0.00001234:
Valid. It is a floating-point constant.
2.16 Which of the following are invalid variable names and why?
● Minimum: Valid. It starts with a letter and contains only letters.
● [Link]: Invalid. It contains a period (.), which is not allowed in variable names.
● n1+n2: Invalid. It contains a plus sign (+), which is not allowed in variable names.
● &name: Invalid. It contains an ampersand (&), which is not allowed in variable names.
● doubles: Valid. It starts with a letter and contains only letters.
● 3rd_row: Invalid. It starts with a digit, which is not allowed in variable names.
● **n∗∗:[Link](∗∗:[Link](), which is not allowed
in standard C.
● Row1: Valid. It starts with a letter and contains letters and digits.
● float: Invalid. It is a reserved keyword in C.
● Sum Total: Invalid. It contains a space, which is not allowed in variable names.
● Row Total: Invalid. It contains a space, which is not allowed in variable names.
● Column-total: Invalid. It contains a hyphen (-), which is not allowed in variable names.

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

int, float, double, etc.

5. m,n,z: INTEGER
○ Error: The syntax is incorrect. In C, the correct syntax is int m, n, z;.

INTEGER is not a valid keyword in C.


6. short char c;
○ Error: short char is not a valid combination. It should be either char c; or

short int c;.

7. long int m; count;


○ Error: The declaration is incomplete. It should be long int m, count;.
8. long float temp;
○ Error: long float is not a valid data type in C. Use double for double-precision
floating-point numbers. Corrected code:

2.18 What would be the value of x after execution of the following


statements?

The value of x would be 107. This is because the character 'a' has an ASCII value of 97.

Adding y (which is 10) to z (which is 97) results in 107.


2.19 Identify syntax errors in the following program. After corrections, what
output would you expect when you execute it?
Here is the original program with syntax errors:

Syntax Errors:

1. Incomplete comment: The comment on the line int R,C; is not properly closed.

2. Missing semicolon: The line C = PI is missing a semicolon at the end.


3. Incorrect variable names: Perimeter and Area should be perimeter and area
respectively.
4. Incorrect printf statement: The format specifiers and arguments in the printf
statement are incorrect. The & (address-of) operator should not be used for printing
values.
5.

2.21a) Global and Local Variables

● 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.

(b) Automatic and Static Variables


● Automatic Variables:
○ Declared within a function or block without any storage class specifier or with the
auto keyword.

○ 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;

(c) Initialization and Assignment of Variables


● Initialization:
○ The process of assigning an initial value to a variable at the time of its declaration.
○ Example: int x = 10;
○ Ensures that the variable has a valid value as soon as it is created. ●
Assignment:
○ The process of giving a value to a variable after it has been declared.
○ Example: int x; x = 10;
○ Can be done multiple times throughout the program.

3.1 State whether the following statements are true or false.


(a) All arithmetic operators have the same level of precedence.

● False. Arithmetic operators have different levels of precedence. For example,


multiplication and division have higher precedence than addition and subtraction.
(b) The modulus operator % can be used only with integers.

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.

(e) In C, if a data item is zero, it is considered false.

● True. In C, a zero value is considered false in a boolean context.

(f) The expression f(x≤y)f(x≤y) is same as the expression x > y.

● 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.

(g) A unary expression consists of only one operand with no operators.

● False. A unary expression consists of one operand and one unary operator (e.g., -x, ++x).

(h) Associativity is used to decide which of several different expressions is evaluated


first.

● True. Associativity determines the order in which operators of the same precedence level are
evaluated.

(i) An expression statement is terminated with a period.

● False. An expression statement in C is terminated with a semicolon (;), not a period.

(j) During the evaluation of mixed expressions, an implicit cast is generated


automatically.

● True. In mixed expressions, C automatically performs implicit type conversion (casting) to ensure
consistent types.

An explicit cast can be used to change the expression



(k) .

● True. An explicit cast can be used to convert one data type to another, changing the
expression's type.

(l) Parentheses can be used to change the order of evaluation expressions.


True. Parentheses can be used to override the default precedence and associativity rules,
changing the order of evaluation.
3.3 Given the statement int a = 10, b = 20, c;, determine whether
each of the following statements are true or false.

(a) The statement a = + 10; is valid.

● True. The statement is valid. The + is a unary plus operator, and a = +10; assigns the

value 10 to a.

(b) The expression a + 4/6 * 6/2 evaluates to 11.

● False. The expression evaluates to 10. The calculation is as follows:

○ 4/6 is 0 (integer division).

○ 0 * 6 is 0.

○ 0 / 2 is 0.

○ a + 0 is 10.

(c) The expression b + 3/2 * 2/3 evaluates to 20.

● True. The expression evaluates to 20. The calculation is as follows:

○ 3/2 is 1 (integer division).

○ 1 * 2 is 2.

○ 2 / 3 is 0.

○ b + 0 is 20.

(d) The statement a += b; gives the values 30 to a and 20 to b.



● True. The statement a += b; is equivalent to a = a + b;, so a becomes 30 and b

remains 20.

(e) The statement ++a++; gives the value 12 to a.

● False. The statement ++a++; is invalid because it attempts to apply both the

preincrement and post-increment operators to a simultaneously, which is not allowed.

(f) The statement a = 1/b; assigns the value 0.5 to a.


False. The statement a = 1/b; performs integer division, so 1/20 is 0, and a is

assigned 0.

3.4 Declared a as int and b as float, state whether the following


statements are true or false.
(a) The statement a = 1/3 + 1/3 + 1/3; assigns the value 1 to a.

● False. The expression 1/3 + 1/3 + 1/3 performs integer division, so each 1/3 is 0,

and the sum is 0. Thus, a is assigned 0.

(b) The statement b = 1.0/3.0 + 1.0/3.0 + 1.0/3.0; assigns a value 1.0


to b.

● True. The expression 1.0/3.0 + 1.0/3.0 + 1.0/3.0 evaluates to approximately

1.0, so b is assigned 1.0.

(c) The statement b = 1.0/3.0 * 3.0 gives a value 1.0 to b.

● True. The expression 1.0/3.0 * 3.0 evaluates to 1.0, so b is assigned 1.0.

(d) The statement b = 1.0/3.0 + 2.0/3.0 assigns a value 1.0 to b.

● True. The expression 1.0/3.0 + 2.0/3.0 evaluates to 1.0, so b is assigned 1.0.



3. 5.a) !(5 + 5 >= 10)

1. Evaluate 5 + 5 >= 10:

○ 5 + 5 is 10.

○ 10 >= 10 is true.

2. Apply the NOT operator !:

○ !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.

3. Apply the OR operator ||:

○ true || false is true.

Result: true

(c) 5 > 10 || 10 < 20 && 3 < 5

1. Evaluate 5 > 10:

○ 5 > 10 is

false. 2. Evaluate

10 < 20:

○ 10 < 20 is true.

3. Evaluate 3 < 5:

○ 3 < 5 is true.

4. Apply the AND operator &&:

○ true && true is true.

5. Apply the OR operator ||:

○ false || true is true.

Result: true

(d) 10 != 15 && !(10 < 20) || 15 > 30

1. Evaluate 10 != 15:

○ 10 != 15 is true.

2. Evaluate 10 < 20:

○ 10 < 20 is true.

Apply the NOT operator !: ○ !true is false


3. .

4. Apply the AND operator &&:

○ true && false is false.

5. Evaluate 15 > 30:

○ 15 > 30 is false.

6. Apply the OR operator ||:


○ false || false is false.

Result: false

Summary of Results:

● (a) false

● (b) true ● (c) true

● (d) false 3.6(a)

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

(g) (5/3)∗(5/3)∗ 3+5%3+5% 3


1. Validity: Invalid.
2. Reason: The expression contains an invalid operator ^*. It seems to be a typo or
incorrect syntax.

Result: Invalid (h)

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'.

○ printf("%c\n", y); prints the character representation of y. Since y is 125, it

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:

○ Reads formatted input from the standard input.


○ Requires a format specifier to determine the type of data to be read.
○ Can read multiple types of data (e.g., integers, floats, strings) in a single call.
○ Example: scanf("%d", &num); (b)

%s and %c specifications for reading

● %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:

○ Reads a single character from the input. ○


Does not skip whitespace characters.

○ Example: scanf("%c", &ch); (c)

%s and %[ ] specifications for reading

● %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.

(d) %g and %f specifications for printing

● %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.

(e) %f and %e specifications for printing

● %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.

4.6 State errors, if any, in the following input statements.

(a) scanf("%c%f%d", city, &price, &year);

● Error: city should be passed with an ampersand (&city) since it is a single


character, not a string.

(b) scanf("%s%d", city, amount);

● Error: amount should be passed with an ampersand (&amount) to provide the


address of the variable.

(c) scanf("%f, %d, &amount, &year);

● Error: The format string should not include the commas and ampersands. It should
be "%f%d", &amount, &year.

(d) scanf("n "%f", root);


● Error: The format string is incorrect. It should be "%f" and root should be passed

with an ampersand (&root).

(e) scanf("%c %d %ld", "code, &count, Root);

● 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:

(a) scanf("%d %c", &year, &code);

● Values: year will be 1988 and code will be 'x'.

(b) scanf("%c %d", &year, &code);

● Values: This will cause incorrect assignments because year is expected to be a

character and code an integer. year will be '1' (the first character of 1988) and

code will be 988.

(c) scanf("%d %c", &code, &year);

● Values: code will be 1988 and year will be 'x'.

(d) scanf("%s %c", &year, &code);

● 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.

4.13 What is the purpose of scanf() function?

● 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.

● Answer: Commonly used conversion characters in scanf() include: ○


%d for integers.

○ %f for floating-point numbers.

○ %c for single characters.

○ %s for strings.

○ %lf for double-precision floating-point numbers.


These conversion characters specify the type of data to be read and stored
in the corresponding variables.

4.16 What is the purpose of printf() function?

● 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.

● Answer: Commonly used conversion characters in printf() include:

○ %d for integers.

○ %f for floating-point numbers.

○ %c for single characters.

○ %s for strings.

○ %lf for double-precision floating-point numbers.


These conversion characters specify the type of data to be printed.
4.18 How does a control string in a printf() function differ from the control
string in a scanf() function?

● 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

format of the input, including conversion specifiers and optional whitespace or


literal characters to match.
Chapter 5
5.1 State whether the following are true or false:

(a) When if statements are nested, the last else gets associated with the nearest if without an
else. → True

(b) One if can have more than one else clause.


→ False (Each if can have only one else, but else if can chain.)

(c) A switch statement can always be replaced by a series of if..else statements. → True

(d) A switch expression can be of any type.


→ False (Only integral types: int, char, enum.)

(e) A program stops its execution when a break statement is encountered.


→ False (It exits the loop/switch, not the whole program.)

(f) Each expression in the else if must test the same variable.
→ True (To be replaced with switch.)

(g) Any expression can be used for the if expression. → True

(h) Each case label can have only one statement.


→ False (Can have a block of statements.)

(i) The default case is required in the switch statement. → False

(j) The predicate !(x >= 10||(y <= 5)) is equivalent to (x < 10)&&(y > 5). → True (By De
Morgan's law.)

5.2 Fill in the blanks:

(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:

(a) if (x + y = z && y > 0) Error:


= used instead of ==.
✅ Correct: if ((x + y == z) && y > 0)

(b)

c
if (code > 1);
a = b + c;
else a =
0;

Error: Semicolon after if (code > 1); ends the if. ✅


Correct: Remove the semicolon.

(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))

5.4 What will be the values of x and y if n assumes:


c x = 1; y =
1; if (n > 0)
x = x + 1; y
= y - 1;

• (a) n = 1:
→ x = 2, y = 0 •
(b) n = 0:
→ x = 1, y = 0

5.5 Rewrite without compound


relations: (a) if (grade <= 59 &&
grade >= 50) second =
second + 1;
c
✅ Without compound relation:

c CopyEdit if (grade >= 50)


if (grade <= 59)
second = second + 1;

(b)

c CopyEdit if (number > 100 ||


number < 0) printf("Out of
range"); else sum = sum +
number;

✅ Without compound relation:

c CopyEdit if (number >


100) printf("Out of
range"); else if (number <
0) printf("Out of
range"); else sum =
sum + number;

(c)

c CopyEdit if ((M1 > 60 && M2 > 60)


|| T > 200) printf("Admitted\n");
else printf("Not admitted\n");
✅ Without compound relation:

c CopyEdit if (M1 > 60) if


(M2 > 60)
printf("Admitted\n"); else
if (T > 200)
printf("Admitted\n"); else
printf("Not admitted\n"); else
if (T > 200)
printf("Admitted\n");
else
printf("Not admitted\n");

5.6 State whether the following logical expressions are true or false (assuming x = 10)

(a) x == 10 && x > 10 && !x →


False
Explanation: x == 10 is true, x > 10 is false, and !x is false (since x ≠ 0).
(b) x == 10 || x > 10 && !x
→ True
Explanation: || has lower precedence than &&, so it's: x == 10 || (x > 10 && !x). The first part is
true.

(c) x == 10 && x > 10 || !x


→ False
Explanation: (x == 10 && x > 10) is false. !x is also false.

(d) x == 10 || x > 10 || !x → True

Explanation: x == 10 is true.

5.7 Find errors in switch-related statements (assume int x=1, y=2)

(a) switch(y);
→ Error: Semicolon ends the statement — no case block.
✅ Correct: Remove semicolon and add braces and case.

(b) case 10:


→ Error: Case must be inside a switch block.

(c) switch (x + y)
→ Valid if followed by a valid case block.

(d)

c Copy code switch (x)


{ case 2: y = x +
y; break; }

→ Valid

5.8 Simplify the compound logical expressions:

(a) !(x <= 10)


→ x > 10

(b) !(x == 10) || (y == 5) || (z < 0)


→ x != 10 || y == 5 || z < 0
(c) !( (x + y == 2) && (z > 5) )
→ x + y != 2 || z <= 5

(d) !( (x <= 5) && (y == 10) && (z < 5)


)
→ x > 5 || y != 10 || z >= 5

5.9 What will be x, y, z after execution (x=5, y=0, z=1)

(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;

• x = 0 || x && y → x = 0 (assignment!) → false, skip body.


→ x = 0, y = 0, z = 1
5.10 Assuming x=2, y=1, z=0

(a)

c Copy code switch


(x) { case 2:
x = 1; y
= x + 1; case
1: x = 0;
break;
default:
x = 1; y
= 0; }

→ 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; }

→ No case matches (y = 1), goes to default → x = 1, y = 2, z = 0

5.11 Find the error in the following statements

(a)

c Copy code if (x
> 10) then
printf("\n");

Error: then is not valid in C. ✅ Remove then.

(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");

Error: Assignment instead of comparison. ✅ Use == instead.

(d)

c Copy code if (x <


10)
printf("Welcome");

✅ Correct

5.12 Output of the program:


c Copy code main() {
int m = 5; if (m <
3) printf("%d",
m1); else if (m < 5)
printf("%d", m2);
else if (m < 7)
printf("%d", m3);
else
printf("%d", m4); }

Error: m1, m2, m3, m4 are undeclared → Compile-time error

5.13 What is the output of the following program?

C
main ( ) { int m = 1; if
( m == 1 ) { printf ( "
Delhi " ); if ( m == 2 )
printf ( " Chennai " );
else
printf("Bangalore");
}
else
printf(" END"); }

Answer:

• The variable m is initialized to 1.


• The first if condition (m == 1) is true.
• printf ( " Delhi " ); executes, printing " Delhi ".
• The inner if condition (m == 2) is false (since m is 1).
• The else block associated with the inner if executes, printing "Bangalore".
• The else block associated with the outer if is skipped.

Output of 5.13:
Delhi Bangalore

5.14 What is the output of the following program?

C
main ( ) {
int m ;
for ( m = 1 ; m<5 ; m++ )
printf("%d\n", (m%2) ? m : m*2); }

Answer:

• The for loop iterates for m values 1, 2, 3, and 4.


• Inside the loop, the ternary operator (m%2) ? m : m*2 checks if m is odd.
o If m is odd (m % 2 is non-zero), it prints m. o
If m is even (m % 2 is zero), it prints m * 2.

Let's trace the execution:


• 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

5.15 What is the output of the following program?

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.

The value of x when the segment is executed is 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.

5.13 What is the output of the following program?

C
main ( ) { int m = 1; if
( m == 1 ) { printf ( "
Delhi " ); if ( m == 2 )
printf ( " Chennai " );
else
printf("Bangalore");
}
else
printf(" END");
}
Answer:

• The variable m is initialized to 1.


• The first if condition (m == 1) is true.
• printf ( " Delhi " ); executes, printing " Delhi ".
• The inner if condition (m == 2) is false (since m is 1).
• The else block associated with the inner if executes, printing "Bangalore".
• The else block associated with the outer if is skipped.

Output of 5.13:
Delhi Bangalore

5.14 What is the output of the following program?

C
main ( ) {
int m ;
for ( m = 1 ; m<5 ; m++ )
printf("%d\n", (m%2) ? m : m*2); }

Answer:

• The for loop iterates for m values 1, 2, 3, and 4.


• Inside the loop, the ternary operator (m%2) ? m : m*2 checks if m is odd.
o If m is odd (m % 2 is non-zero), it prints m.
o If m is even (m % 2 is zero), it prints m * 2.

Let's trace the execution:

• 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

5.15 What is the output of the following program?

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.

The value of x when the segment is executed is 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

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.

(c) for ( n = 1; n <= 5; n = n + 1 ) sum = sum + n; Answer: This loop initializes n to 1. It


continues as long as n is less than or equal to 5. In each iteration, n is incremented by 1, and sum is updated
by adding the current value of n to it. If sum was initialized to 0, the loop will calculate the sum of numbers
from 1 to 5 (1 + 2 + 3 + 4 + 5 = 15).

(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.

(e) for ( n = 1; n = 5; n ++ ) Answer: This loop initializes n to 1. The condition is n = 5,


which is an assignment. The value 5 is assigned to n, and the result of the assignment (which is 5, a non-
zero value) is treated as true. The loop will execute once. After the first iteration, n becomes 6 due to n++,
but the loop has already completed its single iteration because the condition was evaluated at the
beginning.

(f) for ( n = 1; n = 5; n + + ) Answer: This loop initializes n to 1. The condition is n = 5


(assignment), making the condition true. The loop executes once. After the iteration, n++ (post-increment)
is executed, increasing n to 2. However, similar to the previous case, the loop only runs once based on the
initial condition evaluation.

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".

Output of (a): countcountcountcount... (infinitely)

(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.

Output of (b): (no output)

(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.

Output of (c): countcountcountcount... (infinitely)

(d)

C
int count = 0;
while (count < 7)
{
printf("count");
count++; }
printf("\n");

Answer: This loop will execute 7 times.


• count starts at 0.
• The condition count < 7 is true. "count" is printed, and count becomes 1.
• This continues until count becomes 7. At that point, count < 7 is false, and the loop terminates.
• Finally, printf("\n"); prints a newline character.

Output of (d): countcountcountcountcountcountcount (followed by a newline)

(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.

Output of (e): 10 9 8 7 6 5 4 3 2 1 0 (followed by a newline)

6.10 Compare, in terms of their functions, the following pairs of statements:

(a) while and do...while Comparison:

• 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.

(d) break and continue Comparison:

• 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).

(e) continue and goto Comparison:

• 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):

• break: Exits the immediate loop or switch.


• continue: Skips the current loop iteration and proceeds to the next.
• goto: Jumps to an arbitrary labeled point within the function.
Key Difference: break and continue are loop-specific control flow statements that maintain some level
of structure. goto is a more general jump statement that can disrupt the logical flow of the program more
significantly and is often discouraged for routine control flow.

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:

1. Initially, x = 5 and y = 50.


2. Iteration 1: x <= y (5 <= 50) is true. x becomes 50 / 5 = 10.
3. Iteration 2: x <= y (10 <= 50) is true. x becomes 50 / 10 = 5.
4. Iteration 3: x <= y (5 <= 50) is true. x becomes 50 / 5 = 10.
5. Iteration 4: x <= y (10 <= 50) is true. x becomes 50 / 10 = 5. The values of x will oscillate
between 10 and 5. The condition x <= y will always be true. This is an infinite loop. Therefore,
the body will be executed infinitely many times.

(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).

Corrected (assuming the intent was to loop while count is 10):

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 (

name = count + 1 ); Errors:

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 );

Let's move on to the next questions.


6.13 Write a for statement to print each of the following sequences of integers: (a)

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) 4, -2, 1, -0.5, 0.25

C
for (float i = 4.0; i >= 0.25; i /= -2.0) {
printf("%.2f ", i);
} printf("\n");

(d) -4, -2, 0, 2, 4

C
for (int i = -4; i <= 4; i += 2) {
printf("%d ", i);
} printf("\n");

(e) 20, 14, 8, 2, -4, -10

C
for (int i = 20; i >= -10; i -= 6) {
printf("%d ", i);
} printf("\n");

(f) -10, 0, 10, 20, 30

C
for (int i = -10; i <= 30; i += 10) {
printf("%d ", i);
} printf("\n");

6.14 Change the following for loops to while loops:

(a) for (x = 1; x <= 10; x++) printf("%d\n", x);


C
int x = 1; while (x
<= 10) {
printf("%d\n", x);
x++; }

(b) for (printf("Hi\n"); i <= 5; printf("Hello\n"), i++) printf("%d\n", i);

C
printf("Hi\n");
int i; // Assuming 'i' is declared before
while (i <= 5) { printf("%d\n", i);
i++;
printf("Hello\n"); }

(c) for (sum = 0; number != 0; scanf("%d", &number)) sum += number;

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.

(a) int x = 1; while (x <= 10) { printf("%d\n", x); x++; }

C
int x = 1; do
{
printf("%d\n", x);
x++;
} while (x <= 10);

(b) printf("Hi\n"); int i; while (i <= 5) { printf("%d\n", i); i++; printf("Hello\n");


}

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.

6.16 What is the output of the following code?

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.

6.17 What is the output of the following code?

C
int n = 5;
do {
if (n == 10)
continue; n++;
} while (n < 7); printf("n

= %d\n", n); Analysis:

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

6.18 What is the output of the following code?

C
int n = 0, m = 1;
do {
printf("%d ", m);
m++;
} while (m == n);
printf("\n");

Analysis:

1. n is initialized to 0, and m is initialized to 1.


2. The do...while loop starts.
3. Iteration 1:
o printf("%d ", m); prints the current value of m, which is 1, followed by a space.
o m++; increments m to 2.
4. The while condition (m == n) is evaluated: (2 == 0), which is false.
5. The loop terminates because the condition is false.
6. printf("\n"); prints a newline character.

Output of 6.18:
1

6.19 What is the output of the following code?

C
int n = 0, m;
for (m = 1; m = n + 1; m++)
printf("%d ", m);
printf("\n"); Analysis:

1. n is initialized to 0. m is declared but not initialized initially.


2. The for loop starts.
3. Initialization: m = 1.
4. Condition: m = n + 1. This is an assignment, not a comparison. n + 1 evaluates to 0 + 1 = 1.
So, m is assigned the value 1. The result of the assignment (1, which is non-zero) is treated as true.
5. Since the condition is true, the loop body executes.
6. printf("%d ", m); prints the current value of m, which is 1, followed by a space.
7. Increment: m++ increments m to 2.
8. The loop condition m = n + 1 is evaluated again. n + 1 is still 1. So, m is assigned 1. The
condition is true.
9. The loop body executes again, printing 1.
10. The increment m++ makes m equal to 2. This pattern will continue. In each iteration, m is reassigned
the value of n + 1 (which is 1), the condition is true, m is printed as 1, and then m is incremented.
This will result in an infinite loop printing 1 repeatedly.

Output of 6.19:
1 1 1 1 1 1 1 1 1 1 ... (infinitely)

6.20 When do we use the following statement?

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.

Common scenarios where an infinite loop might be used include:

• 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.

Corrected: float values[10][15];

(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.

Corrected: float average[ROW + CONSTANT][COLUMN]; (where CONSTANT is an integer or another


symbolic constant to complete the size expression) or float average[ROW][COLUMN]; (if ROW itself
represents the size).

(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.

Corrected: double salary[CONSTANT][ROW]; (where CONSTANT is an integer or symbolic constant for


the first dimension's size).

(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).

Corrected: int array[COLUMN];

7.4 Identify errors, if any, in each of the following initialization statements.

(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).

(b) float item [3] [2] = { (0,1,2,3,4,5) }; Errors:

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).

Corrected: float item[3][2] = { {0, 1}, {2, 3}, {4, 5} };

(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++)

scanf("%f", &B[i]); Errors:

• 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.

Considerations (depending on the intended behavior):

• 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.

Corrected (to initialize all elements):

C
for (i=0; i<4; i++)
scanf("%f", &B[i]);

(c)

C
for (i=0; i<=4; i++)

B[i] = B[i] + i; Errors:

• 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.

9.5 What is prototyping? Why is it necessary?

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.6 Distinguish between the following:

(a) Actual and formal arguments


Answer: Actual arguments are the values/variables passed during a function call. Formal arguments are
the parameters in the function definition.
(b) Global and local variables
Answer: Global variables are declared outside all functions and accessible everywhere. Local variables
are declared inside a function and accessible only within that function.

(c) Automatic and static variables


Answer: Automatic variables are created/destroyed with function calls and don’t retain values between
calls. Static variables retain values between calls and are initialized only once.

(d) Scope and visibility of variables


Answer: Scope is the region where a variable can be accessed. Visibility determines if a variable can be
used at a point, affected by blocks or shadowing.

(e) & operator and * operator


Answer: & returns the address of a variable. * dereferences a pointer to access the value at that address.

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.

9.8 Which of the following prototype declarations are invalid? Why?

(a) int (fun) void;


Answer: Invalid: Incorrect syntax. Should be int fun(void); to indicate no parameters.

(b) double fun (x, y);


Answer: Invalid: Parameter types must be specified, e.g., double fun(int x, int y);.

(c) float fun (x, y, n);


Answer: Invalid: Parameter types must be specified, e.g., float fun(int x, int y, int n);.

(d) void fun (void, void);


Answer: Invalid: void cannot be used as a parameter type; it indicates no parameters.
(e) int fun (int a, b);
Answer: Invalid: All parameters need types, e.g., int fun(int a, int b);.

(f) void fun (int a, int &b);


Answer: Invalid: C doesn’t support reference parameters (&b). Use pointers instead, e.g., int *b.

9.9 Which of the following header lines are invalid? Why?

(a) float average (float x, float y, float z);


Answer: Valid: Correct syntax with proper parameter types.

(b) double power (double a, int n - 1);


Answer: Invalid: int n - 1 is incorrect syntax; it should be int n, with subtraction inside the function.

(c) int product (int m, n, 10);


Answer: Invalid: All parameters need types, e.g., int product(int m, int n, int x);. Also, 10 as a parameter
is invalid.

9.10 Find errors, if any, in the following function definitions:

(a)

Copy

int (a, b)

return (a + b);

Answer: Invalid: Missing return type (int) and parameter types. Should be:

Copy

int sum(int a, int b) {

return (a + b);

}
(b)

Copy

void (int a, int &b)

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

void sum(int a, int *b) {

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.11 Find errors in the following function calls:

(a) fun (int a, b);


Answer: Invalid: Function calls don’t specify parameter types. Should be fun(a, b); with a and b as
variables.

(b) fun (x, y - z);


Answer: No error: Valid if x, y, and z are defined and fun expects two arguments of matching types.

(c) fun (float x, float y);


Answer: Invalid: Function calls don’t specify types. Should be fun(x, y); with x and y as float variables.

9.12 What should be the value of the following ‘function calls’?

(a) double (2, 3);


Answer: Invalid: Missing function name. If it’s meant for a function like double add(int a, int b), it would
return 5.0 (after type conversion).

(b) double (4, 5, 3);


Answer: Invalid: Missing function name. If meant for a function like double sum(int a, int b, int c), it
would return 12.0.

9.13 While calling the function calls if in change the header line:

(a) double (x, y, z) to double (y, x, z)


Answer: Invalid: Missing return type and function name. If corrected to double fun(double x, double y,
double z) and changed to double fun(double y, double x, double z), the parameter order changes, so the
arguments in the call must match the new order.

(b) double (x, y, z) to double (x, y)


Answer: Invalid: Missing return type and function name. If corrected, changing from three to two
parameters means the function call must also provide only two arguments, or it will cause a compilation
error.
9.14 Determine the output of the following program?
c

Copy

#include <stdio.h>

void fun(int *a, int *b);

int main()

int x = 10, y = 20;

printf("%d %d\n", x, y);

fun(&x, &y);

printf("%d %d\n", x, y);

return 0;

void fun(int *a, int *b)

*a = *a + *b;

*b = *a - *b;

*a = *a - *b;

Answer:
The function swaps the values of x and y using pointers:

• Initial: x = 10, y = 20 → First print: 10 20


• After fun(&x, &y):
o *a = *a + *b → *a = 10 + 20 = 30
o *b = *a - *b → *b = 30 - 20 = 10
o *a = *a - *b → *a = 30 - 10 = 20
• Final: x = 20, y = 10 → Second print: 20 10
Output:
text
Copy

10 20

20 10

9.15 What will be the output of the following program?


c

Copy

#include <stdio.h>

int prod (int a, int b)

return (a * b);

int main()

int x = 5, y = 4, z;

z = prod (x, y);

printf ("%d\n", 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.

9.16 The function test is coded as follows:


c

Copy

int test (int number)


{

int n = 0;

while (number > 0)

if (n % 2 == 0)

number = number / 10;

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.

You might also like