0% found this document useful (0 votes)
53 views51 pages

FINAL UNIT 1 Notes

Uploaded by

kathpalsiya01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views51 pages

FINAL UNIT 1 Notes

Uploaded by

kathpalsiya01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

UNIT -1- Part 1- INTRODUCTION TO PROGRAMMING

• Computer system,
• components of a computer system,
• computing environments,
• computer languages, creating and running programs,
• Preprocessor, Compilation process, role of linker, idea of invocation and execution
of a programme.
• Algorithms: Representation using flowcharts, pseudocode.

Introduction to computer System


A computer is an electronic device that can be programmed to accept data (input), process it
and generate result (output). A computer along with additional hardware and software together
is called a computer system.
A computer system primarily comprises a central processing unit (CPU), memory, input/output
devices and storage devices. All these components function together as a single unit to deliver
the desired output. A computer system comes in various forms and sizes. It can vary from a
high-end server to personal desktop, laptop, tablet computer, or a smartphone.

Components of a computer system


Every computer system has the following three basic components:

1. Input unit

2. Central processing unit

3. Output unit
Input Unit

These components help users enter data and commands into a computer system. Data can be
in the form of numbers, words, actions, commands, etc. The main function of input devices is
to direct commands and data into computers. Computers then use their CPU to process this
data and produce output.
For example, a laptop’s keyboard is an input unit that enters numbers and characters. Similarly,
even a mouse can be an input unit for entering directions and commands. Other examples
include barcode readers, Magnetic Ink Character Readers (MICR), Optical Character Readers
(OCR), etc.
Another example of input devices is touch-screens. Users can simply touch these screens
without using any other device to enter commands. From smartphones to ATM machines, these
input devices are becoming very popular these days.

Central Processing Unit (CPU)

After receiving data and commands from users, a computer system now has to process it according
to the instructions provided. Here, it has to rely on a component called the central
processing unit. The CPU further uses these three elements:

a) Memory Unit
Once a user enters data using input devices, the computer system stores this data in its
memory unit. This data will now remain here until other components of CPU process it.
The memory unit uses a set of pre-programmed instructions to further transmit this data
to other parts of the CPU.
b) Arithmetic and Logic Unit
This part of the CPU performs arithmetic operations. It does basic mathematical
calculations like addition, subtraction, division, multiplication, etc. Further, it can even
perform logical functions like the comparison of data.
c) Control Unit
This unit is the backbone of computers. It is responsible for coordinating tasks between
all components of a computer system. The control unit collects data from input units and
sends it to processing units depending on its nature. Finally, it also further transmits
processed data to output units for users.

Output Unit

The third and final component of a computer system is the output unit. After processing of data,
it is converted into a format which humans can understand. After conversion, the output units
displays this data to users. Examples of output devices include monitors, screens, printers and
speakers. Thus, output units basically reproduce the data formatted by the computer for users’
benefit.
//*Units of Memory
A computer system uses binary numbers to store and process data. The binary digits 0 and 1,
which are the basic units of memory, are called bits. Further, these bits are grouped together to
form words. A 4-bit word is called a Nibble. Examples of nibble are 1001, 1010, 0010, etc. A
two nibble word, i.e., 8-bit word is called a byte, for example, 01000110, 01111100, 10000001,
etc.
Like any other standard unit, bytes are grouped together to make bigger chunks or units of
memory. Table 1.1 shows different measurement units for digital data stored in storage devices.
Computer
Table 1.1 Measurement units for digital data
KB (Kilobyte) MB (Megabyte) GB (Gigabyte) TB (Terabyte)
Description
1 KB = 1024 Bytes
1 MB = 1024 KB
1 GB = 1024 MB
1 TB = 1024 GB
Unit
PB (Petabyte)
EB (Exabyte)
ZB (Zettabyte)
YB (Yottabyte)
Description
1 PB = 1024 TB
1 EB = 1024 PB
1 ZB = 1024 EB
1 YB = 1024 ZB //*

Computing Environment

In the world of technology where every tasks are performed with help of computers, these
computers have become one part of human life. Computing is nothing but process of
completing a task by using this computer technology and it may involve computer hardware
and/or software. But computing uses some form of computer system to manage, process, and
communicate information.
When a problem is solved by the computer, during that computer uses many devices,
arranged in different ways and which work together to solve problems. This constitutes a
computing environment where various number of computer devices arranged in different
ways to solve different types of problems in different ways. In different computing
environments computer devices are arranged in different ways and they exchange
information in between them to process and solve problem. One computing environment
consists of many computers other computational devices, software and networks that to
support processing and sharing information and solving task.
Based on the organization of different computer devices and communication processes there
exists multiple types of computing environments. Now lets know about different types of
computing environments.
Types of Computing Environments :

1. Personal Computing Environment :


In personal computing environment there is a stand-alone machine. Complete
program resides on computer and executed there. Different stand-alone machines
that constitute a personal computing environment are laptops, mobiles, printers,
computer systems, scanners etc. That we use at our homes and offices.
2. Time-Sharing Computing Environment :
In Time Sharing Computing Environment multiple users share system
simultaneously. Different users (different processes) are allotted different time
slice and processor switches rapidly among users according to it. For example,
student listening to music while coding something in an IDE. Windows 95 and
later versions, Unix, IOS, Linux operating systems are the examples of this time
sharing computing environment.
3. Client Server Computing Environment :
In client server computing environment two machines are involved i.e., client
machine and server machine, sometime same machine also serve as client and
server. In this computing environment client requests resource/service and server
provides that respective resource/service. A server can provide service to multiple
clients at a time and here mainly communication happens through computer
network.
4. Distributed Computing Environment :
In a distributed computing environment multiple nodes are connected together
using network but physically they are separated. A single task is performed by
different functional units of different nodes of distributed unit. Here different
programs of an application run simultaneously on different nodes, and
communication happens in between different nodes of this system over network
to solve task.
5. Grid Computing Environment :
In grid computing environment, multiple computers from different locations
works on single problem. In this system set of computer nodes running in cluster
jointly perform a given task by applying resources of multiple computers/nodes.
It is network of computing environment where several scattered resources provide
running environment for single task.
6. Cloud Computing Environment :
In cloud computing environment on demand availability of computer system
resources like processing and storage are availed. Here computing is not done in
individual technology or computer rather it is computed in cloud of computers
where all required resources are provided by cloud vendor. This environment
primarily comprised of three services i.e. Software as a
service(SAAS),Infrastructure as a service(IAAS),Platform as a service(PAAS).
7. Cluster Computing Environment :
In cluster computing environment cluster performs task where cluster is a set of
loosely or tightly connected computers that work together. It is viewed as single
system and performs task parallelly that’s why also it is similar to parallel
computing environment. Cluster aware applications are especially used in cluster
computing environment.

Programming Languages Types


Different kinds of languages have been developed to perform different types of work on the
computer. Languages can be divided into two categories according to how the computer
understand them.
Two basic types of computer languages
• Low level Languages
• High level Languages

Low- level Languages


Low level languages are either machine codes or are very close them. A computer cannot
understand instructions given to it in high level languages. It can only understand and execute
instructions given in the form of machine language i.e. binary. There are two type of low level
language:
• Machine language
• Assembly language
Machine Language

Every computer works only on 0s and 1s, i.e., binary number system and can understand only
its own machine language which is its “natural language” defined by its hardware design.
Therefore , in machine language programming programmers have to instruct computers using
different combinations of 0s and 1s.

Advantages of Machine Language:

• Programs written in machine language can be executed very fast by the computer. This
is mainly because machine instructions are directly understood by the CPU and no
translation of the program is required.
• Efficient use of primary memory
Disadvantages of Machine Language:

• Machine dependent
• Difficult to program
• Difficult to modify
• Error prone

Assembly Language

In assembly language programming to overcome disadvantages of machine language,


programmers began using English like abbreviations to represent elementary operations instead
of using the strings of 0s and 1s. These symbolic instructions formed the basis of assembly
languages and translator programs that were developed to convert assembly language programs
to machine language are known as assemblers.

Advantages of Assembly Language


• Programs written in machine language are replaceable by mnemonics which are easier
to remember.
• Memory efficient
• It is not required to keep track of memory locations
• Faster in speed
• Easy to make insertion and deletion.
• Requires fewer instructions to accomplish the same result
Disadvantages of Assembly Language

• Long programs written in such languages cannot be executed on small sized computers.
• It takes lot of time to code or write the program, as it is more complex in nature.
• Difficult to remember the syntax
• Lack of portability of program between computers of different makes.

High Level Language

Despite the advent of assembly language, programmers still had to use many instructions to
accomplish even the simplest task . Thus to speed up the programming process, high level
languages were developed in which single statements could be written to perform substantial
tasks. High level language programming allowed the programmers to write instruction that
look almost like everyday English and contain commonly used mathematical notations.
Advantages of high level language
• High level languages are programmer friendly. They are easy to write , debug and
maintain.
• It provides higher level of abstraction from machine languages.
• It is machine independent language.
• Easy to learn
• Less error prone, easy to find and debug errors.
• Higher level programming results in better programming productivity.
Disadvantages of high level language

• It takes additional translation times to translate the source to machine code.


• High level programs are comparatively slower than low level programs.
• Compared to low level programs, they are generally less memory efficient.
• Cannot communicate directly with the hardware.

Compilation process in c

The compilation is a process of converting the source code into object code. It is done with
the help of the compiler. The compiler checks the source code for the syntactical or structural
errors, and if the source code is error-free, then it generates the object code.

The c compilation process converts the source code taken as input into the object code or
machine code. The compilation process can be divided into four steps, i.e., Pre-processing,
Compiling, Assembling, and Linking.

The pre-processor takes the source code as an input, and it removes all the comments from the
source code. The pre-processor takes the pre-processor directive and interprets it. For example,
if <stdio.h>, the directive is available in the program, then the pre-processor interprets the
directive and replace this directive with the content of the 'stdio.h' file.

The following are the phases through which our program passes before being transformed into
an executable form:

• Pre-processor
• Compiler
• Assembler
• Linker
Pre-processor
The source code is the code which is written in a text editor and the source code file is given
an extension ".c". This source code is first passed to the pre-processor, and then the pre-
processor expands this code. After expanding the code, the expanded code is passed to the
compiler.
Compiler
The code which is expanded by the pre-processor is passed to the compiler. The compiler
converts this code into assembly code. Or we can say that the C compiler converts the pre-
processed code into assembly code.
Assembler
The assembly code is converted into object code by using an assembler. The name of the object
file generated by the assembler is the same as the source file. The extension of the object file
in DOS is '.obj,' and in UNIX, the extension is 'o'. If the name of the source file is 'hello.c', then
the name of the object file would be 'hello.obj'.
Linker
Mainly, all the programs written in C use library functions. These library functions are pre-
compiled, and the object code of these library files is stored with '.lib' (or '.a') extension. The
main working of the linker is to combine the object code of library files with the object code
of our program. Sometimes the situation arises when our program refers to the functions
defined in other files; then linker plays a very important role in this. It links the object code of
these files to our program. Therefore, we conclude that the job of the linker is to link the object
code of our program with the object code of the library files and other files. The output of the
linker is the executable file. The name of the executable file is the same as the source file but
differs only in their extensions. In DOS, the extension of the executable file is '.exe', and in
UNIX, the executable file can be named as 'a.out'. For example, if we are using printf() function
in a program, then the linker adds its associated code in an output file.

Let's understand through an example.

hello.c
#include <stdio.h>
int main()
{
printf("Hello ABC");
return 0;
}

Algorithms: Representation using flowcharts, pseudocode.

The algorithm and flowchart are two types of tools to explain the process of a program. In this
page, we discuss the differences between an algorithm and a flowchart and how to create a
flowchart to illustrate the algorithm visually.

Algorithms and flowcharts are two different tools that are helpful 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.

• Part 1: Definition of Algorithm


• Part 2: Definition of Flowchart
• Part 3: Difference between Algorithm and Flowchart
• Part 4: Types of Algorithm
• Part 5: Use Flowcharts to Represent Algorithms
• Part 6: Conclusion

Part 1: Definition of Algorithm

Writing a logical step-by-step method to solve the problem is called the 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 in the process.

An algorithm includes calculations, reasoning, and data processing. Algorithms can be


presented by natural languages, pseudocode, and flowcharts, etc.
Part 2: Definition of Flowchart

A flowchart is the graphical or pictorial representation of an algorithm with the help of


different symbols, shapes, and arrows to demonstrate a process or a program. With algorithms,
we can easily understand a program. The main purpose of using a flowchart is to analyze
different methods. Several standard symbols are applied in a flowchart:

Terminal Box - Start / End

Input / Output

Process / Instruction

Decision
Connector / Arrow

The symbols above represent different parts 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 certain elements and the relationships between each part.

Part 3: Difference between Algorithm and Flowchart

Algorithm Flowchart
It is a procedure for solving problems. It is a graphic representation of a process.
The process is shown in step-by-step The process is shown in block-by-block information
instruction. diagram.
It is complex and difficult to understand. It is intuitive and easy to understand.
It is convenient to debug errors. It is hard to debug errors.
The solution is showcased in natural
The solution is showcased in pictorial format.
language.
It is somewhat easier to solve complex
It is hard to solve complex problem.
problem.
It costs more time to create an algorithm. It costs less time to create a flowchart.

Part 4: Types of Algorithm(Just For Information not in the syllabus)

It is not surprising that algorithms are widely used in computer programming. However, it can
be applied to solving mathematical problems and even in everyday life. Here comes a question:
how many types of algorithms? According to Dr. Christoph Koutschan, a computer scientist
working at the Research Institute for Symbolic Computation (RISC) in Austria, he has
surveyed voting for the important types of algorithms. As a result, he has listed 32 crucial
algorithms in computer science. Despite the complexity of algorithms, we can generally divide
algorithms into six fundamental types based on their function.
1. Recursive Algorithm

It refers to a way to solve problems by repeatedly breaking down the problem into sub-
problems of the same kind. The classic example of using a recursive algorithm to solve
problems is the Tower of Hanoi.

2. Divide and Conquer Algorithm

Traditionally, the divide and conquer algorithm consists of two parts: 1. breaking down a
problem into some smaller independent sub-problems of the same type; 2. finding the final
solution of the original issues after solving these more minor problems separately.

The key points of the divide and conquer algorithm are:

• If you can find the repeated sub-problems and the loop substructure of the original
problem, you may quickly turn the original problem into a small, simple issue.
• Try to break down the whole solution into various steps (different steps need different
solutions) to make the process easier.
• Are sub-problems easy to solve? If not, the original problem may cost lots of time.

3. Dynamic Programming Algorithm

Developed by Richard Bellman in the 1950s, the dynamic programming algorithm is generally
used for optimization problems. In this type of algorithm, past results are collected for future
use. Like the divide and conquer algorithm, a dynamic programming algorithm simplifies a
complex problem by breaking it down into some simple sub-problems. However, the most
significant difference between them is that the latter requires overlapping sub-problems, while
the former doesn’t need to.

4. Greedy Algorithm

This is another way of solving optimization problems – greedy algorithm. It refers to always
finding the best solution in every step instead of considering the overall optimality. That is to
say, what he has done is just at a local optimum. Due to the limitations of the greedy algorithm,
it has to be noted that the key to choosing a greedy algorithm is whether to consider any
consequences in the future.

5. Brute Force Algorithm

The brute force algorithm is a simple and straightforward solution to the problem, generally
based on the description of the problem and the definition of the concept involved. You can
also use "just do it!" to describe the strategy of brute force. In short, a brute force algorithm is
considered as one of the simplest algorithms, which iterates all possibilities and ends up with
a satisfactory solution.

6. Backtracking Algorithm

Based on a depth-first recursive search, the backtracking algorithm focusing on finding the
solution to the problem during the enumeration-like searching process. When it cannot satisfy
the condition, it will return “backtracking” and tries another path. It is suitable for solving large
and complicated problems, which gains the reputation of the “general solution method.” One
of the most famous backtracking algorithm example it the eight queens puzzle.

Part 5: Use Flowcharts to Represent Algorithms

Now that we have learned the definitions of algorithm and flowchart, how can we use a
flowchart to represent an algorithm? To create an algorithm flowchart, we need to use a handy
diagramming tool like EdrawMax to finish the work.

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

Example 1: Print 1 to 20:

Algorithm:

• Step 1: Initialize X as 0,
• Step 2: Increment X by 1,
• Step 3: Print X,
• Step 4: If X is less than 20 then go back to step 2.

Flowchart:
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)

Algorithm:

• Step 1: Read temperature in Fahrenheit,


• Step 2: Calculate temperature with formula C=5/9*(F-32),
• Step 3: Print C.

Flowchart:
Example 3: Determine Whether A Student Passed the Exam or Not:
Algorithm:

• Step 1: Input grades of 4 courses M1, M2, M3 and M4,


• Step 2: Calculate the average grade with formula "Grade=(M1+M2+M3+M4)/4"
• Step 3: If the average grade is less than 60, print "FAIL", else print "PASS".

Flowchart:

Part 6: Conclusion

From the above, we can come to the conclusion that a flowchart is a pictorial representation of
an algorithm, an algorithm can be expressed and analyzed through a flowchart. An algorithm
shows you every step of reaching the final solution, while a flowchart shows you how to carry
out the process by connecting each step. An algorithm uses mainly words to describe the steps
while you can create a flowchart with flowchart symbols to make the process more logical.

Pseudo Code

Pseudo code is an informal high-level description of the operating principle of a computer


program or other algorithm. It is a procedure for solving a problem in terms of the actions to
be executed and the order in which those actions are to be executed.

Pseudo code uses the structural conventions of a programming language, but is intended for
human reading rather than machine reading. It typically omits details that are not essential for
human understanding of the algorithm, such as variable declarations, system-specific code and
some subroutines. The programming language is augmented with natural language description
details, where convenient, or with compact mathematical notation.

The purpose of using pseudo code is that it is easier for people to understand than conventional
programming language code, and that it is an efficient and environment-independent
description of the key principles of an algorithm. It is commonly used in textbooks and
scientific publications that are documenting various algorithms, and also in planning of
computer program development, for sketching out the structure of the program before the
actual coding takes place.

In the following example, the pseudocode is on program that can add 2 numbers together
then display the result.
Solution:
• Start Program
• Enter two numbers A,B.
• Add the two numbers together
• Print Sum
• End Program.

UNIT-1-Part 2-Introduction to C language:


• History of C
• Basic structure of C programs
• Process of compiling and running a C program
• C tokens, keywords, identifiers, constants, strings, special symbols, variables, data
types, I/O statements. Interconversion of variables

• History of C

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of


AT&T (American Telephone & Telegraph), located in the U.S.A.
Dennis Ritchie is known as the founder of the c language.
It was developed to overcome the problems of previous languages such as B, BCPL, etc

Initially, C language was developed to be used in UNIX operating system. It inherits many
features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.

Language Year Developed By

Algol 1960 International Group


BCPL 1967 Martin Richard

B 1970 Ken Thompson

Traditional C 1972 Dennis Ritchie

K&RC 1978 Kernighan & Dennis Ritchie

ANSI C 1989 ANSI Committee

ANSI/ISO C 1990 ISO Committee

C99 1999 Standardization Committee

Features of C Language

C is the widely used language. It provides many features that are given below.

1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible

• Basic structure of C programs

To write the first c program, open the C console and write the following code:

#include <stdio.h>
int main(){
printf("Hello C Language");
return 0;
}

#include <stdio.h> includes the standard input output library functions. The printf()
function is defined in stdio.h .
int main() The main() function is the entry point of every program in c language.

The printf() and scanf() functions are used for input and output in C language. Both functions
are inbuilt library functions, defined in stdio.h (header file).

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

printf("format string",argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

Scanf() function

The scanf() function is used for input. It reads the input data to the console.

scanf("format string",argument_list);

return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.

Program to print cube of given number


Let's see a simple example of c language that gets input from the user and prints the cube of
the given number.

#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}
Output
enter a number:5
cube of number is:125

The scanf("%d",&number) statement reads integer number from the console and stores the
given value in number variable.
The printf("cube of number is:%d ",number*number*number) statement prints the cube of
number on the console.

Program to print sum of 2 numbers


Let's see a simple example of input and output in C language that prints addition of 2 numbers.
#include<stdio.h>
int main(){
int x=0,y=0,result=0;
printf("enter first number:");
scanf("%d",&x);
printf("enter second number:");
scanf("%d",&y);
result=x+y;
printf("sum of 2 numbers:%d ",result);
return 0;
}
Output
enter first number:9
enter second number:9
sum of 2 numbers:18

• Process Of Compiling And Running a C Program


In the above flow diagram, the following steps are taken to execute a program:

o Firstly, the input file, i.e., hello.c, is passed to the preprocessor, and the preprocessor
converts the source code into expanded source code. The extension of the expanded
source code would be hello.i.
o The expanded source code is passed to the compiler, and the compiler converts this
expanded source code into assembly code. The extension of the assembly code would
be hello.s.
o This assembly code is then sent to the assembler, which converts the assembly code
into object code.
o After the creation of an object code, the linker creates the executable file. The loader
will then load the executable file for the execution.

• C tokens:

Tokens in C is the most important element to be used in creating a program in C. We can define
the token as the smallest individual element in C. For `example, we cannot create a sentence
without using words; similarly, we cannot create a program in C without using tokens in C.
Therefore, we can say that tokens in C is the building block or the basic component for creating
a program in C.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

• Keywords can be defined as the pre-defined or the reserved words having its own
importance, and each keyword has its own functionality. Since keywords are the pre-defined
words used by the compiler, so they cannot be used as the variable names. If the keywords are
used as the variable names, it means that we are assigning a different meaning to the keyword,
which is not allowed. C language supports 32 keywords given below:

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

• Identifiers in C

Identifiers are used for naming variables, functions, arrays, structures, etc. Identifiers in C are
the user-defined words. It can be composed of uppercase letters, lowercase letters, underscore,
or digits, but the starting letter should be either an underscore or an alphabet. Identifiers cannot
be used as keywords. Rules for constructing identifiers in C are given below:

o The first character of an identifier should be either an alphabet or an underscore, and


then it can be followed by any of the character, digit, or underscore.
o It should not begin with any numerical digit.
o In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say
that identifiers are case sensitive.
o Commas or blank spaces cannot be specified within an identifier.
o Keywords cannot be represented as an identifier.
o The length of the identifiers should not be more than 31 characters.
o Identifiers should be written in such a way that it is meaningful, short, and easy to read.
• Constants in C

A constant is a value assigned to the variable which will remain the same throughout the
program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

o Using const keyword


o Using #define pre-processor

Types of Constants in C

Constant Example

Integer constant 10, 11, 34, etc.

Floating-point constant 45.6, 67.8, 11.2, etc.

Octal constant 011, 088, 022, etc.

Hexadecimal constant 0x1a, 0x4b, 0x6b, etc.

Character constant 'a', 'b', 'c', etc.

String constant "java", "c++", ".net", etc.

• Strings in C

Strings are always represented as an array of characters having null character '\0' at the end of
the string. This null character denotes the end of the string. Strings in C are enclosed within
double quotes, while characters are enclosed within single characters. The size of a string is a
number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of characters.

• Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be used
for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For
example, printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing
the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that
we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.

• Operators in C

Operators in C is a special symbol used to perform the functions. The data items on which the
operators are applied are known as operands. Operators are applied between the operands.
Depending on the number of operands, operators are classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment operator
(++), decrement operator (--), sizeof, (type)*.

Binary Operator

The binary operator is an operator applied between two operands. The following is the list of
the binary operators:

o Arithmetic Operators
o Relational Operators
o Shift Operators
o Logical Operators
o Bitwise Operators
o Conditional Operators
o Assignment Operator
o Misc Operator

• Data types

A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.

There are the following data types in C language.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure, union

Enumeration Data Type enum

Void Data Type void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating
system.

Let's see the basic data types. Its size is given according to 32-bit architecture.
Data Types Memory Size Range

char 1 byte −128 to 127

signed char 1 byte −128 to 127

unsigned char 1 byte 0 to 255

short 2 byte −32,768 to 32,767

signed short 2 byte −32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 2 byte −32,768 to 32,767

signed int 2 byte −32,768 to 32,767

unsigned int 2 byte 0 to 65,535

short int 2 byte −32,768 to 32,767

signed short int 2 byte −32,768 to 32,767

unsigned short int 2 byte 0 to 65,535

long int 4 byte -2,147,483,648 to


2,147,483,647

signed long int 4 byte -2,147,483,648 to


2,147,483,647

unsigned long int 4 byte 0 to 4,294,967,295

float 4 byte

double 8 byte

long double 10 byte

Int:
Integers are entire numbers without any fractional or decimal parts, and the int data type is used
to represent them.
It is frequently applied to variables that include values, such as counts, indices, or other
numerical numbers. The int data type may represent both positive and negative
numbers because it is signed by default.
An int takes up 4 bytes of memory on most devices, allowing it to store values between around
-2 billion and +2 billion.

Char:
Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols,
or commas. There are 256 characters that can be represented by a single char, which takes up
one byte of memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.

Float:
To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.
The float type is usually used for variables that require very good precision but may not be very
precise. It can store values with an accuracy of about 6 decimal places and a range of about 3.4
x 1038 in 4 bytes of memory.

Double:
Use two data types to represent two floating integers. When additional precision is needed,
such as in scientific calculations or financial applications, it provides greater accuracy
compared to float.
Double type, which uses 8 bytes of memory and has an accuracy of about 15 decimal places,
yields larger values. C treats floating point numbers as doubles by default if no explicit type is
supplied.
int age = 25;
char grade = 'A';
float temperature = 98.6;
double pi = 3.14159265359;
In the example above, we declare four variables: an int variable for the person's age, a char
variable for the student's grade, a float variable for the temperature reading, and two variables
for the number pi.

Derived Data Type


Beyond the fundamental data types, C also supports derived data types, including arrays,
pointers, structures, and unions. These data types give programmers the ability to handle
heterogeneous data, directly modify memory, and build complicated data structures.

Array:
An array, a derived data type, lets you store a sequence of fixed-size elements of the same type.
It provides a mechanism for joining multiple targets of the same data under the same name.
The index is used to access the elements of the array, with a 0 index for the first entry. The size
of the array is fixed at declaration time and cannot be changed during program execution. The
array components are placed in adjacent memory regions.
Here is an example of declaring and utilizing an array:

#include <stdio.h>
int main() {
int numbers[5]; // Declares an integer array with a size of 5 elements

// Assign values to the array elements


numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

// Display the values stored in the array


printf("Values in the array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

return 0;
}
Output:
Values in the array: 10 20 30 40 50

Pointer:
A pointer is a derived data type that keeps track of another data type's memory address. When
a pointer is declared, the data type it refers to is stated first, and then the variable name is
preceded by an asterisk (*).
You can have incorrect access and change the value of variable using pointers by specifying
the memory address of the variable. Pointers are commonly used in tasks such as function
pointers, data structures, and dynamic memory allocation.

Here is an example of declaring and employing a pointer:


#include <stdio.h>

int main() {
int num = 42; // An integer variable
int *ptr; // Declares a pointer to an integer

ptr = # // Assigns the address of 'num' to the pointer

// Accessing the value of 'num' using the pointer


printf("Value of num: %d\n", *ptr);

return 0;
}
Output:
Value of num: 42

Structure:
A structure is a derived data type that enables the creation of composite data types by allowing
the grouping of many data types under a single name. It gives you the ability to create your
own unique data structures by fusing together variables of various sorts.
A structure's members or fields are used to refer to each variable within it.
Any data type, including different structures, can be a member of a structure.
A structure's members can be accessed by using the dot (.) operator.

A declaration and use of a structure is demonstrated here:


#include <stdio.h>
#include <string.h>
// Define a structure representing a person
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declare a variable of type struct Person
struct Person person1;

// Assign values to the structure members


strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 1.8;

// Accessing the structure members


printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.2f\n", person1.height);

return 0;
}
Output:
Name: John Doe
Age: 30
Height: 1.80

Union:
A derived data type called a union enables you to store various data types in the same memory
address. In contrast to structures, where each member has a separate memory space, members
of a union all share a single memory space. A value can only be held by one member of a union
at any given moment. When you need to represent many data types interchangeably, unions
come in handy. Like structures, you can access the members of a union by using the dot
(.) operator.
Here is an example of a union being declared and used:
#include <stdio.h>
// Define a union representing a numeric value
union NumericValue {
int intValue;
float floatValue;
char stringValue[20];
};
int main() {
// Declare a variable of type union NumericValue
union NumericValue value;
// Assign a value to the union
value.intValue = 42;
// Accessing the union members
printf("Integer Value: %d\n", value.intValue);
// Assigning a different value to the union
value.floatValue = 3.14;
// Accessing the union members
printf("Float Value: %.2f\n", value.floatValue);

return 0;
}
Output:
Integer Value: 42
Float Value: 3.14

Enumeration Data Type


A set of named constants or enumerators that represent a collection of connected values can be
defined in C using the enumeration data type (enum). Enumerations give you the means to give
names that make sense to a group of integral values, which makes your code easier to read and
maintain.
Here is an example of how to define and use an enumeration in C:
#include <stdio.h>

// Define an enumeration for days of the week


enum DaysOfWeek {
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
};

int main() {
// Declare a variable of type enum DaysOfWeek
enum DaysOfWeek today;

// Assign a value from the enumeration


today = Wednesday;

// Accessing the enumeration value


printf("Today is %d\n", today);

return 0;
}
Output:
Today is 2

Void Data Type


The void data type in the C language is used to denote the lack of a particular type. Function
return types, function parameters, and pointers are three situations where it is frequently
utilized.

Function Return Type:


A void return type function does not produce a value. A void function executes a task or action
and ends rather than returning a value.
Example:
void printHello() { printf("Hello, world!\n"); }

Function Parameters:
The parameter void can be used to indicate that a function accepts no arguments.
Example:
void processInput(void) { /* Function logic */ }
Pointers:
Any address can be stored in a pointer of type void*, making it a universal pointer. It offers a
method for working with pointers to ambiguous or atypical types.
Example:
void* dataPtr;
The void data type is helpful for defining functions that don't accept any arguments when
working with generic pointers or when you wish to signal that a function doesn't return a value.
It is significant to note that while void* can be used to build generic pointers, void itself cannot
be declared as a variable type.

Here is a sample of code that shows how to utilize void in various situations:
#include <stdio.h>
// Function with void return type
void printHello() {
printf("Hello, world!\n");
}
// Function with void parameter
void processInput(void) {
printf("Processing input...\n");
}

int main() {
// Calling a void function
printHello();

// Calling a function with void parameter


processInput();

// Using a void pointer


int number = 10;
void* dataPtr = &number;
printf("Value of number: %d\n", *(int*)dataPtr);

return 0;
}
Output:
Hello, world!
Processing input...
Value of number: 10

• C Operators

An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

1. Arithmetic Operators
2. Increment and Decrement Operators
3. Relational Operators
4. Logical Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

• Arithmetic Operators
Arithmetic Operators are used to perform mathematical calculations like addition (+),
subtraction (-), multiplication (*), division (/) and modulus (%).

Operator Description Example

+ Adds two operands. A + B = 30

− Subtracts second operand from the first. A − B = -10

* Multiplies both operands. A * B = 200

/ Divides numerator by de-numerator. B/A=2

% Modulus Operator and remainder of after an B%A=0


integer division.

Example of Arithmetic Operator


#include <stdio.h>
void main ()
{
int num1;
int num2;
int num3;
num1 = 5;
num2 = ++num1 * num1++;
num3 = num1+num2;
printf("num1= %d“, num1);
printf("num2=%d“, num2);
printf("num3= %d“, num3);
}

• Increment and Decrement Operators

Increment and Decrement Operators are useful operators generally used to minimize the
calculation.

++x and x++ mean x=x+1


or
−−x and x−− mean x=x-1
But there is a slight difference between ++ or −− written before or after the operand.
Applying the pre-increment first add one to the operand and then the result is assigned to the
variable on the left whereas post-increment first assigns the value to the variable on the left and
then increment the operand.

Example of Increment and Decrement Operator

#include <stdio.h>
void main()
{
int a=5, b=5;
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);
printf("\n%d %d",a--,--b);


Relational Operator
Relational operators are used to comparing two quantities or values.

Operator Description

== Is equal to

!= Is not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to


• Logical Operator

C provides three logical operators when we test more than one condition
to make decisions. These are:
&& (meaning logical AND),
|| (meaning logical OR) and
! (meaning logical NOT).

Operator Description

&& And operator. It performs logical conjunction of two expressions. (if both
expressions evaluate to True, result is True. If either expression evaluates to
False, the result is False)

|| Or operator. It performs a logical disjunction on two expressions. (if either or


both expressions evaluate to True, the result is True)

! Not operator. It performs logical negation on an expression.

Example
• Assignment operator
Assignment operators applied to assign the result of an expression to a variable. C has a
collection of shorthand assignment operators.

Operator Description

= Assign

+= Increments then assign

-= Decrements then assign

*= Multiplies then assign

/= Divides then assign

%= Modulus then assign

<<= Left shift and assign

>>= Right shift and assign


&= Bitwise AND assign

^= Bitwise exclusive OR and assign

|= Bitwise inclusive OR and assign

Example : working of an assignment operator

#include <stdio.h>
Int main()
{
Int a=5,c;
c =a;
printf(“c=%d\n”,c);
c +=a;
printf(“c=%d\n”,c);
c -= a;
printf(“c=%d\n”,c);
c*=a;
printf(“c=%d\n”,c);
c /=a;
printf(“c=%d\n”,c);
c %=a;
printf(“c=%d\n”,c);
return o;
}

•Bitwise Operator
C provides a special operator for bit operation between two variables

Operator Description

& Binary AND Operator copies a bit to the result if it exists in both operands.

| Binary OR Operator copies a bit if it exists in either operand.

^ Binary XOR Operator copies the bit if it is set in one operand but not both.

~
Binary One's Complement Operator is unary and has the effect of 'flipping' bits.

<< Binary Left Shift Operator. The left operands value is moved left by the number
of bits specified by the right operand.

>> Binary Right Shift Operator. The left operands value is moved right by the
number of bits specified by the right operand.
Example of AND
12=00001100 (In binary)
25=00011001 (In Binary)

Bit Operation of 12 and 25


00001100
&00011001
---------------
00001000 =8 (in decimal)

Example using C code


#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}

OUTPUT:
8

Example of OR
12=00001100 (In binary)
25=00011001 (In Binary)

Bit Operation of 12 and 25


00001100
| 00011001
---------------
00011001 =29 (in decimal)

Example using C code


#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
return 0;
}

OUTPUT:
29

Example of XOR
12=00001100 (In binary)
25=00011001 (In Binary)

Bit Operation of 12 and 25


00001100
^ 00011001
---------------
00010101 =21 (in decimal)

Example using C code


#include <stdio.h>
int main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
return 0;
}

OUTPUT:
21

Example of Binary 1’s

35=00100011(in Binary)
Bitwise Complement operation of 35
~00100011
--------------
11011100 =220 (in decimal)

#include <stdio.h>
int main()
{
printf("Output = %d\n",~35);
printf("Output = %d\n",~-12);
return 0;
}

Output
-36
11

• Right Shift Operator & Left shift Operator


Example
#include <stdio.h>
int main()
{
int num=212, i=3;
printf("Right shift by %d: %d\n", i, num>>i);
printf("\n");
printf("Left shift by %d: %d\n", i, num<<i);
return 0;
}

• Conditional Operator
C offers a ternary operator which is the conditional operator
(? : in combination) to construct conditional expressions.

conditional_expression ? expression1 : expression2;


This above statement works something like this:
• The 1st operand (here conditional expression), gets implicitly converted to Boolean
(bool) type (either true or false).
• When the 1st operand results to true, expression1 (which is the 2 nd operand) gets
evaluated, and
• When the 1st operand results to false, expression2 (which is the 3rd operand) get
evaluated.

Example
int number = 8;
(num%2 == 0) ? printf("Divisible by two") : printf("Not divisible by two");

• Special Operator in C
C supports some special operators

Operator Description

sizeof() Returns the size of a memory location.


& Returns the address of a memory location.

* Pointer to a variable.
• Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to
left.

Let's understand the precedence by the example given below:

int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before +
(additive operator).

The precedence and associativity of C operators is given below:

Operator Meaning of operator Associativity


() Functional call
[] Array element reference
Left to right
-> Indirect member selection
. Direct member selection
! Logical negation
~ Bitwise(1 's) complement
+ Unary plus
- Unary minus
++ Increment
Right to left
-- Decrement
& Dereference Operator(Address)
* Pointer reference
sizeof Returns the size of an object
(type) Type cast(conversion)
* Multiply
/ Divide Left to right
% Remainder

Operator Meaning of operator Associativity


+ Binary plus(Addition)
Left to right
- Binary minus(subtraction)
<< Left shift
Left to right
>> Right shift
< Less than
<= Less than or equal
Left to right
> Greater than
>= Greater than or equal
== Equal to
Left to right
!= Not equal to
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
Operator Meaning of operator Associativity
?: Conditional Operator Right to left
Simple assignment
=
Assign product
*=
Assign quotient
/=
Assign remainder
%=
Assign sum
-=
Assign difference Right to left
&=
Assign bitwise AND
^=
Assign bitwise XOR
|=
Assign bitwise OR
<<=
Assign left shift
>>=
Assign right shift
, Separator of expressions Left to Right
Example:
(i) 5+9*3^2-4>10 AND (2+2/4-8/4>6 OR (2<6 AND 10>11))
(ii) 2*3+4/2>3 AND 3<5 OR 10<9
(iii) a=6, b=3, c=4, d=1, e=2, f=10
a+b-(c+d)*3%e+f/9;
(iv) int i=3;
j=++i*++i*++i;
printf(“i=%d j=%d”,i,j);

• Type Conversion in expression

Type Conversion in C is used to convert a variable from one data type to another data type, and
after type casting compiler treats the variable as of the new data type.

Without Type conversion

#include <stdio.h>
main ()
{
int a;
a = 15/6;
printf("%d",a);
}

In the above C program, 15/6 alone will produce integer value as 2.

With Type Conversion


#include <stdio.h>
main ()
{
float a;
a = (float) 15/6;
printf("%f",a);
}

After type conversion is done before division to retain float value 2.500000.
MID TERM EXAMINATION
B.Tech Programmes
2nd Sem, May 2023
Paper Code:ES-102 Subject: Programming in C
Answer Key
Que1 (a) What is the ternary operator? Explain with an example? (CO1)(2.5)
Ans. Ternary operator in C is also known as the Conditional Operator. It is an operator which
takes three operands or variables, unlike the other operators which take one or two
operands. It is a way to shorten the simple if-else code of the block.
Syntax:
Condition?exp2:exp3

Working of Syntax:
• If the condition in the ternary operator is met (true), then the exp2 executes.
• If the condition is false, then the exp3 executes.

Example:
The following example explains the working of the Ternary Operator in C.
int max= 10>15?10:15

So, if the condition 10 > 15 is true (which is false in this case) max is initialized with
the value 10 otherwise with 15. As the condition is false so max will contain 15.

Que 1 (b)Find the output of the following program:- (CO1)(2.5)


Void main()
{int m=10,b,a;
a=++m;
b=m++;
a--;
--b;
a-=b;
printf(“%d”,a);}

Ans: int m=10,a,b; //This line declares variables a,b and m and assigns value 10 to
variable m
a=++m; //As this statement uses pre-increment operator so the value of a and m
after execution of this line will be a=11 and m=11
b=m++; //As this statement uses post-increment operator so the value of b and
m after execution of this line is b=11 m=12
a--; //After this statement the value of a is 10
--b; //After this statement the value of b is 10
a-=b; //This statement is equivalent to a=a-b. After execution the value of a
becomes 0
printf("%d",a); //This statement prints the value of a to the user.
So the output of the above code will be 0 (Zero)
Que 1(c) Differentiate between identifier and variable? (CO1)(2.5)
Ans. Identifiers are used for the naming of variables, functions, and arrays. It is a string
of alphanumeric characters that begins with an alphabet, or an underscore (_ ) that
are used for variables, functions, arrays, structures, unions, and so on. We cannot
use keywords as identifier as keywords are reserved for special use.
A variable is a name that points to a memory location. It is the basic unit of storage
in a program. The value of a variable can be changed during program execution. All
the operations are done on the variable effects that memory location. In C, all the
variables must be declared before use.

Difference Between Identifiers and Variables

Identifiers Variables
It is a unique name which is given to an A Variable is a name that is assigned to a
entity to distinctly identify it during the memory location, which is used to contain
execution of the source-code the corresponding value in it. Variables are
only the sort of identifiers.
C Code cannot have the same of two or All variables are identifiers whereas vice-
more identifiers. For example Structure versa isn’t true. The values can be Real, Char,
name, Function name, Enumerator name, String, Int, Float, Double, Unsigned, etc.
Union, etc. cannot be same.
An identifier name shouldn’t resemble The value that is stored in memory block can
with the keywords because keywords are be modified during the program
predefined. Double, Continue, float, else, execution. Similarly, as identifiers, two or
etc can’t be used as identifiers in a more variables also can’t have the same name
program. in a program.

Que 1 (d) Describe the complete execution of the C program?(CO1)(2.5)

Ans. The execution process of a C Program is as follows:


i) C program (source code) is sent to preprocessor first. The preprocessor is responsible
to convert preprocessor directives into their respective values. The preprocessor
generates an expanded source code.
ii) Expanded source code is sent to compiler which compiles the code and converts it
into assembly code.
iii) The assembly code is sent to assembler which assembles the code and converts it
into object code. Now a file with .obj extension is generated.
iv) This object code is sent to linker which links it to the library such as header files.
Then it is converted into executable code. Here a file with .exe extension is generated.
v) This executable code is sent to loader which loads it into memory and then it is
executed. After execution, output is displayed.

Que 1(e) Write an algorithm and design a flowchart to print the factorial of a
number?(CO1)(2.5)
Ans: Algorithm to display factorial of a number
Step 1: Start
Step 2: Read a number say n
Step 2: Initialize variables: i = 1, fact = 1
Step 3: if i <= n go to step 4 otherwise go to step 6
Step 4: Calculate fact = fact * i
Step 5: Increment the value of i by 1 (i=i+1) and go to step 3
Step 6: Print fact
Step 7: Stop

Flowchart to print factorial of a number

Start

Read n

i=1
fact=1

Is No
i<=
n

Yes
Print fact
fact=fact*i

Que 2 (a) Write a program in C to print the table of two using all three basic
loops?(CO2)(5) i=i+1 Stop

Ans. Program to print table of two using for Loop

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

Program to print table of two using While Loop

#include <stdio.h>
void main()
{
int num=2,i=1;
while(i<=10)
{
printf("%d * %d =%d\n",num,i,num*i);
i++;
}
}

Program to print table of two using Do-While Loop

#include <stdio.h>
void main() {
int num=2,i=1;
do
{
printf("%d * %d =%d\n",num,i,num*i);
i++;
}while(i<=10);
}

Que 2(b) Explain break, continue , goto and jump statements with an
examples?(CO2)(5)
Ans. The break, continue and goto statements are known as Jump Statements. These
statements are used to alter the normal flow of a program.
Sometimes there is a need to skip some statement/s inside loop or terminate the loop
immediately without checking the test expression. In such cases, break and continue
statements are used.
break statement
In C programming, break statement is used with conditional if statement. The break
is used in terminating the loop immediately after it is encountered. It is also used in
switch...case statement.
Example
#include<stdio.h>
void main(){
int num, sum=0;
int i,n;
printf("Note: Enter Zero for break loop!\n");
printf("Enter Number of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter num%d: ",i);
scanf("%d",&num);
if(num==0) {
break; /*this breaks loop if num == 0 */
printf("Loop Breaked\n");
}
sum=sum+num;
}
printf("Total is %d",sum);
}

continue statement
It is sometimes desirable to skip some statements inside the loop. In such cases,
continue statement is used. It is also used with if statement.
Example
#include<stdio.h>
void main()
{
int i,n;
printf("Enter Number of odd terms you want\n");
scanf("%d",&n);
for(i=1;i<=2*n;++i)
{
if(i%2==0)
continue;
printf(“%d”,i);
}}

goto statement
In C Language, goto statement is used for altering the normal sequence of program
execution by transferring control to some other part of the program.
Syntax:
goto label;
.............
.............
.............
label:
statement;

For Example
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
count: //This is Label
printf("%d\n",i);
i++;
if(i<=10) {
goto count; //This jumps to label "count:"
}
getch();
}

Q3.a) Explain the various categories of user-defined functions in C with examples?


(CO2)(5)
Ans. Various Categories of User Defined Functions in C
1. Function with no argument and no return type
2. Function with no argument and return type
3. Function with argument and no return type
4. Function with argument and return type

1)Function with no argument and no return type


This type of function does not take any argument and does not return any value to the
calling function.
# include <stdio.h>
#include <conio.h>
void add(); // Function Declaration
void main()
{
add(); //function call
getch();
}
// function definition
Void add()
{
Int a=5, b= 45;
Int c;
C=a+b;
Printf(“\n addition result : %d +%d =%d” , a,b,c);
}

2)Function with arguments and no return type


This type of function takes arguments but does not return any value to the calling
function
# include <stdio.h>
void add1(int a, int b); // Function Declaration
void main()
{
Int a=10, b=20;
Add1(a,b); //function call
}
// function definition
Void add1(int a, int b)
{
Int c;
c=a+b;
Printf(“\n addition result : %d +%d =%d” , a,b,c);
}

3)Function with no argument and return type


This type of function does not take any argument and returns value to the calling
function
# include <stdio.h>
#include <conio.h>
int add2(); // Function Declaration
void main()
{
Int c;
C=add2(); //function call
Printf(“ addition result :%d” , c);
getch();
}
// function definition
int add2()
{
Int a=5, b= 45;
Int c;
C=a+b;
return (c);
}
4)Function with arguments and return type
This type of function takes arguments but returns value to the calling function
# include <stdio.h>
int add3(int a, int b); // Function Declaration
void main()
{
Int c;
Int a=90, b=88;
C=add3(a,b); //function call
Printf(“\n addition result : %d +%d =%d” , a,b,c);

}
// function definition
int add3(int a, int b)
{
Int c;
c=a+b;
return c;
If Statement Switch Case Statement
This statement Can be used check multiple Switch Statements Can be used to check a
conditions at a time single condition at a time
If more conditions are used, it is more Even if the number of conditions increase,
difficult to understand switch statement is still easier to understand
It is popular for nesting of a loop It is not popular for nesting of a loop
It is used for comparing string vs string It is used for Comparing int, byte, char,
long, short, and enum
#include<stdio.h> #include <stdio.h>
main() void main()
{ {
int a = 15, b = 20; int num; // Input a number from user
if (b > a) printf("Enter any number to check even or
{ odd: "); scanf("%d", &num);
printf("b is greater"); switch(num % 2) // If n%2 == 0
} {
} case 0: printf("Number is Even");
break;
case 1: printf("Number is Odd");
break;
}}

Q 3 b) Differentiate between if and switch decision statements with an example.(CO2)(5)


Ques 4(a)Write the characteristics of an array? Write a program in C for adding two
matrices of the same size? (5) (CO3)
Ans: 1) An array holds elements that have the same data type.
2) Array elements are stored in subsequent memory locations.
3) Two-dimensional array elements are stored row by row in subsequent
memory locations.
4) Array name represents the address of the starting element.
5) Array size should be mentioned in the declaration. Array size must be a constant
expression and not a variable.
//* adding two matrices of the same size.
#include<stdio.h>
int main()
{
int mat1[3][3], mat2[3][3], i, j, mat3[3][3];
printf("Enter 3*3 matrix 1 elements :");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d",&mat1[i][j]);
}
printf("Enter 3*3 matrix 2 elements :");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d",&mat2[i][j]);
}
printf("\nAdding the two matrix.....");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
mat3[i][j]=mat1[i][j]+mat2[i][j];
}
printf("\nBoth matrix added successfully!");
printf("\nHere is the new matrix:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
printf("%d ", mat3[i][j]);
printf("\n");
}}

Que 4 (b) What will be the output of the following program?(CO3)(5)


Int main()
{Char srt1[20]= “Hello”, Str2[20]= “World”;
Printf(“%s\n”, strcpy(str2,strcat(str1,str2)));
Printf(“s\n”, strrev(str1));
Printf(“s\n”, strlen(str2));
return 0;}
Ans: Output of the program
Str1=”Hello” Str2=”World”
Statement1: printf(“%s\n”, strcpy(str2,strcat(str1,str2)));
Strcat(str1,str2) will concatenate the contents of both the strings and store in str1 so
str1= “HelloWorld” and strcpy(str2,strcat(str1,str2)) will copy the concatenated string
in str2 so after execution of the entire command str2 will become “HelloWorld”.
So, the above statement will print “Hello World”
Statement2: printf(“%s\n,strrev(str1));
It will reverse the contents of str1 which is “HelloWorld”
So, the above statement will print “dlroWolleH”
Statement3: printf(“%s\n,strlen(str2));
The above statement will give an error as strlen() returns an integer whereas the code
has used %s as format specified which is used to print string.
If the access specifier is assumed as %d then the above statement will return the
length of the string.
So, the above statement will print 10

You might also like