I'm reading a file with a set format so I'm sort of aware of what to expect from the file, however, when I try to print all the input, just to make sure that the code works, the console crashes with a timeout exception. I've got a nested for loop, since I find it the easiest way to handle the file format. But I don't know if there's a better way to handle this.
The problem is a geeks for geeks coding challenge. I noticed that when I change the for variable use in the for loop the code compiles, but this way I wouldn't be able to handle different file formats. As long as I have a constant in the for loop as my parameter it runs. Any idea as to why that is?
the first line is the number of cases, every first line after that tells me the number of node and the number of links, and the following line has linking nodes.
The expected output would be 4 and 3 but I haven't made it that far yet, I'm still making sure that I'm able to read in file properly.
#include <stdio.h>
#include <ctype.h>
int nextInt();
int main() {
int c = getchar() - '0';
printf("%d\n", c);
while(c > 0){
int x, y;
x = nextInt();
y = nextInt();
printf("%d%4d\n", x, y);
int i, a, b;
for(i = 0;i<2*y; i++){
a = nextInt();
printf("%4d", a);
}
printf("\n");
c--;
}
return 0;
}
int nextInt(){
int c, n;
int num;
while(isspace(c=getchar())){;}
num = c - '0';
while(!isspace(n = getchar())){
num = (num * 10) + (n - '0');
}
return num;
}
An example for the input looks something like this:
2
4 4
0 2 0 3 1 3 2 3
4 3
0 2 0 1 0 3
output
4
3
The while loop in nextInt() doesn't stop when it reads EOF. If the last line doesn't end with a newline, you'll go into an infinite loop, because it will never find the delimiter after the last number.
int nextInt(){
int c, n;
int num;
while(isspace(c=getchar())){;}
num = c - '0';
while(!isspace(n = getchar()) && n != EOF){
num = (num * 10) + (n - '0');
}
return num;
}
Related
I am trying to generate numbers from 1-5 using for loop and display their sum. I am aiming to have an output that looks like this:
1 + 2 + 3 + 4 + 5 = 15
But instead, I get the output:
+ 1 + 2 + 3 + 4 + 5 = 15
#include <stdio.h>
void main()
{
int a, sum = 0;
for (a = 1; a <= 5; a++)
{
printf("+\t%d\t",a);
sum = sum + a;
}
printf("=\t%d", sum);
}
This is encountered very frequently whenever outputting lists separated by some value. The problem is that you have 5 values to output, but only 4 separators. If you don't do anything special, then you will output 5 separators which is exactly what's happening in your example. Even if you move the separator to after your value, you'll still have one too many.
The way I prefer to do it is this:
for (a = 1; a <= 5; ++a)
{
if (a > 1) printf("\t+\t");
printf("%d", a);
sum += a;
}
The reason I prefer this approach, versus outputting some value outside of the loop, is because often the thing you're outputting is more complicated, possibly involving additional calculation or function calls and I don't like duplicating that code.
So, I only output a separator if I know that I'm about to output the other thing. That means, output a separator for every loop iteration except the first.
I also like doing it prefix-style because usually the condition for the first item in a loop is simpler than the condition for the last item. It's also compatible with a different approach involving a flag:
int first = 1;
for (a = 1; a <= 5; ++a)
{
if (!first) printf("\t+\t");
first = 0;
printf("%d", a);
sum += a;
}
There are many other ways you'll see this kind of pattern occur. And there may be various forms of optimizing it that reduce readability. But this approach is simple and easy to follow.
You can take pointer of type char and assign it an empty string as a separator for the first iteration and after printing first number assign the separator string, to the pointer, that you want to print between two number in further iterations.
Implementation:
#include <stdio.h>
int main (void) {
int a, sum = 0;
char * str = "";
for (a = 1; a <= 5; a++) {
printf("%s%d\t", str, a);
sum = sum + a;
str = "+\t";
}
printf("=\t%d\n", sum);
return 0;
}
Output:
# ./a.out
1 + 2 + 3 + 4 + 5 = 15
Additional:
Using void as return type of main() function is not as per standards. The return type of main() function should be int.
Odd question, but I'm currently working on an assignment where I am asked to do the following:
Write a program that prompts the user for an integer between 1 and 1000, then prints from 1 to the entered number EXCEPT when the following conditions are met:
If the current number is a multiple of 3 OR contains a 3, print "Hello"
if the current number is a multiple of 7 OR contains a 7, print "Goodbye"
I understand how to determine if a number is a multiple of 3 or 7, but how would I determine if it contained a 3 or 7? I have all of my code written except for this part, and I am just a little lost and unsure what to do.
Thanks!
You should use mod % to find if somethings is dividable with 3 or 7.
To find the last digit of a number you should use mod 10 and then divide it by 10 to get the next digit.
The digits could also be obtained by using three nested loops from 0 to 10 with a break at final number or with a function like this:
#include <stdio.h>
int contains(unsigned long num,int x){
while(num){
if(num % 10 == x){
return 1;
}
num/=10;
}
return 0;
}
int main(){
printf("%d\n",contains(1237002,7));
printf("%d\n",contains(10000002,7));
printf("%d\n",contains(1234002,7));
printf("%d\n",contains(123002,7));
printf("%d\n",contains(7237002,7));
printf("%d\n",contains(1237007,7));
printf("%d\n",contains(7,7));
}
As #chux-ReinstateMonica suggested, you could print the integer to a buffer and then search for the '3' and '7' characters.
#include <string.h>
#include <stdbool.h>
bool contains_3_or_7(int num) {
char buffer[15];
sprintf(buffer,"%i",num);
return (strchr(buffer,'3') || strchr(buffer,'7'))
}
I think you must split the 2 parts:
First with your % comparaison which determine if it's a multiple like if (x % 7 == 0) (0 means x is a multiple of 7)
and for the seconde part convert your int into an str with itoa function or by coding your own like this:
char* itoa(int i, char b[]){
char const digit[] = "0123456789";
char* p = b;
if(i<0){
*p++ = '-';
i *= -1;
}
int shifter = i;
do{ //Move to where representation ends
++p;
shifter = shifter/10;
}while(shifter);
*p = '\0';
do{ //Move back, inserting digits as u go
*--p = digit[i%10];
i = i/10;
}while(i);
return b;
}
then you can determine for each condition if they are true or false
#include <stdio.h>
main()
{
int n=10;
for(int a=n;a>=1;a++) //for bringing out numbers from 1-10
{
int e=a%2; //int e to figure out if the number is even(divisible by 2)
if(e==0)
printf("%d\n",a); //printing the even numbers
}
}
I am new to programming. Learning C.
Here I am trying to make a program that prints even numbers till 10. Executing this code leads to endless even numbers starting from 10.
Can't seem to figure out the logic error here. Some help, please?
The logic for the for loop is not correct.
int n = 10;
for(int a = 0; a <= n; a++) {
if(a%2==0){
printf(a);
}
}
Notice that this is stating at 0, because in CS almost all the time the count starts at 0.
Your loop will never end, it should be:
for(int a = 1; a <= 10; a++)
The entire program should be like that:
#include <stdio.h>
int main(void)
{
for(int a = 1; a <= 10; a++) //for bringing out numbers from 1-10
{
int e = a % 2; //int e to figure out if the number is even(divisible by 2)
if(e == 0)
printf("%d\n", a); //printing the even numbers
}
}
Output:
2
4
6
8
10
I am currently working on a project for college, first year computing class. With that being said, I am not asking for the answer, but I am asking more for some advice. In order to begin the project, I have decided to create a function called collatzSequencer that takes one argument type int.
Here is my function prototype:
int collatzSequencer(int);
Here is my function definition:
int collatzSequencer(int n) {
int stepCounter = 0;
if (n % 2 == 0) {
stepCounter += 1;
collatzSequencer(n / 2);
}
else if (n % 2 == 1) {
stepCounter += 1;
collatzSequencer((3 * n) + 1);
}
else if (n == 1) {
printf("%d\n", n);
printf("%d\n", stepCounter);
return 0;
Here is where I call the function within my main function:
int main(int argc, char* argv[]) {
int num = 5;
collatzSequencer(num);
return 0;
}
When I run my program, nothing happens and I exit with code 0. I have tried debugging my program, and I see that for some reason my IDE doesn't even run the collatzSequencer function when it is called. Although I am a beginner, I feel like I have enough knowledge to be able to find problems within only 48 lines of code, however I cannot find the issue here. Anyone have any ideas?
You are checking for three cases:
n % 2 == 0 (eg. n is Even)
n % 2 == 1 (eg. n is Odd)
n == 1 (eg. n is exactly ONE; this is also the only if-statement with a return)
Except: value 1 is an ODD number, which is captured by the second case.
Your code will never reach the n==1 case, because when n is 1, it will always get captured by the Odd-value if-statement first.
The function has undefined behavior because it does not return anything when n % 2 is equal 0 or 1 and the last else-if statement is not reached by the function control.
Moreover the variable stepCounter can have the maximum value of 1 because it is a local variable of the function that in each recursive call of the function is initialized by zero.
int stepCounter = 0;
The function can be defined the following way as it is shown in the demonstrative program
#include <stdio.h>
size_t collatzSequencer( unsigned int n )
{
return n < 2 ? 0 : 1 + collatzSequencer( n % 2 == 0 ? n / 2 : 3 * n + 1 );
}
int main(void)
{
printf( "%zu\n", collatzSequencer( 27 ) );
return 0;
}
Its output is
111
as it is written in https://en.wikipedia.org/wiki/Collatz_conjecture
Task is to get int using scanf("%d") then print it again using printf("%с") without standard functions like atoi , itoa .As i understood i need to divide all numbers then add \0 char and print it, however how can i divide it. I thought about loop for dividing number%10 + /0 and number/10 to decrease number for 1 character .
Therefore code should look smoothing like this
#include <conio.h>
#include <stdio.h>
main(void)
{
int number,reserve ;
char Array[50];
scanf_s("%d",&number);
if (number > 0 || number == 0)
{
do
{
reserve = number % 10;
printf("%c", reserve + '/0');
number /= 10;
} while (number != 0);
}
else
{
number *= -1;
printf("-");
do
{
reserve = number % 10;
printf("%c", reserve + '/0');
number /= 10;
} while (number != 0);
}
_getch();
return 0;
}
As well there can be negative number so i need some if statement to check if it is negative and in case it is loop should avoid it it so we won't get smthing like -%10
So i don't know if loop is correct (hope someone will fix it and explain me how it is supposed to be). Waiting for your advices.
One side effect of the line
number = number % 10;
is that you lose the original value of number. So when you go to do
number = number/10;
it would always get the value zero. To fix this, store the original value somewhere else, or use another variable to do your character conversion (modulo 10, then plus \0).
Also, your loop needs to be re-examined. This process of modulo, add \0, divide, repeat, should stop when the result of the division is zero (i.e. there are no more digits to print). Another thing to think about is: in what order are these digits being printed?
I'll leave it to you to to figure out how to determine if the value of an int is greater than or less than zero, since you didn't attempt that in this snippet.
this will help you, adopt for your purposes
#include <stdio.h>
int main() {
int a;
int i = 0;
int str_size = 0;
char str[11] = {};
char tmp;
scanf("%d", &a);
while (a) {
str[str_size++] = a % 10 + '0';
a /= 10;
}
str_size--;
while (i < str_size) { // rewind
tmp = str[i];
str[i++] = str[str_size];
str[str_size--] = tmp;
}
printf("%s", str);
return 0;
}