*** stack smashing detected ***: terminated - arrays

#include <stdio.h>
#include <stdlib.h>
void get_nbits(int num, int n);
void replace_nbits(int num, int n, int val);
void get_nbits_from_pos(int num, int n, int pos);
void replace_nbits_from_pos(int num, int n, int pos, int val);
void toggle_bits_from_pos(int num, int n, int pos);
void print_bits(unsigned int num, int n);
int main()
{
printf("\tThis program is to show the below mentioned bitwise functions\n\n");
printf("Select bit operation from below list:\n1. get_nbits\n2. set_nbits\n3. get_nbits_from_pos\n");
printf("4. set_nbits_from_pos\n5. toggle_bits_from_pos\n6. print_bits\n");
printf("Enter your choice: ");
int choice,num,n,pos,val;
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
get_nbits(num,n);
printf("\n");
break;
case 2:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter val: ");
scanf("%d",&val);
replace_nbits(num,n,val);
printf("\n");
break;
case 3:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter pos: ");
scanf("%d",&pos);
get_nbits_from_pos(num,n,pos);
printf("\n");
break;
case 4:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter val: ");
scanf("%d",&val);
printf("Enter pos: ");
scanf("%d",&pos);
replace_nbits_from_pos(num,n,pos,val);
printf("\n");
break;
case 5:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
printf("Enter pos: ");
scanf("%d",&pos);
toggle_bits_from_pos(num,n,pos);
printf("\n");
break;
case 6:
printf("Enter number: ");
scanf("%d",&num);
printf("Enter n: ");
scanf("%d",&n);
print_bits(num,n);
printf("\n");
break;
}
}
void get_nbits(int num, int n)
{
int bin_num[9];
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
for(int i=0;i<8;i++)
{
bin_num[i+cnt] = 0;
}
printf("The binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
for(int i=0;i<n;i++)
{
bin_dig = bin_dig + multiple*bin_num[i];
multiple*=10;
}
while ( bin_dig > 0)
{
rem = bin_dig % 10;
decimal_num = decimal_num + rem * base;
bin_dig = bin_dig / 10;
base = base * 2;
}
printf("\nThe decimal number is: %d\n",decimal_num);
}
void replace_nbits(int num, int n, int val)
{
int bin_num1[9],bin_num2[9];
int cnt1 = 0,cnt2 = 0;
int bin_dig = 0,bin_dig2 = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num1[cnt1] = num % 2;
num = num / 2;
cnt1++;
}
for(int i=0;i<8;i++)
{
bin_num1[i+cnt1] = 0;
}
printf("\nThe binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
while (val > 0) {
bin_num2[cnt2] = val % 2;
val = val / 2;
cnt2++;
}
for(int i=0;i<8;i++)
{
bin_num2[i+cnt2] = 0;
}
printf("\nThe binary form of given value: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num2[i]);
}
for(int i=0;i<n;i++)
{
bin_dig = bin_dig + multiple*bin_num2[i];
multiple*=10;
}
multiple = 1;
int temp = bin_dig;
for(int i=0;i<n;i++)
{
bin_num1[i] = temp%10;
temp/=10;
}
printf("\nThe binary form of given number after replacing is: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
for(int i=0;i<cnt1;i++)
{
bin_dig2 = bin_dig2 + multiple*bin_num1[i];
multiple*=10;
}
while ( bin_dig2 > 0)
{
rem = bin_dig2 % 10;
decimal_num = decimal_num + rem * base;
bin_dig2 = bin_dig2 / 10;
base = base * 2;
}
printf("\nThe decimal from given number after replacing is: %d\n",decimal_num);
}
void get_nbits_from_pos(int num, int n, int pos)
{
int bin_num[9];
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
for(int i=0;i<8;i++)
{
bin_num[i+cnt] = 0;
}
printf("\nThe binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
int from_num = 0;
for(int i = pos;from_num<n;i--,from_num++)
{
bin_dig = bin_dig + multiple*bin_num[i];
if(bin_dig==1) multiple*=10;
}
while ( bin_dig > 0)
{
rem = bin_dig % 10;
decimal_num = decimal_num + rem * base;
bin_dig = bin_dig / 10;
base = base * 2;
}
printf("\nThe decimal number is: %d\n",decimal_num);
}
void replace_nbits_from_pos(int num, int n, int pos, int val)
{
int bin_num1[9],bin_num2[9];
int cnt1 = 0,cnt2 = 0;
int bin_dig = 0,bin_dig2 = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num1[cnt1] = num % 2;
num = num / 2;
cnt1++;
}
for(int i=0;i<8;i++)
{
bin_num1[i+cnt1] = 0;
}
printf("\nThe binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
while (val > 0) {
bin_num2[cnt2] = val % 2;
val = val / 2;
cnt2++;
}
for(int i=0;i<8;i++)
{
bin_num2[i+cnt2] = 0;
}
printf("\nThe binary form of given value: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num2[i]);
}
for(int i=n;i>0;i--)
{
bin_dig = bin_dig + multiple*bin_num2[i];
if(bin_dig==1) multiple*=10;
}
multiple = 1;
int temp = bin_dig;
printf("\n%d",bin_dig);
for(int i=pos;i>(pos-n);i--)
{
bin_num1[i] = temp%10;
temp/=10;
}
printf("\nThe binary form of given number after replacing is: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num1[i]);
}
for(int i=0;i<8;i++)
{
bin_dig2 = bin_dig2 + multiple*bin_num1[i];
multiple*=10;
}
while ( bin_dig2 > 0)
{
rem = bin_dig2 % 10;
decimal_num = decimal_num + rem * base;
bin_dig2 = bin_dig2 / 10;
base = base * 2;
}
printf("\nThe decimal from given number after replacing is: %d\n",decimal_num);
}
void toggle_bits_from_pos(int num, int n, int pos)
{
int bin_num[9];
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
for(int i=0;i<8;i++)
{
bin_num[i+cnt] = 0;
}
printf("The binary form of given number: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
int from_num = 0;
for(int i = pos;from_num<n;i--,from_num++)
{
bin_num[i] = bin_num[i]^1;
}
printf("\nThe binary form of given number after toggling: ");
for(int i=7;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
for(int i=0;i<8;i++)
{
bin_dig = bin_dig + multiple*bin_num[i];
multiple*=10;
}
while ( bin_dig > 0)
{
rem = bin_dig % 10;
decimal_num = decimal_num + rem * base;
bin_dig = bin_dig / 10;
base = base * 2;
}
printf("\nThe decimal number is: %d\n",decimal_num);
}
void print_bits(unsigned int num, int n)
{
int* bin_num = malloc(n*sizeof(int));
int cnt = 0;
int bin_dig = 0;
int multiple = 1;
int decimal_num = 0, base = 1, rem;
while (num > 0) {
bin_num[cnt] = num % 2;
num = num / 2;
cnt++;
}
if(n>num)
{
for(int i=0;i<n;i++)
{
bin_num[i+cnt] = 0;
}
}
if(cnt>n)
{
printf("The n value is lower than the orignal number of digits\n");
n = cnt;
}
printf("The binary form of given number: ");
for(int i=n-1;i>=0;i--)
{
printf("%d ",bin_num[i]);
}
free(bin_num);
}
I'm a beginner and working with Arrays switch cases and loops of arrays concept coding to do some operations on binary numbers using arrays Here I am able to get the output as expected, but I can't figure out the problem of *** stack smashing detected ***: terminated. This comes at the end of the output I don't know why; anyone can help me with it please? And please tell me what the error means.

This answer is not related for the error, however, using this bit position arithmetic technique you would get rid of the main causes of that error. In this technique you don't have to use neither arrays nor number base conversions but bit arithmetics only.
Consider the number 105 which would be expressed as 01101001 in 8-bit binary right? If it is assigned to an int there will be 24 more digits toward MSb (Most Significant bit). Using bit position arithmetic we can read and print the bit values and we can slice between any 2 positions within the type's bit count range.
Here I show how it could be done using your 2 functions called get_nbits and get_nbits_from_msb_pos (I changed the 2nd one's name to specify the direction operation). I modified their content for this purpose and also added a utility function called printBinary to print binary values of a given int variable, within the desired range.
#include <stdio.h>
#define mBitCount(var) (sizeof(var) * 8)
void printBinary(int val, int from, int to);
void get_nbits(int num, int n);
void replace_nbits(int num, int n, int val);
void get_nbits_from_msb_pos(int num, int n, int pos);
void replace_nbits_from_msb_pos(int num, int n, int pos, int val);
void toggle_nbits_from_msb_pos(int num, int n, int pos);
int main(void) {
/* 105 in decimal, 01101001 in 8-bit binary */
#define NUM 105
get_nbits(NUM, 4);
get_nbits_from_msb_pos(NUM, 4, 6);
replace_nbits(NUM, 4, 7);
replace_nbits_from_msb_pos(NUM, 4, 6, 15);
toggle_nbits_from_msb_pos(NUM, 4, 6);
return 0;
}
void printBinary(int val, int from, int to) {
int bit_count = mBitCount(val);
if(from < to) {
puts("Argument error: from cannot be lesser than or equal to 'to'");
return;
}
else if(from >= bit_count || to < 0) {
puts("Argument error: Position values out of range");
return;
}
for(int i = from; i >= to; i--)
{
if((val & (1 << i))) {
// The ith digit is one
printf("%d",1);
}
else {
// The ith digit is zero
printf("%d",0);
}
}
putchar('\n');
}
void get_nbits(int num, int n)
{
puts("\nget_nbits:");
printf("Parameters: num %d, n %d\n", num, n);
if(n >= mBitCount(num)) {
printf("Argument error: The n must not exceed the bit count of num type which is: %lu\n", (sizeof(num) * 8));
return;
}
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
// No need to align since bits ranges to 0th bit
int decimal_num = num & ((1 << n) - 1);
printf("The decimal number is: %d\n",decimal_num);
}
void replace_nbits(int num, int n, int val)
{
puts("\nreplace_nbits:");
printf("Parameters: num %d, n %d, val %d\n", num, n, val);
if(n >= mBitCount(num)) {
printf("Argument error: The n must not exceed the bit count of num type which is: %lu\n", (sizeof(num) * 8));
return;
}
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
puts("The binary form of given value: ");
printBinary(val, n - 1, 0);
// No need to align since bits ranges to 0th bit
int mask = (1 << n) - 1; // Set n bits from zero to 1
int decimal_num = num & ~mask; // Clear out the bits that will be replaced
decimal_num |= val & mask;
puts("The binary form of given number after replacing is: ");
printBinary(decimal_num, mBitCount(num) - 1, 0);
printf("The decimal number is: %d\n",decimal_num);
}
// Get n bits from Most Significant Bit (from left to right)
void get_nbits_from_msb_pos(int num, int n, int pos)
{
puts("\nget_nbits_from_msb_pos:");
printf("Parameters: num %d, n %d, pos %d\n", num, n, pos);
if((pos - n) < 0) {
puts("Argument error: n from position should not underflow the bit position");
return;
}
int decimal_num = 0;
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
int mask = ((1 << (pos + 1)) - 1); // Mask beyond the pos toward MSb
mask &= ~((1 << ((pos + 1) - n)) - 1); // Mask below pos - n toward LSb
// Slice the num between the pos and n, and then align it to the right
// in order to get the correct value
decimal_num = ((num & mask) >> (pos - (n - 1)));
printf("The decimal number is: %d\n",decimal_num);
}
// Replace n bits from Most Significant Bit (from left to right)
void replace_nbits_from_msb_pos(int num, int n, int pos, int val)
{
puts("\nreplace_nbits_from_msb_pos:");
printf("Parameters: num %d, n %d, pos %d, val %d\n", num, n, pos, val);
if((pos - n) < 0) {
puts("Argument error: n from position should not underflow the bit position");
return;
}
int decimal_num = 0;
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
puts("The binary form of given value: ");
printBinary(val, n - 1, 0);
int mask = ((1 << (pos + 1)) - 1); // Mask beyond the pos toward MSb
mask &= ~((1 << ((pos + 1) - n)) - 1); // Mask below pos - n toward LSb
decimal_num = num & ~mask; // Clear the corresponding bits first
decimal_num |= val << (pos - (n - 1)); // Replace the corresponding bits
puts("The binary form of given number after replacing is: ");
printBinary(decimal_num, mBitCount(num) - 1, 0);
printf("The decimal number is: %d\n",decimal_num);
}
void toggle_nbits_from_msb_pos(int num, int n, int pos)
{
puts("\ntoggle_nbits_from_msb_pos:");
printf("Parameters: num %d, n %d, pos %d\n", num, n, pos);
if((pos - n) < 0) {
puts("Argument error: n from position should not underflow the bit position");
return;
}
puts("The binary form of given number: ");
printBinary(num, mBitCount(num) - 1, 0);
int decimal_num = num, i = pos - n; // Get the start index
// Start toggling from start index to the pos
do {
decimal_num ^= 1 << i;
i++;
}
while(i <= pos);
puts("The binary form of given number after toggling: ");
printBinary(decimal_num, mBitCount(decimal_num) - 1, 0);
printf("The decimal number is: %d\n",decimal_num);
}
The output
get_nbits:
Parameters: num 105, n 4
The binary form of given number:
00000000000000000000000001101001
The decimal number is: 9
get_nbits_from_msb_pos:
Parameters: num 105, n 4, pos 6
The binary form of given number:
00000000000000000000000001101001
The decimal number is: 13
replace_nbits:
Parameters: num 105, n 4, val 7
The binary form of given number:
00000000000000000000000001101001
The binary form of given value:
0111
The binary form of given number after replacing is:
00000000000000000000000001100111
The decimal number is: 103
replace_nbits_from_msb_pos:
Parameters: num 105, n 4, pos 6, val 15
The binary form of given number:
00000000000000000000000001101001
The binary form of given value:
1111
The binary form of given number after replacing is:
00000000000000000000000001111001
The decimal number is: 121
toggle_nbits_from_msb_pos:
Parameters: num 105, n 4, pos 6
The binary form of given number:
00000000000000000000000001101001
The binary form of given number after toggling:
00000000000000000000000000010101
The decimal number is: 21

stack smashing occur when one exceeds the size of a specific array(buffer overflow). It a defense mechanism to prevent overwriting of data. Please check your for loop in your functions the value of cnt goes beyond 9 which the size of the array. You can also you refer to What is the "stack smashing detected" error?

Related

I want to print a series of Armstrong numbers which lie between m and n. Here m and n are the two inputs given by the user

I am trying to print the series but whenever I set the range (input given by me) above 407. I only get the output till 407. However, when I set the range below 407 it gives me the result according to the input I have given. Can anybody tell me what I'm doing wrong?
I used an online compiler (www.onlinegdb.com) to write my code.
Here is the code.
#include<stdio.h>
#include<stdlib.h>
int
main ()
{
int m, n;
printf
("Enter two numbers to find the Armstrong numbers that lie between them.\n");
scanf ("%d%d", &m, &n);
system("clear");
if(m>n)
{
m = m + n;
n = m - n;
m = m - n;
}
for (; m < n; m++)
{
int i = m + 1, r, s = 0, t;
t = i;
while (i > 0)
{
r = i % 10;
s = s + (r * r * r);
i = i / 10;
}
if (t == s)
printf ("%d ", t);
}
return 0;
}
enter image description here
enter image description here
Try this code!!!
#include <math.h>
#include <stdio.h>
int main() {
int low, high, number, originalNumber, rem, count = 0;
double result = 0.0;
printf("Enter two numbers(intervals): ");
scanf("%d %d", &low, &high);
printf("Armstrong numbers between %d and %d are: ", low, high);
// swap numbers if high < low
if (high < low) {
high += low;
low = high - low;
high -= low;
}
// iterate number from (low + 1) to (high - 1)
// In each iteration, check if number is Armstrong
for (number = low + 1; number < high; ++number) {
originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++count;
}
originalNumber = number;
// result contains sum of nth power of individual digits
while (originalNumber != 0) {
rem = originalNumber % 10;
result += pow(rem, count);
originalNumber /= 10;
}
// check if number is equal to the sum of nth power of individual digits
if ((int)result == number) {
printf("%d ", number);
}
// resetting the values
count = 0;
result = 0;
}
return 0;
}
Try this code :
#include <stdio.h>
#include <math.h>
int main()
{
int start, end, i, temp1, temp2, remainder, n = 0, result = 0;
printf(“Enter start value and end value : “);
scanf(“%d %d”, &start, &end);
printf(“\nArmstrong numbers between %d an %d are: “, start, end);
for(i = start + 1; i < end; ++i)
{
temp2 = i;
temp1 = i;
while (temp1 != 0)
{
temp1 /= 10;
++n;
}
while (temp2 != 0)
{
remainder = temp2 % 10;
result += pow(remainder, n);
temp2 /= 10;
}
if (result == i) {
printf(“%d “, i);
}
n = 0;
result = 0;
}
printf(“\n”);
return 0;
}

Extract a number from a position in C

In this exercise he asks me to create a function
Number_pos (N, pos, m) which allows to extract a number composed of m digits
from position pos using functions.
Example:
N = 12345, pos = 2, m = 3
Number_pos (N, pos, m) = 234
I use an Extraxt_from_position function which extracts a number from a given position, then I use a function which calculates the number of digits of the number to extract, then I have a mirror function which inverts the number and I do the successive division until the number of digits are equal to the number of digits of the number we want to extract.
The problem is: forbidden to use mirror function, can you help me
int Extract_from_position(int n, int r)
{
int m = 0, s = 0;
while (n != 0)
{
m = n % 10;
s++;
if (s == r)
{
return n;
}
n = n / 10;
}
}
int Number_of_digits(int n)
{
int m = 0, s = 0;
while (n != 0)
{
m = n % 10;
s++;
n = n / 10;
}
return s;
}
int Mirror(int n)
{
int m = 0, s = 0;
while (n != 0)
{
m = n % 10;
s = s * 10 + m;
n = n / 10;
}
return s;
}
int Number_Pos(int N, int pos, int m)
{
int x = Extract_from_position(N, pos);
int y = 0;
int R = Mirror(x);
int T = Number_of_digits(R);
while (T >= m + 1)
{
y = R % 10;
R = R / 10;
T--;
}
return Mirror(R);
}
int main()
{
int n, pos, nbcx;
printf("Give n :");
scanf("%d", &n);
printf("Give the position :");
scanf("%d", &pos);
printf("give the number of digits of the number to extract :");
scanf("%d", &nbcx);
printf("\nThe result after the amber extract from position %d on the right and the number of digits %d is : %d \n", pos, nbcx, Number_Pos(n, pos, nbcx));
}
UPDATE: Count from right
If you want count the digits from right, the NumberPos function will be just:
#include <stdio.h>
#include <math.h>
int NumberPos(int N, int pos, int m)
{
int trc = (int)(N / (int)pow(10, pos - 1));
trc = trc % (int)pow(10, m);
return trc;
}
int main()
{
int n, pos, nbcx;
printf("Give n :");
scanf("%d", &n);
printf("Give the position :");
scanf("%d", &pos);
printf("give the number of digits of the number to extract :");
scanf("%d", &nbcx);
printf("\nThe result after the amber extract from position %d on the right and the number of digits %d is : %d \n", pos, nbcx, NumberPos(n, pos, nbcx));
}
And the output will be, for example:
Give n :1234567
Give the position :3
give the number of digits of the number to extract :2
The result after the amber extract from position 3 on the right and the number of digits 2 is : 45
OLD: This could be a solution (in basically 4 line):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int NumberPos(int N, int pos, int m)
{
int digit = floor(log10(abs(N))) + 1;
int trc = N % (int)pow(10, digit - pos + 1);
digit = floor(log10(abs(trc))) + 1;
trc = (int)(trc / (int)pow(10, digit - m));
return trc;
}
int main()
{
int n, pos, nbcx;
printf("Give n :");
scanf("%d", &n);
printf("Give the position :");
scanf("%d", &pos);
printf("give the number of digits of the number to extract :");
scanf("%d", &nbcx);
printf("\nThe result after the amber extract from position %d on the right and the number of digits %d is : %d \n", pos, nbcx, NumberPos(n, pos, nbcx));
}
The output will be:
Give n :12345
Give the position :2
give the number of digits of the number to extract :2
The result after the amber extract from position 2 on the right and the number of digits 2 is : 23
UPDATE: Library restriction
If for whatever reason you are not allowed to use math.h or stdlib.h you can:
Re-implement pow reading: Write Pow Function Without math.h in C
Re-implement abs reading: this
Re-implement the digit counter: C program to count number of digits in an integer
Something like this might work. I trim the digits you don't want on the right then mod to mask off the digits on the left you don't want.
Based on your sample I assume that pos is 1-based. If not there's a comment on the code you would need to remove.
You'd probably want to add error checking to make sure that pos and num_digits are valid for the given N, but that's an exercise for you.
#include <stdio.h>
int Number_of_digits(int n)
{
int count = 0;
while (n != 0)
{
n = n / 10;
++count;
}
return count;
}
int Number_Pos(int N, int pos, int num_digits)
{
int len = Number_of_digits(N);
pos -= 1; //pos is 1 based.
//trim right side
for (int i = 0; i < len - num_digits - pos; ++i)
{
N /= 10;
}
//calculate mod to keep num_digits.
int m = 10;
for (int i = 0; i < num_digits - 1; ++i)
{
m *= 10;
}
return N % m;
}
int main()
{
int n = 1234567;
int pos = 2;
int num_digits = 3;
int result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
pos = 3;
num_digits = 4;
result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
pos = 1;
num_digits = 4;
result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
pos = 6;
num_digits = 2;
result = Number_Pos(n, pos, num_digits);
printf("Num: %d, Pos: %d, Digits: %d - Result: %d\n", n, pos, num_digits, result);
return 0;
}
Output:
Num: 1234567, Pos: 2, Digits: 3 - Result: 234
Num: 1234567, Pos: 3, Digits: 4 - Result: 3456
Num: 1234567, Pos: 1, Digits: 4 - Result: 1234
Num: 1234567, Pos: 6, Digits: 2 - Result: 67

How many prime numbers C program

I wrote this program to find prime numbers between 1 and 50000, and I still need to find how many prime numbers there is (I tried a lot of tricks but I did not succeed)
#include <stdio.h>
//int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = 23;
PrintListOfPrime(value);
return 0;
}
void PrintListOfPrime(int value) {
int ValueIsPrime; //ValueIsPrime is used as flag variable
printf("The list of primes: ");
for (int i = 2; i <= value; i++) {
ValueIsPrime = 1;
/* Check if the current number i is prime or not */
for (int j = 2; j <= i / 2; j++) {
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if (i % j == 0) {
ValueIsPrime = 0;
break;
}
}
/* If the number is prime then print */
if (ValueIsPrime == 1)
printf("%d, ", i);
}
printf("\n");
}
I tried a lot of tricks but I did not succeed
If OP's code takes too long to ran, iterate to the square root of i, not up to i/2.
j <= i / 2 is very slow. Use j <= i / j instead.
Form a count and increment with every prime. #gspr
if (ValueIsPrime == 1) {
printf("%d, ", i);
prime_count++;
}
Bigger change yet even faster to "find prime numbers between 1 and 50000", research Sieve of Eratosthenes
Hello fast answer is to create a variable in main, int totaleOfPrimes = 0; for example.
then send it by reference to the fucntion :
Function declaration : void PrintListOfPrime(int value,int* counter);
Function call : void PrintListOfPrime(value,&totaleOfPrimes);
then Increment counter befor printing :
if (ValueIsPrime == 1){
(*counter)++;
printf("%d, ", i);
}
There is no need to iterate the loops for all numbers between 2 and value. You should consider only 2 and odd numbers.
The function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
static inline size_t PrintListOfPrime( unsigned int n )
{
size_t count = 0;
printf( "The list of primes:\n" );
for ( unsigned int i = 2; i <= n; i = i != 2 ? i + 2 : i + 1 )
{
int isPrime = 1;
/* Check if the current number i is prime or not */
for ( unsigned int j = 3; isPrime && j <= i / j; j += 2 )
{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
isPrime = i % j != 0;
}
/* If the number is prime then print */
if ( isPrime )
{
if ( ++count % 14 == 0 ) putchar( '\n' );
printf( "%u ", i );
}
}
return count;
}
int main(void)
{
unsigned int n = 50000;
size_t count = PrintListOfPrime( n );
printf( "\n\nThere are %zu prime numbers up to %u\n", count, n );
return 0;
}
Run this code in C. It will return the value of a pi(x) function. It is basically the Prime counting function:
#include <stdio.h>
#define LEAST_PRIME 2
#include <math.h>
int main() //works for first 10000 primes.
{
int lower_limit = 2, no_of_sets;
// printf("NUMBER OF SETS: ");
// scanf("%d", &no_of_sets);
int remainder, divisor = 2, remainder_dump, upper_limit; //upper limit to be specified
//by user.
int i = 1;
// printf("SPECIFY LOWER LIMIT: ");
// scanf("%d", &lower_limit);
int number_to_be_checked = lower_limit;
printf("SPECIFY UPPER LIMIT: ");
scanf("%d", &upper_limit);
printf("2\t\t\t\t", number_to_be_checked);
//PRINTS 2.*/
do
{
remainder_dump = 1;
divisor = 2;
do
{
remainder = number_to_be_checked % divisor;
if (remainder == 0)
{
remainder_dump = remainder_dump * remainder; // dumping 0 for rejection.
break;
}
++divisor;
} while (divisor <= number_to_be_checked / divisor); // upto here we know number
is prime or not.
if (remainder_dump != 0)
{
++i;
printf("%d.\t\t\t\t", number_to_be_checked); //print if prime.
};
number_to_be_checked = number_to_be_checked + 1;
} while (number_to_be_checked <= upper_limit);
printf("\n pi(x) = %d \n", i);
//printf("pi function value is %f.", (i - 1) / (log(i - 1)));
float app;
app = upper_limit / (log(upper_limit));
float plot_value;
plot_value = (i) / app;
printf(" BETA FUNCTION VALUE ~ %f", plot_value);
return 0;
}

Binary addition in c, why does run time error occur?

i'm trying to write a code which can convert 2 decimal numbers 0 to 1 into binary, then adding them and printing the binary values for the 2 initial numbers AND the final sum. It compiles with no problems however when I run it crashes right after it converts and prints num1 and num2 (the initial numbers), I can't seem to find the problem.
the general formula for binary addition is:
*ith bit of sum = ith bit of binary1 + ith bit of binary2 + carry factor (0 or 1)
if sum > 1, subtract 2 and add 1 to the next operation (which is the carry factor i mentions earlier)
Below is the code
#include <stdio.h>
// Converting decimal number to a binary number
void convertDecToBin(double num, int len, int binary[]) {
// this function STORES conversion result in binary[]
double tmp = num;
binary[0] = 0;
for (int i = 0; i < len; i++) {
tmp *= 2;
binary[i + 1] = tmp >= 1;
if (tmp >= 1) {
tmp -= 1;
}
}
}
// Binary number addition
void addTwoBinary(int binary1[], int binary2[], int sum[]) {
int tmp;
int carry;
for (unsigned int i = 20; i >= 0; i--) {
if (i == 20 || tmp <= 1) {
carry = 0;
}
else if (tmp > 1) {
carry = 1;
}
sum[i] = binary1[i] + binary2[i] + carry;
tmp = sum[i];
if (sum[i] > 1) {
sum[i]-=2;
}
}
}
//Printing the numbers
void PrintBinary(int binary[], int len) {
for (unsigned int i = 0; i < len; i++) {
printf("%d", binary[i]);
}
}
int main(void) {
double num1, num2;
int binary1[30], binary2[30], sum[30];
scanf("%lf", &num1);
scanf("%lf", &num2);
convertDecToBin(num1, 30, binary1);
convertDecToBin(num2, 30, binary2);
printf("num1 is ");
PrintBinary(binary1, 21);
printf("\nnum2 is ");
PrintBinary(binary2, 21);
addTwoBinary(binary1, binary2, sum);
printf("\nsum is ");
PrintBinary(sum, 21);
return 0;
}

Decimal to Binary convert in C

My simple program fails to convert 7 to 111 (the current code gives 101). I know myArray[] and the last printf() can be improved, but we can talk about that next time.
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3];
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
while(quo != 1){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
} myArray[i] = quo;
printf("\nBinary: %d %d %d", myArray[i + 2], myArray[i + 1], myArray[i] );
return 0;
}
It's work fine for me. have you include header files properly? and which compiler do you using ?
#include <stdio.h>
#include <conio.h>
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3];
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
while(quo != 1){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
} myArray[i] = quo;
printf("\nBinary: %d %d %d", myArray[i + 2], myArray[i + 1], myArray[i] );
return 0;
}
Output
I also try this. you also can try this if you want :)
#include <stdio.h>
#include <conio.h>
int main() {
long myDecimal;
long binary = 0, i = 1;
int rem;
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
while(myDecimal != 0) {
rem = myDecimal%2;
myDecimal = myDecimal/2;
binary= binary + (rem*i);
i = i*10;
}
printf("Binary number is %ld",binary);
}
There's some errors that should be taken care of..
Initialize the array because for conversion of 1, it maybe garbage 0 1
Don't force the myArray[i] = quo;
You should take care of printing as i maybe of different length and may cause unstable behavior.
Also initialize quo before use as it may lead to garbage comparison.
Also follow the tips in comments, they are useful.
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3] = {0};
printf("Enter valid decimal number: \n");
scanf("%d", &myDecimal);
quo = myDecimal;
while(quo > 0){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
}
printf("Binary: %d %d %d", myArray[2], myArray[1], myArray[0]);
return 0;
}
By your logic you have used you need to make smaller changes to get this to work.
check.c
#include<stdio.h>
int main() {
int myDecimal, quo, rem;
int i = 0; //counter
int myArray[3];
printf("Enter valid decimal number: ");
scanf("%d", &myDecimal);
//check myDecimal whether it's above 0 after each iteration
while(myDecimal > 0){
quo = myDecimal / 2;
rem = myDecimal % 2;
myArray[i] = rem;
myDecimal = quo;
i++;
} myArray[i] = quo;
//print the array in the reverse order
for(i=2;i>=0;i--){
printf("%d",myArray[i]);
}
printf("\n");
return 0;
}
Ouput:

Resources