Need help breaking down code to smaller parts C - c

I'm pretty new to C so be gentle, somewhy my code doesn't work, be kind and help my figure it out why it doesn't, also if it's possible to make it shorter without making it too complicated, please help in that too.
main.c
#include <stdio.h>
#include <stdlib.h>
#include "swap.h"
#include "magic.h"
int main(int argc, char *argv[])
{
int i,j,count;
int min=atoi(argv[1]);
int max=atoi(argv[2]);
if(min>max)
{
swap(&min, &max);
}
if (min<0)
{
min=1;
}
if(argc<2 || argc>5){exit(EXIT_FAILURE);}
else
{
magic();
}
}
Magic.c
#include <stdlib.h>
#include <stdio.h>
#include magic.h
magic(char *argv[])
{
for(i = min; i<=max; i++)
{
count = 0;
for(j=2; j<=i/2; j++)
{
if(i%j==0)
{
count++;
break;
}
}
if(count==0 && i!= 1 && i!= 0)
printf("%d \n",i);
}
return 0;
}

this is as single file for simplicity
#include <stdio.h>
#include <stdlib.h>
void swap(int *a,int *b){
int c=*a;
*a=*b;
*b=c;
}
void magic(int min, int max);
int main(int argc, char *argv[])
{
int min,max;
if(argc!=3) // (argc<2 || argc>5)
exit(EXIT_FAILURE);
min=atoi(argv[1]);
max=atoi(argv[2]);
if(min>max)
swap(&min, &max);
if (min<0)
min=1;
magic(min,max);
return EXIT_SUCCESS;
}
void magic(int min, int max){
int i,j,count;
for(i = min; i<=max; i++){
count = 0;
for(j=2; j<=i/2; j++) {
if(i%j==0){
count++;
break;
}
}
if(count==0 && i!= 1 && i!= 0)
printf("%d \n",i);
}
}

You have some error in your code :
you are trying to use the variables min, max and countin your function magic however since they are declared in your main function magic does not have knowledge of them.
you should change your main function like :
#include <stdio.h>
#include <stdlib.h>
#include "swap.h"
#include "magic.h"
int main(int argc, char *argv[])
{
int min=atoi(argv[1]);
int max=atoi(argv[2]);
if(min>max)
{
swap(&min, &max);
}
if (min<0)
{
min=1;
}
if(argc<2 || argc>5){exit(EXIT_FAILURE);}
else
{
magic(min, max);
}
return EXIT_SUCCESS;
}
and your magic function :
#include <stdlib.h>
#include <stdio.h>
#include "magic.h"
int magic(int min, int max)
{
int count;
for(int i = min; i<=max; i++)
{
count = 0;
for(int j=2; j<=i/2; j++)
{
if(i%j==0)
{
count++;
break;
}
}
if(count==0 && i!= 1 && i!= 0)
printf("%d \n",i);
}
return 0;
}
In the main function I change magic(); by magic(min, max); to pass parameters to the function which can be retrieve in magic with it's new signature int magic(int min, int max).
Since your magic function return an integer don't forget to specify the return value in the signature of your function.

Related

How to make this conditional be true in C++

Somebody know how to make char str[20]="reviver",palind=1 be true printf("%s eh palindromo.\n",str)?
My code below
#include <stdio.h>
#include <string.h>
int main()
{
char str[20]="reviver",palind=1;
int tam = strlen(str);
int i=0; char cont = tam;
for(; i <= cont; i++,cont--)
{
if(str[i]!=str[cont])
{
palind=0;
break;
}
cont--;
}
if(palind)
printf("%s eh palindromo.\n",str);
else
printf("%s nao eh palindromo.\n",str);
return 0;
}
I hope if you do two corrections in line numbers 7 and 15 as below, you may get expected result.
#include <stdio.h>
#include <string.h>
int main()
{
char str[20]="reviver",palind=1;
int tam = strlen(str);
int i=0; char cont = tam-1;
for(; i <= cont; i++,cont--)
{
if(str[i]!=str[cont])
{
palind=0;
break;
}
/*cont--;*/
}
if(palind)
printf("%s eh palindromo.\n",str);
else
printf("%s nao eh palindromo.\n",str);
return 0;
}

I'm trying to count the numbers in a string in C

What's wrong with my code? I'm trying to count the numbers in a string after skipping all alphabets.
How to skip the alphabets and only count the numbers?
#include <stdio.h>
#include <stdlib.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if(a[i]>='a'&&a[i]<='z')
{
continue;
}
else
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[100001];
scanf("%s",a);
function(a);
printf("\n");
}
}
I switched your usage of scanf to use fgets. This works:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if (isdigit(a[i]))
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t = 0;
scanf("%d", &t);
while(t--)
{
char a[100001];
fgets(a, sizeof(a), stdin);
function(a);
puts("\n");
}
}
If the OP's intent was in fact to count up the groups of digits (in which the definition of 'number' is each contiguous run of digits), this will accomplish the goal:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int function(char a[])
{
size_t i = 0;
int cnt = 0;
// convert all non-digits to whitespace
printf("Converting\n");
for (char *p = a; *p != '\0'; ++p)
{
*p = isdigit(*p) ? *p : ' ';
}
printf("Found Groups: %s\n",a);
// note: strtok mutates the string it is given, it will not be usable after this:
for (char *gr = strtok(a," "); gr != NULL; gr = strtok(NULL, " "))
{
cnt++;
}
printf("Number of Groups: %d\n", cnt);
}
int main()
{
printf("Enter strings (Ctrl-C to end)\n");
while(1)
{
int result = 0;
char a[100001];
scanf("%s",a);
result = function(a);
printf("\n");
}
}
(I was not able to get the version using fgets to work, but how the string is gathered is not really in the scope of the question, the OP's original code in main is functional, I just made it an open-ended loop for my tests)
In your code continue statement is responsible for wrong answer. Because of it your code is not encountering the statement a[i] !='\0'. so suggest you to just avoid it and close your if statement without any code as like me. One more suggestion use also uppercase letters as user can also enter uppercase letters and using fgets() function you can also read white spaces.
Try out this
#include <stdio.h>
#include <stdlib.h>
void function(char a[])
{
int i=0,count=0;
while(a[i]!='\0')
{
if((a[i]>='a'&&a[i]<='z') || (a[i]>='A'&&a[i]<='Z'));
else
{
count++;
}
i++;
}
printf("%d",count);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
char a[100001];
scanf("%s",a);
function(a);
printf("\n");
}
}

strange character is output to the terminal

I'm beginer in C/C++ programming.
This is my program that displays binary numbers in ascending order in the terminal (I'm compiling in Linux Mint).
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
int main()
{
unsigned int bitCount;
unsigned int naborCount;
printf("Число битов в наборе: ");
scanf("%d", &bitCount);
printf("\n");
naborCount = pow(2, bitCount);
char naborStr[bitCount*2];
for(int i = 0; i<naborCount; i++)
{
for(int j = 0; j<bitCount; j++)
{
if((i & (1<<j))==0)
{
strcat(naborStr, "0 ");
}
else
{
strcat(naborStr, "1 ");
}
if(j == bitCount-1)
{
reverse(naborStr, 0, strlen(naborStr)-1);
printf("%s \r\n", naborStr);
memset(naborStr, 0, sizeof(naborStr));
}
}
}
return 0;
}
This is what I see in the terminal
Where did this symbol come from? How to solve it?
C strings are null terminated.
The %s specifier searches for a null termination.
In your case it keeps on printing until it finds one, so you get some random symbols.
Try making use of null character at the end of the string and check.
Have a look at the following implementation:
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#include <string.h>
void reverse(char *x, int begin, int end)
{
char c;
if (begin >= end)
return;
c = *(x+begin);
*(x+begin) = *(x+end);
*(x+end) = c;
reverse(x, ++begin, --end);
}
int main()
{
unsigned int bitCount;
unsigned int naborCount;
printf("Число битов в наборе: ");
scanf("%d", &bitCount);
printf("\n");
naborCount = pow(2, bitCount);
char naborStr[bitCount*2 + 1]; //Increased size by 1 for null character
for(int i = 0; i<naborCount; i++)
{
for(int j = 0; j<bitCount; j++)
{
if((i & (1<<j))==0)
{
strcat(naborStr, "0 ");
}
else
{
strcat(naborStr, "1 ");
}
if(j == bitCount-1)
{
reverse(naborStr, 0, strlen(naborStr)-1);
naborStr[bitCount*2 +1] = '\0'; //Appending null character
printf("%s \r\n", naborStr);
memset(naborStr, 0, sizeof(naborStr));
}
}
}
return 0;
}

Check command line input in C

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int allDigits(char *S) {
while ( *S ) {
if ( ! isdigit(*S)) return 0;
S++;
}
return 1;
}
int main (int argc, char *argv[]) {
int i, /*for loop index*/
sum=0; /*the sum of the arguments*/
for (i=1; i<argc; i++) {
if ( allDigits(argv[i]))
sum = sum + atoi(argv[i]);
else {
fprintf(stderr,"Usage: %s [<int> <int> ... <int>]\n",argv[0]);
exit(1);
}
}
printf("Sum of the %d integers is %d\n", argc-1, sum);
exit(0);
}
I got this example from my notes, which check the command line input to see whether is a number or not. However, there is one part I don't really understand how that works, in the function allDigits we used isdigit() to check the input. But why we put ! in front of isdigit?
Can anyone explain this part to me?

Simple program crashes after using switch - C

I just have written a program which suppose to return char which appears the most/least. Program work during the testing without switch statement, but when I added it start to crash. Can you have a look?
Main function
#include <stdio.h>
#include <stdlib.h>
#include "tools.h"
int main(int argc, char *argv[]) {
int count[256] = { 0 };
int c;
while ( (c=getchar())!=EOF ){
count[c]++;
}
switch (argv[1][1]) {
case 'm': case 'M':
mostOften(count);
break;
case 'l': case 'L':
leastOften(count);
break;
default:
mostOften(count);
break;
}
return 0;
}
Tools function
#include <stdio.h>
#include <stdlib.h>
#include "tools.h"
void mostOften(int *s) {
int j;
int max, cha;
for(j=32; j<126; j++){
if(s[j]>max) {
max=s[j];
cha=j;
}
}
printf("char %c: %d times\n", cha, max);
}
void leastOften(int *s) {
int j;
int min=10000, cha;
for(j=32; j<126; j++){
if(s[j] && s[j]<=min) {
min=s[j];
cha=j;
}
}
printf("char %c: %d times\n", cha, min);
}
You are using max uninitialized, thus, reading garbage:
int max, cha;
for(j=32; j<126; j++){
if(s[j]>max) {
Also, you need to check if argv[1][1] exists before using it:
switch ((argc > 1 && argv[1][0]) ? argv[1][1] : 0) {

Resources