0% found this document useful (0 votes)
6 views

Study Notes of Unit 1 and Unit 2

Uploaded by

amarnathm2007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Study Notes of Unit 1 and Unit 2

Uploaded by

amarnathm2007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Subject: Programming for Problem Solving (CSE 113)

Unit 1 and 2
Compiled by Dr. Shree Harsh Attri
Associate Professor (Dept. of CSE)
Sharda School of Engineering & Technology
Sharda University, Greater Noida

1. What is meant by programming language and give some examples?

• Programming language is a language designed to communicate with machines through


instructions and commands.
• Normally computers are machines and programs are written using some programming
languages to control the behavior of machines/computers and to make them to perform
required tasks.
• Programming language example: Assembly language, C language, C++ language, Java, C#,
.NET, Python etc.

2. What is C language?

• C language is a structure/procedure oriented, middle level programming language developed


at Bell Laboratories in 1972 by Dennis Ritchie.
• C language was invented for implementing UNIX operating system.
• In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language”.
• Also, C language is an ANSI/ISO standard and powerful programming language for
developing real time applications
• C language has been developed using assembly level language.

3. Describe about history of C programming language.

• C language features were derived from earlier language called “B” (Basic Combined
Programming Language – BCPL)
• In earlier days, programs were written in assembly level language. So, it had happened to
write very big programs to perform specific tasks using assembly code.
• But, ‘B’ language could perform the same task in few lines of program and it was faster than
assemble language code.
• But, B language did not support some features like data types and structures etc. So, this was
a drawback of B language. So, Dennis Ritchie developed C language by keeping most part of
the B language and adding many features that produced powerful and effective outputs.
• So, C language was invented for implementing UNIX operating system. Most of the UNIX
components were rewritten in C.
• In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C
Programming Language” and commonly known as K&R C
• In 1983, the American National Standards Institute (ANSI) established a committee to
provide a modern, comprehensive definition of C. The resulting definition, the ANSI
standard, or “ANSI C”, was completed late 1988.
• C89/C90 standard – First standardized specification for C language was developed by
American National Standards Institute in 1989. C89 and C90 standards refer to the same
programming language.
• C99 standard – Next revision was published in 1999 that introduced new futures like
advanced data types and other changes.
• C11 standard adds new features to C and library like type generic macros, anonymous
structures, improved Unicode support, atomic operations, multi-threading, and bounds-
checked functions. It also makes some portions of the existing C99 library optional, and
improves compatibility with C++.
• Embedded C includes features not available in normal C like fixed-point arithmetic, named
address spaces, and basic I/O hardware addressing.

4. Where is C programming language used or uses of C language?

C language is used to develop system applications that forms major portion of operating systems
such as Windows, UNIX and Linux. Operating systems, C compiler and all UNIX application
programs are written in C language. Below are some examples of uses of C language.

• Database systems
• Graphics packages
• Word processors
• Spread sheets
• Operating system development
• Compilers and Assemblers
• Network drivers
• Interpreters

5. Describe about C standards.

• C89/C90 standard – First standardized specification for C language was developed by


American National Standards Institute in 1989. C89 and C90 standards refer to the same
programming language.
• C99 standard – Next revision was published in 1999 that introduced new futures like
advanced data types and other changes.
• C11 standard adds new features to C and library like type generic macros, anonymous
structures, improved Unicode support, atomic operations, multi-threading, and bounds-
checked functions. It also makes some portions of the existing C99 library optional, and
improves compatibility with C++.

6. What are the key features or characteristics of C language?

• Reliability
• Portability
• Flexibility
• Interactivity
• Modularity
• Efficiency and Effectiveness

7. What is embedded C?

• Embedded C is the extension of C programming language.


• Embedded C is used to develop micro controller based applications.
• Embedded C includes features not available in normal C like fixed-point arithmetic, named
address spaces, and basic I/O hardware addressing.
• Cell phones, MP3 players are some example for embedded systems in which embedded C is
used to program and control these devices.

8. Which level is C language belonging to?

• C language is belonging to middle level language. C language behaves as a bridge between


machine level (low level) languages and high level languages.
• C language is more user friendly than machine level languages. And, C language does not
support all the concepts that high level languages offer. So, C programming language is
called as middle level language.
9. What do you mean by high level, middle level and low level languages and give an example
for each?

High level languages –

• These level languages provide almost everything that the programmer might need to do
as already build into the language.
• Example: Java, Python etc.
• These languages are machine independent, means it is portable. The language in this
category is Pascal, Cobol, Fortran, Java, Python etc. High level languages are understood
by the machine. So it need to translate by the translator into machine level. A translator is
software which is used to translate high level language as well as low level language in to
machine level language. Three types of translator are: Compiler Interpreter Assembler

Middle level languages –

• These languages don’t provide all the built-in functions found in high level languages,
but provide all building blocks that we need to produce the result we want.
• Example: C, C++

Low level languages –

• Low level languages are machine level and assembly level language.
• In machine level language computer only understand digital numbers i.e. in the form of 0
and 1. So, instruction given to the computer is in the form binary digit, which is difficult
to implement instruction in binary code. This type of program is not portable, difficult to
maintain and also error prone.
• The assembly language is on other hand modified version of machine level language.
Where instructions are given in English like word as ADD, SUM, MOV etc. It is easy to
write and understand but not understand by the machine. So the translator used here is
assembler to translate into machine level. Although language is bit easier, programmer
has to know low level details related to low level language.
• In the assembly level language the data are stored in the computer register, which varies
for different computer. Hence it is not portable.

10. What is the difference between structured oriented, object oriented and non-structure
oriented programming language?

Structured oriented programming language –

• In this type of language, large programs are divided into small programs called functions.
• Prime focus is on functions and procedures that operate on data
• Data moves freely around the systems from one function to another
• Program structure follows “Top Down Approach”
• Example: C, Pascal, ALGOL and Modula-2

Object oriented programming language –

• In this type of language, programs are divided into objects


• Prime focus is on the data that is being operated and not on the functions or procedures
• Data is hidden and cannot be accessed by external functions
• Program structure follows “Bottom UP Approach”
• Example: C++, JAVA and C# (C sharp)

Non-structure oriented programming language –


• There is no specific structure for programming this language.
• Example: BASIC, COBOL, FORTRAN

11. Explain Algorithm and Flowchart with examples.


Algorithms and flowcharts are two different tools used for creating new programs, especially in
computer programming.
An algorithm is a step-by-step analysis of the process, while a flowchart explains the steps of a
program in a graphical way.

Definition of Algorithm

To write a logical step-by-step method to solve the problem is called algorithm, in other words,
an algorithm is a procedure for solving problems. In order to solve a mathematical or computer
problem, this is the first step of the procedure. An algorithm includes calculations, reasoning and
data processing. Algorithms can be presented by natural languages, pseudo code and flowcharts,
etc.

Definition of Flowchart

A flowchart is the graphical or pictorial representation of an algorithm with the help of different
symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we
can easily understand a program. The main purpose of a flowchart is to analyze different
processes. Several standard graphics are applied in a flowchart:

• Terminal Box - Start / End • Decision

• Input / Output • Connector / Arrow

• Process / Instruction

The graphics above represent different part of a flowchart. The process in a flowchart can be
expressed through boxes and arrows with different sizes and colors. In a flowchart, we can easily
highlight a certain element and the relationships between each part.

11.1 How to Use Flowcharts to Represent Algorithms


Algorithms are mainly used for mathematical and computer programs, whilst flowcharts
can be used to describe all sorts of processes: business, educational, personal and of course
algorithms.
So flowcharts are often used as a program planning tool to visually organize the step-by-
step process of a program.

Here are some examples:


Example 1: Print 1 to 20: Example 2: Convert Temperature from
Fahrenheit (℉) to Celsius (℃)
Algorithm:
Step 1: Initialize X as 0, Algorithm:
Step 2: Increment X by 1, Step 1: Read temperature in Fahrenheit,
Step 3: Print X, Step 2: Calculate temperature with
Step 4: If X is less than 20 then go back to formula C=5/9*(F-32),
step 2. Step 3: Print C,

Flowchart: Flowchart:

Conclusion:
An algorithm shows every step of reaching the final solution, while a flowchart shows how to carry
out the process by connecting each step.
An algorithm uses mainly words to describe the steps while a flowchart uses the help of symbols,
shapes and arrows to make the process more logical.

12 What is a Compiler?
When a program is written, it usually done in some high-level language like C or Fortran or Java
etc. In program, a line written likes this:
printf ("Hello, world!\n");

That's not something that computer's processor can understand. The C statement needs to be
translated into a different low-level language of ones and zeros that expresses the same thing in
terms of instructions that the CPU can understand. The result might look like:

1001110001010111011110001001111001.......

To get from the more-or-less readable C statement to the opaque binary statement, there is a need
of a kind of translator. That translator is called a "compiler".
12.1 How compiler works?

a) Source code written in computer language [ C,C++ ] is present in Source Code file which is
saved it as .c, .cpp
b) Compiler job is to take this file as input and create Object Code file.
c) Linker job is to add references to external Library Files include those in code and create
executable.

Fig 1: Working of Compiler

13 Structure of a simple Hello World Program in C


A C program basically consists of the following parts −
• Preprocessor Commands
• Function
• Variables
• Statements & Expressions
• Comments

• The first line of the program #include <stdio.h> is a preprocessor command, which tells
a C compiler to include stdio.h file before going to actual compilation.
• The next line int main() is the main function where the program execution begins.
• The next line printf(...) is another function available in C which causes the message
"Hello, World!" to be displayed on the screen.
• The next line return 0; terminates the main() function and returns the value 0.
14 What is Preprocessor? Explain Preprocessor Directives with examples.
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation
process. In simple terms, a C Preprocessor is just a text substitution tool which instructs the
compiler to do preprocessing before actual compilation.

It performs preprocessing of the High Level Language (HLL). Preprocessing is the first step
of the language processing system. Language processing system translates the high level
language to machine level language or absolute machine code (i.e. to the form that can be
understood by machine).
All preprocessor commands begin with a hash symbol (#)
A Preprocessor mainly performs three tasks on the HLL code:

a) Removing comments: It removes all the comments. A comment is written only for
the humans to understand the code. So, it is obvious that they are of no use to a
machine. So, preprocessor removes all of them as they are not required in the
execution and won’t be executed as well.

b) File inclusion: Including all the files from library that a program needs. In HLL write
#include is written which is a directive for the preprocessor that tells it to include
the contents of the library file specified. For example, #include will tell the
preprocessor to include all the contents in the library file stdio.h.
This can also be written using double quotes – #include “stdio.h”

Note: If the file name is enclosed within angle brackets, the file is searched for in the
standard compiler include paths. If the filename is enclosed within double quotes, the
search path is expanded to include the current source directory.

c) Macro expansion: Macros can be called as small functions that are not as overhead
to process. If a function (having a small definition) that needs to be called recursively
(again and again), then it’s preferred to write a macro over a function. So, defining
these macros is done by preprocessor.

Example:
#define SI 1000
is a simple example of a macro.

Preprocessor Directives
Preprocessor commands often known as directives. These directives can be placed
anywhere in a program but are most often placed at the beginning of a program, just
before main().
Preprocessing directives are lines in a program that start with #.

The preprocessor directives are divided into following manners:

Preprocessor
Syntax/Description
Directives
Syntax: #define
Macro This macro defines constant value and can be any of the
basic data types.
Syntax: #include <file_name>
File Inclusion The source code of the file “file_name” is included in the
main program at the specified place.
Syntax: #ifdef, #ifndef, #if, #endif, #else, #elif
Conditional
Set of commands are included or excluded in source program
Compilation
before compilation with respect to the condition.
Syntax: #undef, #pragma
Other #undef is used to undefine a defined macro variable.
Directives #pragma is used to call a function before and after main
function in a C program.
15 What is header file in C language?

• Header file is a file that contains function declaration and macro definition for C in-
built library functions.
• All C standard library functions are declared in many header files which are saved as
file_name.h.
• These header files in our C program are used as “#include <file_name.h>”
command to make use of the functions those are declared in the header files.
• When header files include in C program using “#include <filename.h>”
command, all C code of the header files include into the C program. Then, this C
program is compiled by compiler and executed.

16 Explain Assembler, Linker and Loader.

Assembler:
An assembler translates assembly language programs into machine code. The output of an
assembler is called an object file, which contains a combination of machine instruction as well as the
data required to place these instructions in memory.

Linker:
Linker is a computer program that links and merges various object files together in order to make
an executable file. All these files might have been compiled by separate assembler.
The major task of a linker is to search and locate referenced module/routines in a program and to
determine the memory location where these codes will be loaded making the program instruction to
have absolute reference.

Loader:
Loader is a part of operating system and is responsible for loading executable files into memory
and executes them.
It calculates the size of a program (instructions and data) and creates memory space for it. It
initializes various registers to initiate execution.

Working of Compiler, Assembler, Linker and Loader

17 Explain the simple Input Output Function calls from library.


The simple input output functions are scanf() and printf() which allows to transfer the
single characters, numerical values and strings.
The header file required by the simple input/output library functions is called stdio.h.

Entering Input Data: the scanf() Function


Input data can be entered from a standard input device by means of the C library function
scanf(). This function can be used to enter any combination of numeric values, single
characters and strings.
In general terms, the scanf() function is written as:
scanf(control string, arg1, arg2,.........,argN);
where control string refers to a string containing certain required formatting information,
and arg1,arg2,….,argN are arguments that represent the individual data items.

The control string consists of the individual group of characters called format specifiers,
with one character group for each input data item. Each character group must begin with a
percent sign (%) and be followed by a conversion character which indicates the type of the
data item. Within the control string, multiple character groups can be contiguous, or they can
be separated by whitespace characters (i.e. white spaces, tabs or newline characters).

The most commonly used conversion characters or format specifiers are listed below:

Format Supported data


Description
specifier types
char
%c Character
unsigned char
short
unsigned short
%d Signed Integer
int
long
float
%e or %E Scientific notation of float values
double
%f Floating point float
float
%g or %G Similar as %e or %E
double
%hi Signed Integer(Short) short
%hu Unsigned Integer(Short) unsigned short
short
unsigned short
%i Signed Integer
int
long
%l or %ld or
Signed Integer long
%li
%lf Floating point double
%Lf Floating point long double
unsigned int
%lu Unsigned integer
unsigned long
%lli, %lld Signed Integer long long
unsigned long
%llu Unsigned Integer
long
short
unsigned short
%o Octal representation of Integer. int
unsigned int
long
%p Address of pointer to void void * void *
%s String char *
unsigned int
%u Unsigned Integer
unsigned long
Format Supported data
Description
specifier types
short
unsigned short
Hexadecimal representation of
%x or %X int
Unsigned Integer
unsigned int
long
%n Prints nothing
%% Prints % character

The arguments to a scanf function are written as variables or arrays whose types match
the corresponding character groups in the control string. Each variable name must be
preceded by an ampersand (&). However, character array names/strings do not begin
with an ampersand. The actual values of the arguments must correspond to the arguments
in the scanf function in number, type and order.
If two or more data items are entered, they must be separated by whitespace characters.
The data items may continue onto two or more lines, since the newline character is
considered to be a whitespace character and can therefore separate consecutive data
items.
Example:

#include <stdio.h>
main()
{
char name[40];
int rollno;
char grade;
scanf("%s %d %f", name, &rollno, &grade);
}

A sample data input could be - Sanjay 12345 A

Note: The variable name being a string (an array of characters) is not preceded by &,
but the numerical variables rollno and grade are preceded by &. This is because,
in case of an array type variable, the variable name itself represents its address in
the memory.
Getting Output: the printf() function

• printf() function is used to print the “character, string, float, integer, octal and
hexadecimal values” onto the output screen.

printf() function sends formatted output to the standard output (screen).

In general, the printf function is written as:


✓ printf(“ Any message ”);
the above statement prints the message on the output screen.

✓ printf(<control string>, arg1, arg2, . . . , argn);


where the <control string> refers to a string containing required formatting
information as in scanf, and arg1, arg2, ..., argn are individual data variables whose
values are to be printed. However, unlike scanf, these data variable names are not
preceded by the & symbol. This is because printf is expected to only output the
values of these variables and not their addresses.
Example 1:

#include <stdio.h>
main()
{
printf("Our first program in C\n");
}

Output: Our first program in C

Example 2:
#include <stdio.h>
main()
{
int n;
n = 25;
printf("The value of n = %d\n", n);
//note the usage of format specifier %d
}

Output: The value of n = 25

18 What do you mean by token in C? What are the types of C tokens?


• C tokens are the basic buildings blocks in C language which are constructed together
to write a C program.
• Each and every smallest individual unit in a C program is known as C token.
C tokens are of six types. They are,
a) Keywords (eg: int, while),
b) Identifiers (eg: student_name, roll_number),
c) Constants (eg: 10, 20),
d) Strings (eg: “total”, “hello”),
e) Special symbols (eg: ( ), {}),
f) Operators (eg: +, /,-,*)
19 What are the data types in C? Explain briefly.
• Data types in C language are defined as the data storage format that a variable can store a
data to perform a specific operation.
• Data types are used to define a variable before to use in a program.
• Size of variable, constant and array are determined by data types.

Type Data types


Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
20 Differentiate between Keywords and Identifiers.

Keywords Identifier
• Predefined-word • User-defined word
• Must be written in lowercase only • Can written in lowercase and uppercase
• Has fixed meaning • Must be meaningful in the program
• Whose meaning has already been explained to • Whose meaning not explained to the C
the C compiler compiler
• Combination of alphabetic characters • Combination of alphanumeric characters
• Used only for it intended purpose • Used for required purpose
• Underscore character is not considered as a • Underscore character is considered as a
letter letter

21 What is modifier in C language? Explain the different types of modifiers of C language.


Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of
storage space allocated to a variable.
For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the
range by using long int which is 8 byte. We can decrease the range by using short int which is 2
byte.
There are 5 modifiers available in C language. They are,
• short
• long
• signed
• unsigned

Type Storage size Value range


Char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 bytes -32,768 to 32,767
unsigned int 2 bytes 0 to 65,535
short 2 bytes -32,768 to 32,767
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295
float 4 bytes 1.2E-38 to 3.4E+38 (6 decimal places)
double 8 bytes 2.3E-308 to 1.7E+308 (15 decimal places)
long double 10 bytes 3.4E-4932 to 1.1E+4932 (19 decimal places)

22 What is the use of main() function in C?


main() function is the function from where execution of any C program begins. So, main()
function is mandatory for any C program.
23 What is variable in C? How variable is declared and initialize?

• C variable is a named location in a memory where a program can manipulate the data. This
location is used to hold the value of the variable.
• The value of the C variable may get change in the program.
• C variable might be belonging to any of the data type like int, float, char etc.
Declaring & Initializing of C variable:
• Variables should be declared in the C program before to use.
• Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
• Variable initialization means assigning a value to the variable.

Type Syntax
data_type variable_name;
Variable declaration
Example: int x, y, z; char flat, ch;
data_type variable_name = value;
Variable initialization Example:
int x = 50, y = 30; char flag = ‘x’, ch=’l’;

Difference between variable declaration & definition in C:

Variable declaration Variable definition


Declaration tells the compiler about data type and Definition allocates memory for the
size of the variable. variable.
It can happen only one time for a variable
Variable can be declared many times in a program.
in a program.
The assignment of properties and identification to a Assignments of storage space to a
variable. variable.

24 What are the different types of variable in C?

a) Local variable
b) Global variable
c) Environment variable

25 What is local variable in C?

• The variables which are having scope/life only within the function are called local variables.
• These variables are declared within the function and can’t be accessed outside the function.
• In the below example, m and n variables are having scope within the main function
only. These are not visible to test function.
• Likewise, a and b variables are having scope within the test function only. These are not
visible to main function.

#include<stdio.h>
void test();

main()
{
int m = 22, n = 44; // m, n are local variables of main function
/*m and n variables are having scope within this main function only. These are
not visible to test function.*/
/* If you try to access a and b in this function, you will get 'a' undeclared and 'b'
undeclared error */
printf("\nvalues : m = %d and n = %d", m, n);
test();
}
void test()
{
int a = 50, b = 80; // a, b are local variables of test function
/*a and b variables are having scope within this test function only. These are not
visible to main function.*/
/* If you try to access m and n in this function, you will get 'm' undeclared and 'n'
undeclared error */
printf("\nvalues : a = %d and b = %d", a, b);
}
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80

26 What is global variable in C?

• The variables which are having scope/life throughout the program are called global variables.
These variables can be accessed from anywhere in the program.
• Global variable is defined outside the main function. So, this variable is visible to main function
and all other sub functions.

#include<stdio.h>
void test();
int m = 22, n = 44; // global declaration
int a = 50, b = 80; // global declaration

main()
{
printf("All variables are accessed from main function");
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
test();
}

void test()
{
printf("\n\nAll variables are accessed from" \" test function");
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
}
Output:
All variables are accessed from main function
values: m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80

27 Is C language case sensitive?

Yes. C language instructions/commands/functions and everything used in C program are case


sensitive

28 What is the difference between constant and variable in C?


Constant values can’t be modified by the program once it is declared. But, variable values
can be modified by the program.

29. Can variable name start with numbers?

No. Variable names can’t start with numbers as per the variable naming rule.

30. Can variable name be start with underscore in C?


Yes. A variable name can start with underscore in C programming language.

31. Can variable name have special symbols in C?

No. except underscore (_), other special symbols are not allowed to use for naming the
variables in C.

References:
1. https://techblogmu.blogspot.com/2017/03/define-compiler-interpreter-assembler.html
2. http://www.herongyang.com/Computer-History/C-Program-Compilation-and-Execution-
Process.html
Subject: Programming for Problem Solving (CSE 113)
Unit 2 – Operators, Expressions and Control Statements
Compiled by Dr. Shree Harsh Attri
Associate Professor (Dept. of CSE)
Sharda School of Engineering & Technology
Sharda University, Greater Noida

1. What are the different types of operators in C?

C language offers many types of operators. They are,

a) Arithmetic Operators
b) Assignment Operators
c) Relational Operators
d) Logical Operators
e) Equality Operators
f) Bit wise Operators
g) Conditional Operators (ternary operators)
h) Unary Operators
i) Comma Operators
j) Sizeof Operators

2. What is arithmetic operator in C?

• C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.
• Arithmetic operators are +, -, *, /, %

Example program for C arithmetic operators:


In this example program, two values “40” and “20” are used to perform arithmetic
operations such as addition, subtraction, multiplication, division, modulus and output is
displayed for each operation.
#include <stdio.h>

int main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
}
Output:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
3. What is assignment operator in C?
• Assignment operators are used to assign the values to the variables.
• For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned
as “sum = 10;”
• There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator (Example: =)
2. Compound assignment operators (Example: +=, -=, *=, /=, %=, &=, ^= )

Operators Example/Description
= sum = 10;
10 is assigned to variable sum
+= sum += 10;
This is same as sum = sum + 10
-= sum -= 10;
This is same as sum = sum – 10
*= sum *= 10;
This is same as sum = sum * 10
/= sum /= 10;
This is same as sum = sum / 10
%= sum %= 10;
This is same as sum = sum % 10
&= sum&=10;
This is same as sum = sum & 10
sum ^= 10;
^=
This is same as sum = sum ^ 10

4. What is the relational operator in C?


• Relational operators are used to find the relation between two variables. i.e. to compare the values
of two variables in a C program.
• Relational operators are >, <, >=, <=, ==,!=

Operators Example/Description
> x > y (x is greater than y)
< x < y (x is less than y)
>= x >= y (x is greater than or equal to y)
<= x <= y (x is less than or equal to y)
== x == y (x is equal to y)
!= x != y (x is not equal to y)
5. What is the logical operator in C?
• Logical operators are used to perform logical operations on the given expressions.
• There are 3 logical operators in C language. They are,
1. logical AND (&&)
2. logical OR (||)
3. logical NOT (!)
Operators Example/Description
(x>5)&&(y<5)
&& (logical AND)
It returns true when both conditions are true
(x>=10)||(y>=10)
|| (logical OR)
It returns true when at-least one of the condition is true
!((x>5)&&(y<5))
! (logical NOT) It reverses the state of the operand “((x>5) && (y<5))”
If “((x>5) && (y<5))” is true, logical NOT operator makes it false

6. What is the syntax for ternary operator in C?

• Ternary operator is same as if else control statement in C.


• Syntax : (Condition? true_value: false_value);
• Example : (A > 100? 0: 1);

7. What is bitwise operator in C?


• Bitwise operators are used to perform bit operations. Decimal values are converted into binary
values which are the sequence of bits and bit wise operators work on these bits.
• Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
Truth table for bit wise operation & Bit wise operators:

Below are the bit-wise operators and their name in C language.


a) & – Bitwise AND
b) | – Bitwise OR
c) ~ – Bitwise NOT
d) ^ – XOR
e) << – Left Shift
f) >> – Right Shift

Consider x=40 and y=80. Binary forms of these values are given below:
x = 00101000
y= 01010000

All bit wise operations for x and y are given below.

1. x&y = 00000000 (binary) = 0 (decimal)


2. x|y = 01111000 (binary) = 120 (decimal)
3. ~x = 11111111111111111111111111 11111111111111111111111111111111010111 = -41 (decimal)
4. x^y = 01111000 (binary) = 120 (decimal)
5. x << 1 = 01010000 (binary) = 80 (decimal)
6. x >> 1 = 00010100 (binary) = 20 (decimal)
8. What are Unary Operators?

• Unary operators act on single operands. C language supports three unary operators:

a) Unary minus (-)


b) Increment Operator
c) Decrement Operator

• Unary Minus (-)


When an operand is preceded by a minus sign, the unary operator negates its value.
For Example:
int a, b = 10;
a = - (b);
Output
a = -10

• Increment operators are used to increase the value of the variable by one and Decrement
operators are used to decrease the value of the variable by one in C programs.

• Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;

• Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;

Difference between pre/post increment & decrement operators in C:

Operator Operator/Description
Pre increment operator (++i) value of i is incremented before assigning it to the variable i
Post increment operator (i++) value of i is incremented after assigning it to the variable i
Pre decrement operator (--i) value of i is decremented before assigning it to the variable i
Post decrement operator (i--) value of i is decremented after assigning it to variable i

For example:
int x = 10, y;
y = x++;
statement y = x++ is equivalent to writing
y = x;
x = x+1;
whereas y = ++x is equivalent to writing
x = x + 1;
y = x;
above said principle is applies to decrement operators too.

Program to illustrate increment and decrement Unary Operator

#include<stdio.h>
#include<conio.h>
main()
{
int i,x;
clrscr();
printf("enter the value of i: ");
scanf("%d",&i);
x=i;
printf("\nvalue of i is %d",i);
printf("\nvalue of ++i is %d",++i);
printf("\ndvalue of i++ is %d",i++);
printf("\n new updated value of i is %d",i);
printf("\nrevised value of i is %d",x);
printf("\nvalues of ++i,i++,i--,i is %d %d %d %d",++x,x++,x--,x);
printf("\n new updated value of i is %d",x);
getch();
}
Output:
enter the value of i: 5
value of i is 5
value of ++i is 6
value of i++ is 6
new updated value of i is 7
revised value of i is 5
values of ++i, i++, i--, i is 6 4 5 5
new updated value of i is 6

9. Explain sizeof Operator.


sizeof() operator is used to find the memory space allocated for each C data types.

For example:
int x = 10;
unsigned int result;
result = sizeof(x);

Output
result = 2; // since x is an integer, it requires 2 bytes of storage space.

10. What is the difference between single equal “=” and double equal “= =” operators in C?

• Single equal is an assignment operator used to assign the values to the variables.
• But, double equal is relational operator used to compare two variable values whether they are
equal are not.

11. What are all decision control statements in C?

In any programming language, there is a need to perform different tasks based on the condition. For
example, consider an online website, when you enter wrong id or password it displays error page and
when you enter correct credentials then it displays welcome page.
So there must be logic in place that checks the condition (id and password) and if the condition returns
true it performs a task (displaying welcome page) else it performs a different task (displaying error
page).
It allows the programmers to build the programs that determine which statements of the code should
be executed and which are to be ignored

The conditional statements help to jump from one part of a program to another depending if a particular
condition is satisfied or not.
Following are the types of decision making control statements in C language. They are,
o if statements
o if else statements and nested if statements
o switch case statements

Syntax for each C decision control statements are given in below table with description

Decision
control Syntax/Description
statements
if (condition)
{
Statements;
if }
Description:
In these type of statements, if condition is true, then respective block of code is
executed.
if (condition)
{
Statement1;
Statement2;
}
else
if…else {
Statement3;
Statement4;
}
Description:
In these type of statements, group of statements are executed when condition is
true. If condition is false, then else part statements are executed.
if (condition1)
{ Statement1;
}
else if(condition2)
{
Statement2;
nested if
}
else
Statement 3;
Description:
If condition 1 is false, then condition 2 is checked and statements are executed if it is
true. If condition 2 also gets failure, then else part is executed.

• If statement: The if statement evaluates the test expression inside the parenthesis.

If the test expression is evaluated to true (nonzero), statements inside the body of if is
executed.
If the test expression is evaluated to false (0), statements inside the body of if are skipped
from execution.
// Program to display a number if user enters negative number
// If user enters positive number, that number won't be displayed

#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);

// Test expression is true if number is less than 0


if (number < 0)
{
printf("You entered positive number);
}
}

• If-else statement: In this decision control statement, we have two blocks of statements.
If condition results true then if block gets executed otherwise statements inside else block
executes.
Note: else cannot exist without if statement.

// Program to check whether an integer entered by the


user is odd or even

#include <stdio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);

// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
}

Output
Enter an integer: 7
7 is an odd integer.
• Nested if-else
The if...else statement executes two different codes depending upon whether the
test expression is true or false. Sometimes, a choice has to be made from more than 2
possibilities.
The nested if...else statement allows you to check for multiple test expressions and
execute different codes for more than two conditions.
// Program to relate two integers using =, > or <

#include <stdio.h>
main()
{
int number1, number2;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);

//checks if two integers are equal.


if(number1 == number2)
{
printf("Result: %d = %d",number1,number2);
}
//checks if number1 is greater than number2.
else if (number1 > number2)
{
printf("Result: %d > %d", number1, number2);
}
// if both test expression is false
else
{
printf("Result: %d < %d",number1, number2);
}
}
Output
Enter two integers: 12
23
Result: 12 < 23

• Switch-case statement: This is very useful when multiple conditions need to be evaluated.

The switch block defines an expression (or condition) and case has a block of statements,
based on the result of expression, corresponding case block gets executed.
A switch can have any number of cases; however there should be only one default handler.
The switch statement is often faster than nested if...else (not always). Also, the syntax of switch
statement is cleaner and easy to understand.
When a case constant is found that matches the switch expression, control of the program passes
to the block of code associated with that case.

Syntax of switch...case

switch (n)
{
case constant1:
// code to be executed if n is equal to constant1;
break;

case constant2:
// code to be executed if n is equal to constant2;
break;
.
.
.
default:
// code to be executed if n doesn't match any constant
}

// Program to create a simple calculator


// Performs addition, subtraction, multiplication or division depending
the input from user

# include <stdio.h>
main()
{
char operator;
double firstNumber,secondNumber;

printf("Enter an operator (+, -, *, /): ");


scanf("%c", &operator);

printf("Enter two operands: ");


scanf("%lf %lf",&firstNumber, &secondNumber);

switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber+secondNumber);
break;

case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-
secondNumber);
break;

case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;

case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
break;

// operator is doesn't match any case constant (+, -, *, /)


default:
printf("Error! operator is not correct");
}
}
Output
Enter an operator (+, -, *,): -
Enter two operands: 32.5
12.4
32.5 - 12.4 = 20.1
12. What are all iterative / loop control statements in C?

• Loop control statements in C are used to perform looping operations until the given condition is
true. Control comes out of the loop statements once condition becomes false.
• There are 3 types of loop control statements in C language. They are,

a) while loop
i. This loop has a mechanism of repeating one or more statements while a particular
condition is true.
ii. In this type of loop, the condition is generally executed before any of the statements
are executed.
iii. If the condition is found to be true then only will the statements execute otherwise
the condition will be false.
iv. While loop will keep on executing as long as the condition is true.

Syntax:
statement x;
while (condition)
{
statement block;
}
statement y;

Example: Write a program to calculate the sum of first 20 numbers.

#include<stdio.h>
void main()
{
int x=0, sum=0;
while (x<=20)
{
sum=sum+x;
x=x+1;
}
printf("Sum of the first 20 numbers = %d", sum);
}

Output:
Sum of the first 20 numbers = 210

b) do-while loop
It is similar to the while loop with a difference that:
i. In do-while loop control statement, while loop is executed irrespective of the condition for
first time.
ii. Then 2nd time onwards, loop is executed until condition becomes false.
iii. The only difference is that the test condition here is ended at the end of the loop.
iv. From this, it is clear that the body of the loop will be executed atleast once.
Syntax:
statement x;
do
{
statement block;
}
while (condition);
statement y;

Example: Write a program to calculate the average of the first 10 numbers.

#include <stdio.h>
void main()
{
int a=0, sum = 0;
float avg;
do
{
sum=sum+a;
a=a+1;
}
while (a<=10);
avg = sum/10.0;
printf("The sum of the first 10 numbers are = %d",sum);
printf("\n The average of the first 10 numbers are = %f",avg);
}

Output:
The sum of the first 10 numbers are = 55
The average of the first 10 numbers are = 5.000000

c) for loop

i. It is a determinate or definite loop, as the programmer is aware as to how many times


does he want the loop to be repeated.
ii. This loop is initialized only once. When the loop is run, with every iteration the
value of the loop is updated and the condition is checked.
iii. If the condition is true the loop will be executed else the statements are skipped.

Syntax:
for (initialization; condition; increment/decrement)
{
statement block;
}
statement y;
Example: Write a simple “for loop” program to print the first 5 numbers

#include <stdio.h>
void main()
{
int i;
for (i=1; i<=5 ; i++)
printf("%d \n", i);
}

Output:
1
2
3
4
5

13. What is a Difference between while & do while loops in C language?

while do while
Loop is executed for first time irrespective of the condition.
Loop is executed only
After executing while loop for first time, then condition is
when condition is true.
checked.

14. What are Nested Loops?

i. The loops inside the loop are called Nested loops. The most popular types of nested
loops are 'for' loops as they are very easy to control.
ii. 'For' loop can be used to control the number of times any statement needs to be
executed. An outer loop is used for controlling the number of time the loop should be
repeated.
iii. They should be indented properly so that the reader can easily determine what
statements are written within each of them.
Example: Write a program to print the following pattern:
*
**
***

#include <stdio.h>
void main()
{
int i,j;
for (i=1; i<=3; i++)
{
for(j=1; j<=i; j++)
printf("*");
printf("\n");
}
}

15. What are Loop Control Statements?


a. Break Statement
• The break statement terminates the execution of the nearest enclosing loop in which it appears.
• Whenever the compiler comes across the break statement, the control is passed to the
statement that follows the loop in which this statement appears.
• The break statement is used for exiting a loop from the point within its body by passing a
normal termination expression.

Syntax:
break;

b. Continue Statement

• This statement appears only in the body of the loop.


• Whenever the compiler encounters this statement the rest of the statements are skipped
and control is unconditionally transferred to the loop continuing portion of the nearest
enclosing loop.

Syntax:
continue;
• It is the opposite of break statement.
• The next iteration of the loop is forced by skipping any code in between itself and the
test condition of the loop. It is used for restarting a statement sequence whenever an
error occurs.
• For the for loop, continue statement causes the conditional test and increment portions of the
loop to execute.
• For the while and do...while loops, continue statement causes the program control to pass to
the conditional tests.

#include <stdio.h> Output:


main () value of a: 10
value of a: 11
{
value of a: 12
int a = 10; value of a: 13
/* do loop execution */ value of a: 14
do { value of a: 16
if( a == 15) value of a: 17
{ value of a: 18
value of a: 19
/* skip the iteration */
a = a + 1;
continue;
}
printf("value of a: %d\n", a);
a++;

} while( a < 20 );
return 0;
}

c. Goto Statement

By using the goto statement, control can be transferred to any part of the program.

Syntax:

• The label is an identifier. When goto statement is encountered, control of the program
jumps to label: and starts executing the code.
• The label should be there in the same function and can appear only one statement
before the same function.
• Whenever the goto statement is encountered the control gets transferred
immediately to the statements following the label. It breaks the normal sequence
of the execution.
Example:

//Write a C Program Which Print 1 To 10 Number Using goto statement.


#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
clrscr();
count: //This is Label

printf("%d\n",i);
i++;
if(i<=10)
{
goto count; //This jumps to label "count:"
}
getch();
}

Output:
1
2
3
4
5
6
7
8
9
10

Note:

Though goto statement is included in ANSI standard of C, use of goto statement should be reduced
as much as possible in a program.

Reasons to avoid goto statement

• Though, using goto statement give power to jump to any part of program, using goto statement
makes the logic of the program complex and tangled.
• In modern programming, goto statement is considered a harmful construct and a bad
programming practice.
• The goto statement can be replaced in most of C program with the use of break and continue
statements.
• In fact, any program in C programming can be perfectly written without the use of goto
statement.
• All programmer should try to avoid goto statement as possible as they can.

16. What is Comma Operator?


It is special kind of operator which is widely used in programming to separate the
declaration of multiple variables.
Following are the hidden secrets of Comma operator and how it can be used in
programming in efficient manner.

#include<stdio.h>
void main()
{
int num1 = 1, num2 = 2;
int res;
res = (num1, num2);
printf("%d", res);
}

Explanation:

1. Comma Operator has Lowest Precedence i.e it is having lowest priority so it is evaluated
at last.
2. Comma operator returns the value of the rightmost operand when multiple comma
operators are used inside an expression.
3. Comma Operator Can acts as :–
o Operator : In the Expression e.g. res = (num1, num2);
In this case value of rightmost operator will be assigned to the variable. In this case
value of num2 will be assigned to variable res.

o Seperator : Declaring Variable , In Function Call Parameter List


e.g: int num1 = 1, num2 = 2;

It can acts as Separator in –

1. Function calls
2. Function definitions
3. Variable declarations
4. Enum declarations

17. Explain the storage classes of C

A storage class defines the scope (visibility) and life-time of variables and/or functions within
a C Program. Storage class in C decides the part of storage to allocate memory for a variable;
it also determines the scope of a variable.

All variables defined in a C program get some physical location in memory where variable's
value is stored. Memory and CPU registers are types of memory locations where a variable's
value can be stored. The storage class of a variable in C determines the life time of the variable
if this is 'global' or 'local'. Along with the life time of a variable, storage class also determines
variable's storage location (memory or registers), the scope (visibility level) of the variable,
and the initial value of the variable.
There are four storage classes in C those are automatic (auto), register, static (local and
global), and external (extern).

Storage
Storage class Declaration Default
Scope (Visibility) Lifetime Storage
Class specifier Location Value

Inside a
until the function / block
Automatic auto function / within the function / block RAM
completes Garbage
block
until the function / block CPU
Register register within the function / block
completes Register

entire file and other files


Outside all
External extern too where the variable is
functions
declared as extern
until the program
RAM
Inside a terminates Zero
static (local) function / within the function / block
static block
static Outside all entire file in which it is
(global) functions declared

Syntax to declare storage class:


storage_class_specifier data_type variable_name;

Note: One storage class specifier may be given in a declaration.


If no storage class specifier is specified then following rules are used:
1. Variables declared inside a function are taken to be auto.
2. Functions declared within a function are taken to be extern.
3. Variables and functions declared outside a function are taken to be static, with external
linkage.

Variables and functions having external linkage are available to all files that constitute a program.
File scope variables and functions declared as static (described shortly) have internal linkage.
These are known only within the file in which they are declared. Local variables have no linkage
and are therefore known only within their own block.

a) Automatic Storage Class:


The auto storage class is the default storage class for all local variables.
A variable defined within a function or block with auto specifier belongs to automatic storage
class. If no storage class is mentioned than all variables defined within a function or block by
default belong to automatic storage class.
Variables having automatic storage class are local to the block which they are defined in, and
get destroyed on exit from the block. They are assigned a garbage value by default whenever
they are declared.
Syntax:
auto int x;

The following C program demonstrates the visibility level of auto variables.

#include <stdio.h>
int main( )
{
auto int i = 1;
{
auto int i = 2;
{
auto int i = 3;
printf ( "%d ", i);
}
printf ( "%d ", i);
}
printf( "%d", i);
}

OUTPUT
======
3 2 1

Following code uses an auto integer that is local to the function in which it is defined:
#include<stdio.h>
void func1()
{
int a =10;
printf(“\n a = %d”, a) ; // auto integer local to func1()
}
void func2()
{
int a = 20;
printf(“\n a = %d”, a); // auto integer local to func2()
}
void main()
{
int a = 30; // auto integer local to main()
func1();
func2();
printf(“\n a = %d”, a);
}
Output
a = 10
a = 20
a = 30

b) Register Storage Class:


a. The register storage class is used to define local variables that should be stored in the
register of microprocessor.
b. The number of variables which can be declared register are limited. This means that the
variable has a maximum size equal to the register size. If more variables are declared as
register variable, they are treated as auto variables stored in the RAM only.
c. Register variables are used when quick access to the variable is needed.
d. Register variables can't be operated using unary '&' operator because it does not have a
memory location associated with it.
e. A program that uses register variables executes faster as compared to similar program
without register variable.
Note: The address of a register variable cannot be obtained by using pointers.
Syntax:
register int x = 10;

Following code uses a register variable


Output:
#include<stdio.h>
#include<conio.h> Enter first number
int main() 10
{ Enter second number
int a,b; 20
register int c;
clrscr(); The sum of 10 and 20 is
printf(“Enter first number \n”); 30
scanf(“%d”,&a);
printf(“Enter second number\n”)
scanf(“%d”,&b);
c = a+b;
printf(“The sum of %d and %d is %d ”,a,b,c);
getch();
}
c) External storage Class:
a. External storage class variables are global to the file in which they are defined. External
variables are used only when all functions needed a particular variable. It retains the
assigned value within the scope.
b. The extern specifier tells the compiler that the variable has already been declared
elsewhere and therefore it should not allocate storage space for that variable again.
During the compilation of the program, the linker will automatically resolve the
reference problem.
c. The extern modifier is most commonly used when there are two or more files
sharing the same global variables or functions
Syntax:
extern int x;

Program 1: Following is the code which uses the extern keyword in two different
FILES.

// FILE 1.C
#include<stdio.h>
#include<FILE2.C> //Programmer’s own header file
int x;
void print(void);
main()
{
x = 10;
printf(“\n x in FILE 1 = %d”, x);
print();
}
// END of FILE1.C
// FILE2.C
#include<stdio.h>
extern int x;
void print()
{
printf(“\n x in FILE 2 = %d”,x);
}
main()
{
int x= 5;
printf(“value of x inside main in FILE 2 is : %d”,x);
}
// END of FILE2.C

FILE1 has declared a global variable x. FILE1 also includes FILE2 which has a print function
that uses the external variable x to print its value on the screen.
Program 2: Use of extern keyword in one file only
#include<stdio.h>
int i = 5;
main()
{
extern int i;
while(i>0)
printf("i = %d\n",i--);
}
Output:

Note:

a) Declaration within the function indicates that the function uses external variable.
b) Functions belonging to same source code does not require declaration (no need to write
extern).
c) If variable is defined outside the source code, then declaration using extern keyword is
required.
d) Static Storage Class:
a. As we know auto is the default storage class of all local variables, static is the default
storage class for all global variables.
b. Static variables have a 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.
c. Static variables can be declared within a function which is called as local static variables.
These variables retain their values from the previous call. i.e., the value that they had
before returning from the function.
d. If a static variable is declared outside all the functions in a program, it can be used only in
the program in which it is declared and is not visible to other program files.
Syntax:
Static int x = 10;
Program 1: Let's see an example of a use of Static Variable
#include<stdio.h>
int main()
{
int i =0;

while(i<=4)
{
static int j = 0; // static keyword used here
printf("i = %d\t",i++);
printf("y = %d\n",j++);
}
}
Output:

Program 2: Above same program without using static storage class


#include<stdio.h>
int main()
{
int i =0;
while(i<=4)
{
int j = 0; // static keyword not used here
printf("i = %d\t",i++);
printf("y = %d\n",j++);
}
}
Output:

You might also like