C Programming Problem Solving Guide
C Programming Problem Solving Guide
Branch [Link](CSE)
Date 07/08/2024
UNIT-II ........................................................................................................................................... 61
Q1. Differentiate object code and executable code. ....................................................................... 61
Q2. Define an expression? How can you evaluate an expression? ................................................ 62
Q3. Define precedence and associativity? Give an example? ........................................................ 64
Or ................................................................................................................................................... 64
Explain the hierarchy (priority) and associativity (clubbing) of operators in ―C‟ withexample? ........ 64
Q4. What are different types of storage classes in C ? ..................................................................... 1
(or) ................................................................................................................................................... 1
Explain briefly auto and static storage classes with examples?(or) Explain extern and register
storage classes with example programs........................................................................................... 1
Q,[Link] explain the pre-processor directives in detail. ................................................................. 5
1
Q6. What do you mean by conditional statement in C? .................................................................. 13
Describe all the variants of if-else statement with clear syntax and examples. ............................... 13
Q8. Write in detail about different types of loop statements in C..................................................... 27
Q9. Explain Jumping control-flow statements. (Or) Differentiate between the following with
example? ....................................................................................................................................... 33
What are the differences between break statement and Continue statement?........................................ 33
Q10. What are the differences between while and do-while statements?Ans: ................................ 39
UNIT -4 ................................................................................................................................... 90
1. What is array? Explain the declaration and initialization of one dimensional and two
dimensional array with an example? .............................................................................................. 90
2. How to declare and initialize a Two-dimensional array? Discuss with examples. ............. 91
3. Illustrate multidimensional arrays with example program. ................................................ 93
2
6. How to Memory Map of a 2 Dimensional Array. ............................................................... 99
12. Explain with syntax and example , the different string manipulation library functions with
example? .............................................................................................................................. 107
13. How does a for loop operate, and what is its typical structure? ....................................... 107
for Loop in C ............................................................................................................................ 107
15. What is recursion? What are the advantages and Disadvantages of recursion? ............. 109
16. Discuss about passing arrays to function? ...................................................................... 109
17. Distinguish between Actual and formal arguments ? ....................................................... 111
18. Distinguish between Global and local variables ?............................................................ 112
3
UNIT -1
Ans: - The problem is defined as the objective or the specific output that we want to attain;
through a sequence of steps and activities and, specific input.
According to Sprankle and Hubbard (2012), there are six step in problem solving:
4
Q2. What do you mean by computer language?
Ans :
A computer language is a formal language used to communicate with a computer.
Query language – a language used to make queries in databases and information systems
Data exchange language – a language that is domain-independent and can be used for data
from any kind of discipline; examples: JSON, XML
5
Hardware description language – used to model integrated circuits
Page description language – describes the appearance of a printed page in a higher level
than an actual output bitmap
Style sheet language – a computer language that expresses the presentation of structured
documents, such as CSS
6
Q3. Explain programming language with its types.
Ans: - A programming language is a set of grammatical rules (both syntactic and semantic) that
instruct a computer or a device to behave in a certain way. Each programming language has a
vocabulary—a unique set of keyword that follows a special syntax to form and organise
computer instructions.
More ambiguous. Human beings have the Stricter and less tolerant. Computers are very precise
ability to clarify the meaning of an about the instructions they like to receive.
expression. The built-in redundancy of Therefore, programming languages have practically no
human languages allows some ambiguity to redundancy to prevent ambiguity and issue the correct
be resolved using context. commands.
Are open and allow combinations without Are closed and fixed to avoid confusion and mistakes.
the risk of making mistakes.
Natural languages are spoken by people, while programming languages are intended for
machines.
Both languages contain important similarities, such as the differentiation they make
between syntax and semantics and the existence of a basic composition.
Essentially, the two types were created to communicate ideas, expressions, and
instructions.
7
Machine language is directly understood by the computer’s processing unit. A programmer
will first write his code in a high-level language, then compile it into a machine-readable
format where instructions are represented in binary.
High-level languages, on the other hand, are designed to be easy to read and understood,
allowing programmers to write source code using logical, meaningful words and symbols.
They encapsulate everything from early algorithmic languages such as FORTRAN to more
widespread, object-oriented languages like C++, C#, and Java.
• Flowcharts These are charts or diagrams which represent the flow of the
algorithm.
8
Q5. Explain about Algorithm? (or) Define an Algorithm and State Properties of it?
Ans: An algorithm is an effective, efficient and best method which can be used to express
solution of any problem within a finite amount of space and time and in a well-defined
formal language.
or
An algorithm is a sequence of unambiguous instructions for solving a problem, i.e.,
for obtaining a required output for any legitimate input in a finite amount of time
9
Step 1: Unlock the phone
Step 2: Open Menu and got to Message app.
Step 3: Select option “create message”
Step 4: Now type the message and sent it
Algorithm:
Step1: Accept two numbers
Step2: Perform addition of two numbers
Step3: Display result.
Ans:-
Problem must be analyzed thoroughly.
10
Ans: - Characteristics of an Algorithm
Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases),
and theirinputs/outputs should be clear and must lead to only one meaning.
Finiteness: If we trace out the instructions of an algorithm, then for all cases, the
algorithmterminates after a finite number of steps.
Effectiveness: Every instruction must be very basic so that it can be carried out, in principle,
by a person using only pencil and paper. It is not enough that each operation be definite as
in criterion3; italso must be feasible.
Step 1: Start
Step 2: Read number n
Step 7: Loop
else
11
Step 9: Stop
Ans: Flowchart
While making a flow chart a programmer need not to pay attention on the
Purpose of a Flowchart :
Provides communication.
Provides an overview.
Shows all elements and their relationships.
12
Quick method of showing program flow.
Checks program logic.
Facilitates coding.
Provides program revision.
Provides program
documentation.
Advantages of a Flowchart :
Limitations of a Flowchart :
Complex logic.
Drawing is time consuming.
Difficult to draw and remember.
Technical detail.
13
Q11. Explain the Symbols in a Flowchart?
Ans:
Symbols: Symbols are divided in to the following two parts.
Auxiliary Symbols.
Primary Symbols.
Flowcharts:
15
Q14. Explain the programming languages?
1. Machine language: Computers are made of two-state electronic devices they can
understand only pulse and no-pulse (or ‗1‗ and ‗0‗) conditions. Therefore, all
instructions and data should be written using binary codes 1 and 0. This binary code is
called the machine code or machine language. Computers do not understand English,
Hindi or Telugu. They respond only to machine language. Added to this, computers are
not identical in design, therefore, each computer has its own machine language.(However
the script 1 and 0 , is the same for all computers). This poses two problems for theuser.
It is difficult to understand and remember the various combinations of 1‗s and
0‗s representing numerous data and instructions. Also, writing error-free
instructions is a slow process.
As every machine has its own machine language, the user cannot communicate
with other computers. Machine languages are usually referred to as the first
generation languages.
2. Assembly language: The Assembly language which is introduced in 1950s reduced
programming complexity and provided some standardization to build an application. The
assembly language, also referred to as the second-generation programming language, is
also a low-level language. In an assembly language, the 0s and 1s of machine language are
replaced with abbreviations or mnemonic code.
16
The main advantages of an assembly language over a machine language are:
As we can locate and identify syntax errors in assembly language, it is easy to
debug it.
It is easier to develop a computer application using assembly language in
comparison to machine language.
17
3. High-level
level languages: High level languages further simplified programming
programm tasks by
reducing the number of computer operation details that had to be specified. High level
languages like COBOL, Pascal, FORTRAN, and C are more abstract, easier to use, and more
portable across platforms, as compared to low level programming languages.
lang Instead of
dealing with registers, memory addresses and call stacks, a programmer can concentrate
more on the logic to solve the problem with help of variables, arrays or Boolean
expressions.
High-level languages can be classified into the following three categories:
Procedure-oriented
oriented languages (third generation)
Problem-oriented
oriented languages (fourth generation)
Natural languages (fifth generation)
Procedure-oriented languages
High level languages designed to solve general lled procedural languages
general-purpose problems are called
or third generation languages. These include BASIC, COBOL, FORTRAN, C, C++, and JAVA, which
are designed to express the logic and procedure of a problem.
Problem-oriented languages
Problem-oriented languages are used to solve specific problems and are known as the fourth-
generation languages. These include query languages, report generators and application
generators which have simple, english-like
english syntax rules.
Natural languages
to behave like an expert and solve problems.
Natural languages are designed to make a computer to
The programmer just needs to specify the problem and the constraints for problem
problem- solving.
Natural languages such as LISP and PROLOG are mainly used to develop artificial intelligence and
nguages are widely known as fifth generation languages.
expert systems. These languages
18
Q14. Explain the history of C ?
Ans:- The root of all modern languages is ALGOL which is introduced in early [Link]
was the first computer language to use a block structure. ALGOL gave the
concept of structured programming tocomputer science community.
In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming
Language) primarily for writing system software. In 1970, Ken Thompson created a language using
many features of BCPL and called it as ‗B‘. ‘B‘was used to create early versions of UNIX
operating system at BELL laboratories.
‘C‘ was evolved from ALGOL,BCPL and B by Dennis Ritchie at the Bell laboratories in [Link]
language became more popular after the publication of the book ―The C Programming
Language‖ by Brain Kernighan and Dennis Ritchie in 1978.C uses many concepts from these
19
languages and added the concept of data types and other powerful features. Since it was
developed along with the UNIX operating system, it is strongly associated with UNIX.
For many years C was used mainly in academic environments but eventually with the release of many
C compilers for commercial use it increased its popularity. This rapid growth of C led to the
development of different versions of the language that were similar but often incompatible, this
posed a serious problem for system developers. In order to assure that the C language remains
standard in 1983 American National Standards Institute (ANSI) appointed a technical committee to
define a standard for C. The committee approved a version of C in December 1989 which is now
known as ANSI C which is approved by the International Standards Organization (ISO) in [Link]
version of C is referred to as C89.
During 1990's C++,a language entirely based on C , underwent a number of improvements and
changes and became an ANSI/ISO approved language in November 1977.C++ added several new
features to C to make it not only a true object–oriented language but also a more versatile
language. Although C++ and Java were evolved out of C, the standardization committee of C felt
that a few features of C++/Java, if added to C, would enhance the usefulness of the language. The
result was the 1999 standard for C. This version is usually referred to as C99.
Q.15 What is the general structure of a `C' program and explain with example?
20
Documentation section:
This section consists of a set of comment lines giving the name of the program, and other
[Link] the programmer would like to user later.
Ex:- # include<stdio.h>
Global declaration section: Some of the variables that are used in more than one function
through out the program are called global variables and
declared outside of all the functions. This section declares all
the user-defined functions.
main() function section: Every C program must have one main ( ) function section. This
contains two parts.
o Declaration part: This part declares all the variables used in the executable part.
Ex:- int a,b;
o Executable part: This part contains at least one statement .These two parts must
appear between the opening and closing braces. The program execution begins at the
opening brace and ends at the closing brace. All the statements in the declaration and
executable parts end with a semicolon (;).
Sub program section: This section contains all the user-defined functions that are called
in the main() function. User-defined functions are generally placed immediately after the
main() function, although they may appear in any order.
Ex:
21
Q16. What is a variable? Write the rules for constructing a variable? Ans:
Variable: It is a data name that may be used to store a data value. It cannot be changed during the
execution of a program. A variable may take different values at different times during execution. A
may
variable name can be chosen by the programmer in a meaningful way so as to reflect its function
Rules:
Ex:- mark,sum1,tot_value,delhi
t_value,delhi ----------valid
Ans:
Declaration does two things:
It tells the compiler what the variable name is.
It specifies what type of data the variable will hold.
The declaration of variables must be done before they are used in the program.
22
The syntax for declaring a variable is as follows:data-type v1,v2,…….,vn;
v1,v2,…,vn are the names of variables.
Variables are separated by commas. A declaration statement must end with a semicolon.
For example, valid declarations are:
int count;
int number, total;
double ratio;
Example:
/*…………….Program Name…............................................... */
main()
{
/*……………….Declaration............................................................. */
float x,y;
int code;
shortint count;
long int amount;
double
deviation;
unsigned n;
char c;
/*…………………………Computation ............................................................... */
}/*…………………………Program ends .......................................................... */
Initialization of variable: Initialize a variable in c is to assign it a starting value. Without this wecan't get
whatever happened to memory at that moment.
C does not initialize variables automatically. So if you do not initialize them properly, you can get
unexpected results. Fortunately, C makes it easy to initialize variables when you declare them.
23
For Example :
int x=45;
int month_lengths[] ={23,34,43,56,32,12,24};
struct role = { "Hamlet", 7, FALSE, "Prince of Denmark ", "Kenneth Branagh"};
Note: The initialization of variable is a good process in programming.
Data type is the type of the data that are going to access within the program. C supports different
data types. Each data type may have pre-defined memory requirement and storage representation. C
supports 4 classes of data types.
i) Integer (int)
ii) Character(char)
iii) Floating (float)
iv) Double – precision floating point(double)
Integers are whole numbers with a range of values supported by a particular machine. Integers occupy
one word of storage and since the word size of the machine vary. If we use 16 bit word length the size of
an integer value is -32768 to +32767. In order to control over the range of numbers and storage space, C
has 3 classes of integer storage, namely short, long, and unsigned.
24
-215 to 215 -1
Int 2 bytes %d (or) %i
-32768 to +32767
-128 to +127 1 byte %d (or) %i
signed short int(or)short int
%d (or) %i
unsigned short int 0 to 255 1 byte
25
C –supports a feature known as ―type definition‖ that allows users define an identifier
that would represents an existing type.
(or)
enum day{Monday…Sunday}week-f, week-end;
26
[Link] the different types of constants in C with example? or What are the
rules for creating C constants explain with example?
Ans:
Types of c constants
1. Integer constants
2. Real constants
3. Character constants
4. String constants
1. Integer constants: An integer constant refers to a sequence of digits. There are three
types ofintegers, namely, decimal integer, octal integer and hexadecimal integer.
Examples of Integer Constants:
426 ,+786 , -34(decimal integers)
037, 0345, 0661(octal integers)
0X2, 0X9F, 0X (hexadecimal integers)
2. Real constants: These quantities are represented by numbers containing fractional parts like
18.234. Such numbers are called real (or floating point) constants.
Examples of Real Constants:
+325.34
426.0
-32.67 etc.
The exponential form of representation of real constants is usually used if the value of the
constant is either too small or too large. In exponential form of representation the real
constant is represented in two parts. The first part present before 'e' is called Mantissa and
the part following 'e'is called Exponent. For ex. 0.000342 can be written in Exponential form
as 3.42e-4.
3. Single Character constants: Single character constant contains a single character enclosed
27
within a pair of single quote marks.
For ex. 'A',‗5‗,‗;‗,‗‖‘
Note that the character constant ‗5‗ is not same as the number 5. The last constant is a
blank [Link] constant has integer values known as ASCII values. For example, the
statement Prin (―%d‖,a); would print the number 97,the ASCII value of the letter a.
Similarly, the statement prin (―%c‖,97); would output the letter ‗a‗
Backslash Character Constants: C supports some special backslash character constants that are
used in output functions. Some of the back slash character constants are as follows:
Constant Meaning
‗\0‗ Null
‗\t‗ Horizontal tab
‗\b‗ Back space
‗\a‗ Audible alert
‗\f‗ Form feed
‗\n‗ New line
‗\r‗ Carriage return
‗\v‗ Vertical tab
‗\‗‗ Single quote
‗\‖‗ Double quote
‗\?‗ Question mark
‗\\‗ backslash
String constants: A string constant is a sequence of character enclosed in double quotes. The
characters may be letters, numbers, special characters and blank space.
28
Examples are: ‖HELLO!‖ ‖979‖ ‖welcome‖ ― !1‖ ―5+3‖ ―X‖
4. Range of real constants expressed in exponential form is -3.4e38 to 3.4e38. Ex. +3.2e-5
29
Q20. What do you mean by Reserved word/keyword in c. List all the keyword of C?
Ans:
Keywords are certain reserved words that have standard and pre-defined meaning in ‘C’.
These keywords can be used only for their intended purpose. The C keywords are essential
language constructs with established meanings. Understanding these keywords is critical for
error-free coding. Keywords are reserved words that convey a special meaning and purpose
within the context of the language. They are used in the syntax and cannot be used as
a variable name.
Example: int a
Here int is a keyword that conveys, a is a variable that can store the value of integer data type.
Local variable
Those variables which are defined within some function and are accessible to that function only
are called Local Variables.
o These variables only exist inside the specific function that creates them.
30
o They are unknown to other functions and to the main program.
o As such, they are normally implemented using a stack.
o Local variables cease to exist once the function that created them is completed.
o They are recreated each time a function is executed or called.
o Example: Here x and y are local variables.
#include<stdio.h>
void main()
{
int x=23, y=4;
printf(“x = %d and y=%d”,x,y);
}
Global variable
Those variables which are defined outside of function block and are accessible to entire program
are known as Global Variables.
o These variables can be accessed (ie known) by any function comprising the program.
o They are implemented by associating memory locations with variable names.
o They do not get recreated if the function is recalled.
o Example: Here ‘a’ and ‘b’ are global variables.
#include<conio.h>
int a=10,b;
void main()
{
printf(“a = %d and b=%d”,a,b);
}
31
Q22. Explain the types of type conversions/typecasting in C with example?
Converting a variable value or a constant value temporarily from one data type to other data type for
the purpose of calculation is known as type conversion.
The sequence of rules that are applied while implicit type conversion is as follows:
All short and char are automatically converted into int
if one of the operands is long double the other will be converted to long double and the
resultwill be long double..
32
if one of the operand is float ,the other will be converted to float and the result will be float.
if one of the operand is unsigned long int,
int, the other will be converted to unsigned long int
andthe result will be unsigned long int.
else if one of the operand is long int ,the other will be converted into long int and the result
willbe long int.
else if one of the operand unsigned int ,the other will be converted into unsigned int and the
result will be unsigned int.
nt.
The final result of an expression is converted to the type of the variable on the left of the assignment sign
before assigning the value to it. The following changes are introduced during the final assignment.
33
2. Explicit: In this type of conversion, the programmer can convert one data type to other data type
explicitly.
float(a)->10.00000
#include <stdio.h>
// Driver Code
int main()
// Given a & b
int a = 15, b = 2;
float div;
// Division of a and b
div = a / b;
34
printf("The result is %f\n", div);
return 0;
35
Q23. List out built-in type casting function. WAP to show Implicit and explicit
typecasting using C.
#include <stdio.h>
// Driver Code
int main()
{
// Given a & b
int a = 15, b = 2;
char x = 'a';
double div;
36
x = x + 3;
Ans: - Header files are an essential part of both programming languages, and they serve as a
means to include predefined standard library functions, data types, macros, and other
features in your programs.
1. In C, header files typically have the “.h” extension, and you include them in your code
using the #include pre-processor directive.
2. These header files provide access to various libraries and functions to simplify
programming.
#include <stdio.h>
int main()
{
printf( "Printf() is the function in stdio.h header file");
return 0;
}
Output
38
Q25. Describe the standard header files in C.
Ans:- Standard header files contain libraries and functions that are defined in the ISO
standard of the C programming language. These header files are typically stored in the
default directory of the C compiler, making them universally accessible and present in
all C compilers from different vendors. This standardization ensures that C programs
can be written and compiled consistently across different platforms and compilers,
making it a powerful feature of the C programming language.
<assert.h> It has information regarding adding diagnostics that aid program debugging.
<errorno.h> It has to perform error-handling operations like errno(), strerror(), perror(), etc.
<float.h> It has to perform error-handling operations like errno(), strerror(), perror(), etc.
<math.h> It has to perform mathematical operations like sqrt(), log2(), pow(), etc.
<signal.h> It has to perform signal handling functions like signal() and raise().
It has function prototypes for functions that will test characters for certain
<ctype.h>
properties and also function prototypes for functions that will be used to convert
uppercase letters to lowercase letters and vice versa.
39
Header File Description
It even contains standard utility functions like malloc(), realloc(), etc. It contains
<setjump.h> function prototypes for functions that allow bypassing of the usual function call and
return sequence.
It determines the various properties of the various variable types. The macros
defined in this header limit the values of various variable types like char, int, and
<string.h>
long. These limits specify that a variable cannot store any value beyond these
limits, for example, an unsigned character can store up to a maximum value of 255.
It determines the various properties of the various variable types. The macros
defined in this header limits the values of various variable types like char, int, and
<limits.h>
long. These limits specify that a variable cannot store any value beyond these
limits, for example, an unsigned character can store up to a maximum value of 255.
It will perform functions related to date() and time() like setdate() and getdate(). It
<time.h>
is also used to modify the system date and get the CPU time respectively.
<stddef.h> It will contain common type definitions used by C for performing calculations.
40
Header File Description
It will contain function prototypes and other information that enables a program to
be modified for the current locale on which it’s running. It enables the computer
<locale.h>
system to handle different conventions for expressing data such as times, dates, or
large numbers throughout the world.
Ans:-
/ C program to illustrate
// the use of header file
// in C
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Driver Code
int main()
{
char s1[20] = "12345";
char s2[10] = "Geeks";
char s3[10] = "ForGeeks";
long int res;
41
// Convert a string to long long int
// using a function in stdlib.h library
long int a = atol(s1);
printf("Using stdlib.h, the string");
printf(" to long int: %ld\n", a);
Output
Using math.h, The value is: 729
Using stdlib.h, the string to long int: 12345
Non-standard header files are not part of the ISO standard of the C programming language. These
header files are typically created by programmers for various purposes, such as containing custom
library functions or platform-specific code. They are not part of the standard library and are not
guaranteed to be available on all C compilers.
Non-standard header files can be manually installed by the user, included as part of a third-party library,
or provided by specific vendors. Their use is often limited to specific projects or platforms and may not
be portable across different environments or compilers.
42
Header File Description
C language has standard libraries that allow input and output in a program.
The stdio.h or standard input output library in C that has methods for input and output.
scanf()
The scanf() method, in C, reads the value from the console as per the type specified and store
it in the given address.
Syntax:
scanf("%X", &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and & is the address operator in C, which tells the compiler to change the real value
of variableOfXType, stored at this address in the memory.
printf()
The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf("%X", variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a
variable and variableOfXType is the variable to be printed.
43
How to take input and output of basic types in C?
The basic type in C includes types like int, float, char, etc. Inorder to input or output the
specific type, the X in the above syntax is changed with the specific format specifier of that
type. The Syntax for input and output for these are:
Integer
There are several standard library functions available under this category-those that can deal with
a string of characters.
Unformatted Input/output is the most basic form of input/output. Unformatted input/output
transfers the internal binary representation of the data directly between memory and the file
44
variables through the assignment statements like x=5, a=0 and so on. Another method is to
which can read data from a keyboard. We have used both the
use the input function scanf, whi
methods in programs. For outputting results, we have used extensively the function printf,
which sends results out to a terminal.
C language has 2 types of I/O statements; all these operations are carried out through function
calls.
Ex:- char x;
x = getchar( );
putchar ( ):- This function is used to display one character at a time on the standard
output device.
Syntax:- putchar(char_variable);
Ex:- char x;
putchar(x);
45
program: main( )
{
char ch;
printf(―enter a char‖);
ch = getchar( );
putchar(ch);
}
Output: enter a char
entered char is a
getc() :- This function is used to accept single character from the file.
Syntax: char variable name = getc();
Ex:-char c;
c = getc();
gets( ):- This function is used to read group of characters(string) from the standard I/P
device.
Syntax:- gets(character array variable);
Ex:- gets(s);
puts( ):- This function is used to display string to the standard O/P device.
Syntax:- puts(character array variables);
46
Ex:- puts(s);
program:
main()
{
char s[10]; puts(―enter name‖);
gets(s);
puts(―print name‖);
puts(s);
}
Ans: - Compilation refers to the process by which human-readable source code written in any
programming language is transformed into machine-executable binary code. This
transformation bridges the gap between the way we write code, which is in a form that's easy
for humans to understand, and the way computers execute code, which is in binary form,
composed of 0s and 1s.
47
The compilation process in C can be divided into several phases, each with specific tasks and
objectives. These phases ensure that the source code is translated into an efficient and
executable form while also checking for errors and allowing for modularity. The phases of the
process are-
1. Pre-processing
2. Compilation
3. Assembling
4. Linking
48
Q31. Explain errors in C with its types.
Ans: -
Error is an illegal operation performed by the user which results in abnormal working of
the program.
Programming errors often remain undetected until the program is compiled or
executed.
Some of the errors inhibit the program from getting compiled or executed.
Thus errors should be removed before compiling and executing.
Syntax errors:
Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax
errors. This compiler error indicates something that must be fixed before the code can be
compiled. All these errors are detected by compiler and thus are known as compile-time
errors.
Most frequent syntax errors are:
1. Missing Parenthesis (})
2. Printing the value of variable without declaring it
3. Missing semicolon like this:
// C program to illustrate
// syntax error
#include<stdio.h>
49
void main()
{
int x = 10;
int y = 15;
printf("%d", (x, y)) // semicolon missed
}
Run-time Errors:
Errors which occur during program execution (run-time) after successful compilation are
called run-time errors. One of the most common run-time error is division by zero also
known as Division error. These types of error are hard to find as the compiler doesn’t point
to the line at which the error occurs.
// C program to illustrate
// run-time error
#include<stdio.h>
void main()
{
int n = 9, div = 0;
// wrong logic
// number is divided by 0,
// so this program abnormally terminates
div = n/0;
Error:
warning:
division by zero [-Wdiv-by-zero]
div = n/0;
Linker Errors:
50
These error occurs when after compilation we link the different object files with main’s
object using Ctrl+F9 key(RUN). These are errors generated when the executable of the
program cannot be generated. This may be due to wrong function prototyping, incorrect
header files. One of the most common linker error is writing Main() instead of main().
// C program to illustrate
// linker error
#include<stdio.h>
Logical Errors:
On compilation and execution of a program, desired output is not obtained when certain input
values are given. These types of errors which provide incorrect output but appear to be error free
are called logical errors. These are one of the most common errors done by beginners of
programming.
These errors solely depend on the logical thinking of the programmer and are easy to detect if we
follow the line of execution and determine why the program takes that path of execution.
// C program to illustrate
// logical error
int main()
{
51
int i = 0;
Semantic errors :
This error occurs when the statements written in the program are not meaningful to the compiler.
// C program to illustrate
// semantic error
void main()
{
int a, b, c;
a + b = c; //semantic error
}
52
Q32. Differentiate source code and object code.
Code Language This type of code exists in This type of code exists in binary format. It is
plain text. It is because because it is a translated form of code that roots
we write it using a high- from the source code.
level type of
programming language.
Understandable by Any human can A machine can understand an object code- not a
Humans understand a source human.
code.
Understandable by Machines cannot directly Any machine can directly understand as well as
Machines understand a source code execute an object code.
unless translated.
Languages Used for We write these types of An assembler, a compiler, or any other form of
Writing Code codes in various high- translator writes these codes into the machine
level languages, such as language from the source code.
Python, Java, C, C++, or
the assembly language.
53
Ease of One can easily modify You cannot modify these codes.
Modification these codes.
Comments A source code can have An object code lacks any kind of comments for
comments by the the machine to understand.
programmer for an
overall better
understanding.
Performance of A source code performs An object code performs more and better than
Code way less than the object the source code because it is comparatively very
code because it is not close to the machines.
very close to the
machines.
Relations with The source code acts as The object code acts as the output of an
Assemblers, the input to an assembler, compiler, or any other type of
Compilers, assembler, compiler, or translator.
Translators any other type of
translator.
Ease of Changes You can easily change the You need to compile the source code or
and Alterations source code over the translate it using any other translator after
course of time. making the necessary changes- so that it reflects
in the recent object code (modified one).
54
Q32. What is an operator and List different categories of C operators based on
their functionality? Give examples?
Ans:
Operators:
An operator is a symbol that tells the computer to perform certain mathematical or logical
manipulations. Operators are used in programs to manipulate data and variables.
1. Arithmetic Operators:
C provides all the basic arithmetic operators. These can operate on any built-in data type
allowed in C.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
55
Integer division truncates any fractional part. The modulo division operation produces
the remainderof an integer division.
Ex: Here a and b are operands, let a=14 and b=4 we have the following resultsa-b = 10
a+b = 18
a*b = 56
a/b = 3(coefficient)
a%b = 2(remainder)
2. Relational Operators:
Relational operators are used for comparing two quantities, and take certain decisions. For
example we may compare the age of two persons or the price of two items….these
comparisons can be done with the help of relational operators.
Ex:- 4.5<=10(true)
6.5<-10(false) 10<4+12(true)
When arithmetic expression are used on either side of a relational operator, the
arithmetic expression will be evaluated first and then the results compared, that
means arithmetic operators have a higher priority over relational operators.
56
3. Logical Operator:
C has 3 logical operators. The logical operators are used when we want to test more than one
condition and make decisions. The operators are as follows:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators && and || are used when we test more than one condition and make
[Link]:- a>b && x==45
0 0 0 0
0 1 0 1
1 0 0 1
1 1 1 1
57
4. Assignment operator:
These operators are used to assign the result of an expression to a variable.
The usual assignment operator is ‖=‟. In addition ,C has a set of shorthand
assignment operators of the form:
v op = exp;
The use of short hand assignment operators has the following advantages:
What appears on the left-hand side need not be repeated and therefore it
becomes easier towrite
The statement is more concise and easier to readThe statement is more
efficient
5. Increment and Decrement operators:
++ and - - are increment and decrement operators in C. The operator ++ adds
1 to the operand,while - - subtracts 1.
We use the increment and decrement statements in for and while loops extensively.
Ex:- m=5;
y=++m;
the value of y=6 and m =6.
58
Suppose if we write the above statement as
m=5;
y= m++;
the value of y=5 and m=6.
A prefix operator first adds 1 to the operand and then the result is assigned to the
variable on left. On the other hand, a postfix operator first assigns the value to the
variable on left and then increments the operand.
Conditional operator:
A ternary operator pair ‖?:‖ is available in C to construct conditional expressions of the form
exp1 ?exp2 : exp3 Where exp1,exp2 and exp3 are expressions,
The operator ?: works as follows: exp1 is evaluated first. If it is non-zero (true), then the
expression exp 2 is evaluated and becomes the value of the expression. If exp1 is false, exp3 is
evaluated and its value becomes the value of the expression.
Operator Meaning
^ Bitwise exclusive OR
Comma operator:
The comma operator is used to link the related expressions together. A comma- linked
list of expressions is evaluated left to right and the value of right- most expression is the
value of the combined expression.
For example, the statement
value = (x=10, y=5, x+y);
This statement first assigns the value 10 to x, then assigns 5 to y and finally assigns 15. In
for loops:for (n=1 , m=10, n<=m; n++, m++);
Size of operator:
The sizeof is a compile time operator and when used with an operand, it
returns the number of bytes the operand occupies.
The operand may be variable, a constant or a data type qualifier.
m = sizeof (sum);
n = sizeof (long int);
60
UNIT-II
Ans: - The main difference between object code and executable code is that object code is a
program or a file that is created after compiling the source code while executable code
is a file or a program that indicates tasks according to encoded instructions the CPU
can directly execute.
61
Q2. Define an expression? How can you evaluate an expression?
Ans: Expressions:
For example:
sum = x + y + z;
printf("Go Buckeyes!");
o
Expressions are evaluated using an assignment statement of the form:
variable = expression;
Variable is any valid C variable name. When the statement is encountered, the expression is
evaluated first and the result then replaces the previous value of the variable on the left-hand side.
All variables used in the expression must be assigned values before evaluation is attempted.
x = 9-12/3 +3*2-1
62
Step1: x = 9-4+3*2-1 Step2: x = 9-4+6-1
Step3: x = 5+6-1 Step 4: x = 11-1 Step5: x=10
63
Q3. Define precedence and associativity? Give an example?
Or
Explain the hierarchy (priority) and associativity (clubbing) of operators in ―C‟ withexample?
Ans:
Operator precedence:
Various relational operators have different priorities or precedence. If an arithmetic expression
contains more operators then the execution will be performed according to their properties. The
precedence is set for different operators in C.
Type of operator Operators Associativity
Unary operators +,-,!,++,--,type, ͂ ,size of Right to left
Arithmetic operators *, /,%,+,- Left to right
Bit – manipulation operators <<,>> Left to right
Relational operators >,<,>=,<=,==,!= Left to right
Logical operators &&,|| Left to right
Conditional operators ?,: Left to right
Assignment operators =,+=,-=,*=,/=,%= Right to left
Important note:
Precedence rules decide the order in which different operators are applied
Associativity rule decides the order in which multiple occurrences of the same
level operatorsare applied.
Hierarchy of operators in C
There are some operators which are given bellow with their meaning. The higher the position
of anoperator is, higher is its priority.
Operator Type
64
! Logical
*/ % Arithmetic
+- Arithmetic
<><=>= Relational
==!= Relational
&& Logical
|| Logical OR
Associativity of operators
When an expression contains two operators of equal priority the tie between them is settled using the
associativity of the operators.
Consider expression a=3/2*5 Here there is a tie between operators of same priority, that is between /
and *. This tie is settled using the associativity of / and *. But both enjoy Left to Right associativity.
While executing an arithmetic statement, which has two or more operators, we may have some
problem as to how exactly does it get executed.
1st *, / , % multiplication,division,
modular division
2nd +, - addition, subtraction
3rd = Assignment
65
For Example :
i=
2*3/4+4/4+8-
2+5/8
i=6/4+4+8-
2+5/8
i=1+4/4+8-
2+5/8
i=1+1+8-
2+5/8
i=1+1+8-2+0
i=2
+8-
2+0
i=1
0-
2+0
i=8
+0
i=8
(or)
Explain briefly auto and static storage classes with examples?(or) Explain extern and register storage classes
with example programs.
Ans:
Storage classes in C
Variables in C differ in behavior. The behavior depends on the storage class a variable may
assume. From C compiler‟s point of view, a variable name identifies some physical location
within the computer where the string of bits representing the variable‟s value is stored.
There arefour storage classes in C:
Keyword Auto
Storage Memory.
Default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Till the control remains within the block in which the variable is
Life
defined
Following program shows how an automatic storage class variable is declared, and the fact
that ifthe variable is not initialized it contains a garbage value.
main( )
{
auto int i, j ;
printf ( "\n%d %d", i, j ) ;
}
When you run this program you may get different values, since garbage values are
unpredictable. So always make it a point that you initialize the automatic variables properly,
otherwise you are likely to get unexpected results. Scope and life of an automatic variable is
illustrated in the following program
main( )
{
auto int i = 1 ;
{
auto int i = 2 ;
{
auto int i = 3 ;
printf ( "\n%d ",
i);
}
printf ( "%d ", i ) ;
}
printf ( "%d", i ) ;
}
Static Storage Class:-
The features of a variable defined to have a static storage class are as under:
Keyword Static
Storage Memory.
Default initial value Zero.
Scope Local to the block in which the variable is defined.
Life Value of the variable persists between different function calls
Keyword Extern
Storage Memory
default initial value Zero
Scope Global
Life As long as the program execution does not come to
end
External variables differ from those we have already discussed in that their scope is global,
not local. External variables are declared outside all functions, yet are available to all
functions that care to use them. Here is an example to illustrate this fact.
Ex:
#include<std
io.h
> extern
int i; void
main()
{
printf(―i=%d‖,i);
}
Register Storage Class:-
The features of a variable defined to be of register storage class are as under:
Keyword Register
Storage CPU Registers
default initial value An unpredictable value, which is often called a garbage value.
Scope Local to the block in which the variable is defined.
Life Till the control remains within the block in which the variable isdefined.
A value stored in a CPU register can always be accessed faster than the one that is stored in
memory. Therefore, if a variable is used at many places in a program it is better to declare
its storage class as register. A good example of frequently used variables is loop counters.
We can name their storage class as register.
main( )
{
register int i ;
for ( i = 1 ; i <= 10 ;
i++ )printf ( "\n%d", i )
;
Ans:
C Preprocessors:
As the name suggests Preprocessors are programs that process our source code before compilation.
There are a number of steps involved between writing a program and executing a program in C .
You can see the intermediate steps in the above diagram. The source code written by programmers
is stored in the file program.c. This file is then processed by preprocessors and an expanded source
code file is generated named program. This expanded file is compiled by the compiler and an object
code file is generated named program .obj. Finally, the linker links this object code file to the object
code of the library functions to generate the executable [Link].
1. File Inclusion
2. Macros
3. Conditional Compilation
1. File Inclusion: This type of pre-processor directive tells the compiler to include a file in the
source code program. There are two types of files which can be included by the user in the
program:
a) Header File or Standard Functions: These files contains definition of pre-defined functions
like printf(), scanf() etc. These files must be included for working with these functions.
Different function are declared in different header files. For example standard I/O functions
are in „stdio.h‟ file whereas functions which perform string operations are in „string‟ file.
Syntax:
where file_name is the name of file to be included. The „<„ and „>‟ brackets tells the compiler to look for the file in standard
directory.
b) User defined header files: When a program becomes very large, it is good practice to divide it
into smaller files and include whenever needed. These types of files are user defined files.
These files can be included as:
#include"filename"
2. Macros: Macros are a piece of code in a program which is given some name. Whenever this
name is encountered by the compiler the compiler replaces the name with the actual piece
of code. The „#define‟ directive is used to define a macro. Let us now understand the macro
definition with the help of a program:
#include <stdio.h>
// macro definition
#define LIMIT 5
int main()
{
for (int i = 0; i < LIMIT; i++)
printf("%d \n",i);
}
return 0;
}
In the above program, when the compiler executes the word LIMIT it replaces it with 5. The
word „LIMIT‟ in the macro definition is called a macro template and „5‟ is macro expansion.
Note: There is no semi-colon(„;‟) at the end of macro definition. Macro definitions do not
need a semi-colon to end.
Macros with arguments: We can also pass arguments to macros. Macros defined with
arguments works similarly as functions. Let us understand this with a program:
#include <stdio.h>
// macro with parameter
#define AREA(l, b) (l * b)
int main()
{
int l1 = 10, l2 = 5, area;
area = AREA(l1, l2);
printf("Area of rectangle is: %d", area);
return 0;
}
We can see from the above program that whenever the compiler finds AREA(l, b) in the
program it replaces it with the statement (l*b) . Not only this, the values passed to the macro
template AREA(l, b) will also be replaced in the statement (l*b). Therefore AREA(10, 5) will be
equal to 10*5.
To undefine a macro means to cancel its definition. This is done with the #undef directive.
Syntax:
#undef token
#include <stdio.h>
#define PI 3.1415
#undef PI
main()
{
printf("%f",PI);
}
Output: Compile Time Error: 'PI' undeclared
b). #ifdef
The #ifdef preprocessor directive checks if macro is defined by #define. If yes, it executes the code.
Syntax:
#ifdef MACRO
//code
#endif
c) #ifndef
The #ifndef preprocessor directive checks if macro is not defined by #define. If yes, it executes the
code.
Syntax:
#ifndef MACRO
//code#endif
d). #if
The #if preprocessor directive evaluates the expression or condition. If condition is true, it executes
the code.
#if expression
//code
#endif
e) #else
Syntax:
The #else preprocessor directive evaluates the expression or condition if condition of #if
is can be used with #if, #elif, #ifdef and #ifndef directives
Syntax:
#if expression
//if
code
#else
//else code
#endif
#if expression
//if code
#elif expression
//elif
code
#else
//else code
#endif
Example
#include <stdio.h>
#include <conio.h>
#define NUMBER 1
void main() {
#if NUMBER==0
printf("Value of Number is: %d",NUMBER);
#else
print("Value of Number is non-zero");
#endif
getch();
}
Output: Value of Number is non-zero
(Or)
Describe all the variants of if-else statement with clear syntax and examples.
Ans:
1. Simple if statement.
2. if…else statement.
3. Nested if…else statement.
4. else if ladder
1. Simple if statement: Simple if statement is used to make a decision based on the available
choice. It has the following form:
Syntax:
if ( condition )
{
stmt block;
}
stmt-x;
In this syntax,
if is the keyword. <condition>is a relational expression or logical expression or any expression
condition>is
thatt returns either true or false. It is important to note that the condition should be enclosed
within parentheses ‗(‗and ‗ ) ‗.
The stmt block can be a simple statement or a compound statement or a null statement.
stmt-x is any valid C statement.
int main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
}
Output: enter age 57 person is retired
2. if—else statement
if…else statement is used to make a decision based on two [Link] has the following form:
Syntax:
if(condition)
{
}
else
{
}
stmt-x;
true stmt block;
The true stmt block and false stmt block are simple statements or compound
compo statements or
null statements.
Whenever if...else statement is encountered, first the condition is tested. It returns either true
or false. If the condition is true, the control enters into the true stmt block. Once, the end of true
stmt without considering else-body.
stmt block is reached, the control transfers to stmt-x else
If the condition is false, the control enters into the false stmt block by skipp
skipping true stmt block.
Once, the end of false stmt block is reached, the control transfers to stmt
stmt-x.
int main()
{
int age;
printf("enter age\n");
scanf("%d",&age);
if(age>=55)
printf("person is retired\n");
else
printf("person is not retired\n");
}
Output:
enter age 47 person is not retired
3. Nested if—else statement
Nested if…else statement is one of the conditional control-flow statements. If the body of
if statement contains at least one if statement, then that if statement is called as ―Nested
if…else statement‖.
The nested if…else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also
be used to make a decision amongmultiple choices.
}
else
{
stmt2;
}
}
else
{
stmt 3;
}
stmt-x;
In this syntax,
if and else are keywords.
<condition1>,<conditio
<condition1>,<condition2> … <condition>are
are relational expressions or logical
expressions or any other expressions that return true or false. It is important to
note that the condition should be enclosed within parentheses ( and ).
if-body and else-body are simple statements or compound statements or empty
statements.
stmt-x is a valid C statement.
Whenever nested if…else statement is encountered, first <condition1> is tested. It returns either
eith true
or false.
If condition1 (or outer condition) is false, then the control transfers to else
else-body (if exists) by skipping
if-body.
If condition1 (or outer condition) is true, then condition2 (or inner condition) is tested. If the
condition2 is true, if-body
body gets executed. Otherwise, the else body that is inside of if statement gets
else-body
executed.
4 else—if Ladder
else-if ladder is one of the conditional control-flow statements. It is used to make a decision among
multiple choices. It has the following form:
Syntax: if(condition 1)
{
statement 1;
}
else if(condition 2)
{
statement 2;
}
else if(condition 3)
{
statement 3;
}
else if(condition n)
{
}
else
{
}
In this syntax,
if and else are keywords. There should be a space between else and if, if they come together.
<condition1>,<condition2>….<condtionN>are
<condition1>,<condition2>….<condtionN>are relational expressions or logical expressions or
any other expressions that return either true or false. It is important to note that the
condition should be enclosed within parentheses ( and ).
tement 1, statement 2,statement 3……,statement n and default statement are either simple
statement
statements or compound statements or null statements.
stmt-x is a valid C statement.
If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are tested. If all
are false, the default stmt at the end gets executed. After then the control transfers to stmt-x.
If any one of all conditions is true, then the body associated with it gets executed. After then the
control transfers to stmt-x.
Example Program:
{
int m1,m2,m3,avg,tot;
printf("enter three subject
marks");
scanf("%d%d%d", &m1,&m2,&m3);
tot=m1+m2+m3;
avg=tot/3;
if(avg>=75)
{
printf("distinction");
}
else if(avg>=60 &&avg<75)
{
printf("first class");
}
else if(avg>=50 &&avg<60)
{
printf("second class");
}
else if (avg<50)
{
printf("fail");
}
}
Output: enter three subject marks
85 80 81Distinction
Ans: switch statement is one of decision-making control-flow statements. Just like else if ladder,
it is also used to make a decision among multiple choices. switch statement has the following
form:
Syntax:
switch(<exp>)
{
case<exp-val
val-1>:
statements block-1
break;
case<exp-va
val-2>:
statements block-2
break;
case<exp-val
val-3>:
statements block-3
break;
case<exp-val
val-N>:
statements block-N
break; default:
default default
statements block
}
Next-statement;
o In this syntax,
switch, case, default and break are keywords.
<exp>is
is any expression that should give an integer value or character value. In other
expression
words, it should never return any floating-point value. It should always be enclosed
with in parentheses( and ). It should also be placed after the keyword switch.
<exp-val-1>,
1>, <exp-val-2>,
<exp <exp-val-3>…. <exp-val-N> should always be integer
constants or character constants or constant expressions. In other words, variables
can never be used as
val>. There should be a space between the keyword case and <exp-val>.
<exp- val>.
The keyword case along with its <exp-val> is called as a case label. <exp-val>
should always be unique; no duplications are allowed.
block-1, statements block-2, statements block--3… statements block-N
statements block
and default statements block are simple statements, compound statements or null
statements. It is important to note that the statements blocks along with their own
case labels should beseparated with a colon ( : )
The break statement at the end of each statements block is an optional one. It is
recommended that break
break statement always be placed at the end of each statements
block. With its absence, allthe statements blocks below the matched case label along
with statements block of matched case get executed. Usually, the result is unwanted.
The statement block and break statement can be enclosed with in a pair of curly
braces { and }. The default along with its statements block is an optional one. The
break statement can beplaced at the end of default statements block. The default
statements block can be placed at anywhere in the switch statement. If they are
placed at any other place other than at end, it is compulsory to include a break
statement at the end of default statements block.
Next-statement is a valid C statement.
24
Whenever, switch statement is encountered, first the value of <exp> gets matched with case
values. If suitable match is found, the statements block related to that matched case gets
executed. The break statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed and then the control
gets transferred to Next-statement.
Example Program:
#include<stdio.h>
void main()
25
int a,b,c,ch;
printf("\nEnter two numbers :");
scanf("%d%d",&a,&b);
scanf("%d",&ch);
switch(ch)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: c=a/b;
break;
case 5:
return;
26
Q8. Write in detail about different types of loop statements in C.
Ans:
While: The simplest of all the looping structures in c is the while statement. The basic format of the
while statement is:
Syntax:
Initialization statement;
while(condition)
{
statements;
}
The while is an entry –controlled loop statement. The condition is evaluated and if the condition is
true then the statements will be executed. After execution of the statements the condition will be
evaluated and if it is true the statements will be executed once again. This process is repeated until the
condition becomes false and the control is transferred out of the loop .On exit the program continues
with the statement immediately after the body of the loop.
Flow chart:
27
Program to print n natural numbers using using while
#include<stdio.h>
int main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
while(i<=n)
{
printf("%d ",i);
i=i+1;
28
}
}
Output: enter the range 10
1 2 3 4 5 6 7 8 9 10
do-while statement: It is one of the looping control statements. It is also called as exit-
controlled looping control statement. i.e., it tests the condition after executing the do-while
loop body.
The main difference between ―while‖ and ―do-while‖ is that in ―do-while‖ statement, the loop
body gets executed at least once, though the condition returns the value false for the first time,
which is not possible with while statement. In ―while‖ statement, the control enters into the loop
body only when the condition returns true.
Syntax:
Initialization statement;
do
{
statement(s);
}
while(<condition>);
next statement;
29
In this syntax:
30
Program to print n natural numbers using using do while
#include<stdi
o.h> int
main()
{
int i,n;
printf("enter the range\n");
scanf("%d",&n);
i=1;
do
{
printf("%d\n",i);
i=i+1;
}
while(i<=n);
}
Output: enter the range 8
12345678
for statement:
It is one of the looping control statements. It is also called as entry-controlled looping control
statement. i.e., it tests the condition before entering into the loop body. The syntax for ‖for‖
statementis as follows:
Syntax:
for(exp1;exp2;exp3)
{
for-body;
}
next_statement;
31
In this syntax, for is a keyword. exp1 is the initialization statement. If there is more than one
statement,then the statements must be separated with commas. exp2 is the condition. It is a
relational expression or a compound relational expression or any expression that returns
either true or false. The exp3 is the updating statement. If there is more than one
statement then, they must be separated with commas. exp1, exp2 and exp3 should be
separated with two semi-colons. exp1, exp2, exp3, for- body and next_statement are valid ―c‗
Whenever ‖for‖ statement is encountered, first exp1 gets executed. After then, exp2 is tested.
If exp2is true then the body of the loop will be executed otherwise loop will be terminated.
When the body of the loop is executed the control is transferred back to the for
statement after evaluating the last statement in the loop. Now exp3 will be evaluated and the
new value is again tested
.if it satisfies body of the loop is executed .This process continues till condition is false.
void main()
{
int i,n;
32
printf("enter the value");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("%d ",i);
}
}
Output: enter the value 5
12345
Q9. Explain Jumping control-flow statements. (Or) Differentiate between the following with
example?
Break statement
Continue statement
Goto statement (Or)
What are the differences between break statement and Continue statement?
Ans:
Jumping control-flow statements are the control-flow statements that transfer the control to the
specified location or out of the loop or to the beginning of the loop. There are 3 jumping control
statements:
33
1. break statement
The ―break‖ statement is used within the looping control statements, switch statement
and nested loops. When it is used with the for, while or do-while statements, the control
comes out of the corresponding loop and continues with the next statement.
When it is used in the nested loop or switch statement, the control comes out of that loop /
switch statement within which it is used. But, it does not come out of the complete nesting.
break;
statement_1;statement_2;
break;
}
next_statement;
34
Program for break statement:
#include<stdio.h>int main()
{
int i;
for(i=1; i<=10; i++)
{
if(i==6)
break; printf("%d",i);
}
}
Output: 12345
2. Continue statement
A continue statement is used within loops to end the execution of the current iteration and proceed to
the next iteration. It provides a way of skipping the remaining statements in that iteration after the
continue statement. It is important to note that a continue statement should be used only in loop
constructs and not in selective control statements.
continue;
35
statement_1;
statement_2;
continue;
}
next_statement;
Program for continue statement:
#include<stdio.h>i
nt main()
{
int i, sum=0, n;
{
printf("enter any no:");
scanf("%d",&n); if(n<0)
continue;
sum=sum+n;
printf("%d\n",sum);
}
3. goto statement
36
The goto statement transfers the control to the specified location unconditionally. There are
certain situations where goto statement makes the program simpler. For example, if a deeply
nested loop is to be exited earlier, goto may be used for breaking more than one loop at a time. In
this case, a break statement will not serve the purpose because it only exits a single loop.
statement_1;
statement_2;
}
goto label;
In this syntax, goto is the keyword and label is any valid identifier and should be ended with a colon
(:).
The identifier following goto is a statement label and need not be declared. The name of the
statement or label can also be used as a variable name in the same program if it is declared
appropriately. The compiler identifies the name as a label if it appears in a goto statement and as a
variable if it appears inan expression.
If the block of statements that has label appears before the goto statement, then the control has
to move to backward and that goto is called as backward goto. If the block of statements that has
label appears after the goto statement, then the control has to move to forward and that goto is
called as forward goto.
void main()
{
37
printf("www.");
goto x;
y:
printf("expert");
goto z;
x:
printf("c programming");
goto y;
z:
printf(".com");
}
Output: www.c programming [Link]
38
Q10. What are the differences between while and do-while statements? Ans:
The main difference between the while and do-while loop is in the place where the condition
is to be tested.
In the while loops the condition is tested following the while statement then the body gets
executed. Where as in do-while, the condition is checked at the end of the loop. The do-while
loop will execute at least one time even if the condition is false initially. The do-while loop
executes until the condition becomes false.
While do-while
UNIT -III
39
Types of Conditional Statements in C
if Statement:-
Syntax:
Syntax:
if (test expression)
{
Statement-block;
}
Statement-x;
Example:
Output
Execution:
1. First, evaluates the test expression.
2. If the result is TRUE , statement block is executed and continues execution with
statement-x
3. If it is FALSE, statement- block is skipped from execution and continues execution with
the statement-x.
EXAMPLE
//Program to accept the number from user and print if it is a odd.
#include<stdio.h>
main()
{
intnum;
printf(“enter any number”);
40
scanf(“%d”,&num);
if(num%2!=0)
{
printf(“number is odd %d”,num);
}
}
if-else Statement:-
41
}
Nested if…else statement can be used to choose an option from more than two
alternatives. When an if statement is placed in another if statement, it is called nested if
statement.
Syntax:
if(test _expression1)
{
if(test_expression2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
Execution: 1. Evaluates the test_expression1.
2. If the test_expression1 is TRUE, evaluates the test_expression2,iftest_expression2 is
true then executes statement 1 otherwise executes statement2. control is jumped to
statement x
3. If the test_expression1is FALSE statement3 is executed followed by statement-x
execution.
EXAMPLE:
42
//Program to display largest number from three integer numbers using nested if-else
statements.
#include<stdio.h>
int main()
{
float num1, num2, num3;
printf("Enter three numbers: ");
scanf("%f %f %f",&num1,&num2,&num3);
if(num1 >= num2)
{
if(num1 >= num3)
printf("Largest Number=%.2f\n",num1);
else
printf("Largest Number=%.2f\n",num3);
}
else
{
if(num2>=num3)
printf("Largest Number=%.2f\n",num2);
else
printf("Largest Number=%.2f\n",num3);
}
return0;
}
Output:-
Enter three numbers: 12.5, 10, 5.9
Largest Number=12.50
switch Statement
The if-else statement provides a way for selecting any one of the two possible alternatives.
Nested if allows to select one of the many alternatives but it is time consuming. It tests all
conditions and based on the result, a particular branch is taken for execution. To
overcome this, the switch statement is used. The switch statement provides a multiple
way branching. That is, it allows the user to select any one of the several alternatives,
depending upon the value of an expression. The expression is enclosed within the
parentheses. Depending upon the value of an expression, the control is transferred to a
particular case label(branch) and the statements followed by the case label are executed.
Syntax:
switch(expression)
{
case value-1:
block-1;
43
break;
case value-2:
block-2;
break;
……….
………..
default:
default-block;
}
Statement-x;
where expression can be an integer constant or characters. Value-1,value-2 are constants
or constant expressions and are known as case labels.
Working:
1. Evaluates the expression.
2. The resulted integer value is compared with case constants.
3. If match is found , the statements associated with that particular case are executed.
4. If no match is found , statements under default are executed. 5. When break statement
is encountered, the switch is terminated.
Example.
Program for Switch case to Find weekdays name with weekday number.
#include<stdio.h>
intmain()
{
int day;
printf("Enter weekday number (1-7): ");
scanf("%d",&day);
switch(day)
{
case1:
printf("1 - Sunday");
break;
case2:
printf("2 - Monday");
break;
case3:
printf("3 - Tuesday");
break;
case4:
printf("4 - Wednesday");
break;
case5:
printf("5 - Thursday");
break;
case6:
printf("6 - Friday");
44
break;
case7:
printf("7 - Saturday");
break;
default:
printf("%d : Invalid Day Option",day);
}
return0;
}
Output:
Enter weekday number (1-7): 4
4 - Wednesday
Enter weekday number (1-7): 10
10 : Invalid Day Option
Syntax of an if Statement
45
basic syntax of an if statement is:
if (condition) {
// Code to execute if condition is true
}
condition: This is an expression that is evaluated to either true (non-zero value) or false
(zero). The condition can be any expression that results in a boolean value.
Code Block: The code inside the curly braces {} is executed if the condition is true. If the
condition is false, this code block is skipped.
Explanation
1. Condition Evaluation:
o The condition in the if statement is evaluated. In C, any non-zero value is considered true,
and zero is considered false.
o Conditions can involve relational operators (like ==, !=, <, >), logical operators (like && for
logical AND, || for logical OR), and more complex expressions.
2. Code Block Execution:
o If the condition evaluates to true, the statements inside the curly braces {} are executed.
o If the condition evaluates to false, the statements inside the curly braces are skipped, and the
program continues with the code following the if block.
Example
#include<stdio.h>
intmain() {
int number = 10;
if (number >0) {
printf("The number is positive.\n");
}
return0;
}
else if construct plays a critical role in conditional branching, allowing for the evaluation
of multiple conditions sequentially.
It extends the basic if-else structure by providing additional conditions to check if the
initial if condition evaluates to false.
46
It is a way to check multiple conditions and execute different blocks of code based on
those conditions.
The else if statement is used to specify a new condition to test when the previous if or
else if conditions are false.
It enables a program to handle multiple conditions and execute different blocks of code
depending on which condition is true.
Features
1. Sequential Checking: else if allows for the sequential evaluation of multiple conditions.
The program checks each else if condition only if the previous conditions were false.
2. Multiple Conditions: It helps in managing complex decision-making scenarios where
multiple distinct conditions need to be tested.
3. Fall-Through Prevention: By using else if, you ensure that only one block of code is
executed. Once a true condition is found, the rest of the else if conditions are skipped.
4. Execute different blocks of code: Based on the conditions, different blocks of code can be
executed.
5. Reduce nesting: Else If can reduce nesting of If statements, making the code more
readable and maintainable
Syntax
if (condition1) {
// Code to execute if condition1 is true
} elseif (condition2) {
// Code to execute if condition1 is false and condition2 is true
} elseif (condition3) {
// Code to execute if condition1 and condition2 are false and condition3 is true
} else {
// Code to execute if all previous conditions are false
}
condition1: The initial condition that is evaluated. If true, the corresponding block of code
is executed, and the rest of the else if and else blocks are skipped.
condition2: The second condition that is evaluated if condition1 is false. If true, its block
of code is executed.
condition3: The third condition evaluated if both condition1 and condition2 are false.
else: The optional block executed if none of the preceding conditions are true.
Example
#include<stdio.h>
47
intmain() {
int score = 85;
return0;
}
Explanation:
1. Initial Condition (score >= 90): The program first checks if the score is greater than or
equal to 90. If this condition is true, it prints "Grade: A" and skips the remaining checks.
2. Second Condition (score >= 80): If the score is less than 90, the program checks if it is
greater than or equal to 80. If true, it prints "Grade: B".
3. Third Condition (score >= 70): If neither of the previous conditions is true, it checks if the
score is greater than or equal to 70. If true, it prints "Grade: C".
4. Fourth Condition (score >= 60): If none of the previous conditions hold, it checks if the
score is greater than or equal to 60. If true, it prints "Grade: D".
5. else: If none of the conditions are met, it defaults to the else block and prints "Grade: F".
Jumping statements, also known as control flow statements, are a type of statement in C
programming that allows the program to transfer control to a different location in the code. They
are used to alter the normal flow of execution of a program, allowing the program to jump to a
specific location or skip certain sections of code.
Types of Jumping Statements in C
1. Break Statement
The break statement is used to exit a loop or a switch statement. It transfers control to the
statement immediately following the loop or switch statement.
48
Syntax:
break;
Example:
for (inti = 0; i< 5; i++) {
if (i == 3) {
break; // exit the loop when i == 3
}
printf("%d ", i);
}
2. Continue Statement
The continue statement is used to skip the current iteration of a loop and transfer control to the
next iteration.
Syntax:
continue;
Example:
for (inti = 0; i< 5; i++) {
if (i == 2) {
continue; // skip the current iteration when i == 2
}
printf("%d ", i);
}
3. Return Statement
The return statement is used to exit a function and return control to the calling function. It can
also return a value to the calling function.
Syntax:
return [expression];
Example:
int add(int a, int b) {
49
int result = a + b;
return result; // return the result to the calling function
}
4. Goto Statement
goto is a jumping statement in c language, which transfer the program’s control from one
statement to another statement (where label is defined).
goto requires a label to identify the place where the branch is to be made. Label is a valid
variable name, and must be followed by a colon (:). Label is placed immediately before the
statement where the control is to be transferred.
Syntax:
goto label;
Example:
int main() {
int x = 5;
if (x > 10) {
goto skip; // jump to the labeled statement
}
printf("x is less than or equal to 10\n");
skip:
printf("x is greater than 10\n");
return 0;
}
5. What do you mean by goto statement explain in details with syntax and
example
GOTO STATEMENT
goto is a jumping statement in c language, which transfer the program’s control from one
statement to another statement (where label is defined).
goto requires a label to identify the place where the branch is to be made. Label is a valid
variable name, and must be followed by a colon (:). Label is placed immediately before
the statement where the control is to be transferred.
Syntax:
goto label_name;
50
EXAMPLE:
To print numbers from 1 to 10 using goto statement*/
#include <stdio.h>
main()
{
int number;
number=1;
repeat:
printf("%d\n",number);
number++;
if(number<=10)
goto repeat;
}
Output:
1
2
3
4……….10
[Link]:
To read and print the number, if number is positive only*/
#include <stdio.h>
main()
{
int number;
printf("Enter an integer number: ");
scanf("%d",&number);
if(number<=0)
goto end;
printf("Number is : %d", number);
end:
printf("Bye Bye !!!");
return 0;
}
Output:
Enter an integer number: 123
Number is : 123
51
Looping statements are used to execute a statement or group of statements repeatedly
for a specified number of times or as long as the condition is true/ until the condition is
false. A loop is a particular area of a program where some executable statements are
written which gets executed by testing one or more conditions. So, in looping, a sequence
of statements is executed until some conditions for termination are satisfied.
For example, if we need to print ‘UNIVERSITY OF HARYANA’ 10-times then, instead of
using the printf statement 10 times, we can use printf once inside a loop which runs up to
10 iterations.
Entry-controlled loops (Pre-test):-In Entry controlled loop the test condition is checked
first and if that condition is true than the block of statement in the loop body will be
executed
Example: while loop and for loop.
Exit controlled loop (Post-test): -In exit controlled loop the body of loop will be executed
first and at the end the test condition is checked, if condition is satisfied then body of
loop will be executed again.
Example:do-whileloop.
TYPES OF LOOPS
Three types of loops in C language :
while
do while
for
Essential components of a loop:
• Initialisation/Counter : To set the initial values for the loop counter.
• Condition/Decision: Test condition to check whether the to be executed by iteration or
not.
• Increment/decrement: Updation the counter value.
WHILE LOOP
This is used to execute a set of statements repeatedly as long as the specified condition is
true.
Syntax:
initialisation;
while(condition)
{
block of statements to be executed ;
increment;
}
The test-condition is evaluated and if the condition is true, then the body of loop is
executed. After execution of the body, the test-condition is once again evaluated and if it
is true, the body is executed once again. This process is repeated, execution of the body
continues until the test-condition finally becomes false and the control is transferred out
of the loop. If the condition is initially false, the statement will not be executed.
52
[Link]
program to print the natural numbers less than 10 using while loop.
#include #include
void main()
{
inti ; // declaration statement
clrscr(); i=0 ; // initialization statement
while ( i<10)
{
printf( "%d\t" , i ) ;
i++; // increment statement
}
getch();
}
Output: 0 1 2 3 4 5 6 7 8 9
[Link]
Program to print table for the given number using while loop .
#include<stdio.h>
main()
{
inti=1,number,b;
printf("Enter a number: ");
scanf("%d",&number);
while(i<=10)
{
b=number*i;
printf("%d \t", b);
i++;
}
getch();
}
Output
Enter any number :5
51015 20 25 30 35 40 45 50
[Link]
//Program that prompts the user to input a number and reverse its digits.
#include <stdio.h>
intmain()
{
int number, temp, remainder, reverse = 0;
printf("Enter a positive integer :");
53
scanf("%d", &number);
temp = number;
while (temp >0)
{
remainder = temp % 10;
reverse = reverse * 10 + remainder;
temp /= 10;
}
printf("The reverse of %d is %d.", number, reverse);
return0;
}
Output: Enter a positive integer :12345
The reverse of 12345 is 54321.
FOR LOOP
The for statement is most often used in situations where the programmer knows in
advance how many times a particular set of statements are to be [Link] is frequently
used to traverse the data structures like the array and linked list.
Syntax :
for(Expression1; Expression2; Expression3)
{
codes to be executed;
}
Where
Expression 1 : Represents the initialization of the loop variable.
Expression 2 : Represents a conditional expression. It checks for a specific condition to be
satisfied. If it is not, the loop is terminated. It can have more than one condition. However
the loop will iterate until the last condition becomes false.
Expression 3:Represents increment or decrement to update the value of the loop
variable.
[Link]( initialization; test condition; increment or decrement )
{
Statement to be executed;
}
[Link]
//Print out all numbers from 1 to 20.
#include<stdio.h>
main()
{
intnum;
for ( num = 1; num<= 20; num++ )
printf( "%d\n",num ) ;
54
return 0;
}
Output:1 2 3 4 5 6 7 8 9………..20
[Link]
//Program to find the sum of first 50 natural numbers.
#include <stdio.h>
intmain()
{
inti, n, sum = 0;
printf("Enter a positive integer :");
scanf("%d", &n);
for (i = 1; i<= n; i++)
{
sum += i;
}
printf("The sum of first %d numbers is %d.", n, sum);
return0;
}
Output: Enter a positive integer :20
The sum of first 20 numbers is 210.
[Link]
// Write a program that prompts the user to input a number and prints its factorial.
The factorial of an integer n is defined as
n! = 1 x 2 x 3 x ... x n; if n > 0
= 1; if n = 0
For instance, 6! can be calculated as 1 x 2 x 3 x 4 x 5 x 6
#include <stdio.h>
intmain()
{
inti, n, fact = 1;
printf("Enter a number :");
scanf("%d", &n);
for (i = 1; i<= n; i++)
{
fact *= i;
}
printf("The factorial of %d is %d.", n, fact);
return0;
}
Output: Enter a number :6
The factorial of 6 is 720.
55
When a loop written inside the body of another loop then, it is known as nesting of loop.
Any type of loop can be nested in any type such as while, do while, for.C programming
language allows to use one loop inside another loop.
Syntax:
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}
Working:
Initially, Nested for loop evaluates outer for loop condition and evaluates only once. If
the condition is true, the flow of control jumps to the inner for loop.
Then, the loop evaluates the condition of the inner loop. when the condition is true, it
executes codes of inside the inner for loop. If the condition returns false, the flow of
control skips the execution and jumps out to the outer loop for execution.
Then the outer for loop test expression(condition) is evaluated again when the test
expression is false, the flow of control skips the execution and come out of the loop for
rest.
EXAMPLE.
#include <stdio.h>
#include <stdlib.h>
main()
{
inti,j;
for(i=0;i<2;i++)
for(j=0;j<5;j++)
printf(“%d %d”, i, j);
}
Output: when i=0 //inner loop
j=0 1 2 3 4 //outer loop
wheni=1// inner loop
j=0 1 2 3 4//outer loop
EXAMPLE .
Print pattern:
#include <stdio.h>
main()
{
inti, j;
for (i = 1; i<= 5; i++)
{
56
for (j = 1; j <= i; j++)
{
printf("*");
}
printf("\n");
}
getch();
}
Output:
*
**
***
****
*****
DO WHILE LOOP
do-while loop, tests the condition at the bottom after making each pass through the loop
body. The body is always executed at least once.
A do while loop executes the statements inside the body of do-while before checking the
condition. So you can say that if a condition is false at the first place then the do while
would run once.
Syntax:
do
{
Statements
} while(condition test);
[Link]
#include<stdio.h>
intmain()
{
int j=0;
do
{
printf("Value of variable j is: %d, j);
j++;
} while(j<=2);
return0;
}
Output:
Value of variable j is:0
Value of variable j is:1
Value of variable j is:2
57
[Link]
Program to find the factorial of a given number.
#include<stdio.h>
int main()
{
int N, fact=1, i;
printf(“Enter the value of N\n”);
scanf(“%d” , &N);
i=1;
do
{
fact = fact * i;
i++;
} while(i<=N);
printf(“Factorial(%d) = %d\n”, N, fact);
return 0;
}
7. What are logical operators in c language, and how are they used in conditional
statements?
58
int age = 25;
if (age > 18 && age < 65) {
printf("You are an adult and not a senior.\n");
}
Logical OR (||)
The logical OR operator is used to combine two conditions.
It returns 1 (true) if either condition is true.
If both conditions are false, the result is 0 (false).
To check if at least one of multiple conditions is true.
Syntax:
if (condition1 || condition2) {
printf("statement block\n");
}
Example:
if (x > 0 || y < 0) {
printf("Either x is positive or y is negative\n");
}
59
Logical operators can be used in various ways in conditional statements:
Simple conditions: You can use logical operators to combine simple conditions, such as x
> 0 && y > 0.
Compound conditions: You can use logical operators to combine multiple conditions,
such as x > 0 && y > 0 && z > 0.
Nested conditions: You can use logical operators to combine conditions inside other
conditions, such as if (x > 0 && (y > 0 || z > 0)).
Evaluation
C's logical AND (&&) and OR (||) operators use short-circuit evaluation.
This means that the evaluation of expressions stops as soon as the result is determined:
AND (&&): If the first operand is false, the second operand is not evaluated because the
result will be false regardless.
OR (||): If the first operand is true, the second operand is not evaluated because the
result will be true regardless.
8. What is a switch statement, and how does it differ from a series of if-else
statements?
SWITCH STATEMENTS
The if-else statement provides a way for selecting any one of the two possible
[Link] if allows to select one of the many alternatives but it is time [Link]
tests all conditions and based on the result, a particular branch is taken for [Link]
overcome this, the switch statement is [Link] switch statement provides a multiple way
[Link] is, it allows the user to select any one of the several alternatives,depending upon
the value of an [Link] expression is enclosed within the parentheses. Depending upon
the value of an expression,the control is transferred to a particular case label(branch) and the
statements followed by the case label are executed.
Syntax:
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
……….
………..
default:
default-block;
}
60
Statement-x;
where expression can be an integer constant or characters. Value-1,value-2 are constants or
constant expressions and are known as case labels.
Working:
1. Evaluates the expression.
2. The resulted integer value is compared with case constants.
3. If match is found , the statements associated with that particular case are executed.
4. If no match is found , statements under default are executed. 5. When break statement is
encountered, the switch is terminated.
[Link].
Program for Switch case to Find weekdays name with weekday number.
#include<stdio.h>
intmain()
{
int day;
printf("Enter weekday number (1-7): ");
scanf("%d",&day);
switch(day)
{
case1:
printf("1 - Sunday");
break;
case2:
printf("2 - Monday");
break;
case3:
printf("3 - Tuesday");
break;
case4:
printf("4 - Wednesday");
break;
case5:
printf("5 - Thursday");
break;
case6:
printf("6 - Friday");
break;
case7:
printf("7 - Saturday");
break;
default:
printf("%d : Invalid Day Option",day);
}
return0;
}
61
Output:
Enter weekday number (1-7): 4
4 - Wednesday
Enter weekday number (1-7): 10
10 : Invalid Day Option
2. Example
//Program to check Vowel or consonant using switch case with the break
#include <stdio.h>
#include <stdlib.h>
intmain()
{
charch;
printf("Enter any Alphabet\n");
scanf("%c",&ch);
switch(ch)
{
//check lower case vowel letters
case'a':
printf("%c is a vowel",ch);
break;
case'e':
printf("%c is a vowel",ch);
break;
case'i':
printf("%c is a vowel",ch);
break;
case'o':
printf("%c is a vowel",ch);
break;
case'u':
printf("%c is a vowel",ch);
break;
//check upper case vowel letters
case'A':
printf("%c is a vowel",ch);
break;
case'E':
printf("%c is a vowel",ch);
break;
case'I':
printf("%c is a vowel",ch);
62
break;
case'O':
printf("%c is a vowel",ch);
break;
case'U':
printf("%c is a vowel",ch);
break;
default:
printf("%c is a consonant",ch);
break;
}
getch();
return0;
}
Output:
Enter any Alphabet
a
a is a vowel
Enter any Alphabet
g
g is a consonant
The ternary operator, also known as the conditional operator, is a concise way to write a
conditional statement in C programming. It is a shorthand for a simple if-else statement and is
used to evaluate an expression based on a condition
The ternary operator, also known as the conditional operator ?:, is a concise way to write
conditional expressions in many programming languages, including C, C++, Java, Python (to some
extent), and others. It serves as a compact alternative to if-else statements when you need to
make a decision based on a condition. Here's how it works and how to use it:
Print(statement);
63
expression_if_true: The value or expression to be evaluated if the condition is true.
expression_if_false: The value or expression to be evaluated if the condition is false.
How It Works
Expanded Explanation
1. Condition: (a > b)
o Here, a > b is evaluated. If this condition is true (a is greater than b), the ternary
operator returns a; otherwise, it returns b.
2. Result Assignment: int max = (a > b) ? a : b;
o If a > b evaluates to true (a is greater than b), then max will be assigned the value
of a.
o If a > b evaluates to false (a is not greater than b), then max will be assigned the
value of b.
Conciseness: It allows you to write simple conditional expressions in a single line, which
can make your code more compact and readable, especially for simple conditions.
Readability: For straightforward conditions, using the ternary operator can enhance code
readability compared to using an if-else statement.
Efficiency: The ternary operator is more efficient than an if-else statement because it
eliminates the need for a separate if-else block.
Expressiveness: The ternary operator allows you to express complex conditional logic in a
single line of code.
Limitations
Complexity: Avoid using the ternary operator for complex conditions or expressions that
span multiple lines. It can reduce readability in such cases.
Side Effects: Be cautious when using expressions with side effects inside the ternary
operator, as the order of evaluation may affect the behavior of your code
64
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
return 0;
}
When none of the case values are equal to the expression of switch statement then default case
is executed. In the example below, value of number is 4 so case 0, case 1 and case 2 are not
equal to number. Hence sopln of default case will get executed printing "Value of number is
greater than two" to the console.
int number = 4;
switch(number) {
case 0:
[Link]("Value of number is zero");
break;
case 1:
[Link]("Value of number is one");
break;
case 2:
[Link]("Value of number is two");
break;
65
default:
[Link]("Value of number is greater than two");
break;
11. What are loops in programming, and why are they used?
The structure of a Loop can be virtually divided into two parts, namely the control statement,
and the body. The control statement of a Loop comprises the conditions that have to be met
for the execution of the body of the Loop. For every iteration of the Loop, the conditions in
the control statement have to be true. The body of a Loop comprises the block of code or the
sequence of logical statements that are to be executed multiple times. There are two types
of Loops in Python, namely, For Loop, and While Loop. When a Loop is written within another
Loop, the control structure is termed as a nested Loop.
Therefore, when you use a Loop in your program, you will not have to write the block of code
(written in the body of the Loop), over and over again in it. The block of code will be executed
as many times as the control statement will hold true and the Loop will be terminated when
the conditions in the control statement become false. If the conditions are not clearly defined
in the control statement, the Loop will keep on executing. Such Loops are termed as infinite
Loops. If no termination condition is provided in the control statement of a Loop, then it
automatically becomes an infinite Loop.
Below is a detailed discussion of ‘what is Loop’, and the various types of Loops in Python.
Hence, going through the below information will help kids to understand the concepts of
Loops in computer Programming.
Types of Loops
The concept of ‘what is Loop’ will be clearly understood when you get an idea of the syntax
66
and function of various types of Loops. There are basically two types of Loops in most
computer Programming languages, namely, entry controlled Loops and exit controlled Loops.
Entry Controlled Loop
In an entry controlled Loop, the control statement is written right at the beginning of the
Loop. This type of Loop is also called a pre-checking Loop. The conditions in the control
statements are checked at first, and only if the conditions are true, the body of the Loop is
executed. If the condition turns out to be false, the lines of code in the body of the Loop will
not be executed.
FOR Loop is an entry controlled Loop, that is, the control statements are written at the
beginning of the Loop structure, whereas, do-while Loop is an exit controlled Loop, that is,
the control statements are written at the end of the Loop structure.
For Loops
As discussed above, a For Loop is an entry controlled Loop. The general syntax of a For Loop
is given below.
for(initialization; condition; incrementation or decrementation)
{
Body of Loop;
}
The variables required for the control statements can be initialized in the For Loop itself. This
variabl
initialized in the For Loop is called the counter and is incremented or decremented with every
iteration of the Loop. The condition is a boolean statement that compares the value of the
counter to a fixed value, at every iteration, and terminates the Loop when the condition is not
satisfied. The increment or decrement value is set in the Loop.
An example of For Loop is given below.
for(int i=1; i<10; i++)
{
print (i);
}
The above For Loop will print the natural numbers 1 to 10 when executed. The variable ‘i’ is of
integer type, and the condition will check if the value of ‘i’ is less than 10, at each iteration. After
executing the body of the Loop, the value of ‘i’ is incremented by 1, before the next iteration. In
this way, the natural numbers 1 to 10 are displayed on the screen, on executing this Loop.
While Loop
67
A while Loop is an exit controlled Loop. The syntax of the do-while Loop is similar to that of the
while Loop, with the exception of the condition checking. The condition is always checked at the
end of the do-while Loop. The general syntax of the do-while Loop is given below.
do
{
Body of the Loop;
} while(condition);
Unlike the entry controlled Loops, the body of the do-while Loop is executed before the
condition is checked. Even if the condition is not true, the body of the Loop will be executed for
once. If the condition given in the braces () is true, the control is again moved back to the body of
the Loop. If the condition is false, the control is moved out of the Loop and the Loop is
terminated.
An example of the do-while Loop is given below.
int i=10;
do
{
print (i);
i--;
} while(n>0);
The above do-while Loop will display the numbers 10 to 1 when executed. Now, consider the
following example.
int i=0;
do
{
print (i);
i--;
} while(n>0);
The condition ‘n>0’ turns out to be false at the very first iteration of the above-given do-while
Loop. Yet, it will be executed once, and 0 will be displayed on the screen. Unlike the other Loops,
the do-while Loop ends with the condition checking expression followed by a semicolon ‘;’.
Loops in Python
The commonly used Loops in Python are For and While Loops. The syntax and functions of the
For and While Loops in Python are the same as discussed above. When a For Loop or a While
Loop is written within another Loop, the structure is called a nested Loop. For example,
for(int i=0; i<7;i++)
{
for (int j=8; j>4; j--)
{
print (i);
print (j);
68
}
}
The print statements in the above-given nested Loop will be executed only when the conditions
in both the Loops are satisfied. Also, if there is only one line of code to be written in the body of
a Loop, it is not mandatory to put the brackets for it.
Example:
for(int n=5; n<0; n--)
print (n);
Some of the control statements supported in Python are ‘break’, ‘continue’, and ‘pass’. When a
‘break’ statement is encountered in a Loop, the Loop is terminated immediately, and the control
moves to the code followed by the Loop. When a ‘continue’ statement is encountered in a Loop,
the control is transferred to the condition checking part and the rest of the code in the body of
the Loop is skipped. The ‘pass’ statement in Python is a null statement. It is quite similar to a
commented code, however, unlike the commented code, a pass statement is not ignored by the
interpreter. For example, if we want to execute a block of code or any function at a later point in
time, we can use the ‘pass’ statement for it. The block of code will not be executed when the
‘pass’ statement is executed. The pass statement has a result of no operation when executed.
Since Loops make an important part of Python Programming, kids should learn the concepts of
Loops thoroughly, to write advanced programs. Good knowledge of Loops will come in handy
when kids will write programs to design fun interactive games in Python as well.
12. Explain the difference between for, while, and do-while loops.
For Loop, While Loop, and Do-While Loop are different loops in programming. A For loop is
used when the number of iterations is known. A While loop runs as long as a condition is true.
A Do-While loop runs at least once and then continues if a condition is true.
For Loop in Programming:
The for loop is used when you know in advance how many times you want to execute the
block of code.
It iterates over a sequence (e.g., a list, tuple, string, or range) and executes the block of
code for each item in the sequence.
The loop variable (variable) takes the value of each item in the sequence during each
iteration.
For Loop Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed repeatedly
}
#include <iostream>
69
using namespace std;
int main()
{
for (int i = 0; i < 5; i++)
cout << i << "\n";
return 0;
}
While Loop in Programming:
The while loop is used when you don’t know in advance how many times you want to
execute the block of code. It continues to execute as long as the specified condition is true.
It’s important to make sure that the condition eventually becomes false; otherwise, the
loop will run indefinitely, resulting in an infinite loop.
While Loop Syntax:
The syntax of a while loop is straightforward:
while(condition){
# Code to be executed while the condition is true
}
13. How does a for loop operate, and what is its typical structure?
In the C programming language, a for loop is a control flow construct used for the iterative
execution of a block of code. It allows you to repeat a set of instructions a specific number of
times or until a certain condition is met. The for loop is an entry-controlled loop and has a well-
defined structure consisting of three main components, i.e., initialization, condition, and
iteration expression.
Other loop constructs in C include the while loop and the do-while loop. The former of these is
also an entry control loop or a pre-checking loop since the condition is checked at the beginning.
The latter is an exit control loop or a post-checking loop since the condition is checked after the
initial code block has been executed.
The Structure Of For Loop In C
70
As mentioned before, the for loop in C has a well-defined structure comprising three essential
components, i.e., initialization (or the starting value of the control variable), condition, and
iteration expression.
The for-loop syntax in C is as follows:
for (initialization; condition; iteration_expression) {
// Code block to be repeated
}
The for keyword marks the beginning of this loop in a C program. Here is a description of the
three main components of a for loop-
Initialization
This part is executed only once at the beginning of the loop. It is used to initialize one or more
loop control variables in an expression. These variables are crucial for controlling the loop and
keeping track of the current state.
One important thing to note is that, with certain compiler exceptions, we can choose not to
declare the variable in Expression 1. However, would have to modify our code accordingly.
For example:
#include <stdio.h>
int main(){
int i = 1;
for(; i < 5; i++){
printf("%d", i);}}
Here, the first condition, i.e., the initialization, is missing since we have initialized the control
variable outside of the main() function.
Condition/ Test Expression
71
The loop continues executing as long as this specified condition is true (it is also known as the
looping condition). If the condition becomes false, the loop terminates. In this sense, the looping
condition acts as a gatekeeper, determining when the loop should stop or the program should
exit the loop.
Note that we can also have more than one condition. However, the loop will iterate according to
the last condition, and the other conditions will be treated as statements.
Iteration Expression/ Updation Condition
This part is executed after each iteration of the loop and is typically used to update the loop
control variable(s). In other words, allows you to specify how the loop variables should change
with each iteration. We generally use the increment and decrement operators to update the
value of the control variable.
Loop body
This refers to the part of code written within the curly brackets {} of the for loop. This is the code
that will be repeated again and again as per the conditions of the for loop, i.e., till the looping
condition remains true. Note that it is possible to not use the curly braces ( {} ) if the body is of
single line only. This is because curly braces actually define the scope of the for loop.
For example:
#include<stdio.h>
void main (){
for(int i=0; i<10; i++)
printf("%d ", i);}
Loops in C language are the control flow statements that are used to repeat some part of the
code till the given condition is satisfied. The do-while loop is one of the three loop statements
in C, the others being while loop and for loop. It is mainly used to traverse arrays, vectors, and
other data structures.
do…while in C is a loop statement used to repeat some part of the code till the given
condition is fulfilled. It is a form of an exit-controlled or post-tested loop where the test
condition is checked after executing the body of the loop. Due to this, the statements in the
do…while loop will always be executed at least once no matter what the condition is.
72
Syntax of do…while Loop in C
do {
} while (condition);
int main()
{
return 0;
}
73
15. What is the primary difference between a while loop and a do-while loop?
While Do While
If the condition is false initially, the The loop body is executed at least once,
loop body is never executed regardless of the initial condition
16. Explain how the break statement can be used to exit a loop?
74
The break in C is a loop control statement that breaks out of the loop when encountered. It
can be used inside loops or switch statements to bring the control out of the block. The break
statement can only break out of a single loop at a time.
Syntax of break in C
break;
We just put the break where ever we want to terminate the execution of the loop.
Use of break in C
The break statement in C is used for breaking out of the loop. We can use it with any type of
loop to bring the program control out of the loop. In C, we can use the break statement in the
following ways:
Simple Loops
Nested Loops
Infinite Loops
Switch case
Examples of break in C
Break statements in C can be used with simple loops i.e, for loops, while loops, and do-while
loops.
// C Program to demonstrate break statement with for loop
#include <stdio.h>
int main()
{
75
printf("\nbreak in while loop\n");
int i = 1;
while (i < 20) {
if (i == 3)
break;
else
printf("%d ", i);
i++;
}
return 0;
}
17. What is the purpose of the continue statement in loops? Provide an example.
The continue statement in C is a jump statement that is used to bring the program control to
the start of the loop. We can use the continue statement in the while loop, for loop, or do..while
loop to alter the normal flow of the program execution. Unlike break, it cannot be used with a C
switch case.
The C continue statement resets program control to the beginning of the loop when
encountered. As a result, the current iteration of the loop gets skipped and the control moves on
to the next iteration. Statements after the continue statement in the loop are not executed.
Syntax of continue in C
The syntax of continue is just the continue keyword placed wherever we want in the loop body.
continue;
Use of continue in C
The continue statement in C can be used in any kind of loop to skip the current iteration. In C, we
can use it in the following types of loops:
Single Loops
Nested Loops
Using continue in infinite loops is not useful as skipping the current iteration won’t make a
difference when the number of iterations is infinite.
Example of continue in C
Example 1: C Program to use continue statement in a single loop.
The continue statement can be used in for loop, while loop, and do-while loop.
// C program to explain the use
76
// of continue statement with for loop
#include <stdio.h>
int main()
{
// for loop to print 1 to 8
for (int i = 1; i <= 8; i++) {
// when i = 4, the iteration will be skipped and for
// will not be printed
if (i == 4) {
continue;
}
printf("%d ", i);
}
printf("\n");
int i = 0;
// while loop to print 1 to 8
while (i < 8) {
// when i = 4, the iteration will be skipped and for
// will not be printed
i++;
if (i == 4) {
continue;
}
printf("%d ", i);
}
return 0;
}
77
18. What is the difference between a continue statement and a break statement in
C?
Break Continue
Break statement stops the entire process of the loop. Continue statement only stops the
current iteration of the loop.
Break also terminates the remaining iterations. Continue doesn’t terminate the next
iterations; it resumes with the
successive iterations.
Break statement can be used with switch statements Continue statement can be used with
and with loops loops but not switch statements.
In the break statement, the control exits from the In the continue statement, the control
loop. remains within the loop.
It is used to stop the execution of the loop at a specific It is used to skip a particular iteration
condition. of the loop.
78
19. Describe how nested loops work with an example?
Nested for loop refers to any type of loop that is defined inside a ‘for’ loop. Below is the
equivalent flow diagram for nested ‘for’ loops:
Syntax:
79
Example: Below program uses a nested for loop to print a 3D matrix of 2x3x2
int main()
{
// initializing the 3-D array
int arr[2][3][2]
= { { { 0, 6 }, { 1, 7 }, { 2, 8 } },
{ { 3, 9 }, { 4, 10 }, { 5, 11 } } };
The statement within the body of a loop must ensure that the test condition for the loop
eventually becomes false, otherwise, the loop will run infinitely. Hence, the loop which doesn’t
end is called an infinite loop. This leads to a logical error in the program.
Example:
num = 20
while num > 10:
print(num)
num = num + 1
The above statement will create an infinite loop as the value of ‘num’ initially is 20 and each
80
subsequent loop is increasing the value of num by 1, thus making the test condition num >
10 always true.
In C, both if statements and while loops rely on the idea of Boolean expressions. Here is a simple
C program demonstrating an if statement:
This program accepts a number from the user. It then tests the number using an if statement to
see if it is less than 0. If it is, the program prints a message. Otherwise, the program is silent.
The (b < 0) portion of the program is the Boolean expression. C evaluates this expression to
decide whether or not to print the message.
If the Boolean expression evaluates to True, then C executes the single line immediately
following the if statement (or a block of lines within braces immediately following the if
statement). If the Boolean expression is False, then C skips the line or block of lines immediately
following the if statement
#include <stdio.h>
int main()
{
int b;
printf("Enter a value:");
scanf("%d", &b);
if (b < 0)
printf("The value is negative\n");
return 0;
}
In this example, the else if and else sections evaluate for zero and positive values as well.
81
Here is a more complicated Boolean expression:
if ((x==y) && (j>k))
z=1;
else
q=10;
This statement says, "If the value in variable x equals the value in variable y, and if the value in
variable j is greater than the value in variable k, then set the variable z to 1, otherwise set the
variable q to 10." You will use if statements like this throughout your C programs to make
decisions. In general, most of the decisions you make will be simple ones like the first example;
but on occasion, things get more complicated.
equality ==
less than <
Greater than >
<= <=
>= >=
inequality !=
and &&
or ||
not !
You'll find that while statements are just as easy to use as if statements. For example:
while (a < b)
{
printf("%d\n", a);
a = a + 1;
}
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called a recursive function. Using a recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are Towers of Hanoi
(TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. A recursive function
82
solves a particular problem by calling a copy of itself and solving smaller subproblems of the
original problems. Many more recursive calls can be generated as and when required. It is
essential to know that we should provide a certain case in order to terminate this recursion
process. So we can say that every time the function calls itself with a simpler version of the
original problem.
Need of Recursion
Recursion is an amazing technique with the help of which we can reduce the length of our code
and make it easier to read and write. It has certain advantages over the iteration technique
which will be discussed later. A task that can be defined with its similar subtask, recursion is
one of the best solutions for it. For example; The Factorial of a number.
Properties of Recursion:
Performing the same operations multiple times with different inputs.
In every step, we try smaller inputs to make the problem smaller.
Base condition is needed to stop the recursion otherwise infinite loop will occur.
Algorithm: Steps
The algorithmic steps for implementing recursion in a function are as follows:
Step1 - Define a base case: Identify the simplest case for which the solution is known or trivial.
This is the stopping condition for the recursion, as it prevents the function from infinitely calling
itself.
Step2 - Define a recursive case: Define the problem in terms of smaller subproblems. Break the
problem down into smaller versions of itself, and call the function recursively to solve each
subproblem.
Step3 - Ensure the recursion terminates: Make sure that the recursive function eventually
reaches the base case, and does not enter an infinite loop.
step4 - Combine the solutions: Combine the solutions of the subproblems to solve the original
problem.
23. How do you write a conditional statement to check if a number is even or odd?
Odd or Even
// A simple C++ program to
// check for even or odd
#include <iostream>
using namespace std;
83
// Returns true if n is
// even, else odd
bool isEven(int n) { return (n % 2 == 0); }
// Driver code
int main()
{
int n = 101;
isEven(n) ? cout << "Even" : cout << "Odd";
return 0;
}
The five letters A, E, I, O and U are called vowels. All other alphabets except these 5 vowels are
called consonants.
This program assumes that the user will always enter an alphabet character.
#include <stdio.h>
int main() {
char c;
int lowercase_vowel, uppercase_vowel;
printf("Enter an alphabet: ");
scanf("%c", &c);
84
// evaluates to 1 (true) if c is a vowel
if (lowercase_vowel || uppercase_vowel)
printf("%c is a vowel.", c);
else
printf("%c is a consonant.", c);
return 0;
}
In R programming, loops are essential constructs that allow us to repeat a set of instructions
multiple times. The while loop is one such construct that repeatedly executes a block of code
until a certain condition is met. This loop is particularly useful when you want to iterate over
elements without knowing the exact number of iterations in advance. In this article, we will
explore how to use the while loop to print the factorial of a number and understand its step-
by-step implementation.
Formula of factorial:
fact(N)=N*fact(N-1)
Syntax:
factorial <- function(n) {
result <- 1
while (n > 0) {
result <- result * n
n <- n - 1
}
return(result)
}
Include Standard Libraries: The program starts by including the standard input-output library
(stdio.h) which allows the program to use functions like "printf()" and "scanf()".
85
Main Function: The "main()" function is the entry point of the program where execution begins.
Declare Variables: The program declares an integer variable, typically n, to store the number for
which the factorial is to be calculated. Another variable, often called 'result', is initialized to 1 to
store the factorial result.
Input the Number: The program prompts the user to enter a number and reads the input using
the "scanf()" function. This input is stored in the variable 'n'.
o A loop (such as a "for" loop or "while" loop) runs from 1 to the given number 'n'.
o In each iteration of the loop, the current value of the loop counter is multiplied by 'result',
and the result is stored back in 'result'.
Output the Result: After the loop completes, the program prints the value of 'result', which now
holds the factorial of the input number 'n'.
void main()
{
int vote_age; // Declare an integer variable 'vote_age' to store the age of the candidate.
86
printf("Input the age of the candidate : "); // Prompt the user to input the age of the
candidate.
scanf("%d",&vote_age); // Read and store the user's input in 'vote_age'.
printf("You would be able to caste your vote after %d year.\n",18-vote_age); // Print the
number of years until the candidate is eligible to vote.
}
else
printf("Congratulation! You are eligible for casting your vote.\n"); // Print a message
indicating the candidate is eligible to vote.
}
28. What are the steps to evaluate a complex conditional expression involving
multiple conditions?
It's something that's bugged me in every language I've used, I have an if statement but the
conditional part has so many checks that I have to split it over multiple lines, use a nested if
statement or just accept that it's ugly and move on with my life.
Are there any other methods that you've found that might be of use to me and anybody else
that's hit the same problem?
if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true &&
var6 = true)
{
Example, multi-line:
87
if (var1 = true && var2 = true && var2 = true && var3 = true)
{
if (var4 = true && var5 = true && var6 = true)
29. How can you handle invalid input or exceptions within a conditional block?
C does not provide direct support to error handling (or exception handling), there are ways
through which error handling can be done in C. A programmer has to prevent errors in the first
place and test return values from the functions.
A lot of C function calls return -1 or NULL or set an in case of an error code as the global
variable errno, so quick tests on these values are easily done with an instance of ‘if statement’.
errno is a global variable indicating the error occurred during any function call and it is defined
inside <errno.h> header file.
When a function is called in C, a variable named errno is automatically assigned a code (value)
which can be used to identify the type of error that has been encountered. Different codes
(values) for errno mean different types of errors.
Below is a list of a few different errno values and their corresponding meaning:
errno value Error
1 Operation not permitted
2 No such file or directory
3 No such process
4 Interrupted system call
5 I/O error
6 No such device or address
7 The argument list is too long
8 Exec format error
9 Bad file number
10 No child processes
11 Try again
88
12 Out of memory
13 Permission denied
The leap year is necessary to correct the mismatch between the calendar year of 365 days and
the time it takes the Earth to complete its orbit around the sun, which is about 365.25 days. This
is done by adding an extra day, February 29, to the calendar every four years. This means that
the year 2000 was a leap year, but 1900 was not. The next leap year is 2024.
89
UNIT -4
C Array Declaration
In C, we have to declare the array like any other variable before using it. We can declare an
array by specifying its name, the type of its elements, and the size of its dimensions. When we
declare an array in C, the compiler allocates the memory block of the specified size to the array
name.
90
The C arrays are static in nature, i.e., they are allocated memory at the compile time.
int main()
{
return 0;
}
An array with more than one dimension is known as a multi-dimensional array. The most
commonly used multi-dimensional arrays are 2-D and 3-D arrays. We can say that any higher
dimensional array is basically an array of arrays. A very common example of a 2D Array is
Chess Board. A chessboard is a grid containing 64 1×1 square boxes. You can similarly
visualize a 2D array. In a 2D array, every element is associated with a row number and column
number. Accessing any element of the 2D array is similar to accessing the record of an Excel
91
File using both row number and column number. 2D arrays are useful while implementing a
Tic-Tac-Toe
Toe game, Chess, or even storing the image pixels.
import [Link].*;
class GFG {
public static void main(String[] args)
{
92
double[][] double2DArray; // 2D double array
}
}
Array-Basics in Java Multidimensional Arrays can be defined in simple words as array of arrays.
Data in multidimensional arrays are stored in tabular form (in row major order).
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]….[sizeN];
where:
data_type: Type of data to be stored in the array. For example: int, char, etc.
dimension: The dimension of the array created. For example: 1D, 2D, etc.
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions respectively.
Examples:
For example:
The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements. Similarly,
array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements.
● Multidimensional arrays are used to store the data in a tabular form. For example, storing
the roll number and marks of a student can be easily done using multidimensional arrays.
Another common usage is to store the images in 3D arrays.
● In dynamic programming questions, multidimensional arrays are used which are used to
represent the states of the problem.
93
● Apart from these, they also have applications in many standard algorithmic problems like:
Matrix Multiplication, Adjacency matrix representation in graphs, Grid search problems
Array is a data structure that is used to store variables that are of similar data types
at contiguous locations. The main advantage of the array is random access and cache
friendliness. There are mainly three types of the array:
One Dimensional (1D) Array
Two Dimension (2D) Array
Multidimensional Array
94
5. Write the
he list of operations on arrays?
Search − Uses the provided index or the value to search for an element.
When an array in C is started with size, the elements are subsequently given default values in the
manner described below.
#include <stdio.h>
main() {
int Arr[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are:\n");
are:
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n",n", i, Arr[i]);
}
}
95
Insertion Array Operations
One or more data elements are added to an array using the insert array operations. An array can
have a new element inserted at any index, including the start, end, or middle, depending on the
need.
In this example, the insertion action is implemented practically by adding data to the end of the
array.
Example
The implementation of the above algorithm is shown below.
#include <stdio.h>
main() {
int Arr[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are:\n");
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n", i, Arr[i]);
}
n = n + 1;
while( j >= k) {
Arr[j+1] = Arr[j];
j = j - 1;
}Arr[k] = item;
printf("The array elements after insertion:\n");
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n", i, Arr[i]);
}
}
Deletion is the process of eliminating an existing element from an array and rearranging all of the
array’s elements.
Algorithm
Take into consideration that K is a positive integer such that K=N and Arr is a linear array with N
items. The algorithm to remove one element from the Kth position of Arr is shown below.
Start
Set J = K
Repeat steps 4 and 5 while J < N
Set Arr[J] = Arr[J + 1]
96
Set J = J+1
Set N = N-1
Stop
Example
The implementation of the above algorithm is shown below.
#include <stdio.h>
void main() {
int Arr[] = {1,3,5,7,8};
int m = 3, n = 5;
int i, j;
printf("The original array elements are:\n");
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n", i, Arr[i]);
}
j = m;
while( j < n) {
Arr[j-1] = Arr[j];
j = j + 1;
}
n = n -1;
printf("The array elements after deletion:\n");
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n", i, Arr[i]);
}
}
An array element can be found using either its value or its index.
Algorithm
Take into consideration that K is a positive integer such that K=N and Arr is a linear array with N
items. The sequential search technique to locate an element with the value of ITEM is shown
below.
Start
Set J = 0
97
IF Arr[J] is equal ITEM THEN GOTO STEP 6
Set J = J +1
PRINT J, ITEM
Stop
Example
The above algorithm is implemented as follows:
#include <stdio.h>
void main() {
int Arr[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;
printf("The original array elements are:\n");
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n", i, Arr[i]);
}
while( j < n){
if( Arr[j] == item ) {
break;
}
j = j + 1;
}
printf("Found element %d at position %d\n", item, j+1);
}
Update array operations involve changing an existing array element at a certain index.
Algorithm
Take into consideration that K is a positive integer such that K=N and Arr is a linear array with N
items. The technique to update an element that is accessible at the Kth position of Arr is shown
below.
Start
Stop
98
Example
The implementation of the above algorithm is shown below.
#include <stdio.h>
void main() {
int Arr[] = {1,3,5,7,8};
int m = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are:\n");
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n", i, Arr[i]);
}
Arr[m-1] = item;
printf("The array elements after updation:\n");
for(i = 0; i<n; i++) {
printf("Arr[%d] = %d \n", i, Arr[i]);
}
}
2-dimensional array is a powerful data structure that allows for the storage and manipulation of
data in a tabular form. When dealing with a 2-dimensional array, it is important to understand its
underlying memory organization. This article aims to provide a comprehensive explanation of the
memory map of a 2-dimensional array, detailing how elements are stored and accessed in
memory.
Memory Representation of a 2-Dimensional Array:
In memory, a 2-dimensional array is typically represented as a contiguous block of memory cells.
The elements of the array are stored row by row, with each row occupying a continuous segment
of memory. The memory map follows a row-major order, meaning that the elements of each row
are stored together.
Calculating the Memory Address of an Element:
To access a specific element in a 2-dimensional array, you need to calculate its memory address.
The formula to calculate the memory address of an element at row i and column j in a 2-
dimensional array with rows and columns is:
address = base_address + (i * columns + j) * element_size
Here, base_address represents the starting memory address of the array, element_size is the size
(in bytes) of each element, and i and j are the indices of the row and column, respectively.
99
Example of Memory Map of a 2-Dimensional Integer Array:
2-dimensional array of integers with 3 rows and 4 columns:
int array[3][4];
In memory, the array would be represented as a contiguous block of 12 integers. The memory
map would look like this:
array[0][0] --> address1
array[0][1] --> address2
array[0][2] --> address3
array[0][3] --> address4
array[1][0] --> address5
array[1][1] --> address6
array[1][2] --> address7
array[1][3] --> address8
array[2][0] --> address9
array[2][1] --> address10
array[2][2] --> address11
array[2][3] --> address12
Nested function is not supported by C because we cannot define a function within another
function in C. We can declare a function inside a function, but it’s not a nested function.
Because nested functions definitions cannot access local variables of the surrounding blocks,
they can access only global variables of the containing module. This is done so that lookup of
global variables doesn’t have to go through the directory. As in C, there are two nested scopes:
local and global (and beyond this, built-ins). Therefore, nested functions have only a limited
use. If we try to approach nested function in C, then we will get compile time error.
100
// defining view() function inside fun() function.
int view()
{
printf("view");
}
return 1;
}
view();
}
Output:
Compile time error: undefined reference to `view'
A String in C programming is a sequence of characters terminated with a null character ‘\0’. The
C String is stored as an array of characters. The difference between a character array and a C
string is that the string in C is terminated with a unique character ‘\0’.
101
1. Assigning a String Literal without Size
String literals can be assigned without size. Here, the name of the string str acts as a pointer
because it is an array.
char str[] = "GeeksforGeeks";
2. Assigning a String Literal with a Predefined Size
String literals can be assigned with a predefined size. But we should always account for one extra
space which will be assigned to the null character. If we want to store a string of size n then we
should always declare a string with a size equal to or greater than n+1.
char str[50] = "GeeksforGeeks";
3. Assigning Character by Character with Size
We can also assign a string character by character. But we should remember to set the end
character as ‘\0’ which is a null character.
char str[14] = { 'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
9. List and explain the functions used for reading and writing strings?
We will try to understand writing the string by using the programming example shown below.
102
In c, we have two options: printf and other by puts enclosed with the name of the ‘string’.
The essential point that we have to understand in writing and reading a string is the use of %s
conversion specifier.
The %s conversion specifier is used to write or read a string.
Reading String
The image below is the program to understand the scanf() and gets to scan a string.
10. Explain about the Arrays of Strings and its manipulation in detail?
103
Syntax:
char variable_name[r] = {list of string};
We have 3 rows and 10 columns specified in our Array of String but because of prespecifying,
the size of the array of strings the space consumption is high. So, to avoid high space
consumption in our program we can use an Array of Pointers in C.
11. Explain with example (i) Character string (ii) String literal (iii) storage
classes?
104
(i) Character string:
A character string is a series of characters manipulated as a group. A character string differs from
a name in that it does not represent anything — a name stands for some other object.
A character string is often specified by enclosing the characters in single or double quotes. For
example, WASHINGTON would be a name, but ‘WASHINGTON’ and “WASHINGTON” would be
character strings.
Character StringLength
The length of a character string is usually the number of characters in it. For example, the character
string “WASHINGTON” has a length of 10 (the quote marks are not included). Some programs,
however, mark the beginning or end of a character string with an invisible character, so the length
might actually be one greater than the number of characters.
A string literal is a sequence of zero or more characters enclosed within single quotation marks.
The following are examples of string literals: 'Hello, world!' 'He said, "Take it or leave.
In other words- A string literal or anonymous string is a literal for a string value in
the source code of a computer program. Modern programming languages commonly use a
quoted sequence of characters, formally "bracketed delimiters", as in , where is a string literal
with value.
105
1. Auto
This is the default storage class for all the variables declared inside a function or a block.
Hence, the keyword auto is rarely used while writing programs in C language. Auto variables
can be only accessed within the block/function they have been declared and not outside them
(which defines their scope). Of course, these can be accessed within nested blocks within the
parent block/function in which the auto variable was declared.
However, they can be accessed outside their scope as well using the concept of pointers given
here by pointing to the very exact memory location where the variables reside. They are
assigned a garbage value by default whenever they are declared.
2. Extern
Extern storage class simply tells us that the variable is defined elsewhere and not within the
same block where it is used. Basically, the value is assigned to it in a different block and this
can be overwritten/changed in a different block as well. So an extern variable is nothing but a
global variable initialized with a legal value where it is declared in order to be used elsewhere.
It can be accessed within any function/block.
Also, a normal global variable can be made extern as well by placing the ‘extern’ keyword
before its declaration/definition in any function/block. This basically signifies that we are not
initializing a new variable but instead, we are using/accessing the global variable only. The
main purpose of using extern variables is that they can be accessed between two different files
which are part of a large program.
3. Static
This storage class is used to declare static variables which are popularly used while writing
programs in C language. Static variables have the property of preserving their value even after
they are out of their scope! Hence, static variables preserve the value of their last use in their
scope. So we can say that they are initialized only once and exist till the termination of the
program. Thus, no new memory is allocated because they are not re-declared.
Their scope is local to the function to which they were defined. Global static variables can be
accessed anywhere in the program. By default, they are assigned the value 0 by the compiler.
4. Register
This storage class declares register variables that have the same functionality as that of the
auto variables. The only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available. This makes the use of register
variables to be much faster than that of the variables stored in the memory during the runtime
of the program.
If a free registration is not available, these are then stored in the memory only. Usually, a few
variables which are to be accessed very frequently in a program.
106
12. Explain with syntax and example , the different string manipulation library
functions with example?
String.h is a standard header file in the C language that contains functions for manipulating
strings (arrays of characters). <string.h> header file contains some useful string functions that
can be directly used in a program by invoking the #include preprocessor directive.
Syntax:
#include <string.h>
int main()
{
// initializing some strings
char str1[20] = "Geeksfor";
char str2[20] = "Geeks";
return 0;
}
13. How does a for loop operate, and what is its typical structure?
In C programming, loops are responsible for performing repetitive tasks using a short code
block that executes until the condition holds true. In this article, we will learn about for loop in
C.
for Loop in C
The for loop in C Language provides a functionality/feature to repeat a set of statements a
defined number of times. The for loop is in itself a form of an entry-controlled loop.
107
Unlike the while loop and do…while loop, the for loop contains the initialization, condition, and
updating statements as part of its syntax. It is mainly used to traverse arrays, vectors, and
other data structures.
Syntax of for Loop
1. Initialization: This step initializes a loop control variable with an initial value that helps to
progress the loop or helps in checking the condition. It acts as the index value when
iterating an array or string.
2. Check/Test Condition: This step of the for loop defines the condition that determines
whether the loop should continue executing or not. The condition is checked before each
iteration and if it is true then the iteration of the loop continues otherwise the loop is
terminated.
3. Body: It is the set of statements i.e. variables, functions, etc that is executed repeatedly till
the condition is true. It is enclosed within curly braces { }.
4. Updation: This specifies how the loop control variable should be updated after each
iteration of the loop. Generally, it is the incrementation (variable++) or decrementation
(variable–) of the loop control variable.
Loops in C language are the control flow statements that are used to repeat some part of the
code till the given condition is satisfied. The do-while loop is one of the three loop statements
in C, the others being while loop and for loop. It is mainly used to traverse arrays, vectors, and
other data structures.
108
do…while Loop in C:
} while (condition);
15. What is recursion? What are the advantages and Disadvantages of recursion?
Recursion is the process a procedure goes through when one of the steps of the procedure
involves invoking the procedure itself. A procedure that goes through recursion is said to be
'recursive'. To understand recursion, one must recognize the distinction between a procedure
and the running of a procedure.
Advantages Disadvantages
Recursion helps in reducing the length of the Recursive functions are a bit slower than non-
code. recursive functions.
It provides a clean and straightforward way to It has more significant space requirements than the
write the code. iterative programs.
It minimizes the calling to the function again It has a more significant requirement of time due to
and again. function calls.
Recursion is preferred in problems like tree It is a bit difficult to understand.
traversals and the tower of Hanoi.
The whole array cannot be passed as an argument to a function. However, you can pass a pointer
to an array without an index by specifying the array’s name.
Arrays in C are always passed to the function as pointers pointing to the first element of the
array.
109
Syntax
In C, we have three ways to pass an array as a parameter to the function. In the function
definition, use the following syntax:
return_type foo ( array_type array_name[size], ...);
Mentioning the size of the array is optional. So the syntax can be written as:
optional.
return_type foo ( array_type array_name[],
array_name[] ...);
In both of the above syntax, even though we are defining the argument as array it will still be
passed as a pointer. So we can also write the syntax as:
return_type foo ( array_type* array_name, ...);
But passing an array to function results in array decay due to which the array loses information
about its size. It means that the size of the array or the number of elements of the array cannot
be determined anymore.
110
printf("Size of arr[] in func(): %d bytes",
sizeof(arr));
}
// Drive code
int main()
{
int arr[8] = { 1, 2, 3, 4, 5, 6, 7, 8 };
func(arr);
Actual parameters and Formal parameters are the two concepts that immediately strike our
minds when it comes to the oracle database. Both these terminologies are members of the
programming world and SQL.
Actual parameters are those parameters that are specified in the calling function. While on the
other hand, formal parameters are those parameters that are declared in the called function.
Let’s analyze the difference between Actual and Formal Parameters in PL/SQL.
Actual Parameter
It is the actual value that is assigned to the process by a caller. Or in other words, we can say that
it is the parameters that you determine when you invite the subroutine such as, Functions.
Formal Parameter
A formal parameter is a variable that you specify when you determine the subroutine or
function. These parameters define the list of possible variables, their positions, and their data
types.
111
Actual Parameters Formal Parameters
The Actual parameters are the variables that The Formal Parameters are the values determined
are transferred to the function when it is by the function that accepts values when the
requested. function is declared.
In actual parameters, only the variable is In formal parameters, the data type is required.
mentioned, not the data types.
Actual parameters are the values referenced Formal parameters are the values referenced in the
in the parameter index of a subprogram call. parameter index of a subprogram.
In actual parameters, there is no requirement In formal parameters, it is mandatory to define the
to define datatype. datatype of the receiving value.
These can be variables, constants, and Formal parameters are variables with the data
expressions, without data types. type.
Those parameters which are addressed in a Parameters addressed in the function description
function call are called actual parameters. are called formal parameters.
Local variables are declared within a specific block of code, such as a function or method, and
have limited scope and lifetime, existing only within that block. Global variables, on the other
hand, are declared outside of any function and can be accessed from any part of the program,
persisting throughout its execution.
Local Variables:
Local variables are declared within a specific block of code, such as within a function or a
loop.
They are only accessible within the block in which they are declared.
Once the block of code in which they are declared exits, the memory allocated to these
variables is released, and they are no longer accessible.
112
Local variables can have the same name as variables in other blocks without conflict
because their scope is limited to the block in which they are declared.
They are typically used for temporary storage or only relevant data within a specific
context.
Global Variables:
Global variables are declared outside of any function or block of code, usually at the top of
a program or in a separate file.
They are accessible from any part of the program, including within functions, loops, or
other blocks of code.
Global variables retain their value throughout the lifetime of the program unless explicitly
modified or reset.
Due to their accessibility from anywhere in the program, global variables can introduce
unintended side effects and make it harder to understand and debug code, especially in
larger programs.
They are typically used for values that need to be accessed and modified by multiple parts
of the program.
Created when the block is entered Retain their value throughout the lifetime
Lifetime and destroyed when it exits of the program
Name Can have the same name as Should be used carefully to avoid
conflicts variables in other blocks unintended side effects
113
19. Distinguish between Automatic and static variables?
A pointer is defined as a derived data type that can store the address of other C variables or a
memory location. We can access and manipulate the data stored in that memory location using
pointers.
pointers in C store the memory addresses, their size is independent of the type of data they are
pointing to. This size of pointers in C only depends on the system architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.
datatype * ptr;
114
where
ptr is the name of the pointer.
datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to
functions, structures, etc.
21. What are the features of pointers? Write a C program to print address of a
variable?
#include <stdio.h>
int main() {
int a;
int *pt;
115
printf("\n[&pt]:Address of pt = %p", &pt);
printf("\n[pt ]:Value of pt = %p", pt);
return 0;
}
When a program calls a function, the program control is transferred to the called function. A
called function performs a defined task and when its return statement is executed or when its
function-ending closing brace is reached, it returns the program control back to the main
program.
To call a function, you simply need to pass the required parameters along with the function
name, and if the function returns a value, then you can store the returned value.
Control of the program is transferred to the user-defined function by calling it.
Syntax of function:
call functionName(argument1, argument2, ...); In the above example, the function call is made
using addNumbers(n1, n2); statement inside the main() function.
Call by Value and Call by Reference
Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are
generally differentiated by the type of values passed to them as parameters.
The parameters passed to function are called actual parameters whereas the parameters
received by function are called formal parameters.
Call By Value in C: In this parameter passing method, values of actual parameters are copied to
function’s formal parameters and the two types of parameters are stored in different memory
locations. So any changes made inside functions are not reflected in actual parameters of caller
In other words, in this parameter passing method, values of actual parameters are copied to
function's formal parameters, and the parameters are stored in different memory locations. So
any changes made inside functions are not reflected in actual parameters of the caller.
Call by Value Example: Swapping the values of the two variables:
#include
2. void swap(int , int); //prototype of the function
116
3. int main()
4. {
5. int a = 10;
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b);
8. swap(a,b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b); }
10. void swap (int a, int b)
11. {
12. int temp;
13. temp = a;
14. a=b;
15. b=temp;
16. printf("After swapping values in function a = %d, b = %d\n",a,b);
17. }
Call by reference in C
Call by reference method copies the address of an argument into the formal parameter. In this
method, the address is used to access the actual argument used in the function call. It means
that changes made in the parameter alter the passing argument.
In this method, the memory allocation is the same as the actual parameters. All the operations in
the function are performed on the value stored at the address of the actual parameter, and the
modified value will be stored at the same address. Means, both the actual and formal
parameters refer to same locations, so any changes made inside the function are actually
reflected in actual parameters of caller.
1. #include
2. void swap(int *, int *); //prototype of the function
3. int main()
4. {
5. int a = 10;
117
6. int b = 20;
7. printf("Before swapping the values in main a = %d, b = %d\n",a,b);
8. swap(&a,&b);
9. printf("After swapping values in main a = %d, b = %d\n",a,b);
10. }
11. void swap (int *a, int *b)
12. {
13. int temp;
14. temp = *a;
15. *a=*b;
16. *b=temp;
17. printf("After swapping values in function a = %d, b = %d\n",*a,*b);
18. }
23. Give the scope and life time of the following (i)External variable (ii) Static
variable (iii) Automatic variable (iv) Register variable?
(i)External variable:
All variables we have seen so far have had limited scope (the block in which they are declared)
and limited lifetimes (as for automatic variables). However, in some applications it may be useful
to have data which is accessible from within any block and/or which remains in existence for the
entire execution of the program. Such variables are called global variables, and the C language
provides storage classes which can meet these requirements; namely, the external and static
classes.
External variables may be declared outside any function block in a source code file the same way
any other variable is declared; by specifying its type and name. No storage class specifier is used -
the position of the declaration within the file indicates external storage class. Memory for such
variables is allocated when the program begins execution, and remains allocated until the
program terminates. Fo rmost C implementations, every byte of memory allocated for an
external variable is initialized to zero.
The scope of external variables is global, i.e. the entire source code in the file following the
declarations. All functions following the declaration may access the external variable by using its
118
name. However, if a local variable having the same name is declared within a function,
references to the name access the local variable cell.
Static variables have the property of preserving their value even after they are out of their scope!
Hence, a static variable preserves its previous value in its previous scope and is not initialized
again in the new scope.
Syntax:
static data_type var_name = var_value;
Following are some interesting facts about static variables in C:
1) A static int variable remains in memory while the program is running. A normal or auto
variable is destroyed when a function call where the variable was declared is over.
For example, we can use static int to count the number of times a function is called, but an auto
variable can’t be used for this purpose.
// C Program to illustrate the static variable lifetime
#include <stdio.h>
int main()
{
printf("%d ", fun());
printf("%d ", fun());
return 0;
119
}
Union is a data type in C programming that allows different data types to be stored in the same
memory locations. Union provides an efficient way of reusing the memory location, as only one
of its members can be accessed at a time. A union is used almost in the same way you would
declare and use a structure.
#include <stdio.h>
#include <string.h>
union Record {
int i;
float f;
char str[20];
};
int main( ) {
record.i = 10;
record.f = 220.5;
strcpy( [Link], "C Programming");
return 0;
}
120
25. Explain file handling of C language?
File handling in C refers to the process of managing data in a program by storing it in the form of
input or output in a data file. This data file could either be a text file or a binary file. The stored
data can be used later for further analysis or it can be referenced in the same program.
A file in C is a storage unit that preserves information or data in the form of a sequence of bytes
on a disk. Unlike the compiler memory in C which is volatile, the content of a file is more
permanent. A file allows a program to perform various operations such as creating, opening,
reading, and manipulating the data present within it. This process is referred to as file handling in
C.
The Need For File Handling In C
There are certain instances when the output generated by a program after compilation and
execution may not serve our intended purpose. In such scenarios, we may need to examine the
program's output multiple times. However, repeatedly compiling and running the same program
can be a laborious task for any programmer. This is where the concept of file handling comes into
play.
Here are a few reasons that highlight the importance of file handling in making programming
easier:
Reusability: File handling allows us to preserve the information or data generated after running a
program.
Time-saving: Some programs may require a large amount of input from their users. In such
cases, file handling enables you to easily access a part of the code using individual commands.
Ample storage capacity: Storing data in files eliminates the need to store all the information in
bulk in a program.
Portability: The contents of a file can be transferred to another file without any data loss in the
computer system. This not only saves effort but also minimizes the risk of coding errors.
26. What are pseudo-code and flow chart? Explain with example?
Flowcharts are written with program flow from the top of a page to the bottom. Each command
is placed in a box of the appropriate shape, and arrows are used to direct program flow. The
following shapes are often used in flowcharts:
121
Pseudocode is a method of describing computer algorithms using a combination of natural
language and programming language. It is essentially an intermittent step towards the
development of the actual code. It allows the programmer to formulate their thoughts on the
organization and sequence of a computer algorithm without the need for actually following the
exact coding syntax. Although pseudocode is frequently used there are no set of rules for its
exact implementation. In general, here are some rules that are frequently followed when writing
pseudocode:
The usual Fortran symobols are used for arithmetic operations (+, -, *, / , **).
Symbolic names are used to indicate the quantities being processed.
Certain Fortran keywords can be used, such as PRINT, WRITE, READ, etc.
122
Indentation should be used to indicate branches and loops of instruction.
Here is an example problem, including a flowchart, pseudocode, and the final Fortran 90
program. This problem and solution are from Nyhoff, pg 206:
For a given value, Limit, what is the smallest positive integer Number for which the sum
Sum = 1 + 2 + ... + Number
is greater than Limit. What is the value for this Sum?
Pseudocode:
Input: An integer Limit
Ouput: Two integers: Number and Sum
1. Enter Limit
2. Set Number = 0.
3. Set Sum = 0.
4. Repeat the following:
a. If Sum > Limit, terminate the repitition, otherwise.
b. Increment Number by one.
c. Add Number to Sum and set equal to Sum.
5. Print Number and Sum.
Flowchart:
123
Fortran 90 code:
PROGRAM Summation
! Program to find the smallest positive integer Number
! For which Sum = 1 + 2 + ... + Number
! is greater than a user input value Limit.
IMPLICIT NONE
! Declare variable names and types
124
INTEGER :: Number, Sum, Limit
! Initialize Sum and Number
Number = 0
Sum = 0
! Ask the user to input Limit
PRINT *, "Enter the value for which the sum is to exceed:"
READ *, Limit
! Create loop that repeats until the smallest value for Number is found.
DO
IF (Sum > Limit) EXIT ! Terminate repetition once Number is found
! otherwise increment number by one
Number = Number + 1
Sum = Sum + 1
END DO
! Print the results
PRINT *, "1 + ... + ", Number, "=", Sum, ">", Limit
END PROGRAM
In row-major layout, the elements of the rows are contiguous. Array layout is also called order,
format, and representation. The order in which elements are stored can be important for
integration, usability, and performance. Certain algorithms perform better on data stored in a
particular order.
Programming languages and environments typically assume a single array layout for all data.
MATLAB® and Fortran use column-major layout by default, whereas C and C++ use row-major
layout. With MATLAB Coder™, you can generate C/C++ code that uses row-major layout or
column-major layout. See Generate Code That Uses Row-Major Array Layout.
Array Storage in Computer Memory
Computer memory stores data in terms of one-dimensional arrays. For example, when you
declare a 3-by-3 matrix, the software stores this matrix as a one-dimensional array with nine
elements. By default, MATLAB stores these elements with a column-major array layout. The
elements of each column are contiguous in memory.
Consider the matrix A:
125
A=
1 2 3
4 5 6
7 8 9
The matrix A is represented in memory by default with this arrangement:
1 4 7 2 5 8 3 6 9
In row-major array layout, the programming language stores row elements contiguously in
memory. In row-major layout, the elements of the array are stored as:
1 2 3 4 5 6 7 8 9
N-dimensional arrays can also be stored in column-major or row-major layout. In column-major
layout, the elements from the first (leftmost) dimension or index are contiguous in memory. In
row-major, the elements from the last (rightmost) dimension or index are contiguous.
The number of columns of the first matrix should be equal to the number of rows of the second
matrix.
The program below asks for the number of rows and columns of two matrices until the above
condition is satisfied.
Then, the multiplication of two matrices is performed, and the result is displayed on the screen.
126
// function to get matrix elements entered by the user
void getMatrixElements(int matrix[][10], int row, int column) {
127
[Link] Exit and return statement?
exit():
To end a program completely and give the operating system back control, use the exit() function.
It is usually triggered after an unrecoverable fault occurs or the program has completed running.
The function exit() enables a program to end gracefully and do any necessary cleaning before
closing. It may utilize atexit() to run registered functions, release resources, and close open files.
The program control does not go back to the location where exit() was called once it has been
called. Rather, the program ends with a status code and returns control to the operating system.
The caller environment can access this status code, which usually indicates whether the program
succeeded or failed.
return():
A function’s return statement is used to end the function’s execution and give the caller its value
back. If the function has a non-void return type, it is used to convey the result and signal the end
of the function’s execution. Within a function, return() enables fine control over the program’s
execution. It can be used to quit a function and return a specified value at any time throughout
the function’s execution. A function may include several return statements, each with a distinct
return value depending on various circumstances. The function’s execution ends, and the control
returns to the caller function upon encountering a return.
Purpose:
exit(): To end a program completely and give the operating system back control, use the exit()
function. It is usually triggered after an unrecoverable fault occurs or the program has completed
running. It enables the software to finish smoothly and free up resources before closing.
return(): A function’s return statement is used to end the function’s execution and give the caller
its value back. If the function has a non-void return type, it is used to convey the result and signal
the end of the function’s execution.
2. Usage:
exit():
Syntax: void exit (int status);
exit() is typically called from the main() function or any other function to terminate the entire
program.
It is included in the <stdlib.h> header file.
return():
Syntax: return [expression];
128
return is used within a function to return a value to the caller function.
It can be used in any function that has a return type other than void.
It can be used multiple times within a function, each with a different return value.
Preprocessors are programs that process the source code before compilation. Several steps are
involved between writing a program and executing a program in C. Let us have a look at these
steps before we actually start learning about Preprocessors.
The source code written by programmers is first stored in a file, let the name be “program.c“.
This file is then processed by preprocessors and an expanded source code file is generated
named “program.i”. This expanded file is compiled by the compiler and an object code file is
generated named “[Link]”. Finally, the linker links this object code file to the object code
of the library functions to generate the executable file “[Link]”.
Preprocessor Directives in C
Preprocessor programs provide preprocessor directives that tell the compiler to preprocess the
source code before compiling. All of these preprocessor directives begin with a ‘#’ (hash)
symbol. The ‘#’ symbol indicates that whatever statement starts with a ‘#’ will go to the
preprocessor program to get executed. We can place these preprocessor directives anywhere
in our program.
129
Examples of some preprocessor directives are: #include, #define, #ifndef, etc.
130