Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
18 views

C program assignment

Some questions and answers for c programming

Uploaded by

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

C program assignment

Some questions and answers for c programming

Uploaded by

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

NAME ESHAAN MANCHANDA

ROLL_NUMBER
PROGRAM MASTER_OF_COMPUTER_APPLICATIONS (MCA)
SEMESTER I
COURSE_CODE_&_NAM DCA6110, PROGRAMMING & PROBLEM-SOLVING
E USING C
(DCA6110_AUG_2024 MCA_Sem1)
SET - I
Question1.Describe the basic structure of a C program. Explain scanf() function with an
example.

Answer. :- A C introductory structure includes a number of important components.A


typical C program includes the ensuing rudiments

1. Directives for Preprocessors These lines, which start with #, are used to specify constants
or include libraries.
2. Function Delineations Every C program requires at least one function, generally called
main(), which serves as the entry point for program prosecution.
3. Variable Affirmations Before variables can be utilized in the program, they must be
declared., specifying their types( e.g., int, pier, housekeeper).
4. Statements and Expressions These are the factual instructions that the program executes,
including computations and control statements.
5. Statement of Return A return statement that returns an integer value—often 0—signaling
successful prosecution typically follows the main() function.

illustration of a Basic C Program

```int main(){
printf("Hello, World!");//Hello,World!
return 0; }```

An explanation of the function scanf()


Formatted input can be read from normal input, usually the keyboard, using the scanf( )
method. It enables drug users to input information into a program.

Here's how it operates: A format string that indicates the expected input format is the first
argument. The variables where the input data will be saved are indicated by the posterior
arguments.

illustration of scanf()

```int main(){
int age;//age
printf("Enter your age");
scanf("%d",&age);//enter_age
printf("You're %d times old.",age);
return 0;}```

In this example, the stoner is prompted to enter their age by the application. After reading
the input as an integer, the scanf() function stores it in the variable age. It eventually brings
the stoner back to life.
Que2. Decision control statements in C: what are they? Describe the many kinds of C
programming decision control statements.

Answer:- Decision control statements in C enable conditional execution of code


predicated on specific conditions. They guide the program to choose between multiple paths
of execution, adding sense and strictness.

Types of Decision Control Statements

1. if Statement
The if statement runs a block of code if the given condition is true; else, the block is
skipped.
Syntax
If ( condition){
/ code then if the condition is true

illustration
if( age> = 18){
printf(" Eligible to bounce.");}

2. if- else Statement


If the condition is true, the if - else statement runs one piece of code; if it is false, it runs
another block.
Syntax
If (condition ){
/ Execute the code if the condition is true.

differently{
/ code if the condition is false

3. if - else if - else Graduation


This structure allows the evaluation of multiple conditions in sequence. When the first
condition is met, the associated block of code will execute.
Syntax
if( condition1){
/ code for condition1

differently if( condition2){


/ code for condition2

differently{
/ additional code then

4. Nested if Statements
An if statement can be placed inside another if or else to check multiple conditions
crescively.
Syntax
if( condition1){
if( condition2){
/ code for both conditions true

5. switch Statement
The switch statement simplifies the execution of one out of multitudinous blocks of code
predicated on a variable's value. It’s necessary to multiple if- else statements for separate
values.
Syntax
Switch ( expression ){
case value1
// code for value1
Break ;
case value2
// code for value2
Break ;
dereliction
// additional code then

Question 3: What function do C storage classes serve? Talk about the various kinds of
storage classes that C offers.

Answer:-
Storage classes in C programming control a variable's scope, lifetime, visibility, and
default value. They specify the management, access, and storage of variables while a
program is running. Program modularity and efficient memory management depend on an
understanding of storage classes.

Purpose of Storage Classes


1. Scope : Specifies where the variable can be accessed in the program.
2. Lifetime : Defines how long the variable exists in memory.
3. Visibility : Determines whether a variable is accessible outside its defining
file or function.
4. Default Value: Indicates the value assigned to variables if not explicitly
initialized.
Types of Storage Classes in C
1. Automatic ( auto )
The auto class is the default for local variables defined inside functions or blocks.
Variables with this class are created when the block is entered and destroyed when it
exits.
 Scope: Local to the block.
 Lifetime: Exists during block execution.
 Default Value: Undefined (garbage).
 Example:
 void example() {
o auto int x = 5; // 'auto' is optional for local variables}
2. External (extern)
 The extern keyword is used to declare global variables or functions that can be
shared across files.
 The variable is defined in one file and referenced in others using extern.
 Scope : Global (accessible across files).
 Lifetime : Exists throughout program execution.
 Default Value : 0 for uninitialized variables.
 Example:
o // File1.c
o extern int globalVar; // Declaration
o int globalVar = 10; // Definition
3. Static
 The static class serves two purposes: retaining the value of local variables between
function calls and limiting the scope of global variables to the file in which they are
declared.
 Scope : Local for static local variables; file-level for global static variables.
 Lifetime : Entire program execution.
 Default Value : 0 for uninitialized variables.
 Example (local) :
o void counter() {
o static int count = 0; // Retains value between calls
o count++;
o printf("%d\n", count);}
 Example (global):
o static int globalVar = 5; // Only accessible within this file
4. Register
 The register class suggests storing a variable in a CPU register for faster access.
 It is limited to local variables and does not allow taking the variable’s address using
&.
 Scope : Local to the block.
 Lifetime : Exists during block execution.
 Default Value : Undefined (garbage).
 Example:
o void fastAccess() {
o register int x = 10;}
SET - II

Que4. What distinguishes call by reference in C from call by value? Give a relevant
example to illustrate the concept of recursion..

Answer:-
The distinction between C's Call by Reference and Call by Value

Call by Value
 This method involves passing the function a fake version of the factual variable.
 Changes made to the function's parameter have no effect on the original variable.
Because the original data is unaltered, this system is secure.
 Example
o ```void modify( int x){
o x = 20;// Only the dupe is modified
o int main(){
o int a = 10;
o modify( a);
o printf("%d", a);// Affair 10( unchanged)
o return 0;}```

Call by Reference
 In this approach, the address of the factual variable is passed to the function.
 Changes made to the parameter directly modify the original variable.
 This system is effective for handling large data structures as no data copying occurs.
 Example
o ```void modify( int * x){
o x = 20;// Original variable is modified
o int main(){
o int a = 10;
o modify( &a);
o printf("%d", a);// Affair 20( modified)
o return 0;}```

Recursion in C

Recursion refers to a function calling itself to break lower cases of a problem. Every
recursive function requires
1. A base case to terminate the recursion.
2. A recursive step reduces the problem’s size.

Example Calculating Factorial Using Recursion

// Recursive function for factorial


int factorial( int n){
if ( n == 0)// Base case
return 1;
return n * factorial( n- 1);// Recursive call
int main(){
int n = 5;
printf(" Factorial of %d is %d", n, factorial( n));
return 0;

How It Works
1. The base case( n == 0) ensures the recursion stops.
2. For factorial( 5), the function calculates
 5 * factorial ( 4)
 4 * factorial ( 3)
 3 * factorial ( 2)
 2 * factorial ( 1)
 1 * factorial ( 0)( returns 1 and ends recursion)
3. These results are multiplied during backtracking, performing in 120.

Que5. Give an example of pointer arithmetic and define pointers in C.


Hints in C

Answer .:-
A indicator is a variable in C that stores the mind address of another variable. Hands are
important tools for handling mind directly and are essential for tasks like dynamic mind
allocation, working out with arrays, and manipulating data structures. They also enable
effective parameter passing in places.

crucial Features of Hands


1. A indicator is declared utilizing the * hallmark.
2. The & driver retrieves the mind address of a variable.
3. The * driver, known as the dereference driver, accesses the value stored at the indicator's
address.

Example
o ```int main(){
o int a = 10;
o int * ptr = & a;// indicator stores the address of' a'

o printf("Value of a %d", a);// Affair 10


o printf("Address of a %p", &a);// Affair Address of' a'
o printf("Value through indicator %d ", * ptr);// Affair 10
o return 0; }```

indicator computation

indicator computation involves performing missions like extension and deduction on


hands. Since hands store mind addresses, these missions have conning through mind
locales.
manners of indicator computation
1. proliferation() Moves the indicator to the coming mind position, grounded on the size
of the data type.
2. diminishment(--) Moves the indicator to the former mind position.
3. extension/ Deduction( or-) Adjusts the indicator by a special number of rudiments.

Example
o ```int main(){
o int arr() = { 10, 20, 30, 40};
o int * ptr = arr;// indicator to the first component of the batch
o printf("original value %d ", * ptr);// Affair 10
o ptr;// shift to the coming component
o printf(" After proliferation %d", * ptr);// Affair 20
o ptr = 2;// shift two rudiments ahead
o printf(" After extension %d", * ptr);// Affair 40
o ptr--;// shift to the former component
o printf(" After diminishment %d", * ptr);// Affair 30
o return 0; }```

elucidation
1. indicator computation is performed in way determined by the size of the data type. For
case, incrementing a indicator to an int( 4 bytes) moves the address forth by 4 bytes.
2. This point is especially useful for covering arrays or repeating over mind blocks in an
effective manner.
Q.6.a) In C, what distinguishes union from structure?

Answer: - Structures and Unions in C


Structures and couplings are stoner- outlined data manners in C that group variables
of nonidentical manners. still, they differ in how they allow and take mind.
Features Structures Unions
Memory Allocation Allocates separate memory for All members share the same
each member. memory location.
Access All members share the same Only one member can hold a
memory location. value at a time.
Modification Changing one member does not Changing one member
affect others. overwrites the value of others.
Use Case Used for grouping related data Used when only one member
where all members are needed is active at a time to save
at the same time. memory.
Size The size of a structure is the The size of a union is equal to
sum of the sizes of its the size of its largest member.
members.
initialization All members can be initialized Only the first member can be
separately. initialized.

Structure
A structure allows grouping variables of nonidentical manners, each having its own mind
position.

Example
o ```struct Pupil{
o int id;
o float marks;
o };

o int main(){
o struct Pupil s= { 1, 85.5};
o printf(" ID %d", s.id);
o printf("Marks %2f ", s.marks);
o return 0; }```

elucidation
In the below illustration, id and jokes are stored in separate mind locales, allowing
independent access.

Union

A union also groups variables of nonidentical manners, but all ingredients partake the
same mind position. Only one member can store a value at a time.
Example

o ```union Data{
o int i;
o float f; };

o int main(){
o union Data d;
o d.i= 10;// Assign value to' i'
o printf(" Integer %d ", d.i);

o d.f= 5.5;// Assign value to' f'


o printf("float %2f ", d.f);
o return 0;}```

elucidation
Then, d.i and d.f partake the same mind. When f is assigned, the value in i is overwritten.

Q.6.b) Explain various functions used in dynamic memory allocation.

Answer:-
Places in C for Dynamic Mind Allocation
For data structures whose size is unknown at collect time, dynamic mind allocation in C
gives programs the option to demand mind during runtime. There are multiple locations for
dynamic mind allocation and deallocation in the C Standard Library.

Then are the main places exercised for dynamic mind allocation in C
1. malloc () ( Mind Allocation )

 Purpose Allocates a prescribed number of bytes of mind.


 Syntax
o void * malloc( size_t size);

 Parameters size- the number of bytes to allow.


 Return Value
 responses a indicator to the first byte of the distributed mind block.
 If mind allocation fails, it returns NULL.
 operation
o malloc() does n't initialize the distributed mind; the content is
undetermined( scrap valuations).

Example
o int * ptr = ( int *) malloc( 5 * sizeof( int));// distributing mind for 5 integers
o if( ptr == NULL){
o printf(" Mind allocation failed.");
2. calloc () ( conterminous Allocation )

 Purpose Allocates mind for an batch of rudiments, initializing them to zero.


 Syntax
o void * calloc( size_t num_elements, size_t element_size);

 Parameters
 num_elements Number of rudiments to allow.
 element_size Size of each component in bytes.
 Return Value
 responses a indicator to the distributed mind.
 responses NULL if the allocation fails.
 operation
o calloc() initializes the mind to zero, which can be useful when you need
initialized mind.

Example
o int * ptr = ( int *) calloc( 5, sizeof( int));// distributing mind for 5 integers and
initializing to 0
o if( ptr == NULL){
o printf(" Mind allocation failed.");

3. realloc () ( Redistribution)

 Purpose Resizes a preliminarily distributed mind block to a new size.


 Syntax
o void * realloc( void * ptr, size_t new_size);

 Parameters
 ptr indicator to the preliminarily distributed mind block.
 new_size The new size, in bytes, to which the mind block should be resized.
 Return Value
 responses a indicator to the recently distributed mind.
 If the redistribution fails, it returns NULL, and the initial mind block remains
unchanged.
 operation
o realloc() is exercised to expand or reduce the size of an being mind
block. It may remove the mind block to a new position if necessary.

illustration

o int * ptr = ( int *) malloc( 5 * sizeof( int));// original allocation for 5 integers
o ptr = ( int *) realloc( ptr, 10 * sizeof( int));// Resize to 10 integers
o if( ptr == NULL){
o printf(" Redistribution failed.");

4. free() ( Deallocation)

 Purpose Frees the stoutly distributed mind, returning it to the system.


 Syntax
o void free( void * ptr);

 Parameters ptr- indicator to the stoutly distributed mind block.


 Return Value
 This function does n't return any value.
 operation
o free() is called to deallocate mind that was preliminarily distributed
utilizing malloc(), calloc(), or realloc(). It helps help mind leaks by
icing that mind is released when it's noway longer demanded.

Example

o int * ptr = ( int *) malloc( 5 * sizeof( int));// Allocate mind


o free( ptr);// Deallocate mind when no longer demanded

Summary of places

- malloc() Allocates mind but does not initialize it.


- calloc() Allocates mind and initializes it to zero.
- realloc() Resizes preliminarily distributed mind.
- free() Deallocates mind and returns it to the system.

You might also like