Analyze output pattern and write algorithm of a program that prints such a pattern.
Input 4
Pattern:
55555
4444
333
22
1
Input 3
Pattern:
333
22
1
Process (what I have come up with)
n = input (“Enter a positive integer”)
r= 0
while r < n
c = (n – r) + 1
while c > 0
s = n – r
print s
c = c – 1
end
r = r + 1
n = n – 1
print end l
end
Problem: I have used r for rows, and c for columns. The problem rises in c = (n – r) + 1 for first row. It makes the first row n+1, works for following rows.
On dry run i get
Input 3
Pattern:
444
22
1
This should work:
n = input (“Enter a positive integer”)
while n > 0
c = n
while c > 0
print n
c = c – 1
end
n = n - 1
print end l
end
Be careful about what meaning you give to your variables and therefore, how you treat them consitently ;)
why are you using while for something that is an obviously an example of for statement?
n = input (“Enter a positive integer”)
for(i=n ; i > 0 ; i--)
{
for(j=0 ;j<i; j++)
{
print i;
}
print "\n";
}
Related
I have a text file that contains:
1 1 1
1 2 2
1 3 2
1 7 5
1 8 4
1 9 4
1 10 2
...
and this is my function:
void addRatings()
{
int n,m,l;
int a[50][100];
MovieR = fopen("d://ratings.txt","r");
l = LineNum(MovieR);
MovieR = fopen("d://ratings.txt","r");
for(int i=0;i<l;i++)
{
fscanf(MovieR,"%[^\t]\t%[^\t]\t%[^\t]\n",&n,&m,&a[n][m]);
}
}
Now I want to get the first and second column for n and m
then I want to give third column to the a[n][m].
How can I do that?
You need to read the third value into a temporary variable, and then store that value into the array if and only if the following conditions are met:
fscanf returned 3, meaning that it actually found three numbers
the value for n is between 0 and 49 inclusive
the value for m is between 0 and 99 inclusive
And the code doesn't need to count the number of lines (using LineNum()). The loop should end when fscanf runs out of numbers to read, i.e. returns something other than 3.
The resulting code looks something like this:
void addRatings(void)
{
int a[50][100] = {{0}}; // initialize all ratings to 0
FILE *MovieR = fopen("d://ratings.txt", "r");
if (MovieR != NULL)
{
int n, m, rating;
while (fscanf(MovieR, "%d%d%d", &n, &m, &rating) == 3) // loop until end-of-file
{
if (n < 0 || n > 49 || m < 0 || m > 99) // check for valid indexes
break;
a[n][m] = rating;
}
fclose(MovieR);
}
}
Program - Rotating matrix 90 degrees clockwise.
I am a beginner in coding. I came across this question on GeeksforGeeks. I found the solutions very complex so tried applying my logic. But I don't know if my logic is appropriate for the program. Kindly guide me.
#include<stdio.h>
int main()
{
int A = 0 , a = 0 , b = 0;
int arr[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
printf("90 Degree rotation: \n");
printf("\n");
for(A = 2; A >= 0; A--)
{
for(a = 0; a < 3 ; a++)
{
for(b = 0; b < 3 ; b++)
{
if(b==A)
printf("%d\t",arr[a][b]);
}
}
printf("\n");
}
}
Input
1 2 3
4 5 6
7 8 9
Output
3 6 9
2 5 8
1 4 7
This is you matrix, with the axis you chose :
b ->
a 1 2 3
| 4 5 6
V 7 8 9
That is, for a fixed a for instance, if you increase b, you print "the next number" (provided b is not 2). Similarly, if you increase a with the same b, you take the same column, but the next line.
So, you can have the following pseudo program, to print a full column (on a line):
print_column(b):
for a from 0 to 2
print arr[a][b]
print newline
What do you want ? You want to print the following :
3 6 9
2 5 8
1 4 7
That is printing the last column, then the middle one, then the first one, which is done by the following pseudo-program:
print the 3rd column of arr
print the 2nd column of arr
print the 1st column of arr
or, more concisely :
for b from 2 to 0
print the b-th column of arr.
So, the final pseudo code is (inlining the print_column procedure):
for b from 2 to 0
for a from 0 to 2
print arr[a][b]
print newline
Or, in C:
for(b = 2; b >= 0 ; b--)
{
for(a = 0; a < 3 ; a++)
{
printf("%d\t",arr[a][b]);
}
printf("\n");
}
I'm facing a slight problem with one of my projects. I am supposed to write a c program to calculate each character present in the input/file. (It's supposed to be a basic program.) The constraints - I cannot use the math.h library to produce log functions and obtain an output in the format:
1
5 1 2 0 2 2 5 8 4 3 6 6 2 5 5 7 2 1 1 2
7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
The program is supposed to count the number of occurrences of each alphabetic letter (case insensitive) in the stdin input stream and display a histogram.
As you can see, the output is formatted vertically with each line printing the base 10 number of the position of the character.
Now, this might seem silly, but what I have so far is this:
#include <stdio.h>
#include <ctype.h>
/*
int logBase10 (int num) {
method to calculate the log base 10 of num
}
*/
int main (int argc, char * argv[]) {
char alpha;
int count = 0;
int ascii[128] = {0};
while ( (alpha = getchar()) != EOF) {
count++;
ascii[(int)alpha]++;
alpha = getchar();
}
printf("Char \t Count \n");
printf("------------------------\n");
for (int i = 0; i < 127; i++) {
if(ascii[i] > 0) {
printf("%c \t %d \n", i, ascii[i]);
}
}
}
Which produces an output like this:
Char Count
------------------------
5
93
, 6
- 2
. 3
; 2
C 2
I 6
N 1
T 1
W 2
a 26
b 5
c 8
d 13
e 55
f 11
g 7
h 28
i 32
k 3
l 26
m 17
n 31
o 27
p 12
q 1
r 26
s 22
t 42
u 11
v 8
w 8
y 13
z 1
First off, my program is printing unwanted ascii characters (, ; - etc) and I am working on changing the print function to be more vertical, but I cannot figure out the log method at all. I know log(10) is 1 because 10^1 is 1, but I am having trouble figuring out how to use this to create the method itself. Also, for the extra characters, I tried using:
if(ascii[i] > 65 || ascii[i] < 90 || ascii[i] >= 97 || ascii[i] <= 122 ) {
printf("%c \t %d \n", i, ascii[i]);
}
to no avail. Trying that produced more gibberish characters instead.
Any help/feedback is appreciated.
Soul
The commenters have already pointed out issues with your code. Here's a version that counts only letters and prints vertical labels. It doesn't need <ctype.h> or <math.h>.
Each character hets a letter index which is a number from 0 to 25 for upper and lower case letters and −1 if the character isn't a letter. That reduces the array size to 26.
You could find out each digit with elaborate calculations, but the easiest way is to print the number to a string. snprintf does this for you. You can right-align the number with a field width. The maximum value for a typical int is about 2 billion, which has 10 digits. You should account for that, even if you had to pass in the whole Moby-Dick plus the Bible to get that many counts.
You can test whether you should start printing by assuming a width of ten digits first and checking whether the maximum count has ten digits, that is whether it is 1,000,000,000 or higher. Then divide that limit by 10 in each iteration.
Here's the code:
#include <stdio.h>
// return letter index or -1 for non-letter
int letter(int c)
{
if ('a' <= c && c <= 'z') return c - 'a';
if ('A' <= c && c <= 'Z') return c - 'A';
return -1;
}
int main(int argc, char * argv[])
{
int count[26] = {0}; // letter counts
char label[26][12]; // buffer for printing numbers
int limit = 1000000000; // smallest 10-digit number
int max = 0;
int i, j;
// read and count letters
while (1) {
int c = getchar();
if (c == EOF) break;
c = letter(c);
if (c >= 0) count[c]++;
}
// write auxiliary labels
for (i = 0; i < 26; i++) {
snprintf(label[i], sizeof(label[i]), "%10d", count[i]);
if (count[i] > max) max = count[i];
}
// print vertical labels
for (j = 0; j < 10; j++) {
if (max >= limit) {
for (i = 0; i < 26; i++) {
putchar(' ');
putchar(label[i][j]);
}
putchar('\n');
}
limit /= 10;
}
// print horizontal rule
for (i = 0; i < 26; i++) {
putchar('-');
putchar('-');
}
putchar('-');
putchar('\n');
// print letters
for (i = 0; i < 26; i++) {
putchar(' ');
putchar('A' + i);
}
putchar('\n');
return 0;
}
On your example, it produces:
1
5 1 2 0 2 2 5 8 4 3 6 6 2 5 5 7 2 1 1 2
7 9 8 1 7 2 4 1 0 0 4 5 0 2 2 5 2 6 3 6 6 3 7 0 2 2
-----------------------------------------------------
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
One easy way to figure out how many digits that you'll need is to use sprintf to convert the integer count to a string, and then use strlen to find out how many digits you have. For example:
char str[20] = {0}; // 20 digits should be enough for your case
for (i = 0; i < 128; i++) {
sprintf(str, "%d", ascii[i]);
num_digits = strlen(str);
printf("%d has %d digits\n", ascii[i], num_digits);
}
I didn't test the code, but it should be close.
Some pseudo code
Find max count
Find width of that count when printed w=sprintf(buf, "%d", mxcnt)
Loop w times (wi = 0 to w - 1)
for each non-zero count
form string sprintf(buf, "%*d", w, count[i])
print buf[wi] character
print space
print \n
I try to get the VHDL code corresponding to my simulation on MATLAB with HDL coder app, but I get a first error at the line 25 when I build the MATLAB code on the HDL coder app:
Index expression out of bounds. Attempted to access element 15. The valid range is 1-1.
I don't understand because the simulation on MATLAB works and I don't get this error.
function U_p = HDL_decoder_function(r)
H1 = [ 1 0 0 0 1 0 1 1 0 0 0 0 0 0 0 ];
H = 0;
S_in_rows = 0;
Sm = 0;
S = 0;
f_in_column = 0;
f = 0;
f_largest = 0;
f_nth_largest = 0;
% Declaration of the parity-check matrix
% Fill the first row to prepare the shift in the H matrix
for i = 1 : 15
H( 1, i ) = H1(i);
end
% Fill all the other rows with the shift
for j = 2 : 15
for i = 1 : 15
if( i == 1 )
H( j, i) = H( j-1, 15); % first error
else
H( j, i) = H( j-1, i-1);
end
end
end
H;
% Start of the bit-flipping algorithm
for k = 1 : 20 % Authorize 20 executions maximum of the statements of the algorithm
% Calculate the syndrome S = r^T * H
for j = 1 : 15
for i = 1 : 15
S_in_rows(i) = and( r(i), H( j, i) );
end
for i = 1 : 15
Sm = sum(S_in_rows);
end
if rem(Sm, 2) == 1
S(j) = 1;
else
S(j) = 0;
end
end
S;
% Go out from the loop when syndrome S = 0
if S == 0
U_p = r;
break
end
if k == 20
disp('Decoding fail')
U_p = [ 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ];
end
% Find the number f of failed syndrome bits for every received bits r
for i = 1 : 15
f(i) = 0; % Declaration
end
for i = 1 : 15
for j = 1 : 15
f_in_column = and( S(j), H( j, i) );
if f_in_column == 1
f(i) = f(i)+1;
end
end
end
f;
% Flip the the rth bit corresponding to the first largest number of error in f
f_largest = 0;
for i = 1 : 15
if f(i) > f_largest
f_largest = f(i); % Save the number of error
f_nth_largest = i; % Save the position of f_largest
end
end
f_largest;
f_nth_largest;
r(f_nth_largest) = not(r(f_nth_largest));
r;
U_p = r;
end
I don't use the HDL coder, but I have a likely cause. From your code:
H = 0;
% Fill the first row to prepare the shift in the H matrix
for i = 1 : 15
H( 1, i ) = H1(i);
end
Here, you define H to be a single integer, than use it as if it was a matrix. This is bad practice in Matlab (though will run) since each time you write to an array location that doesn't exist, Matlab creates a new array, then copy the current content to it, free the previous content and finally make the assignation. When it comes to VHDL, the variable size must be fixed and known in advance, there is no dynamic array in hardware.
You should pre-allocate your variables to the right dimensions before you use them. Simply change H = 0 to
H = zeros(15, 15);
Note that similarly, other variables are not initialized to the right size, including S, S_in_row and f.
Can anyone explain to me how does this loop works? I understand that the first operator counts its remainder, the second counts its division result, but I can't understand how does it sum them using the loop? Here's the code:
// Calculate the sum of the digits of the number N.
int N, S, Z;
S = 0;
printf("Input N\n");
scanf("%d", &N);
while(N != 0) {
Z = N % 10;
N = N / 10;
S = S + Z;
}
printf("Sum = %d\n", S);
This while loop adds all the digit of your number referred in by N. It add's all the digit by taking remainder of number when divided by 10. And everytime, it eliminates the last digit of the number. So if your number is 326, it will work like:
326 != 0
Z = 6
N = 32
S = 6
32 != 0
Z = 2
N = 3
S = 8
3 != 0
Z = 3
N = 0
S = 11
0 == 0 come out of loop
print value of S i.e. 11
It's basically a sum of digits of an integer number.
Example:
input ==> 1234
output ==> 4+ 3+ 2 + 1 = 10
Code Break down:
Initialize S [sum] to 0.
Loop:
Z = N % 10; , store the remainder of N after %10 into Z.
N = N / 10; , divide the contents on N by 10 and store the result back in N.
S = S + Z;, sum the content of S with the value in Z.
after that, check the modified value of N is 0 or not. If not, continue [1,2,3..)
Suggestion:
Always check the success of scanf("%d", &N);. If by any chance, scanf() fails, your code is trying to access uninitialized variable N, which may very well lead to undefined behaviour.
The loop will execute until the n value become zero. For example
N=123
Then the first time values of the variables is
Z:3 : N:12 : S:3
Second time
Z:2 : N:1 : S:5
Third time
Z:1 : N:0 : S:6
Finally the answer of S will be 3+2+1=6.
Let's for a example take 657:
Z = N % 10; // This line will store 7 in Z
N = N / 10; // this line will convert N to 65
S = S + Z; // and finally this line will add 0+7