Week6_17.6.23

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 26

Week 6

Pre-Lab
Q-1:What is a 1D array in C?

In C, a 1D array is a linear collection of elements of the same data type that are stored in
contiguous memory locations. It is called a "1D" array because it has a single dimension, meaning
it is represented as a single row or line of elements.
The elements in a 1D array are accessed using an index value that represents their position in the
array. The index of the first element is typically 0, and the index of the last element is the size of
the array minus one.
Here's an example declaration of a 1D array in C:
int numbers[5]; // Declaration of a 1D array of integers with a size of 5
In this example, numbers is the name of the array, and it can hold five integer values. The elements
of the array can be accessed using the index notation, such as numbers[0], numbers[1], and so on
1D arrays are commonly used in C to store and manipulate a collection of similar data, such as a
list of numbers, characters, or any other data type. They provide a convenient way to organize and
access data sequentially.
Q-2:How do you declare and initialize a 1D array in C?
To declare and initialize a 1D array in C, we can use the following syntax.
dataType arrayName[arraySize] = {element1, element2, ..., elementN};
Here's an example that demonstrates the declaration and initialization of a 1D array in C:
#include <stdio.h>
int main() {
// Declaration and initialization of a 1D array of integers
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing and printing array elements
for (int i = 0; i < 5; i++) {
printf("Element %d: %d\n", i, numbers[i]);
}
return 0;
}
In this example, we declare an integer array named numbers with a size of 5. The elements of the
array are then initialized with the values 10, 20, 30, 40, and 50.
The for loop is used to iterate over the array and print each element along with its index.
When declaring and initializing a 1D array, make sure to specify the data type of the elements
(dataType in the syntax) and provide the appropriate array size (arraySize in the syntax). The
number of elements in the initializer list should match the size of the array to avoid any unexpected
behavior.
Q-3:How do you access elements of a 1D array in C?
In C, you can access elements of a 1D array using the index notation. The index represents the position
of the element within the array, starting from 0 for the first element. Here's an example that
demonstrates how to access elements of a 1D array:
#include <stdio.h>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
// Accessing and printing array elements
printf("Element 0: %d\n", numbers[0]);
printf("Element 1: %d\n", numbers[1]);
printf("Element 2: %d\n", numbers[2]);
printf("Element 3: %d\n", numbers[3]);
printf("Element 4: %d\n", numbers[4]);
return 0;
}

In this example, we have an integer array named numbers with elements {10, 20, 30, 40, 50}. The
elements are accessed using the index notation, where numbers[0] refers to the first element,
numbers[1] refers to the second element, and so on
The output of the program will be:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50
You can also use variables or expressions as indices to access array elements dynamically. For example:
int index = 2;
printf("Element %d: %d\n", index, numbers[index]);
int index = 2;
printf("Element %d: %d\n", index, numbers[index]);
In this case, the value of the index variable determines which element will be accessed and printed.
Just keep in mind that array indices should be within the valid range of the array (0 to size-1) to
avoid accessing out-of-bounds memory locations, which can lead to undefined behavior or runtime
errors.
Q-4:Can you change the size of a 1D array dynamically in C? If yes, how? If no, why not?
In C, the size of a 1D array cannot be changed dynamically once it has been declared. Once you define
an array with a specific size, that size is fixed and cannot be altered during the runtime of the program.

The reason for this limitation is that arrays in C are allocated as contiguous blocks of memory, and the
size of the array determines the amount of memory reserved for it. Modifying the size of the array
would require allocating a new block of memory with the desired size and copying the existing
elements to the new location. This process is not supported for statically allocated arrays in C.
If you need a resizable collection of elements in C, you can consider using dynamic memory allocation
and pointers to achieve similar functionality. The malloc, calloc, and realloc functions provided by the
C standard library can be used to allocate and reallocate memory dynamically.
Here's an example of dynamically allocating memory for a resizable array in C:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size = 5;
int* numbers = (int*)malloc(size * sizeof(int));
// Use the dynamically allocated array
// If you need to resize the array
size = 10;
numbers = (int*)realloc(numbers, size * sizeof(int));
// Use the resized array
// Don't forget to free the memory when you're done
free(numbers);
return 0;}
In this example, we initially allocate memory for size number of integers using malloc. Later, if we
need to resize the array, we can use realloc to adjust the size to a new value.
Remember to check the return values of malloc and realloc for successful allocation and to free the
dynamically allocated memory using free when you're finished using it to avoid memory leaks.
Q-5:How do you pass a 1D array to a function in C?

In C, you can pass a 1D array to a function by specifying the array name as an argument. Additionally,
you need to provide the size of the array explicitly or use a sentinel value to indicate the end of the
array within the function. Here's an example of how to pass a 1D array to a function:
#include <stdio.h>
// Function that takes a 1D array as a parameter
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
// Call the function and pass the array as an argument
printArray(numbers, sizeof(numbers) / sizeof(numbers[0]));
return 0;}
In this example, the printArray function is defined to accept an integer array arr as its parameter, along
with the size of the array. Within the function, we can access the elements of the array using the index
notation.
In the main function, we declare an integer array named numbers and initialize it with some values.
Then, we call the printArray function, passing numbers as the array argument and using
sizeof(numbers) / sizeof(numbers[0]) to determine the size of the array. This calculation ensures that the
correct size is passed to the function, even if the size of the array changes.
When passing a 1D array to a function, you can omit the size parameter if you include a sentinel value
in the array itself. For example, you can use a specific value (like -1) as the last element of the array to
indicate the end. Inside the function, you can iterate through the array until the sentinel value is
encountered.
#include <stdio.h>
// Function that takes a 1D array as a parameter with a sentinel value
void printArray(int arr[]) {
int i = 0;
while (arr[i] != -1) {
printf("%d ", arr[i]);
i++;
}
printf("\n");
}
int main() {
int numbers[] = {10, 20, 30, 40, 50, -1};

// Call the function and pass the array as an argument


printArray(numbers);

return 0;
}
In this modified example, the printArray function takes the integer array arr as its parameter, and
we iterate through the array until we encounter the sentinel value -1.
Both approaches allow you to pass a 1D array to a function in C. The choice between specifying
the size or using a sentinel value depends on the requirements and design of your program.

In-Lab:
1.You are given a large integer represented as an integer array digits, where each
digits[i] is the ith digit of the integer. The digits are ordered from most significant to
least significant in left-to-right order. The large integer does not contain any
leading 0's.
Increment the large integer by one and return the
resulting array of digits.
https://leetcode.com/problems/plus-one/description/
int* plusOne(int* digits, int digitsSize, int* returnSize){
for (int i = digitsSize - 1; i >= 0; i--) {

digits[i]++;

if (digits[i] == 10) {
digits[i] = 0;
}

else {
*returnSize = digitsSize;
return digits;
}
}
int* result = (int*)malloc((digitsSize + 1) * sizeof(int));
result[0] = 1;
for (int i = 1; i <= digitsSize; i++) {
result[i] = 0;
}

*returnSize = digitsSize + 1;
return result;

}
2.Most programmers will tell you that one of the ways to improve your performance in
competitive programming is to practice a lot of problems.
Our Chef took the above advice very seriously and decided to set a target for himself.
Chef decides to solve at least 10 problems every week for 4 weeks.

Given the number of problems he actually solved in each week over 4 weeks as P1,P2,P3
, and P4, output the number of weeks in which Chef met his target.

Input Format

There is a single line of input, with 4 integers P1,P2,P3, and P4. These are the number
of problems solved by Chef in each of the 4 weeks.

Output Format

Output a single integer in a single line - the number of weeks in which Chef solved at
least 10 problems.
Further details…
https://www.codechef.com/problems/PRACTICEPERF

#include <stdio.h>
int main(void) {
// your code goes here
int arr[4],i,count=0;
for(i=0;i<4;i++){
scanf("%d",&arr[i]);
}
for(i=0;i<4;i++){
if(arr[i]>=10)
count++;
}
printf("%d",count);
return 0;
}
3.Code Chef recently revamped its practice page to make it easier for users to
identify the next problems they should solve by introducing some new
features:Recent Contest Problems - contains only problems from the last 2 contests
Separate Un-Attempted, Attempted, and All tabs
Problem Difficulty Rating - the Recommended dropdown menu has various
difficulty ranges so that you can attempt the problems most suited to your
experience Popular Topics and Tags
Like most users, Chef didn’t know that he could add problems to a personal to-
do list by clicking on the magic '+' symbol on the top-right of each problem
page. But once he found out about it, he went crazy and added loads of
problems to his to-do list without looking at their difficulty rating.
Chef is a beginner and should ideally try and solve only problems with difficulty
rating strictly less than
1000. Given a list of difficulty ratings for problems in the Chef’s to-do list, please
help him identify how many of those problems Chef should remove from his to-
do list, so that he is only left with problems of difficulty rating less than 1000
https://www.codechef.com/problems/TODOLIST?tab=statement

#include <stdio.h>

int main(void) {
// your code goes here
int i,j,T,N,d,count,a[1000];
scanf("%d",&T);
for(i=1;i<=T;i++){
scanf("%d",&N);
for(j=0;j<N;j++){
scanf("%d",&a[j]);
}
count=0;
for(j=0;j<N;j++){
if(a[j]>=1000){
count++;
}
}
printf("\n%d",count);
}
return 0;
}
Post-lab:
1. You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a
different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve
any profit, return 0.
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
Code:

#include <stdio.h>
int maxProfit(int* prices, int pricesSize) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i<pricesSize; i++) {
if (prices[i] <minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice>maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}

int main() {
int prices[] = {7, 1, 5, 3, 6, 4};
int pricesSize = sizeof(prices) / sizeof(prices[0]);
int result = maxProfit(prices, pricesSize);
printf("The maximum profit is: %d\n", result);
return 0;
}
2. Given a non-empty array of integers nums, every element appears twice except for one.
Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra
space.
https://leetcode.com/problems/single-number/description/
Code:
int singleNumber(int* nums, int numsSize) {
int result = 0;
for (int i = 0; i<numsSize; i++) {
result ^= nums[i];
}
return result;
}

3. Given an array nums of size n, return the majority element.


The majority element is the element that appears more than ⌊n / 2⌋ times. You may assume
that the majority element always exists in the array.
https://leetcode.com/problems/majority-element/description/
Code:
int majorityElement(int* nums, int numsSize) {
int candidate = nums[0];
int count = 1;
for (int i = 1; i<numsSize; i++) {
if (nums[i] == candidate) {
count++;
} else {
count--;
if (count == 0) {
candidate = nums[i];
count = 1;
}
}
}
return candidate;
}
Skill
You are asked to calculate factorials of some small positive integers.
Input
1. An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a
single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
https://www.codechef.com/problems/FCTRL2?tab=statement
#include<stdio.h>
int main()
{
int t,n,a[200],i,j,k,l,m;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
m=1;
a[0]=1;
for(j=2;j<=n;j++)
{
l=0;
for(k=0;k<m;k++)
{
a[k]=a[k]*j+l;
l=a[k]/10;
a[k]=a[k]%10;
}
while(l)
{
a[k]=l%10;
k++;
m++;
l=l/10;
}
}
for(i=m-1;i>=0;i--)
printf("%d",a[i]);

printf("\n");
}
return 0;
}
2. The game of billiards involves two players knocking 3 balls around on a green baize table. Well,
there is more to it, but for our purposes this is sufficient.
The game consists of several rounds and in each round both players obtain a score, based on how
well they played. Once all the rounds have been played, the total score of each player is determined
by adding up the scores in all the rounds and the player with the higher total score is declared the
winner.
The Siruseri Sports Club organises an annual billiards game where the top two players of Siruseri
play against each other. The Manager of Siruseri Sports Club decided to add his own twist to the
game by changing the rules for determining the winner. In his version, at the end of each round, the
cumulative score for each player is calculated, and the leader and her current lead are found. Once
all the rounds are over the player who had the maximum lead at the end of any round in the game is
declared the winner.

https://www.codechef.com/problems/TLG?tab=statement
#include <stdio.h>

int main() {
int numRounds;
scanf("%d", &numRounds);

int player1Score = 0;
int player2Score = 0;
int maxLead = 0;
int leader = 0;

while (numRounds > 0) {


int player1RoundScore, player2RoundScore;
scanf("%d %d", &player1RoundScore, &player2RoundScore);

player1Score += player1RoundScore;
player2Score += player2RoundScore;

int lead = player1Score - player2Score;


if (lead > 0 && lead > maxLead) {
maxLead = lead;
leader = 1;
} else if (lead < 0 && -lead > maxLead) {
maxLead = -lead;
leader = 2;
}

numRounds--;
}

printf("%d %d\n", leader, maxLead);

return 0;
}
3. Vasya likes the number 239. Therefore, he considers a number pretty if its last digit 2,3 or 9

Vasya wants to watch the numbers between L and R (both inclusive), so he asked you to determine
how many pretty numbers are in this range. Can you help him?
https://www.codechef.com/problems/NUM239

#include <stdio.h>

int main() {
int T,j,i,L, R,count=0;
scanf("%d",&T);
for(i=1;i<=T;i++){
scanf("%d %d", &L, &R);
for(j=L;j<=R;j++){
if(j%10==2 || j%10==3 || j%10==9){
count++;
}
}
printf("\n%d",count);
count=0;
}
return 0;
}

4. You are participating in a contest which has 11 problems (numbered 1 through 11). The first
eight problems (i.e. problems 1,2,…,8)are scorable, while the last three problems (9,10 and 11)
are non- scorable ― this means that any submissions you make on any of these problems do not
affect your total score.

Your total score is the sum of your best scores for all scorable problems. That is, for each
scorable problem, you look at the scores of all submissions you made on that problem and take the
maximum of these scores (or 0 if you didn't make any submissions on that problem); the total score
is the sum of the maximum scores you took.
You know the results of all submissions you made. Calculate your total score.
https://www.codechef.com/problems/WATSCORE?tab=statement

#include <stdio.h>

int main(void) {

// your code goes here

int T,i,j,N,sum=0,p,s,a[1000],k;

scanf("%d",&T);

for(i=1;i<=T;i++){

for(j=0;j<10;j++){

a[j]=0;

scanf("%d",&N);

for(k=1;k<=N;k++){

scanf("%d %d",&p,&s);

if(p<=8){

if(a[p]<s){

a[p]=s;

for(k=0;k<10;k++){

sum=sum+a[k];

}
printf("\n%d",sum);

sum=0;

return 0;

5) Solve the problem in HackerRank platform


https://www.hackerrank.com/challenges/arrays-ds/proble
m
int* reverseArray(int a_count, int* a, int* result_count) {
int* result = (int*)malloc(a_count * sizeof(int));
// Reverse the elements of the input array and store them in the res
ult array
for (int i = 0; i<a_count; i++) {
result[i] = a[a_count - i - 1];
}
*result_count = a_count; // Update the size of the result array
return result;

.
6.Solve the problem in HackerRank platform
https://www.hackerrank.com/challenges/array-left-rotation/proble
m
int* rotateLeft(int d, int arr_count, int* arr, int* result_count) {
// Calculate the effective rotation amount
int rotations = d % arr_count;
// Create a new array to store the rotated elements
int* rotated_arr = malloc(arr_count * sizeof(int));
// Perform the rotation
for (int i = 0; i < arr_count; i++) {
int new_index = (i + rotations) % arr_count;
rotated_arr[i] = arr[new_index];
}
// Set the result count and return the rotated array
*result_count = arr_count;
return rotated_arr;
}

7.Solve "Constructing a Number" problem in HackerRank.


https://www.hackerrank.com/challenges/constructing-a-number/proble
m

char* canConstruct(int a_count, int* a) {


// Return "Yes" or "No" denoting whether you can construct the re
quired number.
long int sum = 0;
for (int i = 0; i < a_count; i++) {
sum += a[i];
}
if (sum % 3 == 0) {
return "Yes";
}
else {
return "No";
}
}

You might also like