0% found this document useful (0 votes)
12 views36 pages

DS QP

The document outlines a curriculum for an Introduction to Programming course, covering fundamental topics in C programming, computer organization, algorithms, and data types. It includes a list of questions and answers related to the structure of C programs, basic computer organization, algorithm characteristics, and various data types in C. Additionally, it provides programming exercises such as checking for prime numbers and file operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views36 pages

DS QP

The document outlines a curriculum for an Introduction to Programming course, covering fundamental topics in C programming, computer organization, algorithms, and data types. It includes a list of questions and answers related to the structure of C programs, basic computer organization, algorithm characteristics, and various data types in C. Additionally, it provides programming exercises such as checking for prime numbers and file operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIVERSAL COLLEGE OF ENGINEERING & TECHNOLOGY (AUTONOMOUS)

I B.Tech I Sem (UR24)


Subject Name: Introduction to programming Code: UR241107
Staff Name: V. Siva Nandini, P. Radha Rani

Questions

1. Explain the Structure or Parts of C Program.


2. Explain Basic Organization of a Computer.
3. Define Algorithm. Explain the key Features/Characteristics of Algorithms.
4. Explain the basic Data Types in “C”.
5. Problem solving strategies
6. Explain Decision Control Statements in C.
7. Explain Looping Statements in C.
8. Define Array. Explain Declaration & Initialization, Accessing.
9. Explain One Dimensional Array with an Example.
10. Define String. Explain Character Functions in C.
11. Define Pointer. Explain with an Example.
12. Explain Dynamic Memory allocation in C
13. Explain the Difference between Structures and Unions.
14. Define Function. Explain Different types of functions in C.
15. Explain Call by Value and Call by Reference.
16. Define File. Explain File Operations and File Handling Functions in C.
17. Write a c program to check whether given number is prime or not
18. Write a c program to copy the contents of one file to another file
Questions and answers

1.Explain the Structure or Parts of C Program.

Documentation Section
Preprocessor Directive Section
Link Section
Definition Section
Global Declaration Section
Main() Function Section
{
Declaration Part
Executable Part
}
Sub Program Section
Function 1
Function 2 User Defined Functions

Function N

Documentation Section:
The documentation section consists of a set of comment lines giving the name
of the program, the author, and other details.
This will help other programmers to understand your program code quickly. The
Documentation section contains the following information.
 @Project Name
 @Author Name
 @Created Date
 @Program Description, etc.
/* some comments */ – Whatever is inside /*——-*/ are not compiled and executed;
they are only written for user understanding or for making the program interactive by
inserting a comment line. These are known as multiline comments. Single line
comments are represented with the help of 2 forward slashes “//——”.

Preprocessor directives:
In a C program, the statements which are starting with the “#” symbol are
called preprocessor directives. The C program provides a lot of inbuilt preprocessor
directives that are handled by the pre-processor before the compiler starts execution.

What are preprocessor directives?


When we write and compile a C program, the application building process will
start, where the C Compiler will come into action to convert the high-level code
(human understandable) into binary code (Machine understandable).

The application building process won’t be carried out by a single program


called the compiler. There are multiple programs involved in this process. Such as
preprocessor, Assembler, Compiler, and Linker.
Link Section:
The link section provides instructions to the compiler to link functions from the
system library.

Definition section:
The definition section defines all symbolic constants.

Global Declaration Section:


There are some variables that are used in more than one function. Such
variables are called global variables and are declared in the global declaration section
that is outside of all the functions. This section also declares all the user- defined
functions. The Statements present in Global Declaration Section will be accessible by
all the functions in the program.
Function:
A function is a self-contained block of code that performs a specific task. It is
not possible to write a C program without a function. Every function in a C program
must start with Open curly brace “{” and ends with Closed curly brace “}”.

Main () Function Section:


Every C program must have one main function section. This section contains two
parts; the declaration part and the executable part
 Declaration part: The declaration part declares all the variables used in the
executable part.
 Executable part: There is at least one statement in the executable part.
These two parts must appear between the opening and closing braces. The
program execution begins at the opening brace and ends at the closing brace. The
closing brace of the main function is the logical end of the program. All statements in
the declaration and executable part end with a semicolon.

Subprogram Section:
The subprogram section contains all the user-defined functions that are called
in the main () function. User-defined functions are generally placed immediately after
the main () function, although they may appear in any order. All sections, except the
main () function section, may be absent when they are not required.
Statement: A statement is a line of code in a c program and every statement
should end with a semicolon “;”.
Return statement: The return statement is basically used in the c program to return
a value from a function. In C programming, we use functions to achieve modularity.

2.Explain Basic Organization of a Computer.

The basic organization of a computer involves several key components and their
interactions to perform various tasks. Here's an overview of the primary components
and their functions in a typical computer organization:

Central Processing Unit (CPU):


 The CPU is the brain of the computer, responsible for executing
instructions and performing calculations.
 It consists of the control unit, which manages the execution of instructions,
and the arithmetic logic unit (ALU), which performs mathematical and logical
operations.
 The CPU fetches instructions from memory, decodes them, and executes
them in a sequence.
Memory:
 Memory stores data and instructions that the CPU uses during operations.
 There are two main types of memory:
 RAM (Random Access Memory): This is volatile memory used for temporary storage
of data and program code while the computer is running. It allows for fast read and
write access.
 ROM (Read-Only Memory): This is non-volatile memory that contains firmware or
software instructions that are permanently stored and cannot be modified by the
user.

Measurement Units for Data:


 1 Bit = 0 or 1
 1 Nibble= 4 Bits
 1 Byte= 8 Bits
 1 KB (Kilo Byte) = 1024 Bytes (210)
 1 MB (Megabyte) = 1024 KB (1024 X 1024 Bytes)
 1 GB (Gigabyte) = 1024 MB
 1 TB (Terabyte) = 1024 GB
 1 PB (Petabyte) = 1024 TB
 1 EB (Exabyte) = 1024 PB
 1 ZB (Zettabyte) = 1024 EB

Storage Devices:
 Storage devices, such as hard drives (HDDs) and solid-state drives (SSDs),
provide long-term, non-volatile storage for data and programs.
 Unlike RAM, data on storage devices persists even when the computer is
powered off.
 These devices typically use secondary storage media, like magnetic disks or
flash memory.

Input Devices:
 Input devices, like keyboards, mice, touchscreens, and microphones, allow users
to interact with the computer by providing input data.
 They convert user actions or data into digital signals that the computer can
process.
Output Devices:
 Output devices, such as monitors, speakers, and printers, present
information to the user in a human-readable form.
 They convert digital data generated by the computer into a format that can
be perceived by humans.

Motherboard:
 The motherboard is the main circuit board that houses and connects all the
computer's components.
 It contains the CPU socket, memory slots, expansion slots, and various
connectors for peripheral devices.

Expansion Cards:
 Expansion cards are additional circuit boards that can be installed on the
motherboard to enhance a computer's capabilities.
 Common examples include graphics cards, sound cards, and network interface
cards (NICs)
Bus System:
 Buses are communication pathways that allow data and instructions to flow
between different components of the computer.
 The system bus connects the CPU to memory and peripheral devices,
facilitating data transfer.

Power Supply Unit(PSU):


 The PSU provides electrical power to the computer by converting external AC
power into the DC power required by the components.
 It distributes power to various parts of the computer through connectors.

Operating System (OS):


 The operating system is system software that manages computer
hardware and provides services to software applications.
 It controls tasks like memory management, file management, and
device management, allowing users to interact with the computer.
Software:
 Software includes applications, programs, and operating system components
that run on the computer.
 It provides the functionality and utility for various tasks, such as word
processing, web browsing, and gaming.

Program Counter:
Program Counter is a register in a computer processor that contains the
address (location) of the instruction being executed at the current time. As each
instruction gets fetched, the program counter increases its stored value by 1. After
each instruction is fetched, the program counter points to the next instruction in the
sequence. When the computer restarts or is reset, the program counter normally
reverts to 0.
Instruction Fetch:
During the execution of a program, the CPU needs to retrieve instructions from
memory to execute them. The PC is responsible for pointing to the memory location
(address) of the next instruction to be fetched.
Incrementing:
After an instruction is fetched, the PC is typically incremented to point to the
next memory address where the subsequent instruction is stored. In most computer
architectures, instructions are stored sequentially in memory, so incrementing the PC
by the appropriate number of bytes ensures that the CPU fetches the next instruction.
Branching:
The PC can also be modified by certain control instructions, such as branch
instructions. Branch instructions allow the CPU to change the value of the PC,
effectively altering the flow of program execution. This is how conditional statements,
loops, and function calls are implemented in a program. When a branch instruction is
encountered, the PC is set to a new address specified by the instruction.
Program Execution:
The CPU fetches the instruction at the memory address pointed to by the PC,
decodes the instruction, and executes it. This process repeats in a cycle, with the PC
continually advancing to the next instruction until the program's termination condition
is met.

3.Define Algorithm. Explain the key Features/Characteristics of


Algorithms.

Algorithm is a step-by-step procedure, which defines a set of instructions to be


executed in a certain order to get the desired output. Algorithms are generally
created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.
Following are some important categories of algorithms −
 Search − Algorithm to search an item in a data structure.
 Sort − Algorithm to sort items in a certain order.
 Insert − Algorithm to insert item in a data structure.
 Update − Algorithm to update an existing item in a data structure.
 Delete − Algorithm to delete an existing item from a data structure.
Key Features / Characteristics of an Algorithm:
An algorithm should have the following characteristics −
 Unambiguous (Unmistakable) − Algorithm should be clear and
unambiguous. Each of its steps (or phases), and their inputs/outputs should
be clear and must lead to only one meaning.
 Input − an algorithm should have 0 or more well-defined inputs.
 Output − an algorithm should have 1 or more well-defined outputs,
and should match the desired output.
 Finiteness − Algorithms must terminate after a finite number of steps.
 Feasibility − should be feasible with the available resources.
 Independent − an algorithm should have step-by-step directions,
which should be independent of any programming code.

There are many ways to solve most problems and also many solutions to
most problems.
Algorithm to add two numbers.
Step 1: Read two numbers n1 and
n2. Step 2: sum = n1 + n2
Step 3:
Print sum
Step 4:
Stop
Algorithm to find largest number from two numbers.
Step 1: Read two numbers n1 and
n2. Step 2: If n1 > n2 then
Big = n1
else
Big = n2
Step 3:
Print Big
Step 4:
Stop
Algorithm to find largest number from three numbers
Step 1: Read three numbers n1, n2
and n3. Step 2: If n1 > n2 and n1 >
n3 then
Big = n1
Else
If n2 > n1 and n2 >
n3 then Big = n2
else
Big = n3
Step 3: Print Big Step 4: Stop
Algorithm to find smallest number from three numbers.
Step 1: Read three numbers n1, n2
and n3 Step 2: If n1 < n2 and n1 < n3
then
Small = n1
Else If n2 < n1 and n2 < n3
then Small = n2
else
Small = n3
Step 3: Print Small Step 4: Stop
4. Explain the basic Data Types in “C”.

Data type is a special keyword used to allocate sufficient memory space for the
data, in other words Data type is used for representing the data in main memory
(RAM) of the computer.
In general every programming language is containing three categories of data
types. They are
 Fundamental or primitive data types
 Derived data types
User defined data types.

Primitive data types


Primitive data types are those whose variables allows us to store only one
value but they never allows us to store multiple values of same type. This is a
data type whose variable can hold maximum one value at a time.
Example

int a; // valid
a=10; // valid
a=10, 20, 30; // invalid

Here "a" store only one value at a time because it is primitive type variable.

Derived data types


Derived data types are those whose variables allow us to store multiple values of
same type. But they never allows to store multiple values of different types. These are
the data type whose variable can hold more than one value of similar type. In general
derived data type can be achieve using array.

Example

int a[] = {10,20,30}; // valid


int b[] = {100, 'A', "ABC"}; // invalid

Here derived data type store only same type of data at a time not store
integer, character and string at same time.

Integer category data types


These category data types are used for storing integer data in the main
memory of computer by allocating sufficient amount of memory space.
Integer category data types are divided into four types which are given in
following table
Data Type Size Range
1 Byte 1 + 127 to -128
2 Short 2 + 32767 to -32768
3 Int 4 + x to - (x+1)
4 Long 8 + y to - (y+1)
Character category data types
A character is an identifier which is enclosed within single quotes. In C to
represent character data, we use a data type called char. This data type takes
two byte since it follows Unicode character set.

Data Type Size(Byte) Range


Char 2 232767 to -32768
Float category data types
Float category data type are used for representing float values. This
category contains two data types; they are in the given table

Data Type Size Number of decimal places

Float 4 8
Double 8 16
Boolean category data types
Boolean category data type is used for representing or storing logical
values is true or false. In java programming to represent Boolean values or
logical values, we use a data type called Boolean.

Data Type Default size


boolean 1 bit
Enumeration Data type:
Enumeration is a user defined datatype in C language. It is used to assign
names to the integral constants which make a program easy to read and maintain.
The keyword “enum” is used to declare an enumeration.

The following is the way to define the enum in C:

enum flag{integer_const1, integer_const2, integter_constN};

In the above declaration, we define the enum named as flag containing 'N' integer
constants. The default value of integer_const1 is 0, integer_const2 is 1, and so on. We
can also change the default value of the integer constants at the time of the
declaration.

For example:
enum fruits{mango, apple, strawberry, papaya};
The default value of mango is 0, apple is 1, strawberry is 2, and papaya is 3.
If we want to change these default values, then we can do as given below:
enum
fruits{ ma
ngo=2,
apple=1,
strawberr
y=5,
papaya=7
,
};

The following are the Example for Enumerated Data type:


#include<stdio.h>
enum month{January=1,February,March};
main()
{
enum month
m; m=January;
printlf(“\n January is:%d”,m);
printf(“\n March is:%d”,March);
printf(“\n”);
}
Output:

5.Problem solving startegies

Top-Down Approach:
Modularization: In the top-down approach, you start by defining the main function
or the high-level structure of your program. Then, you decompose the problem into
smaller functions or modules that each address a specific part of the problem.
Function Hierarchy: You create a hierarchy of functions, with the main function at
the top and lower-level functions at the bottom. The main function typically calls these
lower-level functions to accomplish the overall task.
Stepwise Refinement: You gradually refine each function, filling in the details and
implementing the logic for that particular part of the problem.
Testing: You can test each function independently to ensure that it works correctly.
This top-down approach makes it easier to isolate and fix issues in smaller, more
manageable pieces of code.
Integration: Finally, you integrate all the functions together to create the complete
program.
Bottom-Up Approach:
Start with Details: In the bottom-up approach, you begin by implementing small,
individual functions or components that perform specific tasks or calculations. These
functions are often created without a clear idea of how they will fit into the larger
program.
Emergent Structure: As you implement these individual functions, you begin to
identify common patterns or needs for coordination. The overall program structure
starts to emerge from the aggregation of these smaller components.
Testing: You test each individual function as you create it, ensuring that it works
correctly in isolation.
Assembly: You gradually assemble these functions into a coherent program
structure, creating the main function or control flow that utilizes the individual
components.
Refinement: As you integrate the components, you may need to refine and adapt
them to work together seamlessly.

6. Explain Decision Control Statements in C.

Decision making structures have one or more conditions to be evaluated or tested by


the program, along with a statement or statements that are to be executed if the
condition is determined to be true, and optionally, other statements to be executed if
the condition is determined to be false.
Following is the general form of a typical decision-making structure found in most
of the programming languages
If Statement:
This is a control statement to execute a single statement or a block of code,
when the given condition is true and if it is false then it skips if block and rest code of
program is executed.

Syntax:
if (conditional expression)
{
<statements>;
...;
...;
}

Example:
If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so
if block is executed. Hence "This is even number" is printed on the screen.

int n = 10;
if(n%2 = =
0){
printf("This is even number");
}
If-else Statement:

The "if-else" statement is an extension of if statement that provides another option


when 'if' statement evaluates to "false" i.e. else block is executed if "if" statement is
false.

Syntax:
if (conditional expression) {
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
Example:
If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to
1 that is not equal to 0 so else block is executed. So "This is not even number" is
printed on the screen.

int n = 11;
if(n%2 = =
0){
printf ("This is even number");
}
else{
printf ("This is not even number");
}

Else-if ladder
Statements which will be executed always as you can see in this else-if ladder,
conditions are evaluated from top. First condition-1 will be evaluated and if this is
true, the code inside the if block will be executed. If condition-1 is false, condition-2
will be evaluated. If condition-2 is true, the code inside that else if block will be
executed. If condition-2 is false, condition-3 will be evaluated. This will go on like this.
If none of the conditions are true, the code inside the else block will be executed.

Syntax:
If (condition-1) {
Statements which will be executed if condition-1 is true
}
else if (condition-2) {
Statements which will be executed if condition-2 is true
}
.
.
else if (condition-n)
{
Statements which will be executed if condition-n is true
}
else
{
Statements which will be executed if none of the conditions in condition-1,
condition2,…condition-n are true.
}

// Sample program on else if ladder


int a=10,b=20,c=30,d=40;
if(a>b && a>c && a>d)
printf ("The biggest Number is:"+a);
else if(b>a && b>c && b>d)
printf ("The biggest Number is:"+b);
else if(c>a && c>b && c>d)
printf ("The biggest Number is:"+c);
else
printf ("The biggest Number is:"+d);
Nested if-else statement
You can combine multiple if / if-else / else-if ladders when a series of decisions
are involved. So you can make sure that your program executes certain instructions
when a series of conditions are met.

Syntax:
If(condition1)
{ If(conditio
n2) {
If(condition
3) {
Statements in condition3:
}
else
Statements in else;
}}

Example:
// Sample program to display the text by using NestedIf
int a=10,b=5,c=11;
if(a>0)
{
if(b>0)
{
if(c%2==0)
printf (" C value is
even"); else
printf (" C value is odd");
}
}

Switch Statement
This is an easier implementation to the if-else statements. The keyword
"switch" is followed by an expression that should evaluates to byte, short, char or int
primitive data types only. In a switch block there can be one or more labeled cases.
The expression that creates labels for the case must be unique. The switch expression
is matched with each case label.
Only the matched case is executed, if no case matches then the default statement (if
present) is executed.

Syntax:
switch (control expression)
{

case expression 1:
<stateme
nt>;
break
;

case expression 2:
<statement>;
break;
...
...

case expression n:
<statement>;
break;

default:
<statement>;
}//end switch

Example: Here expression "day" in switch statement evaluates to 5 which matches


with a case labeled "5" so code in case 5 is executed that results to output "Friday"
on the screen.

int day =
5; switch
(day)
{ case 1:
printf
("Monday");
break;
case 2:
printf ("Tuesday");
break;
case 3:
printf
("Wednesday");
break;
case 4:
printf ("Thursday");
break;
case 5:
printf
("Friday");
break;
case 6:
printf ("Saturday");
break;
case 7:
printf
("Sunday");
break;
default:
printf ("Invalid entry");
break;
}

7. Explain Looping Statements in C.

Looping statements are the statements execute one or more statement repeatedly
several number of times. In C programming language there are three types of loops;
while, do-while and for loop.
while loop:
This is a looping or repeating statement. It executes a block of code or a
statement till the given condition is true. The expression must be evaluated to a
Boolean value. It continues testing the condition and executes the block of code.
When the expression results to false control comes out of loop.

Syntax:
while (test condition)
{
body of the loop
}

Example:
Here expression i<=10 is the condition which is checked before entering into
the loop statements. When i is greater than value 10 control comes out of loop and
next statement is executed. So here i contain value "1" which is less than number
"10" so control goes inside of the loop and prints current value of i and increments
value of i. Now again control comes back to the loop and condition is checked. This
procedure continues until i become greater than value "10". So this loop prints values
1 to 10 on the screen.
int i = 1;
//print 1 to 10
while (i <= 10)
{
printf("%d:",
i); i++;
}

Do-while loop:
This is another looping statement that tests the given condition past so you can say
that the do-while looping statement is a past-test loop statement. First they do block
statements are executed then the condition given in while statement is checked. So
in this case, even the condition is false in the first attempt, do block of code is
executed at least once.

Syntax:
do
{
<statement>;
...;
...;
}while (expression);

Example:
Here first do block of code is executed and current value "1" is printed then the
condition i<=10 is checked. Here "1" is less than number "10" so the control comes
back to do block. This process continues till value of i becomes greater than 10.
int
i =
1;
do
{
printf("%d:",
i); i++;
}while(i <= 10);

For loop:
This is also a loop statement that provides a compact way to iterate over a
range of values. From a user point of view, this is reliable because it executes the
statements within this block repeatedly till the specified conditions are true.

Syntax:
for (initialization; condition; increment or decrement)
{
<statement>;
...;
...;
}

initialization: The loop is started with the value specified.


Condition: It evaluates to either 'true' or 'false'. If it is false then the loop is
terminated.

Increment or decrement: After each iteration, value increments or decrements.

Example:
Here num is initialized to value "1", condition is checked whether num<=10. If
it is so then control goes into the loop and current value of num is printed. Now num is
incremented and checked again whether num<=10.If it is so then again it enters into
the loop. This process continues till num>10. It prints values 1 to10 on the screen.

for (int num = 1; num <= 10; num++)


{
printf("%d:",num);
}

8. Define Array. Explain Declaration & Initialization, Accessing.

An array is defined as the collection of similar type of data items stored at


contiguous memory locations. Array is a kind of data structure that can store a fixed-
size sequential collection of elements of the same type.
Declaration of Array:
To declare an array in C, a programmer specifies the type of the elements and
the number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimensional array. The arraySize must be an integer
constant greater than zero and type can be any valid C data type.
For example, to declare a 10-element array called numbers of type int, use
this statement −
int numbers[10];
Here numbers is a variable array which is sufficient to hold up to 10 integer
numbers.
Initialize Array Elements:
It is also possible to initialize the array at the time of declaration.
The syntax to initialize the array at the time of declaration is,
Datatype arrayname[] = {List of Values};
Example: int marks[] = {15,20,18,17,12};
Accessing Array Elements:
An element are accessed by indexing the array name. This is done by placing
the index of the element within square brackets after the name of the array.

For Example −
double salary = balance[9];
The above statement will take the 10th element from the array and assign the
value to salary variable.

9. Explain One Dimensional Array with an Example.


One dimensional array is an array that has only one subscript specification that is
needed to specify a particular element of an array. A one-dimensional array is a
structured collection of components (often called array elements) that can be
accessed individually by specifying the position of a component with a single index
value.
Syntax: data-type arr_name[array_size];
Rules for Declaring One Dimensional Array
 An array variable must be declared before being used in a program.
 The declaration must have a data type (int, float, char, double, etc.), variable
name, and subscript.
 The subscript represents the size of the array. If the size is declared as 10,
programmers can store 10 elements.
 An array index always starts from 0. For example, if an array variable
is declared as s[10], then it ranges from 0 to 9.
 Each array element stored in a separate memory location.
Initialization of One-Dimensional Array in C
An array can be initialized at either following states:
 At compiling time (static initialization)
 Dynamic Initialization
Compiling time initialization:
The compile-time initialization means the array of the elements are initialized
at the time the program is written or array declaration.
Syntax: data_type array_name [array_size]=(list of elements of an
array);
Example: int n[5]={0, 1, 2, 3, 4};

#include<st
dio.h> int
main()
{
int n[5]={0, 1, 2, 3, 4};
printf("%d", n[0]);
printf("%d", n[1]);
printf("%d", n[2]);
printf("%d", n[3]);
printf("%d", n[4]);
}

Run time initialization:


Run time initialization means the array can be initialized at runtime. That
means array elements are initialized after the compilation of the program.

#include<st
dio.h> int
main()
{
int a[5],i;
printf("Enter Array Elements");
for(i=0;i<5;i++);
{
scanf("%d",&a[i]);
}
printf("The Elements are");
{
for(i=0;i<5;i++);
{
printf("%d",a[i]);
}
}}
Output:

10. Define String. Explain Character Functions in C.


Strings are actually one-dimensional array of characters terminated by a null character
'\0'. This null character indicates the end of the string. Strings are always enclosed by
double quotes. Whereas, character is enclosed by single quotes in C. Example for C
String:
 char string[20] = {‘s’, ’e’, ‘s’, ‘h’, ‘u’, ‘_’, ‘r’, ‘e’, ‘p’, ’u’, ‘d’, ‘i’, ‘\0’};
(or)
 char string[20] = “seshu_repudi”;
(or)
 char string [] = “seshu_repudi”;
Difference between above declarations are, when we declare char as “string[20]”,
20 bytes of memory space is allocated for holding the string value. When we declare
char as “string[]”, memory space will be allocated as per the requirement during
execution of the program.
The following are the example program:
#include
<stdio.h> int
main () {
char name[6] = {'S', 'e', 's', 'h', 'u', '\
0'}; printf("My Name is: %s\n",
name ); return 0;
}
Output:
My Name is:
Seshu
String Functions:
string.h header file supports all the string functions in C language. All the string functions are given
below.

String Functions Description


strcat ( ) Concatenates str2 at the end of str1

strcpy ( ) Copies str2 into str1

strlen ( ) Gives the length of str1

Returns 0 if str1 is same as str2. Returns <0 if


strcmp ( )
strl < str2. Returns >0 if str1 > str2
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase

strrev ( ) Reverses the given string

strcat( ) Function :
strcat() function in C language concatenates two given strings. It concatenates
source string at the end of destination string.
Syntax: char * strcat (char * destination, const char * source);

Example:
strcat( str2, str1 ); - str1 is concatenated at the end of str2.
strcat( str1, str2 ); - str2 is concatenated at the end of str1.

As you know, each string in C is end with null character (‘\0′).

In strcat( ) operation, null character of destination string is overwritten by source


string’s first character and null character is added at the end of new destination string
which is created after strcat() operation.
strcpy( ) Function :
strcpy( ) function copies contents of one string into another string.
Syntax: char * strcpy(char * destination, const char * source);
Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
 If destination string length is less than source string, entire source string value
won’t be copied into destination string.
 For example, consider destination string length is 20 and source string length is
30. Then, only 20 characters from source string will be copied into destination string
and remaining 10 characters won’t be copied and will be truncated.

strlen( ) Function :
strlen( ) function is used to find the length of a character string.
Example: int n;
char st[20] = “Seshu”;
n = strlen(st);
This will return the length of the string 5 which is assigned to an integer variable n.
Note that the null character “\0‟ available at the end of a string is not counted.
strcmp( ) Function :
strcmp( ) function in C compares two given strings and returns zero if they are
same. If length of string1 < string2, it returns < 0 value. If length of string1 >
string2, it returns > 0 value.
Syntax: int strcmp (const char * str1, const char * str2);
strcmp( ) function is case sensitive. i.e., “A” and “a” are treated as different
characters.

Example:
char name[20] =
“Seshu”; char
town[20] =
“Guntur”;
strcmp(name, town);
int n;
n = strcmp(name, town);

strlwr() function :
strlwr() function converts a given string into lowercase.
Syntax : char *strlwr(char *string);
strlwr() function is non standard function which may not available in standard library
in C
Example:
#include<stdio.h>
#include<string.h> int main()
{
char str[ ] = “HI to all”; printf(“%s\n”,
strlwr (str)); return 0;
}

Output:
hi to all
strupr() function :
strupr() function converts a given string into uppercase.
Syntax : char *strupr(char *string);
strupr() function is nonstandard function which may not available in standard
library in C.

Example:

#include<stdio.h>
#include<string.h> int main()
{
char str[ ] = “hi to all”; printf(“%s\n”,
strupr(str)); return 0;
}

Output:
HI TO ALL

strrev() function :
strrev() function reverses a given string in C language.
Syntax : char *strrev(char *string);
strrev() function is non standard function which may not available in standard
library in C.
Example :
char name[20]=”ftl”; then
strrev(name)= ltf
Example:

#include<stdio.h>
#include<string.h> int main()
{
char name[30] = “Hello”;
printf(“String before strrev( ) : %s\n”, name); printf(“String after strrev( ) :
%s”, strrev(name)); return 0;
}

Output:
String before strrev( ) : Hello
String after strrev( ) : olleH

11. Define Pointer. Explain with an Example.

The pointer in C language is a variable which stores the address of another variable.
This variable can be of type int, char, array, function or any other pointer. The size of
the pointer depends on the architecture. However, in 32-bit architecture the size of a
pointer is 2 bytes.

Consider the following example to define a pointer which stores the address of an
integer.
int n = 10;
int* p = &n; // Variable p of type pointer is pointing to the address of the variable n
of type integer.

Declaring a Pointer:
The pointer in c language can be declared using * (asterisk symbol). It is also
known as indirection pointer used to dereference a pointer.

int *a;//pointer to int


char *c;//pointer to
char Pointer
Example:
An example of using pointers to print the address and value is given below.

Here the pointer variable stores the address of number variable, i.e., fff4. The value of
number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

The pointer example as explained for the above figure.


#include<stdio.h
> void main()
{
int
number=5
0; int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the
number therefore printing p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to
dereference a pointer therefore if we print *p, we will get the value stored at the
address contained by p.
getch();
}
Output:
Address of p variable is fff4
Value of p variable is 50

Dereferencing and Address Operators:


Dereferencing and address operators are concepts commonly used in
programming, especially in languages that support pointers. Let's discuss these
concepts:

Address Operator (&):


The address operator, represented by the symbol "&" in many programming
languages, is used to obtain the memory address of a variable.
For Example:
int x = 10;
int *ptr = &x; // &x gets the address of variable x

In this example, &x retrieves the memory address where the variable x is stored,
and the address is assigned to the pointer variable ptr.

Dereference Operator (*):


The dereference operator, represented by the symbol "*" in many languages, is
used to access the value stored at a particular memory address through a pointer.

For example:
int x = 10;
int *ptr = &x; // ptr holds the address of x
int value = *ptr; // *ptr dereferences the pointer to get the value stored at
that address (value will be 10)

Here, *ptr retrieves the value stored at the memory address held by the pointer
ptr.

Combined Use:
The address and dereference operators are often used together when working
with pointers.

For Example:
int x = 10;
int *ptr = &x; // ptr holds the address of x
*ptr = 20; // *ptr dereferences the pointer to access the value at
that address and assigns it a new value (x is now 20)

In this case, *ptr is used to access the value at the memory address held by the
pointer, allowing you to modify the value stored at that address.

Pointer and Address Arithmetic:


Pointer and address arithmetic are concepts closely related to the use of
pointers in programming languages, particularly in languages like C.

Pointer Arithmetic:
In C, you can perform arithmetic operations on pointers. This is particularly
useful when working with arrays or dynamically allocated memory.

For Example:
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the beginning of the array.
// Incrementing the pointer moves to the next element in the array.
ptr++; // Now, ptr points to the second element of the
array.
// Decrementing the pointer moves to the previous
element ptr--; // Now, ptr is back to the first element.
// Adding an integer to a pointer moves it forward by that many elements
ptr = ptr + 2; // Now, ptr points to the third element of the array.

The actual size of the increment or decrement depends on the data type the
pointer is pointing to. For instance, if ptr is a pointer to an int, incrementing ptr moves
it by the size of an int.

Address Arithmetic:
Address arithmetic involves performing arithmetic operations directly on
memory addresses.

For Example:
int x = 10;
int *ptr = &x; // ptr holds the address of x

// Adding an integer to a memory address


int *newPtr = ptr + 1; // newPtr now holds the address offset by the size of an int

// Subtracting an integer from a memory address


int *prevPtr = ptr - 1; // prevPtr holds the address offset by the size of an int in the
opposite direction

12. Explain Dynamic Memory allocation in C

The concept of dynamic memory allocation in c language enables the C programmer


to allocate memory at runtime. Dynamic memory allocation in c language is possible
by 4 functions of stdlib.h header file.
 malloc ()
 calloc ()
 realloc ()
 free ()
Difference between Static Memory allocation and Dynamic
Memory allocation

Static Memory allocation Dynamic Memory allocation

Memory is allocated at compile time. Memory is allocated at run time.

Memory can't be increased while Memory can be increased while


executing program. executing program.

Used in array. Used in linked list.

malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of
bytes.

Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));

The above statement allocates 400 bytes of memory. It's because the size of
float is 4 bytes. And, the pointer ptr holds the address of the first byte in the allocated
memory.

calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized,
whereas the calloc() function allocates memory and initializes all bits to zero.

Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of
type float.

realloc()
If the dynamically allocated memory is insufficient or more than required, you
can change the size of previously allocated memory using the realloc() function.

Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
free()

Dynamically allocated memory created with either calloc() or malloc() doesn't


get freed on their own. You must explicitly use free() to release the space.

Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.

Drawbacks of pointers in C:
 Uninitialized pointers might cause segmentation(division) fault.
 Dynamically allocated block needs to be freed explicitly. Otherwise, it
would lead to memory leak.
 Pointers are slower than normal variables.
If pointers are updated with incorrect values, it might lead to memory
corruption.

13. Explain the Difference between Structures and Unions.

Structure Union
 You can use a struct keyword to  You can use a union keyword to
define a structure. define a union.
 Every member within structure is  In union, a memory location is
assigned a unique memory location. shared by all the data members.
 Changing the value of one data  Changing the value of one data
member will not affect other data members member will change the value of other
in structure. data members in union.
 It enables you to initialize several  It enables you to initialize only the
members at once. first member of union.
 The total size of the structure is the  The total size of the union is the size of
sum of the size of every data member. the largest data member.

 It is mainly used for storing various  It is mainly used for storing one of
data types. the many data types that are available.

 It occupies space for each and every  It occupies space for a member
member written in inner parameters. having the highest size written in inner
parameters.
 You can retrieve any member at a  You can access one member at a
time. time in the union.
 It supports flexible array.  It does not support a flexible array.

14. Define Function. Explain Different types of functions in C.

A function is a group of statements that together perform a task. Every C program has
at least one function, which is main ().

In C, we can divide a large program into the basic building blocks known as function.
The function contains the set of programming statements enclosed by { }. A function
can be called multiple times to provide reusability and modularity to the C program. In
other words, we can say that the collection of functions creates a program.
Advantage of functions in C
 By using functions, we can avoid rewriting same logic/code again and again in a
program.
 We can call C functions any number of times in a program and from any place in
a program.
 We can track a large C program easily when it is divided into multiple functions.
 Reusability is the main achievement of C functions.

Function Aspects:
There are three aspects of a C function.
 Function declarations A function must be declared globally in a C program to
tell the compiler about the function name, function parameters, and return
type.
 Function call Function can be called from anywhere in the program. The
parameter list must not be different in function calling and function declaration.
 Function definition It contains the actual statements which are to be
executed. It is the most important aspect to which the control comes when the
function is called. Here, we must notice that only one value can be returned
from the function.

SN C function aspects Syntax


Function return_type function_name (argument list);
1
declaration
2 Function call function_name (argument_list)
return_type function_name (argument list)
3 Function definition {
function body;
}

The syntax of creating function in c language is given below:

return_type function_name(data_type parameter...)


{
//code to be executed
}
Types of Functions:
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files
such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C
programmer, so that he/she can use it many times. It reduces the complexity of
a big program and optimizes the code.

Return Value:
A C function may or may not return a value from the function. If you don't
have to return any value from the function, use void for the return type.
Let's see a simple example of C function that doesn't return any value from the
function.

Example without return value:

void hello()
{ printf("hello
c");
}
If you want to return any value from the function, you need to use any data
type such as int, long, char, etc. The return type depends on the value to be returned
from the function.
Let's see a simple example of C function that returns int value from the function.

Example with return value:

int get(){
return 10;
}
In the above example, we have to return 10 as a value, so the return type is int.
If you want to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use
float as the return type of the method.

float get(){
return 10.2;
}
Now, you need to call the function, to get the value of the function.
Different aspects of function calling:
A function may or may not accept any argument. It may or may not return any
value. Based on these facts, there are four different aspects of function calls.

 function without arguments and without return value


 function without arguments and with return value
 function with arguments and without return value
function with arguments and with return value

Example for Function without argument and return value:

#include<stdio.h>
void sum();
void main()
{
printf("\n Calculating the sum of two numbers:");
sum();
}
void sum() // Function without arguments and without return value.
{
int a,b;
printf("\nEnter two
numbers"); scanf("%d
%d",&a,&b); printf("The
sum is %d",a+b);
}

Example for Function without argument and with return value:


#include<stdio.h>
int sum();
void main()
{
int result;
printf("\n Calculating the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum() // Function without arguments and with return value
{
int a,b;
printf("\nEnter two
numbers"); scanf("%d
%d",&a,&b); return a+b;
}
Example for Function with argument and without return value:
#include<stdio
.h> void
sum(int, int);
void main()
{
int a,b,result;
printf("\n Calculating the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b) // Function with argument and without return value
{
printf("\nThe sum is %d",a+b);
}
Example for Function with argument and with return value:

#include<stdio
.h> int
sum(int, int);
void main() {
int a,b,result;
printf("\n Calculating the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d
%d",&a,&b); result =
sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b) // Function with arguments and with return value
{
return a+b;
}

15. Explain Call by Value and Call by Reference.

Functions can be invoked in two ways: Call by Value or Call by Reference. These
two ways are generally differentiated by the type of values passed to them as
parameters.
The parameters passed to the function are called actual parameters whereas
the parameters received by the function are called formal parameters.

Call by Value
In call by value method of parameter passing, the values of actual parameters
are copied to the function’s formal parameters.
There are two copies of parameters stored in different memory locations. One is the
original copy and the other is the function copy. Any changes made inside functions
are not reflected in the actual parameters of the caller.

Example:
The following example demonstrates the call-by-value method of parameter passing
// C program to illustrate call by
value #include <stdio.h>
// Function
Prototype void
swapx(int x, int y);

// Main
function int
main(){
int a = 10, b = 20;
// Pass by Values
swapx(a, b); // Actual Parameters
printf("In the Caller:\na = %d b = %d\n", a, b);
return 0;
}
// Swap functions that swaps
// two values
void swapx(int x, int y) // Formal Parameters
{
int
tem
p;
tem
p=
x; x
= y;
y = temp;
printf("Inside Function:\nx = %d y = %d\n", x, y);
}

Call by Reference
In call by reference method of parameter passing, the address of the actual
parameters is passed to the function as the formal parameters.Both the actual and
formal parameters refer to the same locations.
Any changes made inside the function are actually reflected in the actual
parameters of the caller.

Example:
The following C program is an example of a call-by-reference method.
// C program to illustrate Call by Reference
#include <stdio.h>
// Function
Prototype void
swap(int*, int*);
// Main
function int
main(){
int a = 10, b = 20;
// Pass reference
swap(&a, &b); // Actual Parameters
printf("Inside the Caller:\na = %d b = %d\n", a, b);
return 0;
}
// Function to swap two variables
// by references
void swap(int* x, int* y) // Formal Parameters
{
int
temp;
temp
= *x;
*x = *y;
*y = temp;
printf("Inside the Function:\nx = %d y = %d\n", *x, *y);
}

16. Define File. Explain File Operations and File Handling Functions in
C.

We may require some specific input data to be generated several numbers of times.
Sometimes, it is not enough to only display the data on the console.
The data to be displayed may be very large, and only a limited amount of data can be
displayed on the console, and since the memory is volatile, it is impossible to recover
the programmatically generated data again and again.
However, if we need to do so, we may store it onto the local file system which is
volatile and can be accessed every time. Here, comes the need of file handling in C.
File handling in C enables us to create, update, read, and delete the files stored
on the local file system through our C program.

The following operations can be performed on a file.


 Creation of the new file
 Opening an existing file
 Reading from the file
 Writing to the file
 Deleting the file

Function Description
fopen() opens new or existing file
fprintf() write data into the file
fscanf() reads data from the file
fputc() writes a character into the file
fgetc() reads a character from file
fclose() closes the file
fseek() sets the file pointer to given position

fputw() writes an integer to file


fgetw() reads an integer from file
ftell() returns current position
rewind() sets the file pointer to the beginning of the file

fopen()

We must open a file before it can be read, write, or update. The fopen()
function is used to open a file. The syntax of the fopen() is given below.

FILE *fopen( const char * filename, const char * mode );

The fopen() function accepts two parameters:


The file name (string). If the file is stored at some specific location, then we
must mention the path at which the file is stored.
For example, a file name can be like "c://some_folder/some_file.ext".

The mode in which the file is to be opened. It is a string.

fclose()
The fclose() function is used to close a file. The file must be closed after
performing all the operations on it.

The syntax of fclose() function is given below:


int fclose( FILE *fp );

We can use one of the following modes in the fopen() function

Mode Description

r opens a text file in read mode

w opens a text file in write mode

a opens a text file in append mode

r+ opens a text file in read and write mode

w+ opens a text file in read and write mode

a+ opens a text file in read and write mode

rb opens a binary file in read mode

wb opens a binary file in write mode

ab opens a binary file in append mode

rb+ opens a binary file in read and write mode

wb+ opens a binary file in read and write mode

ab+ opens a binary file in read and write mode

Consider the following example which opens a file in write mode.


#include<stdio.h
> void main( )
{
FILE *fp
; char
ch ;
fp = fopen("file_handle.c","r") ;
while ( 1 )
{
ch = fgetc (
fp ) ; if ( ch
== EOF )
break ;
printf("%c",c
h) ;
}
fclose (fp ) ;
}

fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is
used to write data into file at desired location.

Syntax:
int fseek(FILE *stream, long int offset, int whence)

#include
<stdio.h> void
main()
{
FILE *fp;
fp =
fopen(“sss.txt","w+");
fputs("This is Seshu",
fp); fseek( fp, 7,
SEEK_SET );
fputs(“Harshitha", fp);
fclose(fp);
getch();
}

17. write a c program to check whether given number is prime or not


#include <stdio.h>

int main() {
int num, i, isPrime = 1;

printf("Enter a number: ");


scanf("%d", &num);

if (num <= 1) {
isPrime = 0;
} else {
for (i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
isPrime = 0;
break;
}
}
}

if (isPrime)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);

return 0;
}

18.write a c program to copy the contents of one file to another file


#include <stdio.h>

int main() {
FILE *sourceFile, *targetFile;
char source[100], target[100];
char ch;

// Get file names


printf("Enter source file name: ");
scanf("%s", source);
printf("Enter target file name: ");
scanf("%s", target);

// Open source file in read mode


sourceFile = fopen(source, "r");
if (sourceFile == NULL) {
printf("Cannot open source file.\n");
return 1;
}

// Open target file in write mode


targetFile = fopen(target, "w");
if (targetFile == NULL) {
printf("Cannot open target file.\n");
fclose(sourceFile);
return 1;
}

// Copy content character by character


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, targetFile);
}

printf("File copied successfully.\n");

fclose(sourceFile);
fclose(targetFile);

return 0;
}

You might also like