I am coding a c project, that needs that the user enters a N*N square of integers : that's to say an input of N lines of N integers. The algo works fine.
Now I want the user to input N lines of N integers each of consecutive integers are separated by a space. Here, I don't have the right usage of scanf, because I tried to declare integers array but I was not able to deal with the spacing.
I tried something like this, very unnatural and failing :
int i=0;
int j=0;
int N;
scanf("%d",&N);
char c[N][2*N-1];
while(i < N){
scanf("%s",&c[i]);
i++;
}
i=0;
j=0;
while (i<N){
while (j<N){
c[i][j]=c[i][2*j]-48;
j++;
}
j=0;
i++;
}
Can someone help ?
Best,
Newben
If I understood what your original code was supposed to do then this code should actually do it (and print it out again just to prove it worked).
You need to dynamically allocate the array since it's variable size ( In C99 you could use variable sized arrays on the stack but that's really a different discussion ).
scanf will automatically ignore white-space between the integers (including spaces and new-lines) so you don't need to parse that out manually.
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i=0, j=0, N;
int **c;
scanf("%d",&N);
c = malloc(N*sizeof(int*));
for (i=0;i<N;i++)
{
c[i] = malloc(N*sizeof(int));
for (j=0;j<N;j++)
{
scanf("%d",&c[i][j]);
}
}
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
free(c[i]);
}
free(c);
return 0;
}
C99 alternative without malloc/free for completeness (I'v never liked this C99 feature since there's no way to check that the was/is enough space on the stack):
#include <stdlib.h>
#include <stdio.h>
int main()
{
int i=0, j=0, N;
scanf("%d",&N);
int c[N][N];
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
scanf("%d",&c[i][j]);
}
}
for (i=0;i<N;i++)
{
for (j=0;j<N;j++)
{
printf("%d ",c[i][j]);
}
printf("\n");
}
return 0;
}
Related
textI have to make one array which is A[n][n]. In this array the user puts some numbers and from this array I have to make a second array which is C[n] which numbers are positive number by row from first one. I try do it by this way but in that way it works for every numbers it have to be only by rows .have to look something like that for example
A00:1 A01:-3 A02:5
A10:-7 A11:-8 A12:7
A20:6 A21:9 A22:10
C00:2 C01:1 C02:3
But in my way it look :
C00:3 C01:3 C02:3 which is wrong.
If somebody have an idea where is the problem I will be so thankful.
> const int n=10;
int a[n][n];
int c[n];
int i,j,k,suma;
printf("vuvedete br redove i stalbove n=");
scanf ("%d",&n);
for (i=0;i<n;i++){
for (j=0;j<n;j++){
do{
printf("a[%d][%d]=",i,j);
scanf("%d",&a[i][j]);
}
while(a[i][j]<-1000||a[i][j]>1000);
}
}
suma=0;
for (i=0;i<n;i++){
for (j=0;j<n;j++){
if (a[i][j]>0){
suma=suma+1;}
}
}
for(k=0;k<n;k++){
printf("c[%d]=%d",k,suma);
}
return 0;
}
Main changes:
Populate array c[] and discard variable suma. This was the primary issue with your code.
You declare n as a const but then allow user to enter its value. I've removed the const and used a #define to set the max dimensions for the arrays.
Removed while loop - what's this for?
General tidying up.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX 10
int main() {
int a[MAX][MAX] = {0};
int c[MAX] = {0};
int n = MAX;
printf("vuvedete br redove i stalbove n=");
scanf ("%d",&n);
for (int i=0;i<n;i++)
for (int j=0;j<n;j++) {
printf("a[%d][%d]=",i,j);
scanf("%d",&a[i][j]);
}
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
c[i] += a[i][j] > 0 ? 1 : 0;
for(int k=0;k<n;k++)
printf("c[%d]=%d\n",k,c[k]);
return 0;
}
The pattern is
___1
__141
_14941
I have tried to some extent but looks like i have created a odd number pattern program
#include <stdio.h>
int main()
{
int i, j, N=3;
for(i=1; i<=N; i++)
{
// Prints the first part of pattern
for(j=1; j<=(i*2)-1; j+=2)
{
printf("%d", j);
}
// Prints the second part of pattern
for(j=(i-1)*2-1; j>=1; j-=2)
{
printf("%d", j);
}
printf("\n");
}
return 0;
}
I can see that the pattern has numbers that are off by odd numbers such as 3 and 5 respectively.
But i cant seem to grasp exactly how to do it.
Any help is much appreciated.
#include <stdio.h>
int main()
{
int i, j, N=3;
for(i=0; i<N; i++)
{
//For printing Spaces
for(int sp=0;sp<N-i;sp++){
printf(" ");
}
/*For printing the numbers
from left till the middle column*/
for(int j=1;j<=i+1;j++){
printf("%d",j*j);
}
/*For printing the numbers
from the strict right to the middle column
and till the end*/
for(int j=1;j<i+1;j++){
printf("%d",j*j);
}
printf("\n");
}
return 0;
}
#include<stdio.h>
#include<math.h>
int perfectSquare(int arr[], int n);
int main()
{
int n , arr[n];
printf("number of elements to store in array");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("enter %d number", i+1);
scanf("%d", &arr[i]);
}
perfectSquare(arr, n);
return 0;
}
int perfectSquare(int arr[], int n)
{
int i;
int a;
for (i = 0; i <= n; i++) //i=4 arr[4]==9 //arr[1]=2 i=1
{
a=sqrt((double)arr[i]); //a=3 //a=1.454=1
if ( a*a==arr[i] ) //a==3*3==9==arr[4] //a*a=1!=arr[2]
printf("%d", arr[i]);
}
}
I am new to coding and I am currently learning c. I came up with this code but it doesn't work can someone tell me what is the problem with this code?
There are a couple of issues with this exercise, but generally you're on the right track. Here, a version of your example with some possible corrections:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void perfect_square(int arr[], int n);
int main(void)
{
int i, n, *arr;
printf("number of elements to store in array: ");
scanf("%d", &n);
if (n <= 0)
return -1;
arr = malloc(n*sizeof(int));
if (arr == NULL)
return -2;
for (i = 0; i < n; i++) {
printf("enter number %d: ", i+1);
scanf("%d", &arr[i]);
}
perfect_square(arr, n);
free(arr);
arr = NULL;
return 0;
}
void perfect_square(int arr[], int n)
{
int i, a;
for (i = 0; i < n; i++) {
a = (int)sqrt((double)arr[i]);
if (a*a == arr[i])
printf("%d ", arr[i]);
}
}
Some hints:
Arrays, that have an unknown size at compile time are usually allocated with malloc(), and must be deallocated again with free() (see also: alloca(), calloc(), realloc()). (In "more recent versions of C" there is also the possibility to use variable length arrays, but those can limit the portability of the code).
Always make sure to check the start value and end condition of for-loops, to prevent out of bound errors.
And try to consistently format the code, use good names and nice indentation to improve read-, maintain-, reusablilty.
i'm new to programming and i'm learning about recursion, i am doing exercise 4 from this page
https://www.w3resource.com/c-programming-exercises/recursion/index.php, i am trying to print the elements of the array once the value of "i" in the recursive function gets to the value of "n", however once i run the program it prints garbage values i think.my question is why does it do that? why doesn't it print the values of the array?
#include <stdio.h>
#include <stdlib.h>
void printr(int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
printr(n,0);
}
void printr(int n,int i)
{
int arr[n];
if (i == n)
{
for (int j = 0; j < n; j++)
{
printf("%d",arr[j]);
return;
}
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i]=e;
//do it again
printr(n,i + 1);
}
Then i solved it by passing the array defined in the mein function asan argument in the printr function
it worked but i don't understand why my first attemp didn't?
#include <stdio.h>
#include <stdlib.h>
void printr(int arr[],int n,int i);
int main (void)
{
printf("NUMBER OF ELEMENTS:\n");
int n;
scanf("%i",&n);
int arr[n];
printr(arr,n,0);
}
void printr(int arr[],int n,int i)
{
if (i == n)
{
for (int j = 0; j < n;j++)
{
printf("%d ",arr[j]);
}
printf("\n");
return;
}
printf("element %d :\n",i+1);
int e;
//scan for input
scanf("%d",&e);
//populate array
arr[i] = e;
//do it again
printr(arr,n,i + 1);
}
Thank you!
Because basic C: each invocation of printr has its own arr on the stack, initially uninitialized. And you print it without initializing it first.
When you print out the value, it isn't initialized first. When you create the variable to be printed, its pointing to a place in memory. This memory was probably freed by another program (so its up for grabs). As such, it contains "garbage" data. The way to deal with this is to initialize your values.
In order to avoid stuff like this in the future, get in the habit of setting your pointers to NULL when you don't initialize them so that your programs segfaults when your trying to read an uninitialized value.
How to read space-separated integers representing the array's elements and sum them up in C?
I used the below code but it reads all the elements in a new line:
#include <math.h>
#include <stdio.h>
int main() {
int i = 0, N, sum = 0, ar[i];
scanf("%d" , &N);
for (i = 0; i < N; i++) {
scanf("%d", &ar[i]);
}
for (i = 0; i < N; i++) {
sum = sum + ar[i];
}
printf("%d\n", sum);
return 0;
}
Your array ar is defined with a size of 0: the code invokes undefined behavior if the user enters a non zero number for the number of items.
Furthermore, you should check the return value of scanf(): if the user enters something not recognized as a number, your program will invoke undefined behavior instead of failing gracefully.
Here is a corrected version:
#include <stdio.h>
int main(void) {
int i, N, sum;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
int ar[N];
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
return 0;
}
Note that the program will still fail for a sufficiently large value of N as there is no standard way to check if you are allocating too much data with automatic storage. It will invoke undefined behavior (aka stack overflow).
You should allocate the array with malloc() to avoid this:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i, N, sum;
int *ar;
if (scanf("%d", &N) != 1 || N <= 0) {
fprintf(stderr, "invalid number\n");
return 1;
}
ar = malloc(sizeof(*ar) * N);
if (ar == NULL) {
fprintf(stderr, "cannot allocate array for %d items\n", N);
return 1;
}
for (i = 0; i < N; i++) {
if (scanf("%d", &ar[i]) != 1) {
fprintf(stderr, "invalid or missing number for entry %d\n", i);
return 1;
}
}
sum = 0;
for (i = 0; i < N; i++) {
sum += ar[i];
}
printf("%d\n", sum);
free(ar);
return 0;
}
Finally, there is still a possibility for undefined behavior if the sum of the numbers exceeds the range of type int. Very few programmers care to detect such errors, but it can be done this way:
#include <limits.h>
...
sum = 0;
for (i = 0; i < N; i++) {
if ((sum >= 0 && arr[i] > INT_MAX - sum)
|| (sum < 0 && arr[i] < INT_MIN - sum)) {
fprintf(stderr, "integer overflow for entry %d\n", i);
return 1;
}
sum += ar[i];
}
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
scanf("%d",&ar[i]);
for(i=0; i<N; i++)
sum=sum+ar[i];
printf("%d\n", sum);
return 0;
}
This should be the code.
You have initially declared the array of size 0 (because i=0).
Even though you declared the array of size 0, when I ran it on my machine, it actually executed successfully with the correct output.
This is generally due to undefined behavior which means that we can only guess the output when the code is correct. If the code has undefined behavior, then it can do whatever it wants (and in the worst case the code will execute successfully giving the impression that it's actually correct).
Declaring a Variable Size Array (VLA) is optional in C11 standard. Thus, it depends on the implementation of the compiler whether it will support VLA or not. As pointed out by #DavidBowling in comments, if the compiler does support, then declaring a VLA of size 0 can invoke undefined behavior (which you should avoid in all cases). If it doesn't support, then this will simply give a compilation error and you'll have to declare the array size as some integer constant (example, int arr[100];).
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
}
for(i=0; i<N; i++)
{
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
You should declare the array after accepting the value of N.
#include <math.h>
#include <stdio.h>
int main()
{
int i=0,N,sum=0;
scanf("%d" ,&N);
int ar[N];
for(i=0; i<N; i++)
{
scanf("%d",&ar[i]);
sum=sum+ar[i];
}
printf("%d\n", sum);
return 0;
}
As this is a very simple question I'll expand it a bit to include some good programming practices.
1. Analyze the problem
We have to complete two tasks here:
Read and store the numbers to array.
Sum the array elements.
Of course you can both read and calculate the same time, but we ❤ the SoC design principle. This will help you later with bigger programs.
2. Create the program structure
In this state we have to consider what function to use, as we already solved the data structure problem (we use array).
Of course, we always can put the whole procedure in main function but this would break the SoC principle.
The main principle here is:
I create a function for a separate procedure.
So we'll have to build two functions. Let's consider the following example:
ReadArrayData will be used to read the data from the standard input (your keyboard in other words) to array. But what will declare as parameters? We surely have to pass the array and the array size. The return type of this function will be void (we don't have to return something).
Keep in mind that if you pass array to function you can manipulate it as you please and keep these changes in your main program. This is because the arrays are passed always by reference to a function.
In the end this will be your function prototype:
void ReadArrayData(int arraySize, int array[]);
CalculateArraySum will be used to calculate the sum of the array elements. The function prototype will be the same as for ReadArrayData with the difference that the returning type will be int (we return the sum).
int CalculateArraySum(int arraySize, int array[]);
3. Write your program
#include <stdio.h>
void ReadArrayData(int arraySize, int array[]);
int CalculateArraySum(int arraySize, int array[]);
int main(void) {
int N;
printf("Give the array size: ");
scanf("%d", &N);
int array[N];
ReadArrayData(N, array);
int sumOfArrayElements = CalculateArraySum(N, array);
printf("The sum of array elements is %d.\n", sumOfArrayElements);
return 0;
}
void ReadArrayData(int arraySize, int array[]) {
printf("Give %d elements: ", arraySize);
for (int i = 0; i < arraySize; ++i) {
scanf("%d", &array[i]);
}
}
int CalculateArraySum(int arraySize, int array[]) {
int sum = 0;
for (int i = 0; i < arraySize; ++i) {
sum += array[i];
}
return sum;
}
I know this was a large scaled answer, but I saw you are new to computer programing. I just wanted to present you the main functionality to solve all kinds of problems. This was just a small introduction. In the end, you have to remember what steps we take to solve a problem. With time and as you solve many problems you will learn many many other things.