C Programming Looping with Row and Column - c

Just try to learn and pick up the logic of C programming. I feel little bit confused for the looping to control the row and column
How can i achieve it in C ?
Enter the number: 3
-a-
---
-a-
Enter the number: 5
-a-a-
-----
-a-a-
-----
-a-a-
Thanks for your help!

Since this is a learning exercise, here are some points to get you on the path to a solution:
The most common way of iterating in two dimensions is two nested loops
In this situation, using two nested for loops would be a good idea
Inside the body of the inner for loop you have access to two variables - one denoting the current row, and one denoting the current column
Your code needs to decide if a letter or a dash is to be printed based on the values of the row and the column
When the row is odd, or when the column is even, print a dash; otherwise, print character 'a'
You can tell if a number is odd or even by examining num % 2 or num & 1. In both cases, if the result is zero, the number is even; otherwise, the number is odd.

It is just about using nested loops, I would say if you want to learn specifics about accessing row and coloumn, practice some programs on Matrix operations such as addition, multiplication etc. You will find a lot of them in google.

put this in your gcc -o cloop cloop.c -std=c99 and ./cloop it.
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char**argv){
int i;
do{
i = 0;
printf("Give me an int (0 to quit) ");
if( scanf("%u", &i) != 1) break;
if( i < 0 ) i = 0;
for( int j =0; j<i;j++) {
for( int k =0; k<i;k++)
printf("%s", (
k % 2 == 0
? "-"
: j % 2 == 0 ? "a" : "-" )
);
printf("\n");
}
} while ( i > 0 );
}

#include<stdio.h>
main()
{
int i,j,n;
printf("Enter the number:");
scanf("%d",&n); // Input the number
for(i=0;i<n;i++) // For n rows
{
printf("\n"); // New line after each row
for(j=0;j<n;j++) // For n columns for each row
{
if(i%2==0) // For alternate(even) rows(the one with a's)
{
if(j%2==0) // For alternate(even) columns(the one without a's)
printf("-");
else
printf("a");
}
else
printf("-"); // For alternate(odd) rows(with only -'s)
}
}
}
This is the logic.

Related

How to check if an element of an array has already been inserted in that array in a "fashionable" way?

Context: An exercise asks me to:
Create an array of 20 elements;
Insert manually 20 numbers, ranging from 10 to 100 (these included), in said array;
If the inserted number (example: x) is not 10 <= x <= 100, print that it is not a valid number and prompt the user to reinsert a - valid - number;
Print the - valid - inserted number if it has been inserted for the first time (that is if the inserted number is not already present as an element of the array). If the number has been inserted already, do not consider it as one of the 'to be inserted' 20 numbers.
Problem: The issue is that, as you may notice watching the code, it is incredibly unoptimized as in "I couldn't think of a better way to solve this problem, but I do know that there must be an overall better way of doing this".
Specifically though, I wasn't able to design a better way to check if the newly inserted number was already inserted before printing it (hence my question).
I have written the following code in which I think I have tackled all of the given tasks.
//Esercizio 6.15 ||| Pag. 277
#include <stdio.h>
#define SIZE 20
int main()
{
int a[SIZE];
int nums_left = 20;
for_cycle:
for(int i=0; i<SIZE; ++i){
printf("Please insert %d numbers (whole)\n", nums_left);
scanf("%d", &a[i]);
//Managing Errors
if(a[i]<10 || a[i]>100){
printf("You have inserted a non valid value!\n");
goto for_cycle; //heresy! I know
}
//Effective execution of the printing | The Issue
if(a[i]!=(a[i-1])){
if(a[i]!=a[i-2]){
if(a[i]!=a[i-3]){
if(a[i]!=a[i-4]){
if(a[i]!=a[i-5]){
if(a[i]!=a[i-6]){
if(a[i]!=a[i-7]){
if(a[i]!=a[i-8]){
if(a[i]!=a[i-9]){
if(a[i]!=a[i-10]){
if(a[i]!=a[i-11]){
if(a[i]!=a[i-12]){
if(a[i]!=a[i-13]){
if(a[i]!=a[i-14]){
if(a[i]!=a[i-15]){
if(a[i]!=a[i-16]){
if(a[i]!=a[i-17]){
if(a[i]!=a[i-18]){
if(a[i]!=a[i-19]){
if(a[i]!=a[i-20]){
printf("You have inserted: %d\n", a[i]);
}}}}}}}}}}}}}}}}}}}
//Updates of the variable 'numbers left to insert' accordingly
nums_left--;
}else{i--;} //decrements the counter
}
return 0;
}
There are two main alternatives for tracking and testing which valid numbers have already been added:
search the array itself
maintain and use an external data structure for tracking the stored values
You have implemented a slightly buggy and inelegant form of the first. Another answer, now deleted, demonstrated a correct and more elegant variation on this theme, using a nested loop to iterate over the array elements already assigned.
In the speed for space tradeoff category, however, there are solutions of the second type. You might, for example, use a binary search tree to record the values added so far, and then search that instead of the main array. For so few total values, however, and such a small range of valid ones, a pretty good alternative would be to maintain a simple lookup table of which values had been recorded so far. For example:
#include <stdio.h>
#define SIZE 20
#define MIN_VALID 10
#define MAX_VALID 100
int main(void) {
int a[SIZE];
_Bool seen[MAX_VALID + 1] = { 0 };
for (int next_position = 0; next_position < SIZE; ) {
printf("Please insert %d numbers (whole)\n", SIZE - next_position);
scanf("%d", &a[next_position]);
if (a[next_position] < MIN_VALID || a[next_position] > MAX_VALID){
printf("%d is not a valid value!\n", a[next_position]);
} else if (seen[a[next_position]]) {
printf("You already inserted %d!\n", a[next_position]);
} else {
printf("You have inserted: %d\n", a[next_position]);
seen[a[next_position]] = 1;
next_position += 1;
}
}
return 0;
}
Given that the range of numbers is limited to 91 options, it is reasonable to create an array of bool initialized to false to store flags to determine if a number has been entered.
On each number being added, if the corresponding flag is false, accept the number and change that flag to true.
A simple implementation of this idea might look like:
#include <stdio.h>
#include <stdbool.h>
#define N 20
#define LOWER 10
#define UPPER 100
int main(void) {
bool flags[UPPER - LOWER + 1] = { false };
int input_numbers[N];
for (size_t i = 0; i < N; i++) {
while (true) {
int n;
if (scanf("%d", &n) != 1) {
printf("Please enter a number.\n");
while (getchar() != '\n');
continue;
}
if (n >= LOWER && n <= UPPER && !flags[n-LOWER]) {
input_numbers[i] = n;
flags[n-LOWER] = true;
break;
}
printf("Invalid input.\n");
}
}
return 0;
}

How to input a 2-D array directly in C with negative values, spaces and newline

I want to directly input a 2-D Array in C, separated just by single spaces and newlines. At the same time I also want to verify whether the user is entering a valid single digit integer (either positive or negative).
I tried the following.
int A[3][3];
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&A[i][j]);
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",A[i][j]);
printf("\n");
}
But I want 2 things in this:-
Input that is first verified whether its a single digit integer or not.
Not works merely for positive integers and 0 but also for negative integers.
eg.
input such as the following should be accepted and stored in 2-d array
1 2 -3 4
-5 1 2 -6
1 1 2 3
I'm sorry if I wasn't clear. An important component is that the input should be confirmed whether its integer or not i.e. the input should be either as char or string and if it is an integer (which can be ascertained by functions such as isdigit() , then it should be converted to an integer value.
This following code chunk works for single positive values
char c = getchar();
if (isdigit(c))
int value = c - '0';
However, I don't know how to enable this functionality for negative integers in a complete 2D array input.
If you want to verify that a number is a single digit, just check if its between -9 and 9.
As for negative numbers, im pretty sure the %d modifier for the scanf captures that.
Please comment down below if the answer is incorrect so i could fix it :)
Edit: i forgot to note that scanf returns the number of read elements. so comparing this against 1 (since you read one element at a time) will allow you to know if the input was partial or not.
something like this:
if (scanf(" %d", &A[i][j]) != 1){
//here goes the code for when the input is partial
}
should do the trick
So first, tell the user to enter values row-wise or column-wise. In this case, ask like this
printf("Enter integers row-wise");
Now the user will enter values.
After scanning those values put an if statement to verify that value is greater than or equal to -9 and less than 9. If value is within the range continue; else put a exit(1); statement and tell the user that entered value is incorrect. Like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int A[3][3];
int i, j;
for( i = 0; i < 3; i++ )
{
for( j = 0; j < 3; j++)
{
scanf("%d", &A[i][j]);
if(A[i][j] >= -9 && A[i][j] <= 9)
continue;
else
{
printf("Enter correct values.\n");
exit(1);
}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf("%d ",A[i][j]);
printf("\n");
}
return 0;
}

Floyd's Triangle right pattern

I have to creat a program thats that asks from the user to enter a number of rows and then creats a floyd's triangle. The problem is i don't seem to manage to make this particular pattern:
1
2 3
4 5 6
7 8 9 10
I have only managed to creat the basic program
#include <stdio.h>
#include <stdlib.h>
int rows, r, c, a;
int number=1;
int main()
{
printf("Floyd Triangle\n");
printf("--------------");
printf("\nPlease enter an integer number of rows: ");
scanf("%d",&rows);
while(rows<=0)
{
printf("\nYou must enter an integer value: ");
scanf("%d",&rows);
}
for(r=1;r<=rows;r++)
{
for(c=1;c<=r;+c++)
{
printf("%d ", number++);
}
printf("\n");
}
there are no erros in my code so far
Just print some spaces before the first number in each row
// ...
for (r = 0; r < rows; r++) {
printsomespaces(r, rows); // prints some spaces depending on current row and total rows
for (c = 0; c < r; +c++) {
printf("%d ", number++);
}
printf("\n");
}
// ...
If you can't write your own function (no printsomespaces) use a loop instead:
//...
//printsomespaces(r, rows);
for (int space = 0; space < XXXXXXXX; space++) putchar(' ');
//...
where XXXXXXXX is some calculation using r and rows.
Try (untested) 2 * (rows - r) (2 is the width of each number: 1 for the number + 1 for the space).
i haven't learnt how to make my own functions yet. isnt there a way to accomplish this only by using loops?
There is. A main problem of this exercise is to compute the needed width of each column, which of course depends on the number in the bottom row. The count of digits of a number can be determined in various ways; perhaps the easiest is via the snprintf(char *s, size_t n, const char *format, ...) function, which
… returns the number of characters that would have been written
had n been sufficiently large…
If n is zero, nothing is written,
and s may be a null pointer.
// we need to compute the width the of widest number of each column
int width[rows];
const int max = rows*(rows+1)/2; // the greatest number
for (c=1; c<=rows; ++c) // see how many characters will be written
width[c-1] = snprintf(NULL, 0, "%d ", max-rows+c);
for (r=1; r<=rows; ++r, puts(""))
for (c=1; c<=rows; ++c)
if (c <= rows-r) // here comes an empty cell in this row
printf("%-*c", width[c-1], ' ');
else
printf("%-*d", width[c-1], number++);

Returning to the start of a for loop in C

Even though this question has been asked a million times I just haven't found an answer that actually helps my case, or I simply can't see the solution.
I've been given the task to make a program that takes in a whole number and counts how many times each digit appears in it and also not showing the same information twice. Since we're working with arrays currently I had to do it with arrays of course so since my code is messy due to my lack of knowledge in C I'll try to explain my thought process along with giving you the code.
After entering a number, I took each digit by dividing the number by 10 and putting those digits into an array, then (since the array is reversed) I reversed the reverse array to get it to look nicer (even though it isn't required). After that, I have a bunch of disgusting for loops in which I try to loop through the whole array while comparing the first element to all the elements again, so for each element of the array, I compare it to each element of the array again. I also add the checked element to a new array after each check so I can primarily check if the element has been compared before so I don't have to do the whole thing again but that's where my problem is. I've tried a ton of manipulations with continue or goto but I just can't find the solution. So I just used **EDIT: return 0 ** to see if my idea was good in the first place and to me it seems that it is , I just lack the knowledge to go back to the top of the for loop. Help me please?
// With return 0 the program stops completely after trying to check the digit 1 since it's been checked already. I want it to continue checking the other ones but with many versions of putting continue, it just didn't do the job. //
/// Tried to make the code look better. ///
#include <stdio.h>
#define MAX 100
int main()
{
int a[MAX];
int b[MAX];
int c[MAX];
int n;
int i;
int j;
int k;
int counter1;
int counter2;
printf("Enter a whole number: ");
scanf("%i",&n);
while (1)
{
for (i=0,counter1=0;n>10;i++)
{
a[i] = n%10;
n=n/10;
counter1+=1;
if (n<10)
a[counter1] = n;
}
break;
}
printf("\nNumber o elements in the array: %i", counter1);
printf("\nElements of the array a:");
for (i=0;i<=counter1;i++)
{
printf("%i ",a[i]);
}
printf("\nElements of the array b:");
for (i=counter1,j=0;i>=0;i--,j++)
{
b[j] = a[i];
}
for (i=0;i<=counter1;i++)
{
printf("%i ",b[i]);
}
for (i=0;i<=counter1;i++)
{
for(k=0;k<=counter1;k++)
{
if(b[i]==c[k])
{
return 0;
}
}
for(j=0,counter2=0; j<=counter1;j++)
{
if (b[j] == b[i])
{
counter2+=1;
}
}
printf("\nThe number %i appears %i time(s)", b[i], counter2);
c[i]=b[i];
}
}
The task at hand is very straightforward and certainly doesn't need convoluted constructions, let alone goto.
Your idea to place the digits in an array is good, but you increment counter too early. (Remember that arrays in C start with index 0.) So let's fix that:
int n = 1144526; // example number, assumed to be positive
int digits[12]; // array of digits
int ndigit = 0;
while (n) {
digits[ndigit++] = n % 10;
n /= 10;
}
(The ++ after ndigit will increment ndigit after using its value. Using it as array index inside square brackets is very common in C.)
We just want to count the digits, so reversing the array really isn't necessary. Now we want to count all digits. We could do that by counting all digits when we see then for the first time, e.g. in 337223, count all 3s first, then all 7s and then all 2s, but that will get complicated quickly. It's much easier to count all 10 digits:
int i, d;
for (d = 0; d < 10; d++) {
int count = 0;
for (i = 0; i < ndigit; i++) {
if (digit[i] == d) count++;
}
if (count) printf("%d occurs %d times.\n", d, count);
}
The outer loop goes over all ten digits. The inner loop counts all occurrences of d in the digit array. If the count is positive, write it out.
If you think about it, you can do better. The digits can only have values from 0 to 9. We can keep an array of counts for each digit and pass the digit array once, counting the digits as you go:
int count[10] = {0};
for (i = 0; i < ndigit; i++) {
count[digit[i]]++;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
(Remember that = {0} sets the first element of count explicitly to zero and the rest of the elements implicitly, so that you start off with an array of ten zeroes.)
If you think about it, you don't even need the array digit; you can count the digits right away:
int count[10] = {0};
while (n) {
count[n % 10]++;
n /= 10;
}
for (i = 0; i < 10; i++) {
if (count[i]) printf("%d occurs %d times.\n", i, count[i]);
}
Lastly, a word of advice: If you find yourself reaching for exceptional tools to rescue complicated code for a simple task, take a step back and try to simplify the problem. I have the impression that you have added more complicated you even you don't really understand instead.
For example, your method to count the digits is very confused. For example, what is the array c for? You read from it before writing sensible values to it. Try to implement a very simple solution, don't try to be clever at first and go for a simple solution. Even if that's not what you as a human would do, remeber that computers are good at carrying out stupid tasks fast.
I think what you need is a "continue" instead of a return 0.
for (i=0;i<=counter1;i++) {
for(k=0;k<=counter1;k++) {
if(b[i]==c[k]) {
continue; /* formerly return 0; */
}
for(j=0,counter2=0; j<=counter1;j++)
if (b[j] == b[i]){
counter2+=1;
}
}
Please try and see if this program can help you.
#include <stdio.h>
int main() {
unsigned n;
int arr[30];
printf("Enter a whole number: ");
scanf("%i", &n);
int f = 0;
while(n)
{
int b = n % 10;
arr[f] = b;
n /= 10;
++f;
}
for(int i=0;i<f;i++){
int count=1;
for(int j=i+1;j<=f-1;j++){
if(arr[i]==arr[j] && arr[i]!='\0'){
count++;
arr[j]='\0';
}
}
if(arr[i]!='\0'){
printf("%d is %d times.\n",arr[i],count);
}
}
}
Test
Enter a whole number: 12234445
5 is 1 times.
4 is 3 times.
3 is 1 times.
2 is 2 times.
1 is 1 times.
Here is another offering that uses only one loop to analyse the input. I made other changes which are commented.
#include <stdio.h>
int main(void)
{
int count[10] = { 0 };
int n;
int digit;
int elems = 0;
int diff = 0;
printf("Enter a whole number: ");
if(scanf("%d", &n) != 1 || n < 0) { // used %d, %i can accept octal input
puts("Please enter a positive number"); // always check result of scanf
return 1;
}
do {
elems++; // number of digits entered
digit = n % 10;
if(count[digit] == 0) { // number of different digits
diff++;
}
count[digit]++; // count occurrence of each
n /= 10;
} while(n); // do-while ensures a lone 0 works
printf("Number of digits entered: %d\n", elems);
printf("Number of different digits: %d\n", diff);
printf("Occurrence:\n");
for(n = 0; n < 10; n++) {
if(count[n]) {
printf(" %d of %d\n", count[n], n);
}
}
return 0;
}
Program session:
Enter a whole number: 82773712
Number of digits entered: 8
Number of different digits: 5
Occurrence:
1 of 1
2 of 2
1 of 3
3 of 7
1 of 8

Removing repetitions of same numbers in an array

Task is to display the array that has no repetitions based on some user generated input.
I'm trying to compare the number with every number before it, if the equality happens, a=1, it should skip it. Code doesn't return anything.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int X[30],Y[30],i,j,k=0,a,N;
printf("Length of the vector: ");
scanf("%d",&N);
printf("Input the numbers: ");
for(i=0;i<N;i++)
scanf("%d",X+i);
Y[0]=X[0];
for(i=1;i<N;i++){
for(j=i-1;j>=0;j--)
if(X[i]=X[j])
a=1;
if(a==0){
k++;
Y[k]=X[i];
}
a=0;
}
for(i=0;i<k;i++)
printf("%d",Y[i]);
}
Three separate issues in your code block:
a is not initialized the first time through your loop. Add a line a = 0; above your loop.
Your if block reads if(X[i]=X[j]); it should be if(X[i] == X[j]) (you're missing one =)
Your final value of k is going to be one less than the total number of elements that you have. Change your final for loop to i = 0; i <= k; i++

Resources