0% found this document useful (0 votes)
2 views13 pages

Computer Assignment

The document provides an overview of key programming concepts in C, including pointers, arrays, recursion, structures, and string manipulation. It includes code examples for each concept, demonstrating their usage and functionality. Additionally, it explains differences between call by value and call by reference, as well as the definitions of arguments and parameters in functions.

Uploaded by

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

Computer Assignment

The document provides an overview of key programming concepts in C, including pointers, arrays, recursion, structures, and string manipulation. It includes code examples for each concept, demonstrating their usage and functionality. Additionally, it explains differences between call by value and call by reference, as well as the definitions of arguments and parameters in functions.

Uploaded by

rmrashedul750
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1. Write down the concept of pointer with an example.

Concept of Pointer
A pointer is a special variable in programming (commonly in C/C++) that stores
the memory address of another variable.
Instead of holding a data value directly, a pointer holds where the data is located
in memory.

Pointers are used for:

 Efficient array and string handling


 Dynamic memory allocation
 Passing large data structures to functions
 Creating complex data structures like linked lists, trees, etc.

Example in C
#include <stdio.h>

int main() {
int num = 10; // normal integer variable
int *ptr; // pointer variable that can store address of an int
ptr = &num; // assigning address of num to ptr

printf("Value of num = %d\n", num);


printf("Address of num = %p\n", &num);
printf("Value stored in ptr (address of num) = %p\n", ptr);
printf("Value pointed to by ptr = %d\n", *ptr); // dereferencing

return 0;
}

Output Explanation

 ptrstores the address of num.


 *ptr accesses the value stored at that address (which is 10).
2. What is an array. How to initialize and declaration. Write down the different way to
access array elements

What is an Array?
An array in C is a collection of elements of the same data type stored in contiguous
(continuous) memory locations.
Each element in an array can be accessed using an index, starting from 0.

Example:
Instead of writing

int a0, a1, a2, a3, a4;

you can use

int a[5];

Array Declaration
Declaring an array means telling the compiler its data type, name, and size.

Syntax:

data_type array_name[size];

Example:

int numbers[5]; // array of 5 integers

Array Initialization
You can initialize an array in several ways.

1. Initialization at the time of declaration


int a[5] = {10, 20, 30, 40, 50};

2. Partial initialization (rest become 0)


int a[5] = {10, 20}; // remaining elements = 0, 0, 0
3. Without specifying size
int a[] = {1, 2, 3, 4};

4. Initialize after declaration


int a[3];
a[0] = 5;
a[1] = 10;
a[2] = 15;

Different Ways to Access Array Elements in C


1. Using Indexing (Direct Access)
printf("%d", a[2]); // prints 3rd element

2. Using a for loop


for(int i = 0; i < 5; i++) {
printf("%d ", a[i]);
}

3. Using Pointers

Array name works like a pointer to the first element.

int *p = a;
printf("%d", *(p + 2)); // prints a[2]

4. Using Array Name as Pointer


printf("%d", *(a + 3)); // prints a[3]

5. Using Pointer Loop


int *p = a;
for(int i = 0; i < 5; i++) {
printf("%d ", *(p + i));
}
Simple Complete Example Program
#include <stdio.h>

int main() {
int a[5] = {10, 20, 30, 40, 50};

printf("Access using index:\n");


printf("%d\n", a[2]);

printf("Access using loop:\n");


for(int i = 0; i < 5; i++) {
printf("%d ", a[i]);
}

printf("\nAccess using pointer:\n");


int *p = a;
for(int i = 0; i < 5; i++) {
printf("%d ", *(p + i));
}

return 0;
}

3. Write down the concept of recursion. Write a code for recursion and simulate each step or
n=5.

Concept of Recursion
Recursion is a programming technique in which a function calls itself to solve a
smaller part of the same problem.
Every recursive function must have:

1. Base Case → the stopping condition


2. Recursive Case → the function calls itself with a smaller value

Example problems solved using recursion: factorial, Fibonacci, sum of digits, etc.

C Program Using Recursion (Factorial of n)


#include <stdio.h>

int fact(int n) {
if(n == 0) // base case
return 1;
else
return n * fact(n - 1); // recursive call
}

int main() {
int n = 5;
printf("Factorial of %d = %d", n, fact(n));
return 0;
}

Step-by-Step Simulation for n = 5


We will simulate: fact(5)

Step 1

fact(5)
= 5 * fact(4)

Step 2

fact(4)
= 4 * fact(3)

Step 3

fact(3)

= 3 * fact(2)

Step 4

fact(2)
= 2 * fact(1)

Step 5

fact(1)
= 1 * fact(0)
Step 6 (Base Case Reached)
fact(0) = 1

Now return values step-by-step (backtracking phase):


From Step 6 back to Step 5:

fact(1) = 1 * fact(0)
=1*1
=1

From Step 5 back to Step 4:

fact(2) = 2 * fact(1)
=2*1
=2

From Step 4 back to Step 3:

fact(3) = 3 * fact(2)
=3*2
=6

From Step 3 back to Step 2:

fact(4) = 4 * fact(3)
=4*6
= 24

From Step 2 back to Step 1:

fact(5) = 5 * fact(4)
= 5 * 24
= 120

Final Answer
Factorial of 5 = 120
4. What do you understand by structure? Write a code of by using structure to sow your
name, id and university name.

In C programming, a structure (struct) is a user-defined data type that allows you to


combine data of different types under one name.
It is used to group related information together. For example, a student may have a
name (string), ID (integer), and university name (string). A structure lets you store all
this data in one variable.

C Program Using Structure to Show Name, ID, and University Name


#include <stdio.h>

// Define a structure
struct Student {
char name[50];
int id;
char university[100];
};

int main() {
// Create a structure variable
struct Student s;

// Taking input from user


printf("Enter your name: ");
fgets([Link], sizeof([Link]), stdin);

printf("Enter your ID: ");


scanf("%d", &[Link]);
getchar(); // to clear newline from buffer

printf("Enter your University name: ");


fgets([Link], sizeof([Link]), stdin);

// Displaying the data


printf("\n--- Student Information ---\n");
printf("Name: %s", [Link]);
printf("ID: %d\n", [Link]);
printf("University: %s", [Link]);

return 0;
}

How This Works

 struct Student creates a new data type.


 Variables name, id, and university are grouped together.
 You can store and display multiple pieces of information using one variable (s).
5. What is Fibonacci series. implement a c program with simulation for the first five
steps

What is the Fibonacci Series?


The Fibonacci series is a sequence of numbers where:
 The first two terms are 0 and 1
 Every next term is the sum of the previous two
F (n)=F (n−1)+ F (n−2)
So the beginning of the series is:
0, 1, 1, 2, 3, 5, 8, ...

✅ C Program With Simulation for First Five Steps


#include <stdio.h>

int main() {
int a = 0, b = 1, c;

printf("Fibonacci Simulation for First Five Steps:\n");

// Step 1
printf("Step 1: %d\n", a);

// Step 2
printf("Step 2: %d\n", b);

// Step 3
c = a + b;
printf("Step 3: %d = %d + %d\n", c, a, b);
a = b;
b = c;

// Step 4
c = a + b;
printf("Step 4: %d = %d + %d\n", c, a, b);
a = b;
b = c;

// Step 5
c = a + b;
printf("Step 5: %d = %d + %d\n", c, a, b);

return 0;
}

✅ Output Simulation
Fibonacci Simulation for First Five Steps:
Step 1: 0
Step 2: 1
Step 3: 1 = 0 + 1
Step 4: 2 = 1 + 1
Step 5: 3 = 1 + 2

6. Build a code in C program that counts the vowels in a given string.

C Program: Count Vowels in a String


#include <stdio.h>
#include <ctype.h>

int main() {
char str[200];
int i, count = 0;

// Input string
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

// Count vowels
for (i = 0; str[i] != '\0'; i++) {
char ch = tolower(str[i]); // Convert to lowercase for easy comparison
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}

printf("Number of vowels: %d\n", count);

return 0;
}

7. Build a code in C program that counts the consonants in a given string.

C Program to Count Consonants in a String


#include <stdio.h>
#include <ctype.h>

int main() {
char str[200];
int i, count = 0;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

for (i = 0; str[i] != '\0'; i++) {


char ch = tolower(str[i]);
if (ch >= 'a' && ch <= 'z') { // Check if alphabet
if (ch != 'a' && ch != 'e' && ch != 'i' &&
ch != 'o' && ch != 'u') { // Not a vowel → consonant
count++;
}
}
}

printf("Number of consonants: %d\n", count);


return 0;
}

8. Interpret the differences between typedef and define (Programing C)


The below table lists the primary differences between typedef and
#define:
Aspect typedef #define

Defines a constant or macro that


typedef creates a new type replaces identifiers in the code
alias for an existing type. with predefined values or
Purpose expressions.

Compiler checks type safety No type checking and acts as a


Type for aliases defined using text substitution during
Checking typedef. preprocessing.

Follows C variable scoping Global scope so visible


Scope rules (block or global). throughout the program.

Debuggi Easier to debug as it retains Harder to debug due to direct


ng type information. text substitution.

Used for defining type Used for creating constants,


aliases, especially for macros, or simple text
Usage complex or pointer types. replacements.

Requires specifying type


Simple substitution syntax (e.g.,
information (e.g., typedef
#define MAX 100).
Syntax int myInt;).

9. Differentiate between call by value and call by reference.


The below table lists the primary differences between the Call by Value and Call by Reference:
Feature Call by Value Call by Reference

In this method, the value of the In call by reference, reference to the variable is
Value Passed
variable is passed to the function. passed.

The original value remains


The changes made are reflected in the original
Scope of Changes unchanged even when we make
variable.
changes in the function.

It requires extra memory and time It is more memory and time efficient as it does
Performance
to copy so less efficient. not create a copy.

The memory addresses of the


The actual and the formal parameters point at
Memory Location actual and formal parameters are
the same memory address.
different.

Mainly used to pass values for


It is used when we want to modify the original
Applications small data or when we do not want
value or save resources.
to change original values.

10. Define argument and parameter of a function in c programming language.

In C programming, the terms argument and parameter are closely related but refer to
different things in a function.

Parameter

 A parameter is a variable in the function definition.


 It acts as a placeholder to receive a value when the function is called.
 Parameters exist only inside the function (local scope).
 Example:
void add(int x, int y) // x and y are parameters
{
printf("%d", x + y);
}

Argument

 An argument is the actual value or expression passed to the function when calling it.
 Arguments are assigned to the parameters.
 Example:

add(5, 3); // 5 and 3 are arguments

11. Show 10 most common build in functions of string and write down their working principle
in your own words.

1) len()
Counts how many characters are present in the string, including spaces and punctuation.
2) .upper()
Converts every letter in the string to uppercase without affecting numbers or symbols.
3) .lower() :
Turns all alphabetic characters in the string into lowercase.
4) .strip()
Removes any whitespace (spaces, newlines, tabs) from the beginning and end of the
string.
5) .replace(old, new)
Searches for a part of the string and replaces every occurrence of that part with
something else.
6) .split(separator)
Breaks the string into a list of smaller strings based on a separator (default separator is
space).
7) .join(iterable)
Takes a list (or any iterable) of strings and stitches them together into a single string,
placing the current string between each element.
8) .find(substring)
Looks for a substring and returns the index where it first appears. Returns -1 if not found.
9) .startswith(prefix)
Checks if the string begins with a particular sequence of characters and returns True or
False.
10) .isdigit()
Checks whether every character in the string is a digit. Returns True if all characters are
numbers.

You might also like