Currently the code I have working is close but I'm having issues with printing the saved inputs. My output should look include the input elements above and then the elements reversed. Currently my code will only output the reversed array.
#include <stdio.h>
int main(void) {
const int NUM_VALS = 4;
int courseGrades[NUM_VALS];
int i;
for (i = 0; i < NUM_VALS; ++i) {
scanf("%d", &(courseGrades[i]));
}
//above cannot be modified. Adding print statment below is
//close but only prints 4
printf("%d \n", courseGrades[i];
for (i = NUM_VALS - 1; i > 0; i--) {
printf("%d ", courseGrades[i]);
}
printf("%d \n", courseGrades[i]);
return 0;
}
Just add code for printing array
for (i = 0; i < NUM_VALS; ++i) {
printf("%d ", courseGrades[i]);
}
printf("\n");
In the first for loop, the variable i is incremented to NUM_VALS which is 4.
After that the line has printf(without closing brace)
printf("%d \n", courseGrades[i];
tries to prints coursesGrade[4] because of the reason I've mentioned. But there is no value at 4th index so it causes an undefined behaviour. So you need to remove that line, first.
In addition, as mentioned in comments above, you have an unneccessary line which is
printf("%d \n", courseGrades[i]);
If you insist on using it, then make it
printf("%d \n", courseGrades[0]);
OR
for (i = NUM_VALS - 1; i >= 0; i--) { // i>0 ==> i>=0
printf("%d ", courseGrades[i]);
}
Related
I know it means that there is a problem with trying to access restricted memory but I do not know how to find where the error is occurring or how I would go about fixing it. An small explanation would be very helpful.
int main(int argc, char* argv[1]) {
char emptyBoard[3][3];
char player;
int row, column; // moves
int i, j;
// int x = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
emptyBoard[i][j] = '.';
}
}
/*
for(i = 0; i < 3; i++){
for (j = 0; j < 3; j++){
printf("%c ", emptyBoard[i][j]);
}
printf("\n");
}
*/
FILE* filePtr = fopen(argv[1], "r");
if (filePtr == NULL) {
printf("Cannot open File \n");
return 1;
}
while (fscanf(filePtr, "%c, %d, %d", &player, &row, &column) != EOF) {
// moves = x++;
emptyBoard[row][column] = player;
printBoard(emptyBoard);
}
// printf("Total Moves: %d", moves );
fclose(filePtr);
}
void printBoard() {
int i, j;
char array[3][3];
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
printf("%c ", array[i][j]);
}
printf("\n");
}
}
I know this isn't what you asked for, but I noticed you're passing a variable to printBoard in printBoard(emptyBoard), but the function does not actually take any arguments. What will be printed here is a 'random' collection of values.
As for what you asked, do you pass any arguments to your executable? If it's titled 'run' for example, do you type ./run file.txt or just ./run? If you are doing the latter, that will cause a Segmentation fault because you are trying to load in a value that was not allocated to the argv. Allan is also correct, if the file you are loading calls higher row or column than 3, segmentation fault occurs because you are trying to access memory that you did not allocate to emptyBoard.
As to finding the cause of runtime errors, I have found placing print statements at the different steps of my program to be quite helpful. You could learn to use a debugger.
The program crash if row or column in input file is >= 3.
The fscanf condition is not sufficient to terminate the loop either check on number of records have been processed or add space so scanf eats the trailing newline:
while (fscanf(filePtr, "%c, %d, %d ", &player, &row, &column)) != EOF) {
You call printBoard(emptyBoard) but it's defined as not taking any arguments, and you create a local array. Try this instead:
void printBoard(size_t row, size_t column, char array[row][column]) {
int i, j;
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
printf("%c ", array[i][j]);
}
printf("\n");
}
}
...
printBoard(3, 3, emptyBoard);
This will result in players being accumulated. If you want one player per board, then you need to either initialize the board or operate on a copy of empty board:
char board[3][3];
memcpy(board, emptyBoard, sizeof(emptyBoard);
board[row][column] = player;
printBoard(3, 3, board);
The question i have is similar to some questions answered, but the answer for this in particular wasn't in there. Here is my code
int main()
{ int i,j,k,sorted;
int A[4][4];
int C[16];
int positive = 0;
for(i=0;i<4;i++)
{
for(j = 0; j<4; j++)
{
printf("A[%d][%d]: ", i,j);
scanf("%d", &A[i][j]);
if(A[i][j]>0){
C[positive] = A[i][j];
printf("C = %d\n");
positive++;
}
}
}
for(j=0;j<4;j++)
{
printf("%d ", A[positive]);
}
printf("\n");
//printf("Your positive numbers are: ", positive);
printf("\n");
system("pause");
return 0;
}
I want to check if the input is negative and add it to the 1D array only then. The question is how do I do that?
General Tips
int main()
{
int i,j,k,sorted; // do not declare loop control variables outside of their respective loops
int A[4][4];
int C[16];
int positive = 0; // for readability's sake please refrain from using long ass variable names for simple control var's
for(i=0;i<4;i++) // idiomatic way is for(int i = 0; i < 4; i++)
{
for(j = 0; j<4; j++) // for(int j = 0; j<4; j++)
{
printf("A[%d][%d]: ", i,j);
scanf("%d", &A[i][j]);
if(A[i][j]>0)
{
C[positive] = A[i][j];
printf("C = %d\n"); // missing argument & redundant since you intend to print them afterwards anyway?
positive++;
}
}
}
for(j=0;j<4;j++) // this loop is supposed to print all positive numbers?
{
printf("%d ", A[positive]); // you are looping through A[0-3][0], which are not necessarily the positive numbers of A.
}
printf("\n");
//printf("Your positive numbers are: ", positive);
Now to your question at hand. What the code tries to do and what you ask from us are two different things. Right now you are adding positive values to your C array, but your question asks about negative values?
Cleaned up code that behaves the way i think you want it to.
int main()
{
int A[4][4];
int C[16];
int k = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
printf("A[%d][%d]: ", i, j);
scanf("%d", &A[i][j]);
if (A[i][j] > 0)
{
C[k] = A[i][j];
k++;
}
}
}
printf("positive numbers in matrix A are: ");
for (int i = 0; i < k; i++) // loop from 0 to actual number of positive integers; array size remains at 16 in this case.
{
printf("%d ", C[i]);
}
printf("\n");
//printf("Your positive numbers are: ", positive);
printf("\n");
system("pause");
return 0;
}
int main()
{ int i,j,k,sorted;
int A[4][4];
int C[16];
int positive = 0;
for(i=0;i<4;i++)
{
for(j = 0; j<4; j++)
{
printf("A[%d][%d]: ", i,j);
scanf("%d", &A[i][j]);
if(A[i][j]>0){
C[positive] = A[i][j];
printf("C = %d\n");
positive++;
}
}
}
for(j=0;j<positive;j++)
{
printf("%d ", C[j]);
}
printf("\n");
//printf("Your positive numbers are: ", positive);
printf("\n");
system("pause");
return 0;
}
where you wrong is in the looping for result, you print a 2D array but you just use 1D array, and in the loop is not until 4 but until the positive, and then in the loop, you print A, but the result is C no A
I want to print all combinations of length 2 from an array of characters (like aa, ab, ..., az, ba, bb, ...., etc). Can somebody explain to me why this code incorrect:
int main(void){
char a[]="abcdefghijk";
for (int i=0; i<11; i++){
for (int j=0; j<11 && a[j]!='\n'; j++){
char r[2] = {a[i], a[j]};
printf("I-th element: %c ", a[i]);
printf("J-th element: %c ", a[j]);
printf("Together: %s", r);
printf("\n");
}
}
return 0;
}
The problem is that after every eleventh combination empty line is printed. If an array is shorter than 10 everything seemed to be fine.
Output looks like this:
screenshot of my IDE
here is a version of the posted code, that does not have any undefined behavior, so the output is as expected.
#include <stdio.h> // printf()
int main(void)
{
char a[]="abcdefghijk";
for (int i=0; i<11; i++)
{
for (int j=0; j<11; j++)
{
printf("I-th element: %c ", a[i]);
printf("J-th element: %c ", a[j]);
printf("Together: %c%c", a[i], a[j]);
printf("\n");
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int score,i,j;
int *ptr, *ptr1;
int over;
printf("Enter the number of over");
scanf("%d",&over);
ptr=(int*)malloc(over*sizeof(int));
// do the iteration, outer for loop, read row by row...
for(i=0; i <= (over-1); i++)
{
printf("%d%d ", i, ptr[i]);
// inner for loop, for every row, read column by column and print the bar...
printf("Enter the number of run per over");
scanf("%d",&score);
ptr1=(int*)malloc(score*sizeof(int));
for(j = 1; j<= ptr1[i]; j++)
// print the 'bar', and repeat...
printf("|");
// go to new line for new row, and repeats...
printf("\n");
}
return 0;
}
You are using
ptr1=(int*)malloc(score*sizeof(int));
inside your for loop. That causes memory leak. You should free the memory.
You also have
printf("%d%d ", i, ptr[i]);
But ptr[i] has not been assigned any value, so it just gives garbage value. The same problem occurs in
for(j = 1; j<= ptr1[i]; j++)
So you need to assign some value to them before using them like this.
Casting the result of malloc doesn't make any sense, it is pointless and potentially bad practice.
printf("%d%d ", i, ptr[i]);. You print the value of an uninitialized memory cell. This is undefined behavior and might in theory cause the program to crash on some platforms. If you need the memory allocated to be initialized to zero, you should be using calloc() instead.
ptr1=(int*)malloc(score*sizeof(int)); for(j = 1; j<= ptr1[i]; j++) This code makes no sense whatsoever and will crash the program. You use ptr1 as if it was an initialied array of integers, while it is actually an uninitialized, single integer.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int **scores;
int over, score;
int i, j;
printf("Enter the number of over : ");
scanf("%d", &over);
scores = (int**)malloc(over*sizeof(int*));
for(i = 0; i < over; i++){
printf("%d ", i + 1);
printf("Enter the number of run per over : ");
scanf("%d", &score);
scores[i] = (int*)malloc((score+1) * sizeof(int));// +1 for number of columns
scores[i][0] = score;
for(j = 1; j <= score; j++){
printf("%d Enter the score : ", j);
scanf("%d", &scores[i][j]);
}
}
for(i = 0; i < over; i++){
for(j = 1; j <= scores[i][0]; j++){
printf("|%d", scores[i][j]);
}
printf("|\n");
}
//deallocate
for(i = 0; i < over; i++)
free(scores[i]);
free(scores);
return 0;
}
The following code is for printing the elements of a matrix in spiral order. The program works fine. The problem, however, is that the online compiler against which I'm checking the program, doesn't accept trailing white spaces at the end of the output. Could anyone give me some ideas as to how I can get around the last white space being added at the output?
For reference, my code is as follows (yes the variable names are terrible. I'm working on changing my habit of putting random variable names!!)
#include <stdio.h>
int main()
{
int a[6][6];
int i, k = 0, l = 0, m=3, n=3, j;
scanf("%d %d",&m, &n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
while (k < m && l < n)
{
for (i = l; i < n; ++i)
printf("%d ", a[k][i]);
k++;
for (i = k; i < m; ++i)
printf("%d ", a[i][n-1]);
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
printf("%d ", a[m-1][i]);
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
printf("%d ", a[i][l]);
l++;
}
}
return 0;
}
Input:
1 2 3
4 5 6
7 8 9
Output:
1 2 3 6 9 8 7 4 5{one extra space}
Any way to fix this problem?
(Also sorry for the terrible formatting. First question on StackOverflow!)
You can put an if condition in your for loops
for (i = l; i < n; ++i)
{
printf("%d", a[k][i]);
if(i < n-1)
printf(" ");
}
You need to suppress the space when you don't need one.
You can do it like this:
Add these declarations:
char *format = "%d";
int first_number = 1;
Add this after the first printf:
if (first_number) {
/* Now we want a space between numbers */
first_number = 0;
format = " %d";
}
Change your printf:s to use the new variable:
printf(format, ...);
Looking at your code, this for (the first one in the while loop):
for (i = l; i < n; ++i)
printf("%d ", a[k][i]);
will always be executed at least ones (because l<n, coming from the while's condition).
Then you can just do the following:
always add the space in front of the number
add a single if check just for this very first for-loop (use some bool flag).
For example, something like:
bool first = true;
while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
if( ! first )
{
printf(" %d", a[k][i]);
}
else
{
printf("%d", a[k][i]);
first = false;
}
}
// ....
}
This will be rather efficient and short solution - the if is in just one loop and the flag will be true just once (will avoid cache misses).
You can set a boolean variable isFirst to true before your printing out any stuff, and test it before each printf statement. If isFirst, do not print a space but set isFirst to false; else print a single space. After that, continue with printing your number without a space.
Alternative: Instead of printing your results immediately, create a results array. Store your results in there, and when done, print out the results in a tight loop. You can print the first number without a leading space, then loop over the remainder and print them with a leading space.
the printf() statement,
printf("%d ", a[k][i]);
results in extra space. use
"%d"
without space or use space in the begining as,
" %d"
then at the end there wont be a extra space.
its about how you use space in your printf(). use space in a way that extra space is not present at the end as you wanted.
You can use code like this,
while (k < m && l < n)
{
for (i = l; i < n; ++i)
{
if(l==0&&i==0)
{
printf("%d", a[k][i]);
}
else
printf(" %d", a[k][i]);
}
k++;
for (i = k; i < m; ++i)
printf(" %d", a[i][n-1]);
n--;
if ( k < m)
{
for (i = n-1; i >= l; --i)
printf(" %d", a[m-1][i]);
m--;
}
if (l < n)
{
for (i = m-1; i >= k; --i)
printf(" %d", a[i][l]);
l++;
}
An answer after accepted answer:
Rather than:
while (k < m && l < n) {
...
printf("%d ", a[k][i]);
...
printf("%d ", a[i][n-1]);
...
printf("%d ", a[m-1][i]);
...
printf("%d ", a[i][l]);
...
}
Change the format.
const char *format = "%d";
while (k < m && l < n) {
...
printf(format, a[k][i]);
format = " %d";
...
printf(format, a[i][n-1]);
...
printf(format, a[m-1][i]);
...
printf(format, a[i][l]);
...
}
fputc('\n', stdout); // if desired.