How can I print out each line two more elements of an array...?
I can't get it done.
I have this short code, but this part is missing...
#include <stdio.h>
#include <stdlib.h>
char *toChar(int numbers[]);
int main(){
// FILE *fp;
int num;
printf("Number of rows: ");
scanf("%d", &num);
int val[num], value=num;
for(int i=0; i<num; i++){
val[i]=value;
value+=value;
printf("%d ", val[i]);
...
printf("\n");
}
}
return 0;
}
I would like to achieve this... for input = 4.
4 8
12 16 20 24
28 32 36 40 44 48
52 56 60 64 68 72 76 80
And for input 3, expected output is:
3 6
9 12 15 18
21 24 27 30 33 36
Note that the printed value should increase by the same amount as there should be rows (num).
I would make a list of all you need:
You need num rows
You need the number of columns to increase by 2 every row
You need the printed value to increase by num for each output
With that list, make two loops.
One that iterates over the rows
One that iterates over the columns:
#include <stdio.h>
int main() {
printf("Number of rows: ");
int num;
if (scanf("%d", &num) != 1) return 1;
// row starts at 0 and ends at num-1
// columns start with 2 and increases by 2 for every row
for (int row = 0, columns = 2, value = num; row < num; ++row, columns += 2) {
// and value increases by `num` every time it's been printed:
for (int c = 0; c < columns; ++c, value += num) {
printf("%d ", value);
}
putchar('\n');
}
}
Demo
Decided to take a stab at this using java. I feel like recursion here was a bit easier than trying to wrap my head around two for loops.
class Main {
public static void main(String[] args) {
printTwoMore(0, 1, 1, 4);
}
public static void printTwoMore(int prevTimesToPrint, int multiple, int currentRow, int maxRow) {
if (currentRow > maxRow) {
return;
}
int timesToPrint = 2 + prevTimesToPrint;
for (int i = 0; i < timesToPrint; i++) {
System.out.print(4 * multiple + " ");
multiple++;
}
System.out.println("");
currentRow++;
printTwoMore(timesToPrint, multiple, currentRow, maxRow);
}
}
Related
I have written a code for Binary Search. It has a provision for bubble sorting of array too. The user can either specify the array elements individually or use an RNG for generate the array elements. Even if the array does get sorted properly, I am unable to get the correct index if there is a match and somehow getting a match even if the match doesn't exist. I get no errors or warnings while compiling the code. Please advice on where my code/logic is wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
size_t binary_search(const int b[], int search, size_t low, size_t high);
int value = 0;
int main (void)
{
int selection=0,size=0,key=0; //Value will be used if the match doesn't exist in the array.
int temp=0,pass=0;
printf("\n\tThis program uses Binary Search Technique to find an element in an array.\n\n");
printf("\tThe user can either feed the individual array values or use the inbuilt Random Number Generator to initialise the array elements.\n");
printf("\tPress 1 for RNG fed array values.\n\tPress 2 for user fed array values.\n");
printf("\n\tSelection : ");
scanf("%d",&selection);
printf("\n\tPlease enter the size of the array : ");
scanf("%d",&size);
int a[size];
size_t i=0;
if (selection==1)
{
srand(time(NULL));
printf("\n\tThe random number generator will generate the values between 0 and 100");
for(i=0;i<size;i++)
a[i]=rand()%100;
}
else if (selection==2)
{
printf("\n\tPlease enter the array elements : \n");
for(i=0;i<size;i++)
{
printf("\tElement %d : ",i);
scanf("%d",&a[i]);
}
}
printf("\n\n\tThe array is : \n\n\t");
for(i=0;i<size;i++)
{
printf("%5d",a[i]);
if ((i+1)%20==0)
printf("\n\t");
}
for(pass=1;pass<i-1;pass++) //Bubble sort
{
for (i=0;i<size-1;i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf("\n\n\tThe array after bubble sorting is : \n\n\t");
for(i=0;i<size;i++)
{
printf("%5d",a[i]);
if ((i+1)%20==0)
printf("\n\t");
}
printf("\n\n\tEnter the key value which is to be searched in the array : ");
scanf("%d",&key);
binary_search( a, key, 0, size-1);
if (value!=-1)
{
printf("\n\n\tKey found at a[%d].",value);
}
else
{
printf("\n\n\tNo match found.");
}
}
size_t binary_search(const int b[], int search, size_t low, size_t high)
{
int middle=0;
while (low<=high)
{
middle = (high+low)/2;
if (b[middle]==search)
return middle;
else if (search>b[middle])
{
low = middle+1;
}
else if (search<b[middle])
{
high = middle-1;
}
else
middle=-1;
}
return middle;
}
Edit :
I have made some changes to the code from which I am able to get the index if a match is found. However, I am still unable to get the msg when a match isn't found.
Output for when match doesnt exist 1 :
Please enter the size of the array : 20
The random number generator will generate the values between 0 and 100
The array is :
80 76 14 56 78 60 70 43 55 4 87 25 18 54 36 20 48 73 21 55
The array after bubble sorting is :
4 14 18 20 21 25 36 43 48 54 55 55 56 60 70 73 76 78 80 87
Enter the key value which is to be searched in the array : 90
Key found at a[19].
Process returned 0 (0x0) execution time : 4.759 s
Press any key to continue.
Output when match doesnt exist 2:
Please enter the size of the array : 20
The random number generator will generate the values between 0 and 100
The array is :
12 48 18 15 16 14 46 14 30 75 54 52 14 95 47 40 82 44 30 39
The array after bubble sorting is :
12 14 14 14 15 16 18 30 30 39 40 44 46 47 48 52 54 75 82 95
Enter the key value which is to be searched in the array : 5
For this case, the code doesnt end at all.
The global variable value is not handled correct.
You must make sure to set it inside binary_search both when you have a match (i.e. set it to matching index) and when you have no match (i.e. set it to a value indicating no-match). Your current code doesn't do that.
Apparently you want value to be -1 when you don't have a match so you need:
size_t binary_search(const int b[], int search, int low, int high)
{
int middle=0;
while (low<=high)
{
middle = (high+low)/2;
if (b[middle]==search)
{
value = middle; // Match - save matching index
return middle;
}
else if (search>b[middle])
{
low = middle+1;
}
else if (search<b[middle]) // this if-part is not needed btw
{
high = middle-1;
}
}
value = -1; // No match
return 0;
}
That said, I strongly recommend that you stop using a global variable for this. Instead use the functions return value like:
int binary_search(const int b[], int search, int low, int high)
{
int middle=0;
while (low<=high)
{
middle = (high+low)/2;
if (b[middle]==search)
{
return middle; // Match
}
else if (search>b[middle])
{
low = middle+1;
}
else if (search<b[middle]) // this if-part is not needed btw
{
high = middle-1;
}
}
return -1; // No match
}
(notice that the function returns an int now)
and use it like:
int match = binary_search( a, key, 0, size-1);
if (match >= 0)
{
printf("\n\n\tKey found at a[%d].", match);
}
else
{
printf("\n\n\tNo match found.");
}
Remember to delete the global variable value
I changed line 22 from int a[size]; to
int *a = malloc(sizeof(int) * size);
and each of scanf to scanf_s because I used visual studio to run it
It seems that the sort works fine except when we have zeros in the array
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
size_t binary_search(const int b[], int search, size_t low, size_t high);
int value = 0;
int main(void)
{
int selection = 0, size = 1, key = 0; //Value will be used if the match doesn't exist in the array.
int temp = 0, pass = 0;
printf("\n\tThis program uses Binary Search Technique to find an element in an array.\n\n");
printf("\tThe user can either feed the individual array values or use the inbuilt Random Number Generator to initialise the array elements.\n");
printf("\tPress 1 for RNG fed array values.\n\tPress 2 for user fed array values.\n");
printf("\n\tSelection : ");
scanf_s("%d", &selection, sizeof(int));
printf("\n\tPlease enter the size of the array : ");
scanf_s("%d", &size, sizeof(int));
int *a = malloc(sizeof(int) * size);
size_t i = 0;
if (selection == 1)
{
srand(time(NULL));
printf("\n\tThe random number generator will generate the values between 0 and 100");
for (i = 0; i < size; i++)
a[i] = rand() % 100;
}
else if (selection == 2)
{
printf("\n\tPlease enter the array elements : \n");
for (i = 0; i < size; i++)
{
printf("\tElement %d : ", i);
scanf_s("%d", &a[i], sizeof(int));
}
}
printf("\n\n\tThe array is : \n\n\t");
for (i = 0; i < size; i++)
{
printf("%5d", a[i]);
if ((i + 1) % 20 == 0)
printf("\n\t");
}
for (pass = 1; pass < i - 1; pass++) //Bubble sort
{
for (i = 0; i < size - 1; i++)
{
if (a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
printf("\n\n\tThe array after bubble sorting is : \n\n\t");
for (i = 0; i < size; i++)
{
printf("%5d", a[i]);
if ((i + 1) % 20 == 0)
printf("\n\t");
}
printf("\n\n\tEnter the key value which is to be searched in the array : ");
scanf_s("%d", &key, sizeof(int));
binary_search(a, key, 0, size - 1);
if (value != -1)
{
printf("\n\n\tKey found at a[%d].", value);
}
else
{
printf("\n\n\tNo match found.");
}
}
size_t binary_search(const int b[], int search, size_t low, size_t high)
{
int middle = 0;
while (low <= high)
{
middle = (high + low) / 2;
if (b[middle] == search)
return middle;
else if (search > b[middle])
{
low = middle + 1;
}
else if (search < b[middle])
{
high = middle - 1;
}
}
value = middle;
return 0;
}
I have written this C code to find a minimum number of wires required to switch on all the bulbs.
The problem is that there is x number of computers, some of which are On and some are Off and the distance between these bulb from the first bulb is given. The computer can be switched ON by connecting it to its nearby ON the bulb.
So the inputs are as follows:
X = 6 (number of bulbs)
1 0 1 1 0 1(1 means the bulb is ON and 0 means the bulb is OFF)
2 4 8 36 37 40 (distance between one bulb from the first bulb)
and the output will be:
3 (Reason: 4 - 2 = 2, 37 - 36 = 1, 2 + 1 = 3)
#include <stdio.h>
int main(){
int n,pre,post,sum = 0;
scanf("%d",&n);
int arr[n],dist[n];
for(int i =0;i<n;i++){
scanf("%d ",&arr[i]);
}
for(int i =0;i<n;i++){
scanf("%d ",&dist[i]);
}
for(int i =0;i<6;i++){
if(arr[i] == 0){
pre = dist[i]-dist[i-1];
post = dist[i+1]-dist[i];
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
}
printf("\n %d",sum);
}
It keeps on taking the inputs. Please tell me what is the error in this code?
Thanks in advance.
Edited: I missed that scanf("%d",n) by mistake. It was there in my original code and the problem still persists.
As Sandrin mentioned, n is not defined.
Assuming your input file is:
6
1 0 1 1 0 1
2 4 8 36 37 40
You need to add code to set n:
scanf("%d ",&n);
And, you need to insert this before the definitions of your matrix
Here's the refactored code:
#include <stdio.h>
int
main(void)
{
int n, pre, post, sum = 0;
#if 1
scanf("%d ",&n);
#endif
int arr[n], dist[n];
for (int i = 0; i < n; i++)
scanf("%d ", &arr[i]);
for (int i = 0; i < n; i++)
scanf("%d ", &dist[i]);
for (int i = 0; i < 6; i++) {
if (arr[i] == 0) {
pre = dist[i] - dist[i - 1];
post = dist[i + 1] - dist[i];
if (pre > post) {
sum += post;
}
else {
sum += pre;
}
}
}
printf("\n %d", sum);
return 0;
}
Putting a side technical errors (e.g. n not initialized), the algorithms assumes that all problems can be solved by single pass. This is not true for cases like:
1 0 0 0 0 1
0 1 3 4 6 7
Where the code will choose to connect bulbs [0,1], [2,3], and [4,5], based on pre/post distances. However, bulbs 2 and 3 will remain disconnected.
A better algorithm will attempt to find, for each sequence of off bulbs, which is the most expensive connection, and avoid it.
I have come up with this solution for my code and I have tried to consider all the test cases. If you find any test case that won't run feel free to tell.
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av){
int n,pre,post,sum = 0;
scanf("%d",&n);
int *input,*distance;
input = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &input[i]);
}
distance = malloc(n * sizeof(int));
for (int i=0; i < n; i++)
{
scanf("%d", &distance[i]);
}
for(int i =0;i<6;i++){
if(input[i] == 0){
pre = distance[i]-distance[i-1];
if(input[i+1]==1){
post = distance[i+1]-distance[i];
input[i] =1;
if(pre>post){
sum +=post;
}
else{
sum+=pre;
}
}
else{
sum = sum+pre;
}
printf("%d.....%d....%d\n",pre,post,sum); //Debugging
}
}
printf("\n %d",sum);
free(input);
free(distance);
}
Given an array of unique integer elements, print all the subsets of the given array in lexicographical order.
Input Format
First line of input contains T - number of test cases. Its followed by 2T lines, the first line contains N - the size of the array and
second line contains the elements of the array.
Constraints
1 <= T <= 100
1 <= N <= 10
0 <= A[i] <= 100
Output Format
For each test case, print the subsets of the given array in lexicographical order, separated by new line. Print an extra newline
between output of different test cases.
void solve()
{
int n;
scanf("%d",&n);
int a[n];
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
merge_sort(a,0,n-1);//for sorting, not given here
for(int i=0;i<(1<<n);i++)
{
for(int j=0;j<n;j++)
{
if((i&(1<<j))>0)
printf("%d ",a[j]);
}
printf("\n");
}
}
What shall I do after this should I use a 2d array? if so how?
>
> Sample Input 0
>
> 3(no.of test cases)
>
> 3(size)
>
> 5 15 3(input elements)
>
> 2
>
>57 96
>
> 4
>
>3 15 8 23
>
>
>## Expected output##
3
3 5
3 5 15
3 15
5
5 15
15
57
57 96
96
3
3 8
3 8 15
3 8 15 23
3 8 23
3 15
3 15 23
3 23
8
8 15
8 15 23
8 23
15
15 23
23
ANSWER TO THIS
Without using recursion
this code can still be optimized any help in doing so will be greatly helpful.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
void solve();
void merge(int a[],int s,int e);
void merge_sort(int a[],int s,int e);
int indexSearcher(int a[],int b[],int h,int i);
int main() {
int t;
scanf("%d",&t);/* This is for printing testcases*/
while(t--)
{
solve();
printf("\n");
}
return 0;
}
int compare(const void *a, const void *b) {
return(*(int*)a > *(int*)b);
}
void solve()
{
int n;
scanf("%d",&n);
int a[n+1],main_a[n];
a[n]=-1;
for(int i=0;i<n;i++)
{
scanf("%d",&main_a[i]);
}
qsort(main_a, n, sizeof(int), compare);//for sorting
/* loading all the elements to another array so that it won't miss its original
sorted order and it is used as reference*/
for(int e=0;e<n;e++){
a[e]=main_a[e];
}
int j=0;
int i=0;
for( j=0;j<n;j++){
for( i=0;i<=j;i++)
printf("%d ",a[i]);//This can be optimized also.
printf("\n");
}
a[i]=-1;// the invalid value is replaced by -1 every time
int u=i;//assigning or updating u to last valid index every time
while(a[0]!=main_a[n-1]){
if(a[u-1]==main_a[n-1])
/* If we reach last index every time the penultimate index is updated to it's corresponding consecutive index (successor).*/
{
u=0;
while(a[u]!=-1)
u++;
a[u-2]=indexSearcher(a,main_a,a[u-2],n);//gives the successor of the penultimate index
a[u-1]=-1;
for (j=0;j<=u-2;j++){
printf("%d ",a[j]);
}
u=0;
while(a[u]!=-1)
u++;
//printer(a,i-1);
printf("\n");
}
else if(a[u-1]!=main_a[n-1])
/*If we don't reach the last index we print until we get there every time in a new line by updating the index by 1 */
{
u=0;
while(a[u]!=-1)
u++;
a[u]=indexSearcher(a,main_a,a[u-1],n);/*here we get the correct lexical value
i.e., the element which should come after the current element in lexical order.*/
a[u+1]=-1;
for (j=0;j<u+1;j++){
printf("%d ",a[j]);
}
u=0;
while(a[u]!=-1)
u++;
printf("\n");
}
}
}
int indexSearcher(int a[],int main_a[],int s,int n)
{
for(int i=0;i<n;i++){
if(s==main_a[i]){
return main_a[i+1];
}
}
return 0;
}
I am trying to define a two dimensional array by initially defining elements for 5 x 2 matrix and then I am defining again the elements for 6th row. But when I try to print the elements of this matrix I am getting 0 and 5 for the last value. Tried same by defining elements again for 4th or 6th row but then it is working fine.
#include<math.h>
#include<stdio.h>
main()
{
int arr[ ][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};
int i, j;
arr[5][0]=61; arr[5][1]=62;
for (i=0;i<=5;i++)
{
for (j=0;j<=1;j++)
{
printf ("%d \n", arr[i][j]);
}
}
}
Your initialised array is given exactly enough memory to hold the specified data values. So
int arr[ ][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};
creates the array as int arr[5][2] and then the line
arr[5][0]=61; arr[5][1]=62;
exceeds the array bounds. The maximum index is [4][1] because array indexing is 0 based. If you want to add another element you should specify
int arr[6][2]={{11,12},{21,22},{31,32},{41,42},{51,52}};
and then this line will work.
arr[5][0]=61; arr[5][1]=62;
An alternative would be to use malloc() to allocate memory for the array, and then if you want to add another row you can use realloc(), and this shows how to make a flexible array.
#include <stdio.h>
#include <stdlib.h>
#define COLUMNS 2
#define ROWS 5
typedef int rowtype[COLUMNS];
int main() {
int i, j;
rowtype *array = malloc(ROWS * sizeof(rowtype));
if (array == NULL)
return -1;
for (j=0; j<ROWS; j++)
for (i=0; i<COLUMNS; i++)
array[j][i] = (j+1)*10 + (i+1);
for (j=0; j<ROWS; j++) {
for (i=0; i<COLUMNS; i++)
printf ("%-4d", array[j][i]);
printf ("\n");
}
printf("Add another row\n");
array = realloc(array, (ROWS+1) * sizeof(rowtype));
if (array == NULL)
return -1;
array[ROWS][0] = 61;
array[ROWS][1] = 62;
for (j=0; j<ROWS+1; j++) {
for (i=0; i<COLUMNS; i++)
printf ("%-4d", array[j][i]);
printf ("\n");
}
free(array);
return 0;
}
Program output:
11 12
21 22
31 32
41 42
51 52
Add another row
11 12
21 22
31 32
41 42
51 52
61 62
I'm completing a problem set for an introductory computer science class and I'm a bit confused as to what I'm supposed to be doing with this program. The question is: In one file there is a list of of scores for some participants in an athletic competition. The list is organized in the order in which the participants registered for the competition, not in order of score. A separate file contains a set of ranges. Your job is to write a program that can read the data in these two files and print a table showing how many of the participants fell into each of the given ranges.
The question is copied word for word, but I have a few questions about this question. if you could leave a comment stating your opinion about the following, that would be nice:
1) Okay, so I've written some code in order to read the numbers from the first data file, place the numbers in the array A and return a count of the number of numbers read or N, whichever is smaller. Which follows as:
#include <stdio.h>
int readNumbers(FILE* input, int A[], int N)
{
int n;
n = 0;
while (n < N&&!feof(input))
{
fscanf_s(input, "%f", &A[n]);
n++;
}
return n;
}
int count(const int A[], int N, int low, int high){
}
2) My confusion lies in using this second function to count how many numbers in array A fall in the range from low to high, inclusive. The parameter N tells you how many numbers are in the array. And use these two functions to construct and print a table of how many participants are in each of the categories given in the second file.
Now that I try to talk myself through it, I am now even more confused. Maybe I'm just making the question more difficult. Any tips will help. Thanks
to count how many numbers in array A fall in the range from low to high, inclusive.
That count() could be implemented like this
int count(const int A[], int N, int low, int high){
int i, cnt;
for (i = cnt = 0; i < N; i++) {
if (low <= A[i] && A[i] <= high)
cnt++;
}
return cnt;
}
use these two functions to construct and print a table of how many participants are in each of the categories given in the second file.
You could achieve this by using a simple loop
for (i = 0; i < number_of_categories; i++) {
printf("%d - %d : %d\n", low[i], high[i],
count(A, N, low[i], high[i]));
}
Suppose you already put all those categories information to low[] and high[].
Not sure what the input files are supposed to look like, I guessed one number per line.
Scores file:
0
1
2
3
4
5
6
7
8
9
10
19
29
39
49
59
69
79
89
99
99
99
99
99
99
99
100
Ranges File:
0
10
11
20
21
30
31
40
41
50
51
60
61
70
71
80
81
90
91
100
Source:
#include <stdio.h>
#include <stdlib.h>
int readNumbers(FILE* input, int A[], int N)
{
int n = 0;
while (n < N && !feof(input))
{
fscanf_s(input, "%d", &A[n]);
n++;
}
return n;
}
int count(const int A[], int N, int low, int high) {
int i = 0, numbers_in_range = 0;
for (i = 0; i < N; i++) numbers_in_range += (A[i] >= low && A[i] <= high) ? 1 : 0;
return numbers_in_range;
}
inline int exiting(char* reason)
{
if(reason != 0) printf("%s\n", reason);
printf("Usage: rangechecker \"scoresfilename\" \"rangesfilename\"\n");
printf("exiting...\n");
exit (-1);
}
int main(int argc, char** argv) {
int* scores = 0;
int* ranges = 0;
int num_scores = 0, num_ranges = 0;
FILE* scoresfptr;
FILE* rangesfptr;
switch (argc) {
case 1:
case 2:
exiting(0);
break;
case 3:
//verify files exist and open them
if((scoresfptr = fopen(argv[1], "r")) == NULL || (rangesfptr = fopen(argv[2], "r")) == NULL)
{
exiting("One of the files does not exist or cannot be opened.");
}
break;
default:
exiting(0);
break;
}
//kind of dumb, but because N is a passed value you kinda gotta
//know N ahead of the call to readnumber or count
//that, or I am just tired.
int ch = 0;
//assuming instructions are correct, a list, 1 number per line
//will fail if extra newlines in file
do {
ch = fgetc(scoresfptr);
if (ch == '\n')
num_scores++;
} while(ch != EOF);
//now we have N, can call readnumbers. Put file pointer back at start of file.
rewind(scoresfptr);
//Can also now allocate memory for A[].
scores = (int*)calloc(num_scores, sizeof(int));
//check return value to see if anything was read in
if(readNumbers(scoresfptr, scores, num_scores) > 0) {
//musta been something in the file
//get the ranges
ch = 0;
//assuming instructions are correct, a list, 1 number per line
do {
ch = fgetc(rangesfptr);
if (ch == '\n')
num_ranges++;
} while(ch != EOF);
//now we have N, can call readnumbers. Put file pointer back at start of file.
rewind(rangesfptr);
//Can also now allocate memory for A[].
ranges = (int*)calloc(num_ranges, sizeof(int));
//check return value to see if anything was read in
if(readNumbers(rangesfptr, ranges, num_ranges) > 0) {
//now we can call count
//print header column
printf("ranges\tscores in range\n");
for (int i = 0, j = 0; i < num_ranges/2; i++, j += 2)
{
printf("%d-%d:\t%d\n", *(ranges + j),
*(ranges + j + 1),
count(scores, num_scores, *(ranges + j),
*(ranges + j + 1)));
}
}
else {
exiting("Ranges File empty.");
}
}
else {
exiting("Scores File empty.");
}
free(scores);
free(ranges);
fclose(scoresfptr);
fclose(rangesfptr);
return(0);
}
Output:
ranges scores in range
0-10: 11
11-20: 1
21-30: 1
31-40: 1
41-50: 1
51-60: 1
61-70: 1
71-80: 1
81-90: 1
91-100: 8