I don't know if I'm just being a total fool, most likely I am, it's been a long day, but this isn't working as I want it to, and, well, I don't see why.
It should be able to have 11 numbers entered, a new number on each line, add them to the array, then total them, yet it's just not working. It's not stopping to exit the loop, even though I am incrementing i.
Any ideas?
int main(void) {
int array[10];
int i;
int sum = 0;
for ( i = 0; i < 11; i++){
scanf("%d", &array[i]);
}
for (i = 0; i < 11; i++) {
sum += array[i];
}
printf("%d", sum);
return 0;
}
You have 10 elements in the array, numbered 0 - 9. You are overflowing the buffer, so all bets are off. This is undefined behaviour.
You can't add eleven entries to a ten-element array.
My guess is buffer over-run since the for-loop reads in 11 numbers and the 11th number gets stored outside the array, probably overwriting i.
Try changing the 11 to a 10 in the for loop.
You're storing eleven numbers into an array of size 10. Thus you're storing the last element out of bounds, which invokes undefined behavior.
The reason that this undefined behavior manifests itself as an infinite loop in your case is probably that i is stored after array in memory on your system and when you write a number into array[10] (which is out of bounds, as I said), you're overwriting i. So if you entered a number smaller than 11 this will cause the loop to continue and ask for input once more.
If an array is a[10], then every array starts from its index number 0, so here it will have 10 elements; given that their positions will start from 0 to 9, counting gives 10 elements.
You can try this:
main()
{
int a[10], i, n, sum=0;
printf("enter no. of elements");
scanf("%d",&n);
printf("enter the elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for (i=0;i<n;i++)
sum=sum+a[i];
for(i=0;i<n;i++)
printf("\n a[%d] = %d", i, a[i]);
printf("\n sum = %d",sum);
getch();
}
You have problems with your array declaration. You are defining an array of size 10 array[10] and saying the program to calculate the sum of 11 elements which is resulting in memory overflows.
To correct the program just increase size of the array as array[11]. Also if you wish you can check the recursive approach to find sum of array elements.
Try this:
void main() {
int array[10];
int i;
int sum = 0;
for ( i = 0; i < 11; i++){
scanf("%d", &array[i]);
}
for (i = 0; i < 11; i++) {
sum = sum + array[i] ;
}
printf("%d", sum);
return 0;
}
int main()
{
//this the sum of integers in an array
int array[] = { 22,2,2,1,5,4,5,7,9,54,4,5,4 },x,sum=0;
int cout_elements = sizeof(array) / sizeof(int);
for (x = 0; x < cout_elements; x++) {
sum += array[x];
}
printf("%d",sum);
return 0;
}
int main()
{
int a[10];
int i,j;
int x=0;
printf("Enter no of arrays:");
scanf("%d",&j);
printf("Enter nos:");
for(i=0;i<j;i++)
{
scanf("%d",&a[i]);
}
for (i=0;i<j;i++)
{
x=x+a[i];
}
printf("Sum of Array=%d",x);
return 0;
}
Related
#include <stdio.h>
int main()
{
//Initialize array
int n; // n is use to decide the size of array
int x[n];
int y[n];
printf("enter the size of array:");
scanf("%d", &n);
if (n > 0)
{
for (int i = 0; i < n; i++)
{
printf("enter elements : \n");
scanf("%d", &x[i]);
}
}
printf("Array in reverse order: \n");
//Loop through the array in reverse order
for (int i = n - 1, j = 0; i >= 0; i--, j++)
{
y[j] = x[i];
printf("%d ", y[j]);
}
return 0;
}
In the above program, I have created a array whose size can be decided by the user. The user can also put elements in it.
After that I want to reverse this array and store the data in another array. But I get this error again and again. I am using CodeBlocks with the GCC compiler.
When the x and y arrays are created, n is uninitialized. There's no knowing how large these arrays will be. You loops are almost certainly accessing the array out of bounds.
You want to read n, then create the arrays. Of course you also want to error check the result of scanf.
int n; // n is use to decide the size of array
printf("enter the size of array:");
scanf("%d", &n);
int x[n];
int y[n];
Im making a code for an array that has a dynamic size and filling the array manually.Then, it will print. It will also ask for a number and finding the index that is equal to the two indexes.
I using codeblocks for this code. Id tried for loop to find the two indexes that is eqaul to the inputed number.
#include <stdlib.h>
#include <stdio.h>
void printArray(int *array, int size) {
printf("[");
for (int i = 0; i < size - 1; i++) {
printf("%i,", array[i]);
}
if (size >= 1)
printf("%i", array[size-1]);
printf("]\n");
int num;
printf("Enter number to be calculate: ");
scanf("%d",num);
for(int i= 0; i < size - 1; i++){
if (array[i] + array[size-1] == num){
printf("%d %d", array[i],array[size-1]);
}
size--;
}
}
int main(void) {
int count;
int num;
int sum;
printf("Enter the size of the array:\n");
scanf("%d", &count);
int *array = malloc(count * sizeof(*array));
if (!array) {
printf("There was a problem you entered");
exit(EXIT_FAILURE);
}
printf("Enter the elements of the array:\n");
for (int i = 0; i < count; i++)
scanf("%d", &array[i]);
printArray(array, count);
}
I expect the output:
Index 1 and 5 are eqaul to the inputed number.
but it gives error.
To begin with, the following bug is one of the problem -
scanf("%d",num);
should be -
scanf("%d", &num);
The final loop in printArray is basically iterating through the array one element both upwards & downwards at the same time.
So, for n=6, if sum of either (a[0]+a[5]), (a[1]+a[4]) or (a[2]+a[3]) does not equal the required number , it would show up as unmatched.
This loop should be replaced by a nested loop so that inner loop iterates from j=i+1 to size-1 to allow check for a[i]+a[j] == num for all possible permutations of array indexes.
This code is to find the mean, median and mode for a given sequence of number.
#include <stdio.h>
#include <math.h>
int main()
{ /*Inputs*/
int n;
int a[n];
/*Outputs*/
float mean;
int median;
int mode;
printf("Enter the size of array: ");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
printf("\nEnter the values of array: ");
scanf("%d",&a[i]);
}
/*arrange in ascending order */
int i=0;
for(i=0; i<n-1; i++)
{for(i=0; i<n-1; i++)
{
if(a[i]>a[i+1])
{
int temp = a[i+1];
a[i+1] = a[i];
a[i] = temp;
}
}
}
/*Mean of the series*/
for(i=0; i<n; i++)
{
int sum = 0;
sum = sum + a[i];
mean = sum/n;
}
/*Median of the series*/
I hope the syntax of typecasting here is right, right?
int m = floor((double)n/2);
if(n%2==0)
{
median = (a[m]+a[m-1])/2;
}
else
{
median = a[m];
}
/*Mode of the series*/
int count;
int b = 0;
for(i=0; i<n-1; i++)
{
for(int t=0; t<n; t++) //Compare a[i] with all the elements of the array
{if(a[i]==a[t])
{
count = 0;
count++;
}
if(b<count) //Update the new value of mode iff the frequency of one element is greater than that
{ // of its preceding element.
mode = a[i];
}
}
}
printf("The value of mean: %f",mean);
printf("\nThe value of mean: %d",median);
printf("\nThe value of mean: %d",mode);
return 0;
}
There were no errors in the code.
I received the following message on the prompt after "CentralT...... working":
Process returned -1073741571 (0xC00000FD) execution time : 47.686 s
Press any key to continue.
In C you cannot resize an array.
This line
int n;
defines n and leaves its value as garbage, a random value, perhaps 0.
Based on what ever n holds this line
int a[n];
defines a as array to have the number of element as per n now has.
Reading into n in this line
scanf("%d",&n);
does not change the number over a's elements.
To fix this, define a only after n has a well defined, valid value:
scanf("%d",&n);
int a[n];
To really make sure n had been set you want to test the outcome of scanf() like for example:
do {
if (1 != scanf("%d, &n))
{
puts("Bad input or failure reading n!\n");
continue;
}
} while (0);
Just learning C and I'm trying to understand how I get the sum of numbers using 2 functions but the results is incorrect.
I'm trying to ask the user for 10 numbers which are stored in an array in function main. The sum is then calculated in a separate function and then displayed in main.
Here is my original code without multiple functions that works:
int main()
{
int n[10];
int index;
int sum_n = 0;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
sum_n += n[index];
}
printf("The Sum of numbers is %d\n", sum_n);
}
Here is me trying to convert it to functions but the sum isn't working out:
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
}
if (n[index] = 10){
//sum_n += n[index];
printf("The Sum of numbers is %d\n",calculations(n[index]));
}
&
int calculations (int num){
int sum_n = 0;
sum_n += num;
return sum_n;
}
When I run the second program using functions for numbers 1 to 10 I'm getting:
I'm either doing something blatantly wrong or not understanding what I'm doing at all.
every time you call a function the variables declared within a function are reset.
in case you want a variable that won't be reset every time you call a function you can simply make it static.
moreover you are passing and argument n[10] but your array stores number from n[0] to n[9] . And if you want sum of all ten numbers then you have to call calculation function for every number or you could just pass whole array. here is modified code.
#include<stdio.h>
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
int ans=0;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d",&n[index]);
ans = calculations(n[index]);
}
printf("The Sum of numbers is %d\n",ans);
}
int calculations (int num){
static int sum_n;
sum_n += num;
return sum_n;
}
First you don't need array for sum in this code, Second always remember to check what returned by scanf.The code is very simple.
first part with main
int main()
{
int n;
int sum=0;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
sum+=n;
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Second using function calculation
int sum=0;
void calculation(int num){
sum+= num;
}
int main()
{
int n;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
calculation(n);
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Your function calculations() simply returns its parameter (0 + num is simply num).
The statement
int sum_n = 0;
in it resets sum_n to 0 every time of calling it.
Move this statement out of it - directly into main() function (and before calling calculations()).
Corrections mentioned in comments below.
int calculations (int *num){ //Should be a pointer or array eg. int num[] as you want to pass an array to this function
int sum_n = 0;
int i;
//Create loop here to iterate over array and sum elements
for(i=0; i<sizeof(num)/sizeof(int); i++)
sum_n+=num[i];
return sum_n;
}
And
if (n[index] = 10){ //This is logically incorrect. This should be if(index==10).
// n[index]=10 will assign 10 to a[10] and if will still pass as if(10) is true but make a note of it. Don't use assignment operator inside if, you need comparison operator `==`
printf("The Sum of numbers is %d\n",calculations(n[index])); //You should call calculations like this -> calculations(n). You should pass whole array not just an element.
}
I want to compare two different arrays which are both int. One array is static and contains numbers from 1 to 10 and second arrays asks user to enter ten different numbers and the program checks which elements from both arrays are equal.
#include <stdio.h>
int main(void) {
int array1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int array2[10];
int i;
for (i = 0; i < 11; i++) {
printf("Enter numbers: ");
scanf("%d", &array2);
}
for (i = 0; i < 11; i++) {
if (array1[i] != array2[i]) {
printf("Not equal \n");
} else {
printf("They are equal. \n");
}
}
}
The program always say not equal even if I enter a number that is equal to a number stored in first array.
scanf("%d", &array2);
You are never updating the index of array2 when getting a value from input.
Try
scanf("%d", &array2[i]);
As for comparing, you can also use memcmp to compare memory:
memcmp(array1, array2, sizeof(array1));
Arrays use zero based indices for a start. You are incorrectly populating array2 so you probably want to change your first loop to the following
for (i=0;i<10;i++)
{
printf("Enter numbers: ");
scanf("%d", &array2[i]);
}
as your current code is simply passing the address of array2 as argument to scanf.
Then change the second loop conditional to
for (i=0;i<10;i++)
in your comparison loop so that you do not access items beyond your array boundaries.
Currently your second loop is accessing items at indices 0 to 10 - but there are only 10 items present in array1 so you have undefined behaviour with your current code.
#include <stdio.h>
int main(void) {
int array1[] = {1,2,3,4,5,6,7,8,9,10};
int array2[10];
int i;
for (i=0;i<10;i++) { //fixed the range here
printf("Enter numbers: ");
scanf("%d", &array2[i]); //fixed the indexing
}
for (i=0;i<10;i++) { //fixed the range here
if (array1[i] != array2[i]) {
printf("Not equal \n");
}
else {
printf("They are equal. \n");
}
}
}
I am a beginner and I have this idea about comparing two arrays. Hope It might help someone like me.
/***compare two array: all elements are same or not(if not sorted)***/
#include<stdio.h>
int main()
{
int n;
scanf("%d", &n);
int array1[n], array2[n];
int i, j;
for(i=0; i<n; i++)
{
scanf("%d", &array1[i]);
}
for(i=0; i<n; i++)
{
scanf("%d", &array2[i]);
}
int flg=0;
for(i = 0; i < n; i++)
{
for(j=0; j<n; j++)
{
if(array1[i] == array2[j])
{
flg += 1;
break;
}
}
}
if(flg == n)
{
printf("All The Elements of array1 is present in array2... :)");
}
else
{
printf("All THe Elements of array1 is not present in array2 :(");
}
return 0;
}
I am trying to respond to the answer, even though I am a beginner to C program.
According to your program written above, you are inputting and holding values to int array2[10] which has 11 elements.
Remember that the first element of this array is indexed by zero. Ex: array2[0], until it reaches the last element which is array2[10], you have counted 11.
Now array1 has the pre-defined values write which will be compared to your input values. Enter and store your values into array2[].
#include <stdio.h>
int main(void) {
int array1[] = {1,2,3,4,5,6,7,8,9,10};
int array2[10];
int i;
for (i=0;i<10;i++) { //fixed the range here
printf("Enter numbers: ");
scanf("%d", &array2[i]); //fixed the indexing
if (array1[i] != array2[i]) {
printf("Not equal \n");
}
else {
printf("They are equal. \n");
}
}
}