C - print int with variable 0s [duplicate] - c

This question already has answers here:
Variable leading zeroes in C99 printf
(1 answer)
printf string, variable length item
(2 answers)
Closed 5 years ago.
I've written a programm for college where I print out all prime number twins between two numbers. (f.e. between 1 and 12000)
In my printing statement i've written %04d for 4 digits. But what i want to do is to make this variable. (I tried %0%dd, but this didnt work.) I dont want to do write just the max digit count of int. I count hte digits of the int with int count = floor(log10(abs(b))) + 1;
Heres my complete code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int isPrime(int a);
void listOfPrimeNumberTwins(int a, int b);
typedef int twins[10000][2];
int main(){
int a;
int b;
printf("Check if prime:\nEnter number: ");
scanf(" %d", &a);
b = isPrime(a);
if (b == 0){
printf("No Prime!");
} else if (b == -1){
printf("Negative number!");
} else {
printf("Prime!");
}
printf("\nPrime Number Twins:\nEnter number 1: ");
scanf(" %d", &a);
printf("Enter number 2: ");
scanf(" %d", &b);
listOfPrimeNumberTwins(a,b);
}
int isPrime(int a){
int i;
int b = 0;
if (a == 1){
return 0;
}
if (a <= 0){
return -1;
}
for (i = 2; i < a; i++){
if (a % i == 0){
return 0;
}
}
return 1;
}
void listOfPrimeNumberTwins(int a, int b){
int count = floor(log10(abs(b))) + 1;
int i;
int j = 0;
twins c;
b -= 1;
for (i = a; i < b; i++){
if (i > 1 && isPrime(i) == 1 && isPrime(i + 2) == 1){
c[j][0] = i;
c[j][1] = i + 2;
j += 1;
}
}
if (j == 0){
printf("No Prime number twins between %d and %d!", a,b);
} else {
printf("Prime number twins between %d and %d:\n", a,b);
for (i = 0;i < j; i++){
printf("%04d\t<-->\t%04d\n", c[i][0],c[i][1]);
}
}
}
How can I achieve what I want? Or is it just impossible like I want it?

Related

program modularization (does the if else program below contain the process of modularization?)

hello sorry in advance because i ask a very simple question, but i really ask for help, i have a school assignment, but i don't know how to solve it, please help
Stimulation
After you study program modularization, does the if else program below contain the process of modularization?
#include <stdio.h>
main(){
int a,b,c, max;
printf("enter value a :");scanf("%d",&a);
printf("enter value b :");scanf("%d",&b);
printf("enter value c :");scanf("%d",&c);
//checking 1 program module
if((a>b)&&(a>c))
{
max = a;
printf("highest value checking 1 : %d" ,max);
}else if(b > c)
{
max=b;
printf("highest value checking 1 : %d" ,max);
}else{
max=c;
printf("highest value checking 1 : %d" ,max);
}
printf("\n");
int number1, number2, number3;
number1=a;
number2=b;
number3=c;
//checking 2 main programs
if((number1>number2)&&(number2>number3)){
max = number1;
printf("highest score checking 2 : %d" ,max);
}else if(number2 > number3)
{
max=number2;
printf("highest score checking 2 : %d" , max);
}else{
max=number3;
printf(highest score checking 2 : %d" ,max);
}
}
Identification of problems.
Write down the hypothesis from the results of the if else program study. Is the hypothesis alternative (the if else program line is in accordance with the concept of modularization) or the hypothesis is a null hypothesis (the if else program is not in accordance with the concept of modularization). Explain the hypothesis in detail, and point out which line of if else program strengthens your hypothesis statement!
The program is not modular.
Here is the analysis:
The two if/else blocks are nearly identical.
The printf statements are replicated code.
The scanf calls are replicated code.
The code can only handle three numbers.
Amongst other things, modularization is a process of eliminating replicated/duplicated code that is similar and placing the common code in [smaller] functions.
A good maxim to follow is that a given function: should do one thing well.
We can modularize the code in several steps:
Move the first if/else block into a separate function (e.g. getmax)
Eliminate duplicate printf in getmax
Make getmax more general so it can handle the second if/else more easily
Convert second if/else block in main to use getmax
Put user input (printf/scanf) into common function
Convert program to use arrays rather than individual scalars. This is particularly evident with: int number1,number2,number3;. It can be simplified into: int number[3];
Convert program to prompt user for number of elements in the array
Move the first if/else block into a separate function:
#include <stdio.h>
// checking 1 program module
int
getmax(int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
printf("highest value checking 1 : %d\n", max);
}
else if (b > c) {
max = b;
printf("highest value checking 1 : %d\n", max);
}
else {
max = c;
printf("highest value checking 1 : %d\n", max);
}
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax(a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
if ((number1 > number2) && (number2 > number3)) {
max = number1;
printf("highest score checking 2 : %d\n", max);
}
else if (number2 > number3) {
max = number2;
printf("highest score checking 2 : %d\n", max);
}
else {
max = number3;
printf("highest score checking 2 : %d\n", max);
}
return 0;
}
Eliminate duplicate printf in getmax:
#include <stdio.h>
// checking 1 program module
int
getmax(int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest value checking 1 : %d\n", max);
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax(a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
if ((number1 > number2) && (number2 > number3)) {
max = number1;
printf("highest score checking 2 : %d\n", max);
}
else if (number2 > number3) {
max = number2;
printf("highest score checking 2 : %d\n", max);
}
else {
max = number3;
printf("highest score checking 2 : %d\n", max);
}
return 0;
}
Make getmax more general so it can handle the second if/else more easily:
#include <stdio.h>
// checking 1 program module
int
getmax(const char *what,int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest %s checking 1 : %d\n", what, max);
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax("value",a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
if ((number1 > number2) && (number2 > number3)) {
max = number1;
printf("highest score checking 2 : %d\n", max);
}
else if (number2 > number3) {
max = number2;
printf("highest score checking 2 : %d\n", max);
}
else {
max = number3;
printf("highest score checking 2 : %d\n", max);
}
return 0;
}
Convert second if/else block in main to use getmax:
#include <stdio.h>
// checking 1 program module
int
getmax(const char *what,int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest %s checking 1 : %d\n", what, max);
return max;
}
int
main(void)
{
int a, b, c, max;
printf("enter value a :");
scanf("%d", &a);
printf("enter value b :");
scanf("%d", &b);
printf("enter value c :");
scanf("%d", &c);
getmax("value",a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
getmax("score",number1,number2,number3);
return 0;
}
Step 6: Put user input into common function:
#include <stdio.h>
// ask user for number
int
asknum(const char *prompt)
{
char buf[1000];
int num;
printf("enter value %s : ",prompt);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&num);
return num;
}
// checking 1 program module
int
getmax(const char *what,int a,int b,int c)
{
int max;
if ((a > b) && (a > c)) {
max = a;
}
else if (b > c) {
max = b;
}
else {
max = c;
}
printf("highest %s checking 1 : %d\n", what, max);
return max;
}
int
main(void)
{
int a, b, c, max;
a = asknum("a");
b = asknum("b");
c = asknum("c");
getmax("value",a,b,c);
int number1, number2, number3;
number1 = a;
number2 = b;
number3 = c;
//checking 2 main programs
getmax("score",number1,number2,number3);
return 0;
}
Convert program to use arrays rather than individual scalars:
#include <stdio.h>
// ask user for number
int
asknum(int prompt)
{
char buf[1000];
int num;
printf("enter value %d : ",prompt);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&num);
return num;
}
// checking 1 program module
int
getmax(const char *what,const int *arr,int count)
{
int idx;
int val;
int max = -1;
if (count > 0) {
max = arr[0];
for (idx = 1; idx < count; ++idx) {
val = arr[idx];
if (val > max)
max = val;
}
printf("highest %s checking 1 : %d\n", what, max);
}
return max;
}
int
main(void)
{
int idx;
int count = 3;
int arr[count];
for (idx = 0; idx < count; ++idx)
arr[idx] = asknum(idx);
getmax("value",arr,count);
int number[count];
for (idx = 0; idx < count; ++idx)
number[idx] = arr[idx];
//checking 2 main programs
getmax("score",number,count);
return 0;
}
Convert program to prompt user for number of elements in the array
#include <stdio.h>
// ask user for number
int
asknum(const char *prompt)
{
char buf[1000];
int num;
printf("%s : ",prompt);
fflush(stdout);
fgets(buf,sizeof(buf),stdin);
sscanf(buf,"%d",&num);
return num;
}
// ask user for array value
int
askval(int idx)
{
char prompt[100];
int num;
sprintf(prompt,"Enter array value %d",idx);
num = asknum(prompt);
return num;
}
// checking 1 program module
int
getmax(const char *what,const int *arr,int count)
{
int idx;
int val;
int max = -1;
if (count > 0) {
max = arr[0];
for (idx = 1; idx < count; ++idx) {
val = arr[idx];
if (val > max)
max = val;
}
printf("highest %s value : %d\n", what, max);
}
return max;
}
int
main(void)
{
int idx;
int count = asknum("Enter the number of array elements");
int arr[count];
for (idx = 0; idx < count; ++idx)
arr[idx] = askval(idx);
getmax("value",arr,count);
int number[count];
for (idx = 0; idx < count; ++idx)
number[idx] = arr[idx];
//checking 2 main programs
getmax("score",number,count);
return 0;
}

writing an char array in line with white spaces

The problem is to input some n elements in a line and make an array in c language.
The format of input is This.
input:
15 //number of elements
1 4 4 2 3 5 6 x x x x x x 5 7 // elements
I tried it by using a scanf function, but it didn't work.
char* tree;
int n;
scanf("%d", &n);
tree = (char*)malloc(sizeof(char) * n);
for (int i = 0; i < n; i++)
{
scanf("%c", &tree[i]);
}
what's the problem of this code?
Some what better program would be
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n = 0;
int* numbers = NULL;
printf("How many elements do you want to store:");
do {
if(1 != scanf("%d",&n)) {
puts("error in scanf");
n = 0;
}
if(n <= 0)
printf("Enter a positive number:");
}while(n <= 0);
numbers = malloc(n * sizeof (int));
if( numbers == NULL) {
puts("malloc failed");
return 0;
}
printf("\n Enter %d number of elements:", n);
for(int i = 0; i<n;i++)
if (1 != scanf("%d", &numbers[i]))
printf("error reading input\n");
printf("\n The Entered elements are: ");
for(int i = 0; i < n; i++)
printf("%d ", numbers[i]);
free(numbers);
numbers = NULL;
return 0;
}

Reversal of Array in C Using Given Array

I am having trouble implementing a reversal of an array in C. I am using linux/nano and we have just started, so very minimal has been taught. The code below is what I have, and the array will print of the binary numbers of whatever integer is entered, but in this code, the binary is reversed from what it should be.
#include "stdio.h"
#define MAX_BITS 32
int main()
{
int num;
printf("Enter a valid positive integer: ");
scanf("%d", &num);
int array[MAX_BITS];
int bit, val;
int numDown = 1;
while (numDown <= num)
{
val = numDown;
while (val > 0)
{
bit = val % 2;
printf("%d",bit);
val = val / 2;
}
printf("\n");
numDown = numDown + 1;
}
return 0;
}
I know I need a while loop but I am unsure as to how to go about it.
#include <stdio.h>
#define MAX_BITS 32
int main()
{
int num;
printf("Enter a valid positive integer: ");
scanf("%d", &num);
char array[MAX_BITS];
int index = MAX_BITS - 1;
int temp = num;
do
{
array[index--] = temp % 2;
temp /= 2;
}while(temp != 0);
printf("Binary of %d is: ", num);
for (int i = index + 1; i < MAX_BITS; ++i )
{
printf("%d", array[i]);
}
printf("\n");
return 0;
}

C program to find if a number is palindrome or not

I made a C program to check if a number is palindrome or not. I used the following code, but it shows numbers like 12321 as non palindrome. Can you please explain me the mistake in the program below?
#include <stdio.h>
int main()
{
int i, x, n, c, j;
int d=0;
printf ("enter total digits in number: ");
scanf ("%d", &i);
printf ("\nenter number: ");
scanf ("%d", &n);
j=n;
for (x=1; x<=i; x++)
{
c= j%10;
d=c*(10^(i-x))+d;
j=(j-c)/10;
}
if (d==n)
{
printf ("\npalindrome");
}
else
{
printf ("\nnon palindrome");
}
return 0;
}
^ is the xor operator.
In order to raise power, you need to include math.h and call pow
d = (c * pow(10, i - x)) + d;
this algorithm is as simple as human thinking, and it works
#include <stdio.h>
int main() {
int i=0,n,ok=1;
char buff[20];
printf("Enter an integer: ");
scanf("%d", &n); // i am ommiting error checking
n=sprintf(buff,"%d",n); //convert it to string, and getting the len in result
if(n<2) return 0;
i=n/2;
n--;
while(i && ok) {
i--;
//printf("%c == %c %s\n", buff[i],buff[n-i],(buff[i]==buff[n-i])?"true":"false");
ok &= (buff[i]==buff[n-i]);
}
printf("%s is %spalindrome\n",buff, ok?"":"not ");
return 0;
}
// Yet another way to check for palindrome.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int n, rn, tn;
printf("Enter an integer: ");
scanf("%d", &n);
// reverse the number by repeatedly extracting last digit, add to the
// previously computed partial reverse times 10, and keep dropping
// last digit by dividing by 10
for (rn = 0, tn = n; tn; tn /= 10) rn = rn * 10 + tn % 10;
if (rn == n) printf("%d is palindrome\n", n);
else printf("%d is not palindrome\n", n);
}
A loop like this might do:
int src; // user input
int n; // no of digits
int res = 0;
int tmp; // copy of src
// .... read the input: n and src ....
tmp = src;
for(int i = 0; i < n; i ++)
{
int digit = tmp % 10; // extract the rightmost digit
tmp /= 10; // and remove it from source
res = 10*res + digit; // apend it to the result
}
// ...and test if(res == src)...

Summing only even numbers in an array

After taking ten numbers as input from the user, I want to add up the ones that are evenly divisible by 2.
I am able to get the input from the user, but I'm not sure how to check which numbers are divisible by two, and add only those.
#include <stdio.h>
#include <ctype.h>
int main(void) {
int i = 0;
int val;
char ch;
int numbers[10];
while(i < 10) {
val = scanf("%d%c", numbers + i, &ch);
if(val != 2 || !isspace(ch)) {
while((ch = getchar()) != '\n') // discard the invalid input
;
printf("Error! Entered number is not an integer.\n");
printf("Please enter an integer again.\n");
continue;
}
++i;
}
printf("%d\n", numbers[0]);
printf("%d\n", numbers[1]);
printf("%d\n", numbers[2]);
printf("%d\n", numbers[3]);
printf("%d\n", numbers[4]);
printf("%d\n", numbers[5]);
printf("%d\n", numbers[6]);
printf("%d\n", numbers[7]);
printf("%d\n", numbers[8]);
printf("%d\n", numbers[9]);
return 0;
}
How about:
int sum = 0;
for (int i = 0; i <= 9; i++)
{
if (numbers[i] % 2 == 0)
sum += numbers[i];
}
completely unnecessary optimization
int sum[2]={0};
for(size_t i = 0; i <=9; ++i) sum[numbers[i]&1]+=numbers[i];
int main(void)
{
int i;
int numbers[10];
int sum = 0;
for(i=0; i<10; ++i)
{
printf("Enter #%d:\n", i+1);
scanf("%d", numbers+i);
if (numbers[i] % 2 == 0) // Then Number is even
{
sum += numbers[i];
}
}
printf("The sum of only the even numbers is %d\n", sum);
getch();
return 0;
}

Resources