How to read multiple integers from a single line? - c

Input is some integers separeted by spaces in one line, like this:
enter numbers: 12 41 2
program should get each integers and show the sum:
sum: 55
how can i do that?
edit:I tried this but it is unable to detect enter key. It should stop and show sum when enter is pressed.
printf("\nEnter numbers: ");
int sum =0;
int temp;
while( scanf("%d",&temp))
{
sum+=temp;
}
printf("Sum: %d",sum);

#include <stdio.h>
int main(){
printf("\nEnter numbers: ");
int sum =0, temp;
char ch;
while(2 == scanf("%d%c", &temp, &ch)){
sum+=temp;
if(ch == '\n')
break;
else if(ch != ' '){
fprintf(stderr, "Invalid input.\n");
return -1;
}
}
printf("Sum: %d\n", sum);
return 0;
}

#include <stdio.h>
int main(void){
char line[128], *p=line;
int sum = 0, len, n;
printf("enter numbers: ");
scanf("%127[^\n]", line);
while (sscanf(p, "%d%n", &n, &len)==1){
sum += n;
p += len;
}
printf("sum: %d\n", sum);
return 0;
}

Related

How do I escape while loop when I have N amount of inputs?

using namespace std;
int main() {
int input;
int i=0;
while (1){
scanf("%d", &input);
printf("%d input:%d\n", i, input);
i++;
}
}
Stdin Inputs:
10
65
100
30
95
.
.
.
Is there a way to stop the code and escape from while loop after hitting the last Input?
Amount of Inputs can be N.
edition) Is there a way to calculate the amount of Stdin Inputs? This is my major question.
using namespace std;
int main() {
int input;
int i=0;
while (1){
scanf("%d", &input);
printf("%d input:%d\n", i, input);
i++;
if (i >= 5) break; //change 5 to your desired amount of inputs
}
}
Maybe you are reading an input that has an EOF (End of file)?
In that case you should stop when receiving EOF
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int input;
int i = 0;
while (scanf("%d", &input) != EOF){
printf("%d input:%d\n", i, input);
i++;
}
printf("End\n");
return 0;
}
Otherwise you can do a program that first reads N and then iterate N time
int main(void)
{
int input;
int i = 0;
int n = 0;
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%d", &input);
printf("%d input:%d\n", i, input);
}
return 0;
}

Prime factorization, changing output.

Hello guys i have this code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int num,i,j;
int a=0;
printf("Please input a number: ");
scanf("%d",&num);
printf("The Prime Factorization: ");
for (i=2;i<=num;i++){
if (num%i==0){
a=1;
if (i==num){
printf(" %ld ",num);
} else {
printf(" %ld *",i);
num/=i;
}
}
}
if (a==0){
printf("%ld ",num);
}
return 0;
}
so let's say i input 40,
it gives me
The Prime Factorization: 2 * 4 * 5
this is correct but, how could I make it output the "2 * 4 * 5"
as "2 ^ 3 * 5"?
Since a prime can appear more than once in the factorization you can't just move on to the next candidate without first testing the current prime until the number is no longer divisble by it.
And to get the nice printout you're after, you can keep a count variable as shown below:
#include <stdio.h>
int main(void) {
unsigned int num,i,count;
int a=0;
printf("Please input a number: ");
scanf("%d",&num);
printf("The Prime Factorization: ");
i = 2;
while(num>1){
if (num%i==0){
a=1;
count = 1;
num /= i;
// Exhaust each prime fully:
while (num%i==0) {
count++;
num /= i;
}
printf("%ld",i);
if (count > 1) {
printf(" ^ %ld", count);
}
if (num > 1) {
printf(" * ");
}
}
i++;
}
if (a==0){
printf("%ld ",num);
}
return 0;
}
something like this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num,i,j,count=0;
int a=0;
printf("Please input a number: ");
scanf("%d",&num);
printf("The Prime Factorization: ");
for (i=2;i<=num;i++){
count=0;
a=0;
while(num%i==0){
a=1;
++count;
num/=i;
}
if(a==1)
{
printf("%d ^ %d *",i,count);
}
}
if (a==0){
printf("%ld ",num);
}
return 0;
}

C largest number count

This is problem from textbook. I need to make users be able to enter integers and see the largest and count how many times the largest number appears. I got everything working except for the counting. I have been trying to it figure out for last week.
#include <stdio.h>
#include <limits.h>
int bigEof(void);
int main(void){
bigEof();
}
int bigEof(){
int num;
int big;
int numOld;
int count = 0;
int programFinish = 0;
big = INT_MIN;
printf("Please enter an integer: ");
while (programFinish == 0){
scanf("%d", &num);
if (num > big)
{
big = num;
}
numOld = num;
if (numOld == big){
count++;
}else
count--;
printf("Please enter next Integer <EOF> to stop: ");
printf("The current biggest number is %d and is repeated %d times.", big, count);
}
return big;
}
There is no need of count--, and you'll have to reset your count value each time you get new value for big.
#include <stdio.h>
#include <limits.h>
int bigEof(void);
int main(void){
bigEof();
}
int bigEof(){
int num;
int big;
int numOld;
int count = 0;
int programFinish = 0;
big = INT_MIN;
printf("Please enter an integer: ");
while (programFinish == 0){
scanf("%d", &num);
if (num > big)
{
big = num;
count = 0;
}
numOld = num;
if (numOld == big){
count++;
}
printf("Please enter next Integer <EOF> to stop: ");
printf("The current biggest number is %d and is repeated %d times.", big, count);
}
return big;
}
The function could be defined the following way
void bigEof()
{
int num;
int big;
int count = 0;
printf("Please enter an integer: ");
while ( scanf( "%d", &num ) == 1 )
{
if ( count == 0 || big < num )
{
big = num;
count = 1;
}
else if ( big == num )
{
++count;
}
printf( "Please enter next Integer <EOF> to stop: " );
}
if ( count != 0 )
{
printf( "The current biggest number is %d and is repeated %d times\n", big, count );
}
else
{
puts( "You did not enter numbers." );
}
}

My string compare is coming out wrong

hi my program is to enter a number which gives the length of the string then the string and then finally a letter which should then tell me how many times that letter is in the string. Currently to help me figure out what is wrong with my code i can see that the strcmp is resulting in the same ascii number but negative. eg for the letter a the number is 97 but the strcmp is giving out -97 so the strcmo doesnt show the character as being in the string and results in the incorrect result. Any help would be greatly appreciated. thanks
#include
#include
int main(void)
{
char myChar[100], z, k;
int counter, n, g=0, r, i, l;
counter=0;
scanf("%d",&n);
while (counter<n)
{
counter++;
scanf(" %c",&myChar[counter]);
}
scanf(" %s", &z);
for(i=0;i<n+1;++i)
{
k=myChar[i];
r=strcmp(&z, &k);
l=r;
//printf("\n%c", myChar[i]);
printf("%d\n", l);
if(r==0)
{
g++;
printf("%d\n", g);
}
}
printf("\n\n%d\n", g);
return (0);
}
#include <stdio.h>
#include <string.h>
int main(void){
char myChar[100], str[64];//
int counter, n;
int i, j, k;
printf("number of charactors : ");
scanf("%d",&n);
for (i=0; i<n; ++i){
scanf(" %c", &myChar[i]);
}
printf("input string : ");
scanf("%63s", str);//"%s" : The useless one letter to input as a string. "%c" for &z
for(i=0;i<n;++i){
counter = 0;
for(j=0;str[j]!='\0'; ++j){
k = (str[j] == myChar[i]);//Comparison of each character
counter += k;//if(str[j] == myChar[i]) ++counter;
}
printf("%c is %d\n", myChar[i], counter);
}
return (0);
}

How to use a loop function with user input in C?

Here is the average program I created.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
/* Program to calculate averages. */
/*Asks for the numbers.*/
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
return 0;
}
Now would I turn this into a do-while? Or an if else?
If you want to repeat the whole entry and averaging process, you can wrap a loop around the code:
#include <stdio.h>
int main(void)
{
float f1,f2,f3;
while (1)
{
printf("Please enter three numbers.\n");
printf("\tFirst number please.\n");
if (scanf("%f", &f1) != 1)
break;
printf("\tSecond number please.\n");
if (scanf("%f", &f2) != 1)
break;
printf("\tThird number please.\n");
if (scanf("%f", &f3) != 1)
break;
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
Note that this code checks the return value from scanf() each time it is used, breaking the loop if there's a problem. There's no need for string concatenation, and a single printf() can certainly print a string and a value.
That's a simple first stage; there are more elaborate techniques that could be used. For example, you could create a function to prompt for and read the number:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
If you want to get away from a fixed set of three values, then you can iterate until you encounter EOF or an error:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float value;
float sum = 0.0;
int num = 0;
printf("Please enter numbers.\n");
while (prompt_and_read("\tNext number please.\n", &value) == 0)
{
sum += value;
num++;
}
if (num > 0)
{
printf("You entered %d numbers\n", num);
printf("Your sum is %f\n", sum);
printf("Your average is %f\n", sum / num);
}
return 0;
}
You might also decide to replace the newline at the ends of the prompt strings with a space so that the value is typed on the same line as the prompt.
If you want to check whether to repeat the calculation, you can use a minor variant on the first or second versions of the code:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
static int prompt_continue(const char *prompt)
{
printf("%s", prompt);
char answer[2];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
int c;
while ((c = getchar()) != EOF && c != '\n') // Gobble to newline
;
return 1;
}
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
if (prompt_continue("Do you want to try again?") == 0)
break;
}
return 0;
}
You can do this:
int main()
{
float number, sum=0.0f;
int index=0;
do
{
printf ("\t" "Enter number please.\n"); //Asking for a number from user
scanf("%f", &number); //Getting a number from a user
sum+=number; //Add number entered to the sum
i++;
} while (i < 3);
printf("Excellent, your average is %f\n", sum/3);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
char c='Y';
/* Program to calculate averages. */
/*Asks for the numbers.*/
do
{
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
printf ("Do you wana continue [Y/N]...\n");
scanf("%c", &c);
}while(c!='N'&&c!='n');
return 0;
}

Resources