How to make array 1*x and sum up its digits? - c

So i have this type of problem. How to make an array 1*x and then sum up its digits together. I wrote down something like this for now. Any ideas? Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int a,i,w,j,m;
int s[a];
printf("How many digits do you want to sum up\n");
scanf("%d",&a);
for(i=0;i<a;i++)
{
printf("Enter numer %d: ",i);
scanf("%d",&s[i]);
}
for(j=0;j<a;j++)
{
m=s[j]+s[j++];
}
printf("\n %d",m);
return 0;
}

The problems of your code are:
int a;
int s[a];
Here a is uninitialized.So,array size is unknown which is incorrect.And,instead of this
m=s[j]+s[j++];
you should do like this :
m += s[j];
One more thing,you have initialize m = 0 before starting to add.
I've Changed your program to this:
#include <stdio.h>
int main(int argc, char *argv[]) {
int a,i,m = 0;
//First get the array size
printf("How many digits do you want to sum up\n");
scanf("%d",&a);
//Then declare the array with the size (a)
int s[a];
for(i = 0; i < a; i++){
printf("Enter numer %d: ",i);
scanf("%d",&s[i]);
m += s[i];
}
printf("\n %d",m);
return 0;
}

Using uninitialized variable is undefined behaviour.
int s[a];
The above statement defines an array s of size a but the value of a is unpredictable since it is uninitialized and contains garbage. The size of the array must be known when it defined and it remains the same throughout its lifetime. You cannot resize your array by changing the value of a here. You can use dynamic memory allocation using malloc.
Further, the following statement again invokes undefined behaviour -
m=s[j]+s[j++];
That's because it violates the the following rule stated in the C99 standard §6.5 ¶2
Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an expression.
Furthermore, the prior value shall be read only to determine the value
to be stored.

Related

Facing problem while initializing an array

I am facing a problem while initializing an array in C. I am trying to take input of a variable 'n' and declare an array marks[n] with its value set to zero. I wrote the following part of the program to do it.
int n,k,e,m,x;
scanf("%d %d %d %d", &n,&k,&e,&m);
int marks[n]={0};
but executing the program generates the following warnings and errors:
prog.c: In function ‘main’:
prog.c:10:6: error: variable-sized object may not be initialized
int marks[n]={0};
^~~
prog.c:10:20: warning: excess elements in array initializer
int marks[n]={0};
^
prog.c:10:20: note: (near initialization for ‘marks’)
This is the whole program:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int t;
scanf("%d",&t);
for (int z = 0; z < t; ++z)
{
int num_candidate,num_seat,num_exam,max_mark,mark_needed;
scanf("%d %d %d %d", &num_candidate,&num_seat,&num_exam,&max_mark);
int marks[num_candidate]={0};
/*gets the total marks of each students. mark of the last exam of the */
/*num_candidate-th student is not taken */
for (int i = 0; i < num_candidate; ++i)
{
for(int j=0;j<num_exam;j++)
{
if (i==num_candidate-1 && j==num_exam-1)
{
break;
}
scanf("%d",&mark_needed);
marks[i]=marks[i]+mark_needed;
}
}
/*sorting*/
for (int i = 0; i < num_candidat-2; i++)
{
for(int j=i; j<num_candidat-2; j++)
{
if (marks[j]<marks[j+1])
{
int temp = marks[j];
marks[j]= marks[j+1];
marks[j+1]=temp;
}
}
}
/*prints the needed marks*/
mark_needed=marks[num_seat-1]-marks[num_candidat-1];
printf("%d\n",mark_needed+1 );
}
return 0;
}
My goal is to take num_candidate=number of candidates, num_seat= number of seats in the school, num_exam=number of exams, max_mark=maximum achievable marks in a single exam.
I want to know how many marks the n-th student would need in his final exam to be admitted. his mark of the last exam is not taken as an input in the program and I want to figure out the least marks he would need in the final exam.
How can I solve it?
From the C Standard (6.7.9 Initialization)
3 The type of the entity to be initialized shall be an array of
unknown size or a complete object type that is not a variable length
array type.
So instead of this declaration with an initializer
int marks[n]={0};
use
int marks[n];
memset( marks, 0, n * sizeof( int ) );
Pay attention to that n may not be equal to zero.

Scanf in to array

This a dot_product function of 2 vectors of the same length.
I don't understand how to build the array because how the machine will know which input goes to which input (for example i want a={1,2,3} but the input of 123 will come a[0]= 123)...
How do I make end of array[index] input and how do I make end of the whole array.
#include <stdio.h>
#include <stdlib.h>
#define MAXINPUT 100
int dot_product(int v[], int u[], int n)
{
int result = 0;
int i;
for (i=0; i < n; i++)
result += v[i]*u[i];
return result;
}
int main(){
int v1[MAXINPUT];
int v2[MAXINPUT];
int count = 0
int i,print;
printf(" first vector:");
for(i=0;i<MAXINPUT;i++){
scanf("%d", &v1[i]);
count +=1;
}
printf(" second vector:");
for(i=0;i<MAXINPUT;i++)
scanf("%d", &v2[i]);
print = dot_product(v1, v2, count);
printf("v1*v2:%d",print);
return 0;
}
The first problem I observe here is with
count +=1;
where count is an uninitialized automatic local variable, which makes it's initial value indeterminate. Attempt to use that value invokes undefined behavior.
You should be initializing count to 0.
That said, here, you're depending on the user to input the second array with exact same dimension of that of the first one. In case that does not happen, your program will blow up, as you did not initialize the arrays, again.

Push, pop and display functions from one string to a stack

I'm trying to write a program where the user introduces an array numbers and alphabethic characters. Then the program reads the array, if he sees a number, the program should push that number into one stack. However, if he sees an alphabetical character, the last number pushed is popped.
So far I have this code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 20
int top, i;
void push (double stack[], double x, int top)
{
stack[top] = x;
}
int pop (double stack[])
{
double x;
stack [top]=x;
return x;
}
void display (double stack[],int top)
{
int i;
printf ("\n The stack is: ");
for (i=0; i<=top; i++)
{
printf ("%lf\n",stack[i]);
}
}
void main()
{
int r;
int stack[10];
char array[10];
printf("introduce the numbers");
fgets(array,MAX,stdin);
int l;
r=strlen(array);
top=0;
for (l=0;l<=r;l++)
{
int n;
if (isdigit(array[l]))
{
push(stack,array[l],top);
top=top+1;
}
if (islower(array[l]))
{
pop(stack);
printf("you have popped %d", n);
top=top-1;
}
}
display(stack,top);
}
For some reason the program does not work, if I introduce 22a the output is:
you have popped 4194432
The stack is: 50.00000
50.00000
I am particularly interested in how should I write the pop,push and display to make this program work. How can I do it?
First off, your variable n, the value of which you're printing, is uninitialized and contains whatever garbage that was in the memory at the moment of its creation.
Also, why are you printing it? I think you meant to say n = pop(stack);, right? Otherwise this printing is useless.
Throughout your code you're writing loops the wrong way: for (t=0; t<=threshold; t++). This code will make the loop run threshold + 1 times, but you obviously want only threshold, so do for (t=0; t<threshold; t++) instead.
You're also reading (fgets(array,MAX,stdin);) maximum twenty characters into your array, which can hold only ten characters.
To use strlen on an array, you need it to end with zero (null-terminator). In your code array is not necessarily initialized with zeros, so use memset(array, 0, 10); before using array:
Docs on memset
Tutorial on for loops
void main() is wrong
What to read to learn C

error while using array of pointers instead of 2 dimensional array

the following code crashes if i give array of pointer here is there any other way to accept value through array of pointers or did i do somethong wrong here
the run this program after compiling you should type
objectname -numberoflines
//program to print first n lines of string using command line arguement
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
int less(int x,int y);`enter code here`
int main(int argc,char* argv[])
{
int i,j,n,num;
char *lines[100];/*if I use two dimensional array here the code compiles
char nu[6];
// the whole for loop is for checking error in n
for(i=1,n=strlen(argv[1]);i<n;i++)
{
if(argv[1][i]=='.')
{
printf("your input was not correct \n");
return 0;
}
if(argv[1][i]=='-')
{
printf("your input was not correct \n");
return 0;
}
if(isalpha(argv[1][i])!=0)
{
printf("your input was not correct indeed");
return 0;
}
}
printf("\t\t application to print number of last n lines \n\n\n");
printf("enter the number of lines\n");
scanf("%d",&n);
printf("enter your lines \n");
for(j=0;(n<100)&&(j<=n);j++)
{
gets(lines[j]);
}
strcpy(nu,argv[1]);
nu[0]=' ';
num=atoi(nu);
num=(less(num,n));
for(i=0;i<=num;i++)
{
printf("%s",lines[i]);
}
return 0;
}
int less(int x,int y)
{
int z;
return (z=(x>y?y,printf("your input lines are less\n"):x));
}
The main problem is that when you write
char *lines[100];
You create an array of 100 char* pointers. These pointers have no memory allocated for them and they point to a random location. Writing to that location(using gets in your program) invokes Undefined Behavior.
To fix it, allocate memory for each pointer using
for(i=0 ; i<100 ; i++)
lines[i]=malloc(AMOUNT_OF_BYTES_TO_ALLOCATE);
And later, after the use is over, free the allocated memory using
for(i=0 ; i<100 ; i++)
free(lines[i]);
The reason that it worked when you used a two dimensional array is that you create an array of array of char for which memory is automatically allocated in the stack.

Can't find max and min in my code

I have written two code for max and min. The first is without, the second with an extra function.
The first one works, but for second one minimum is always 1. Why?
What causes the problem?
(1) Code without function:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int x,n,min=x,max=1,cnt;
while(1){
cnt=0;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
printf("enter your numbers\n");
while (cnt!=n){
scanf("%d",&x);
cnt++;
if(x>max)
max=x;
if(x<min)
min=x;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
system("cls");
}
return 0;
}
(2) Code with function:
#include <stdio.h>
#include <stdlib.h>
int maximum(int);
int main(int argc, char *argv[]) {
int n;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
maximum(n);
return 0;
}
//*****************************************
int maximum(int n){
int i,a,max=1,min=a;
printf("enter your number\n");
for(i=1;i<=n;i++){
scanf("%d",&a);
if(a>max)
max=a;
if(a<min)
min=a;
}
printf("maximum is:%d\n",max);
printf("minimum is:%d",min);
getch();
}
Your code causes undefined behavior. Undefined behavior means, anything could happen.
You have not initialized the variable a and you are doing min=a;
C99 section 6.7.8 Initialization:
If an object that has automatic storage duration is not initialized explicitly,
its value is indeterminate.
C99 section 3.18 Un-defined behavior:
Behavior, upon use of a non-portable or erroneous program construct, of erroneous
data, or of indeterminately valued objects, for which this International Standard
imposes no requirements.
This means, compiler is free to do anything. It can crash your program, your program might print JLo pic on your monitor...Etc...
Your code invokes undefined behavior because the assignment min=x in first and min=a in second done without initializing x and a. In this case you may get anything, either expected or unexpected result or segmentation fault or program crash.
To fix this issue you can modify your code as
Code 1.
int x,n,min,max=1,cnt;
while(1){
cnt=1;
printf("how many numbers do you want to enter\n");
scanf("%d",&n);
printf("enter your numbers\n");
scanf("%d",&x);
min = x;
while (cnt!=n){
scanf("%d",&x);
...
...
Code 2.
int maximum(int n){
int i,a,max=1,min;
printf("enter your number\n");
scanf("%d",&a);
min = a;
for(i=1;i<n;i++){
scanf("%d",&a);
...
...

Resources