C nested for loops add empty line after each 10 iterations - c

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;
}

Related

Printing out elements in an array

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]);
}

Reading formatted data in C

I have a data set with specific format that I want to read in C and also print in certain format. Here is the format of my data in text file:
sample[0][0]=1; sample[0][1]=3;
sample[1][0]=2; sample[1][1]=4;
sample[2][0]=3; sample[2][1]=5;
and I want to read this and return
(*inputs)[0][0] = 1; (*outputs)[0]=3;
(*inputs)[1][0] = 2; (*outputs)[1]=4;
(*inputs)[2][0] = 3; (*outputs)[2]=5;
I was able to write a code that will read my file in just the following format:
1 3
2 4
3 5
and here is my code:
int main() {
FILE *samples;
samples = fopen ("peaks.txt","r");
int arr[10][2];
int i;
int j;
for (i=0; i<10; i++) {
for (j=0; j<2; j++) {
fscanf(samples, "%d, ", &arr[i][j]);
printf("int = %d\t", arr[i][j]);
}
printf("\n");
}
}
How do I modify this code to read the format above? Thank you.
You could read in with, for example for the first line of data,
fscanf(filein, "sample[0][0]=%d; sample[0][1]=%d;", &arr[0][0], &arr[0][1]);
but it is very fragile becaues if the input file is not exactly that then you will get unpredictable behaviour
You could print out with
printf("(*inputs)[0][0] = %d; (*outputs)[0]=%d;", arr[0][0], arr[0][1]);
but probably I got the print statement wrong as I don't know exactly what you want your code to do.
Now for lots of data.....
new version... much simpler...D'oh!
int a,b;
for (i=0; i<10; i++) {
for (j=0; j<2; j++) {
fscanf(samples, "sample[%d][%d]=\%d;", &a, &b, &arr[i][j]);
printf("int = %d\t", arr[i][j]);
}
printf("\n");
}
so now you read in the number values from sample as a and b - but then don't used these value of a and b - though to write a good program you could check the values of a and b are equal to i and j as you expect.
old not working version below
char* string_input[100]; // we need this to get the right format for scanf...
for (i=0; i<10; i++) {
for (j=0; j<2; j++) {
sprintf(string_input, "sample[%d][%d]=\%d;", i, j)
fscanf(samples, string_input, &arr[i][j]);
printf("int = %d\t", arr[i][j]);
}
printf("\n");
}
so what this does is make a taylor made string suitable for reading in your data line by line...
so for example if i=8 and j=1 then string_input will be sample[8][1]=%d;

Using Functions to Pass an Array

Hi, i am using a Function for the first time for my 2-D Array and so far i have been told it is right but i am having a problem with the 'For Loop'.
Specifically repeating the printed statement and numbers until the array is full, and also shows the specific array you are filling. (As the image shows).
This only prints 1 statement with 1 Array, whilst 4 numbers afterwards.. How could i get each number printed after each statement? I have tried the only way i know which made it worse.
Incorrectly Looped printed statement
Code below:
void DisplayArray(int a[2][2]);
int main()
{
int a[2][2], i, j, k;
/*Counter variables for the loop*/
printf ("***** Functions ***** \n");
for (i=0; i<2; i++)
for(j=0; j<2; j++)
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
scanf("%d", &a[i][j]);
DisplayArray(a);
return 0;
}
void DisplayArray(int a[2][2])
{
int i, j;
/*Displaying Array elements*/
printf("\n The 2-D Array contains : \n");
for(i=0; i<2; i++)
for(j=0; j<2; j++)
printf("%d \n" , a[i][j]);/*[i] name of 1 Array - [j] name of 2 Array*/
if(j==2)
printf("\n");
}
You forgot to properly define the scope of the inner for loops.
The lines
for (i=0; i<2; i++)
for(j=0; j<2; j++)
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
scanf("%d", &a[i][j]);
are equivalent to:
for (i=0; i<2; i++)
for(j=0; j<2; j++)
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
// Outside of both the for loops.
scanf("%d", &a[i][j]);
The indent expresses the intent to a human reader but not to the computer.
You need to use:
for (i=0; i<2; i++)
for(j=0; j<2; j++)
{ // Add
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
scanf("%d", &a[i][j]);
} // Add
To make the code more readable add an explicit scope for the outer for loops too.
for (i=0; i<2; i++)
{ // Add
for(j=0; j<2; j++)
{ // Add
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
scanf("%d", &a[i][j]);
} // Add
} // Add
Make similar changes to the other loops.
Your for loops are probably not acting as you intended, because without the curly braces, they will only act on the first statement.
void DisplayArray(int a[2][2]);
int main()
{
int a[2][2], i, j, k;
/*Counter variables for the loop*/
printf ("***** Functions ***** \n");
for (i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
scanf("%d", &a[i][j]);
}
}
DisplayArray(a);
return 0;
}
void DisplayArray(int a[2][2])
{
int i, j;
/*Displaying Array elements*/
printf("\n The 2-D Array contains : \n");
for(i=0; i<2; i++)
{
for(j=0; j<2; j++)
{
printf("%d \n" , a[i][j]);/*[i] name of 1 Array - [j] name of 2 Array*/
if(j==2)
printf("\n");
}
}
}
You're missing some curly braces. Change to this:
for (i=0; i<2; i++)
for(j=0; j<2; j++) {
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
scanf(" %d", &a[i][j]);
DisplayArray(a);
}
and
for(i=0; i<2; i++)
for(j=0; j<2; j++) {
printf("%d \n" , a[i][j]);
if(j==2)
printf("\n");
}
Also, note that if(j==2) will never evaluate to true. When j is equal to 2, the loop is over. You should change this to 1. I would also suggest to remove \n in the innermost printf statement.
Complete code:
#include <stdio.h>
void DisplayArray(int a[2][2]);
int main()
{
int a[2][2], i, j, k;
/*Counter variables for the loop*/
printf ("***** Functions ***** \n");
for (i=0; i<2; i++)
for(j=0; j<2; j++) {
printf("\n Enter numeric values for each Array [%d] [%d]: \n", i, j);
scanf(" %d", &a[i][j]);
DisplayArray(a);
}
return 0;
}
void DisplayArray(int a[2][2])
{
int i, j;
/*Displaying Array elements*/
printf("\n The 2-D Array contains : \n");
for(i=0; i<2; i++)
for(j=0; j<2; j++) {
printf("%d " , a[i][j]);/*[i] name of 1 Array - [j] name of 2 Array*/
if(j==1)
printf("\n");
}
}

compare string strcmp() function with 2d pointer of string?

i am doing code practicing which is below
int main() {
int N, Q, cnt;
scanf("%d", &N);
char **str1=(char**)malloc(sizeof(char*)*N);
for(int i=0; i<N; i++) {
str1[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str1[i]);
}
scanf("%d", &Q);
char **str2=(char**)malloc(sizeof(char*)*Q);
for(int i=0; i<Q; i++) {
str2[i]=(char*)malloc(sizeof(char)*20);
scanf("%[^\n]s", str2[i]);
}
for(int i=0; i<Q; i++) {
for(int j=0, cnt=0; j<N; j++) {
// if statement
if( strcmp(str2[i], str1[j]) == 0) cnt++;
}
printf("%d\n", cnt);
}
for(int i=0; i<N; i++){
free(str1[i]);
}
for(int i=0; i<Q; i++) {
free(str2[i]);
}
free(str1);
free(str2);
return 0;
}
STD input are
4
aaa
bbb
ccc
aaa
3
aaa
bbb
cca
than print out
2
1
0
because
'aaa' is 2 times
'bbb' is 1 times
'cca' is 0 times
if( strcmp(str2[i], str1[j]) == 0) cnt++;
however the if statement, doesn't count cnt++
whats wrong, my code with strcmp() ?
You have two variables called cnt.
One declared on this line:
int N, Q, cnt;
and scoped to the entire function.
One declared on this line:
for(int j=0, cnt=0; j<N; j++) {
and scoped to the for loop.
The statement cnt++ modifies the second one since it's inside the for loop.
The statement printf("%d\n", cnt); prints the first one since it's outside the for loop.

Output correct alignment

I have written a code, and it gives me the exact output that I want except for one thing, the alignment of integers in the output is from left to right but I need it to be from right to left.
Here is my code:
#include <stdio.h>
int main()
{
int cols, rows, i,j,num;
scanf("%d %d",&rows, &cols);
for (i=1; i<=1; i++){
for (j=0; j<=cols; j++){
if (j==0) printf("\t ");
else {
num=j;
printf("\t%d", num);
}
}
printf("\n");
}
for (i=2; i<=rows; i++){
for (j=0; j<=cols; j++){
if (j==0) num=i;
else num=power(i,j);
printf("\t%d", num);
}
printf("\n");
}
return 0;
}
The output that I am getting is
The required output is
Use e.g. %6d in the printf() format specifier, and don't use tabs.
See the manual for the format specifier syntax. Field width is a standard feature.

Resources