Prints out the first eight autmorphic numbers - c

Create a program that prints out the first eight[8] automorphic numbers. Output must be done
in the main() function.
Here's the code I worked on:
#include <stdio.h>
#include <conio.h>
main() {
int automorphic[8];
int n;
printf("\t\t\tAUTOMORPHIC\n\n\n");
for(n=1; n<8; n++ ){
if (n*n%10==n || n*n%100==n || n*n%1000==n);
}
printf("\t%d\n\n", automorphic [n]);
getch();
return 0;
}
I don't get why it only prints out 0? Is there something missing on my code? Or am I not doing the right thing at all?

Because:
You are examining only numbers 1 to 7 (only numbers 1, 5 and 6 in this range are automorphic).
You are not storing the number in the array.
You are printing only element 7 of the array (which is always 0).
You need to expect numbers bigger than that.
Additionally, automorphic numbers start at 0, not 1.
int main() {
long automorphic [8];
long i;
int n;
printf("\t\t\tAUTOMORPHIC\n\n\n");
i= 0 ;
n= 0 ;
while( n < 8 ) {
if( i*i%10==i || i*i%100==i || i*i%1000==i || i*i%10000==i || i*i%100000==i ) {
automorphic[n]= i ;
n++;
}
i++;
}
for(n= 0 ; n < 8 ; n++ ) {
printf("\t%d\n\n", automorphic[n] );
}
getch();
return 0;
}
Result should be:
0
1
5
6
25
76
376
625

You're close, but not quite there.
You are only testing the integers from 1 through 8 for the automorphic property. The question asks for the first 8 automorphic numbers, not which numbers less than 8 are automorphic.
Your if statement doesn't do anything if the condition is true.
You are printing the value of automorphic[n] but do not set any values in the automorphic array. Also, at the point the printf executes, n will be 8 because the for loop has already finished.

Related

How to fix program printing a 0 after the print statement executes in C?

This program tests Goldbach's Conjecture, printing a given even integer as the sum of two primes. After printing the first one, the given integer is to iterate by 2 , then find the sum of two primes for that integer. And so on until the program is interrupted by the user.
This problem is that the program prints a '0' after every executed print statement.
The code:
#include <stdio.h>
#include <math.h>
int GC(int goldsum); //function prototype
int main()
{
int goldsum;
printf("Enter an even integer greater than 5: ");
scanf("%d", &goldsum);
printf("%d\n", GC(goldsum));
goldsum = goldsum + 2;
printf("%d\n", GC(goldsum));
}
int GC(int goldsum) //function definition
{
int i, j; //prime addends
int div1, div2; //divisors
char prime1, prime2;
for (i=2 ;i<goldsum ;i++) //when number is less than goldsum, run this loop iterating by 1
{
prime1 = 1;
for (div1=2 ;div1<i ;div1++) //this loop determines if "i" is prime.
if (i % div1 == 0) //if yes, the prime number is stored in "i"
prime1 = 0;
if (prime1)
{
for (j=3; j<goldsum; j+=2) //when number is less than goldsum, run this loop iterating by 2
{
prime1 = 1;
for (div2=2; div2<j; div2++) //this loop determines if "j" is prime.
if(j % div2 == 0) //if yes, the prime number is stored in "j"
prime1 = 0;
if (prime1)
if (i + j == goldsum) //If i + j = goldsum, it prints the result.
{
printf("%d + %d = %d\n",i ,j , goldsum);
return 0;
}
}
}
}
return 0;
}
The output:
Enter an even integer greater than 5: 10
3 + 7 = 10
0
5 + 7 = 12
0
What I want it to look like:
Enter an even integer greater than 5: 10
3 + 7 = 10
5 + 7 = 12
use just GC(goldsum);
instead of printf("%d\n", GC(goldsum));
Maybe you misunderstood the return 0; we put in main(). Every function has to return the value we desire. In the case of main we want 0 because that means everything was OK. In the case of your function the return value should be what YOU want from it.
Edit: re-read the question and adding this: Since you don't want a return value from you function you should declare it as void and not have it in a printf() because all the printing you want is in your function.
Void functions do not return a value, so that is what you want.

Runtime Error - SIGSEGV

I am supposed to write a program for adding array elements and remove the elements from the sum if the previous element is 0,but i'm getting Run Time error as SIGSEGV.How can i solve this error.
#include <stdio.h>
int main()
{
int i,arr[10],n,sum=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d\n",&arr[i]);
}
for(i=0;i<n;i++)
{
sum=sum+arr[i];
}
for(i=0;i<n;i++)
{
if(arr[i]==0)
{
sum=sum-arr[i-1];
}
}
printf("%d",sum);
return 0;
}
In this statement
sum=sum-arr[i-1];
when i is equal to 0 you are trying to access memory beyond the array.
Remove the new line character from the call of scanf
scanf("%d\n",&arr[i]);
^^
And if you ask the user to enter the number of elements of the array then you should check that the entered number is less than or equal to 10.
I think that it does not make sense to ask the user to enter the number of elements of the array. Otherwise it is better to use a Variable Length array if the compiler supports them.
The program can look the following way
#include <stdio.h>
#define N 10
int main( void )
{
int a[N];
printf( "Enter %d elements: ", N );
int n = 0;
while ( n < N && scanf( "%d", &a[n] ) == 1 ) n++;
long long sum = 0;
for ( int i = 0; i < n; i++ )
{
if ( i + 1 == n || a[i+1] != 0 ) sum += a[i];
}
printf( "\nsum = %lld\n", sum );
return 0;
}
If for example to enter the following sequence of numbers
1 2 0 3 4 0 5 6 0 7
then the output can look like
Enter 10 elements: 1 2 0 3 4 0 5 6 0 7
sum = 16
The Problem Here is size of the Array.
You declared array for size 10 and if the user enters the size as 100 then this kind of Run time error will appear.
To avoid this exception simply declare the array after user enters thee size i.e
scanf("%d",&n);
int arr[n];

Optimizing a recursive counting algorithm

I hate posting for homework help on here, but I've exhausted my abilities. I am faced with a Stack Overflow (at least thats what its called in Java) issue while writing a simple recursive function in C.
I need every r-permutation of n numbers, and I figured the best way to do that would be counting in base n to length r.
It works fine for smaller amounts of numbers, but the highest case (n=10, r=6) ends up running out of memory. I could easily have written this iteratively but its required to be recursion. Heres what I have so far:
int permute(int *tempArray, int amtNums, int goalLength, int totalMatches) {
totalMatches += 1; //Temporary, will be replaced by a function later
printArray(tempArray, goalLength);
tempArray[0]++;
int j = 0;
while(tempArray[j] >= amtNums) {
tempArray[j+1]++;
tempArray[j] = 0;
j++;
}
if(j+1 > goalLength) return totalMatches;
return permute(tempArray, amtNums, goalLength, totalMatches);
}
Being called as permute((int*)calloc(numSlots, sizeof(int)), 10, 6, 0); for the max case, n=10 r=6
I should Note: The counting isn't exactly intuitive, its a bit backwards but generates all the number combinations I wanted. As an example: n=4, r=3
0 0 0
1 0 0
2 0 0
3 0 0
0 1 0
1 1 0
2 1 0
3 1 0
.....
0 2 3
1 2 3
2 2 3
3 2 3
0 3 3
1 3 3
2 3 3
3 3 3
I belive that you have to modify your recursive function in order to have a maximum depth of the stack of function calls of goalLength. You can accomplish that adding a parameter depth like I did here:
int permute( int *tempArray, int amtNums, int goalLength, int depth, int totalMatches) {
int i;
if ( depth < goalLength - 1) {
for ( i = 0; i < amtNums; ++i ) {
tempArray[depth] = i;
totalMatches = permute(tempArray, amtNums, goalLength, depth + 1, totalMatches);
}
} else {
for ( i = 0; i < amtNums; ++i ) {
tempArray[depth] = i;
printArray(tempArray, goalLength);
++totalMatches;
}
}
return totalMatches;
}
You can of course rewrite it putting the for loop outside and the if inside. I tryed that code with this little test program:
#include <stdio.h>
#define NDIGIT 4
#define NLENGTH 3
void printArray( int *temp, int size ) {
int i;
for ( i = 0; i < size; ++i ) {
printf("%d ", temp[i]);
}
printf("\n");
}
int permute( int *tempArray, int amtNums, int goalLength, int depth, int totalMatches);
int main(void) {
int results[NLENGTH];
int n = permute(results, NDIGIT, NLENGTH, 0, 0);
printf("Total number of permutations: %d\n", n);
return 0;
}
Setting NDIGIT to 10, NLENGTH to 6 and commenting out the printing function (you can keep it if you want...) the program run fine and the output was:
Total number of permutations: 1000000
Your function uses a tail call to itself, the compiler should be able to turn this recursion into a loop. Enable optimisations with command line option -O3 or whatever your IDE provides. If the compiler implements the recursion, the function will recurse amtNumsgoalLength, which is a large number for n=10 and r=6: 1 000 000 recursion levels likely causes a Stack Overflow

What needs to be modified to get desired result in this C code

I have written a small piece of code that would perform Run length encoding kind of stuff on 1-D array but still far from desired result.
main()
{
int a[8]={2,0,0,0,3,0,0,9};
int i,temp,ct=0,flag,m;
int found[90]={0};
for(i=0;i<=7;i++)
{
if(!a[i])
{
ct++;
if(!found[a[i]])
{
flag=i;
found[a[i]]=1;
}
}
}
a[flag]=ct;
m=ct;
for(i=0;i<m;i++)
{
printf("%d",a[i]);
}
}/* end of main*/
Now for above array i would like to have output something below
2 5 0 3 9
But with my piece of code am getting
2 5 0 0 3
Can I have any suggestion on that?
Shouldn't run length encoding turn 2,0,0,0,3,0,0,9 into 2 1 0 3 3 1 2 0 9 1?
1) The first thing I see is wrong is that you aren't looking at the entire array. You're using < to stop before 8, but also stopping at 7, so you only evaluate array items 0 - 6.
2) If ct stands for count it's never reset (ct=0 only on declaration). Also it's assignment is this: a[flag]= ct; which overwrites your original data. It basically tracks the value of i.
This is my version I've just put together:
#define SZ 8
main()
{
int a[SZ]={2,0,0,0,3,0,0,9};
int i; //absolute position
int runningCount = 1; //because we start at array index 1 and not zero
for (i = 1; i <= SZ; i++) {
if (a[i - 1] == a[i]) //value same as one before it...
runningCount++;
else { // new value found. print last one, and the count of the last one.
printf("%d %d ", a[i - 1], runningCount);
runningCount = 1; //reset for next loop
}
}
return 0;
}
The output is 2 1 0 3 3 1 0 2 9 1
Ok based on the comment left below, your algorithm would actually look like this:
#define SZ 8
main()
{
int a[SZ]={2,0,0,0,3,0,0,9};
int i; //absolute position
int zero_count = 0; //target zeros specifically...
for (i = 0; i < SZ; i++) {
if (a[i] == 0)
zero_count++;
}
//now write it out in a bizarre, unparsable format again...
for (i = 0; i < SZ; i++) {
if (a[i] != 0) //write out all non zero values
printf("%d ", a[i]);
if (i == 0) { //this says put the zero count after the first number was printed
printf("%d 0 ", zero_count); //inserting it into a strange place in the array
}
}
return 0;
}
which outputs: 2 5 0 3 9
You need a <= in your for loop:
for(i=0;i<=7;i++)
instead of
for(i=0;i< 7;i++)
Otherwise you miss the last element.
All you appear to be doing is (a) counting the number of times 0 occurs in the array, and (b) replacing the first occurrence of 0 with that count. It's not clear how this is meant to be a useful encoding.
In any case, you're not getting your desired result, at least in part, because you're only modifying one element of the array. I suspect what you want, or at least think you want, is to shift the non-zero elements of the array to the left as you encounter them.
What is the utility of compressing the array in the way you propose? Is some other piece of code going to have to reconstruct the original, and if so how do you expect to do so from your desired result?

Reading an array of integers and printing them out

I'm learning C on my own and doing a few exercises. The following code reads in an
array of integers from the user. The integers are printed out when the user types in a "0" or when the array is filled. Now the problem is the output. When I type in "0" after I have typed in 3 digits e.g. 1 2 3 the output is the following: 1 2 3 -858993460 -858993460. I am not sure why I get the value "-858993460" but I have already found a solution to avoid it. Now my question is what the values mean and if there is a smarter solution than mine which is presented below as comments.
#include <stdio.h>
#include <string.h>
#define arraylength 5
int main ()
{
//const int arraylength = 21; //alternative possibility to declare a constant
int input [arraylength] ;
int temp = 0;
//int imax = 0;
printf("Please type in a your digits: ");
for (int i = 0; i < arraylength; i++)
{
scanf("%d", &temp);
if ( temp !=0)
{
input[i]= temp;
//imax= i;
}
else
{
//imax= i;
break;
}
if (i < arraylength-1)
printf("Next: ");
}
for (int i =0; i < arraylength; i++ ) // switch arraylength with imax
{
printf("%d", input[i]);
}
getchar();
getchar();
getchar();
}
This happens because irrespective of when the 0 input is given you print all 5 numbers:
for (int i =0; i < arraylength; i++ )
To fix this you can print only the number(s) user entered before entering a 0 by running a loop from 0 to i:
for (int j =0; j < i; j++ )
Those 2 numbers are the garbage that was left in the memory locations for the last 2 parts of your array. You never initialise those when you only input 3 numbers, so when you go through and print all 5 elements in the array, it prints whatever garbage was in the memory.
You print all integers in array which is size of arraylength = 5. So you get 5 integers in output. As you didn't initialize array, you get uninitilized values as 4th and 5th elements of array. You can use memset(&input, 0, arraylength*sizeof(int)); to set initials values in array to 0.

Resources