I want to print multiple values on same line and then go to next line and print the same values and goes to next line and so on.
for ex:-
3 5 10
2 7 15
in C language.
#include <stdio.h>
int main()
{
int a,b,n,i,j,l;
printf("Enter total digit in a line:");
scanf("%d",&n);
printf("Enter number of lines:");
scanf("%d",&l);
for(i=1;i<=l;i++)
{
for(j=1;j<=n;j++)
{
printf("enter values for line :");
scanf("%d",&n);
}
}
}
For each line, read input as string with e.g. fgets, then use e.g. strtok in a loop to extract each number and use strtol to convert the numbers to integer values, and add them up.
The above solution contains of four parts, so lets split it up and do one at a time.
For each line, read input with fgets.
This is pretty simple, as all you have to do is use your outer loop and ask the user to enter numbers there, as well as read the input there as well:
for (i = 1; i <= l; i++)
{
printf("Enter numbers for line number %d: ", i);
char input[128];
fgets(input, sizeof(input), stdin);
}
Use strtok in a loop to extract each number from the input.
for (i = 1; i <= l; i++)
{
/* The code to read the input... */
char *pointer = strtok(input, " ");
while (pointer != NULL)
{
/* `pointer` is now pointing to the next space-delimited number */
/* Find the next space-delimited number */
pointer = strtok(NULL, " ");
}
}
Use strtol to convert the numbers to integer values.
{
/* `pointer` is now pointing to the next space-delimited number */
/* Convert string to number */
long value = strtol(pointer, NULL, 10);
/* Find the next space-delimited number... */
}
Finally add all values in the line.
for (i = 1; i <= l; i++)
{
long sum = 0;
/* ... */
{
long value = strtol(pointer, NULL, 10);
sum += value;
}
printf("The sum of all values on line %d is %ld\n", i, sum);
}
Putting it all together, we get this code:
for (i = 1; i <= l; i++)
{
printf("Enter numbers for line number %d: ", i);
char input[128];
fgets(input, sizeof(input), stdin);
long sum = 0;
char *pointer = strtok(input, " ");
while (pointer != NULL)
{
/* `pointer` is now pointing to the next space-delimited number */
/* Convert string to number */
long value = strtol(pointer, NULL, 10);
sum += value;
/* Find the next space-delimited number */
pointer = strtok(NULL, " ");
}
printf("The sum of all values on line %d is %ld\n", i, sum);
}
Note: The above code have no error checking. I leave that as an exercise to the readers.
E.g.
#include <stdio.h>
int main(void){
int n, l, i, j;
printf("Enter total digit in a line:");
scanf("%d", &n);
printf("Enter number of lines:");
scanf("%d", &l);
for(i=1;i<=l;i++){
long sum =0;
printf("enter values for line : ");
for(j=1;j<=n;j++){
int num;
scanf("%d", &num);//n : Names are colliding
sum += num;
}
printf("sum of line : %ld\n", sum);
}
return 0;
}
Related
So, I have to write a program to ask the user for an integer, and then that integer will determine how many more entries the user gets before adding all the numbers that were entered. So, if the first entered integer is "5", then the user can enter 5 more integers. Those 5 integers are then added together at the end and displayed. I have written a program with for loops, but for some reason, it is only adding first 4 integers and not the 5th one. Here is the code:
int main() { //declare main function
int c=0,n,i; //declare integers
int sum=0;
printf("\nEnter an integer: "); //ask user for input and create a label
scanf("%d",&n);
if (n>=0) { //use if statement
for (i=0;i<n;i++) //use for loop inside if statement to account for negative integers
{
sum+=c;
printf("Enter an integer: ");
scanf("%d",&c);
}
}
else {
printf("Wrong number. You can only enter positive integers!");
}
printf("The sum of the %d numbers entered is: %d",i,sum);
return 0;
}
Just change the position of
sum+=c;
to after the scanf it should work.
It is good to split the program. use functions. Not everything in the main function.
int getInteger(void)
{
char str[100];
int number;
while(!fgets(str, 100, stdin) || sscanf(str, "%d", &number) != 1)
{
printf("Wrong input. Try again:") ;
}
return number;
}
int main()
{
int nsamples;
long long sum = 0;
printf("Enter number of samples:");
while((nsamples = getInteger()) <= 0)
{
printf("Try again, entered number must be >= 0\n");
}
printf("Enter numbers:\n");
for(int i = 1; i <= nsamples; i++)
{
printf("Sample no %d:", i);
sum += getInteger();
}
printf("The sim is: %lld\n", sum);
}
The purpose of my program thus far is to create 4 arrays. 1 'char' array which will take in 10 different string values with each element having a maximum of 25 characters. And 3 other array's that will take in 10 integer values and store them into my array. I compile and run my program, and cycle through my for loops and once completed, I get some weird integer values in the place of my teamName array, and for the 'teamWins' 'teamLosses' and 'teamTies' arrays, it gives me the first value I input for ALL elements in those arrays. I really want to understand how arrays work but I am having trouble declaring them, and using them with input, and output. Can anyone see and explain how I can take in 10 strings with values of 25 characters in each element, and take in 10 integers in the other 3 arrays with elements of 10? I will attach my source code below.
#include <stdio.h>
#include <stdlib.h>
#define NUM_TEAM 10
void displayWelcome(void);
int main(void)
{
char * teamName[NUM_TEAM + 1][30] = { "" };
int teamWins[NUM_TEAM] = {0};
int teamLosses[NUM_TEAM] = {0};
int teamTies[NUM_TEAM] = {0};
int i, bestPercent, worstPercent;
displayWelcome();
//Team Name
for (i = 0; i < NUM_TEAM; i++)
{
//Prompt and enter team name
printf("Enter %i's team name: ", i + 1);
fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);
//Data validation
}
//Team wins
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter wins for team number %i : ", i + 1);
scanf("%i", &teamWins[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamWins) || teamWins <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team losses
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter losses for team number %i : ", i + 1);
scanf("%i", &teamLosses[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamLosses) || teamLosses <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Team ties
for (i = 0; i < NUM_TEAM; i++)
{
printf("Enter ties for team number %i : ", i + 1);
scanf("%i", &teamTies[ i ]);
/*Data validation
while ( 1 != scanf("%i", & teamTies) || teamTies <= 0)
{
fflush(stdin);
printf("Enter a numerical value greater than zero: ");
}*/
}
//Display Data
for (i = 0; i < NUM_TEAM; i++)/* output each word read */
{
printf("%s", teamName);
printf("wins losses ties\n");
printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);
}
return 0;
}
void displayWelcome(void)
{
printf("Welcome to my Football Stats\n\n");
}
You've got four issues:
Declaring teamName as char * teamName[NUM_TEAM + 1][30] = { "" }; is incorrect; if you want an array of strings, it's sufficient to declare char teamName[NUM_TEAM + 1][30] = { "" }; (you want a 2D array of chars, not char *s).
In fgets (teamName[NUM_TEAM], sizeof teamName[NUM_TEAM], stdin);, you're writing each team name to the same unused element. Instead, use fgets (teamName[i], sizeof teamName[NUM_TEAM], stdin); to write to the proper team during each iteration.
Printing using printf("%s", teamName); is incorrect; you want to print each team name rather than attempt to print the address of the teamName array: printf("%s", teamName[i]);
You have an extra argument in printf("%i %i %i\n", teamName[i], teamWins[i], teamLosses[i], teamTies[i]);; since you've already printed teamName[i] in Point 3, you should remove it in this printf() call: printf("%i %i %i\n", teamWins[i], teamLosses[i], teamTies[i]);
I wrote a program in C which takes as an input a value and an ordered Array of integers and performs a ternary search to find the value(if it exists) inside the Array.
I have seen all the possible problems with the usage of scanf and the related topics here in Stackoverflow.
I have noticed that there is a difference if I call the 2 scanf functions in reverse order.
If I use the code as it is below. First read the value and after the array from the user, the program and scanf functions as expected.
printf("Enter the value to be searched in the Array: ");
int k;
scanf(" %d", &k);
printf("Type elements of A(sorted) separated by spaces (type 'end' to stop): ");
i = 0;
while(scanf("%d", &A[i]) == 1) {
i++;
}//while
Although if I use the scanf inputs in the reverse order the second scanf never stops to get user input and read values left in the buffer.
printf("Type elements of A(sorted) separated by spaces (type 'end' to stop): ");
i = 0;
while(scanf("%d", &A[i]) == 1) {
i++;
}//while
printf("Enter the value to be searched in the Array: ");
int k;
scanf(" %d", &k);
I cannot understand what is the difference in the calling order.
I have tried the solutions mentioned in the other threads but none worked.
Just as a reference here is the whole code(working as expected):
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int ternarySearch(int A[], int l, int r, int k){
int i;
int first,second;
if(l>r){
return -1;
}
i= (r - l)/3;
if(i==0){
i++;
}
first = i+l-1;
second = i*2+l-1;
if(A[first]==k){
return first;
}
else if(A[first]>k){
ternarySearch(A, l, first-1, k);
}
else
{
if(A[second]==k)
return second;
else
if(A[second]>k)
ternarySearch(A, first+1,second-1, k);
else
ternarySearch(A, second+1,r, k);
}
}
int main(){
const int maxarraylen = 1000;
int i;
int n;
int A[maxarraylen];
char string[250];
printf("Enter the value to be searched in the Array: ");
int k;
scanf(" %d", &k);
printf("Type elements of A(sorted) separated by spaces (type 'end' to stop): ");
i = 0;
while(scanf("%d", &A[i]) == 1) {
i++;
}//while
n=i-1;
//We assume the array is sorted otherwise we can use any sorting algorithm e.g. code from task1
scanf(" %d", &k);
int result;
result=ternarySearch(A, 0, n, k);
if(result==-1){
printf("The value was not found in the Array.\n");
}
else{
printf("The value was found in position no. %d.\n", result);
}
return 0;
}
Your problem is that you are not 'stepping over' your end input.
We can see this by doing an experiment using the following program:
#include <stdio.h>
#include <stdlib.h>
void main(void) {
FILE *f;
long f_pos;
int ret;
int i;
int data[5];
int data_last;
int search;
f = fopen("./input.txt", "r");
if (f == NULL) {
perror("fopen()");
return;
}
/* read in the values for the array */
data_last = -1;
for (i = 0; i < 5; i++) {
ret = fscanf(f, "%d", &(data[i]));
printf("fscanf(data[%d]): ret: %d\n", i, ret);
f_pos = ftell(f);
printf("ftell(): %ld\n", f_pos);
if (ret != 1) {
break;
}
data_last = i;
}
/* check that we read in at least one value */
if (data_last == -1) {
printf("no input data!\n");
return;
}
/* insert 'fix' here */
/* pre-load the 'search' with known garbage */
search = 987;
/* now read in the search value */
ret = fscanf(f, "%d", &search);
printf("fscanf(search): ret: %d\n", ret);
f_pos = ftell(f);
printf("ftell(): %ld\n", f_pos);
/* print out our info */
for (i = 0; i <= data_last; i++) {
printf("data[%d]: %d\n", i, data[i]);
}
printf("search for: %d\n", search);
return;
}
With the following data in input.txt:
123
456
end
456
The output is as follows:
fscanf(data[0]): ret: 1
ftell(): 3
fscanf(data[1]): ret: 1
ftell(): 7
fscanf(data[2]): ret: 0
ftell(): 8
fscanf(search): ret: 0
ftell(): 8
data[0]: 123
data[1]: 456
search for: 987
ftell() tells us where the file's cursor is, and in this case we can see that it is at byte 8... the e of the input line end.
It doesn't get past it, and thus the next attempt to read a number (%d) will fail too!
It's also a good idea to check the return values! We can see that the fscanf(&search) call has failed to read a number!
The solution is to insert this snippet just after we check that we recieved array values:
/* this is the 'fix' */
ret = fscanf(f, "end");
printf("fscanf(end): ret: %d\n", ret);
f_pos = ftell(f);
printf("ftell(): %ld\n", f_pos);
I am trying to understand why I am having a zero added on to one of my variables userNumberInput. I have been trying to figure out why this is happening for the a bit without a good solution or explanation. It is only happening in the output file, and does not appear to be happening as a result of the variable being set to 0.
For example if you enter 90 the console shows 90, but the output file shows 900.
#include <stdio.h>
#include <stdlib.h>
void Fibonacci (int userInputNumber);
void UserInput (int* userInputNumber);
FILE *fpOut;
int main(int argc, const char * argv[]) {
//Creating global variable for userInput to be passed from function to function
int userInputNumber = 0;
//Opening file for writing output to
if (!(fpOut = fopen("csis.txt", "w"))) {
printf("csis.text could not be opened for output");
exit(1);
}
//Calling two functions and passing appropriate vaiables to each
UserInput(&userInputNumber);
Fibonacci(userInputNumber);
fclose(fpOut);
return 0;
}
void UserInput (int* userInputNumber) {
//Asks the user for a number for the generator
printf("Enter a number into the Fibonacci Generator: ");
scanf("%d", &*userInputNumber);
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
//While the user continues to enter a negative number it forces the user to enter a new number
while (*userInputNumber < 0) {
printf("Invalid user input, enter a positive number\n\n");
fprintf(fpOut,"Invalid user input, enter a positive number\n\n");
printf("Enter a number into the Fibonacci Generator: ");
scanf("%d", &*userInputNumber);
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
}
}
void Fibonacci (int userInputNumber) {
//Defines variables used in this function
int firstNumber, secondNumber, i, seriesNumber, length;
firstNumber = 0;
secondNumber = 1;
seriesNumber = 0;
i = 0;
length = 0;
//For loop that adds the two previous number in the series and prints it and then updates the previous numbers
for (i = 0; seriesNumber < userInputNumber; i++) {
if (i <= 1) {
seriesNumber = i;
length++;
} else {
seriesNumber = firstNumber + secondNumber;
firstNumber = secondNumber;
secondNumber = seriesNumber;
length++;
}
//Statement to break the loop when the next number in the series goes above the user input
if (seriesNumber > userInputNumber) {
length -= 1;
break;
}
//Printing the sequence
printf("%d\n",seriesNumber);
fprintf(fpOut,"%d\n",seriesNumber);
}
//Printing the length of the sequence
printf("Length of the sequence: %d", length);
fprintf(fpOut,"Length of the sequence: %d", length);
}
You have to print a newline after printing the value entered, or 0, which is the first term of the sequence, seems to be appended to the input.
Try changing both of the two
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d", *userInputNumber);
to
fprintf(fpOut,"Enter a number into the Fibonacci Generator: %d\n", *userInputNumber);
I have a homework assignment that requires user to input a set of real numbers. I must store these into an array of size 20, and must print the array in floats.
My problem here is that my array is printing more than the five numbers that are required. the five numbers are 10, 37, 15, 21, 18.
I need help printing only the five numbers, in float with one decimal place.
I'm Using Centos6.7 in Oracle VM VirtualBox, with gedit text editor. Any help is appreciated.
#include <stdio.h>
#define SIZE 20
int main(void)
{
int i, inputs[SIZE];
printf("Enter real numbers, up to %d, q to quit\n", SIZE);
for(i=0; i < SIZE; i++)
scanf("%d", &inputs[i]);
printf("You entered the following values:\n");
for(i=0; i < SIZE; i++)
printf("%4d", inputs[i]);
printf("\n");
return 0;
}
This is the output of the program:
[ee2372#localhost cprog]$ gcc jperez_aver.c
[ee2372#localhost cprog]$ ./a.out
Enter real numbers, up to 20, q to quit
10 37 15 21 18 q
You entered the following values:
10 37 15 21 18 04195443 0-503606696327674196037 0-891225184 494195968 0 0 04195552 0
You must keep track of how many numbers the user has entered. For this, you need a new variable. Increment it if the user enters an integer. Something like this will suffice:
#include <stdio.h>
#define SIZE 20
int main(void)
{
int i, count = 0, inputs[SIZE]; /* Note the new variable */
printf("Enter real numbers, up to %d, q to quit\n", SIZE);
for(i = 0; i < SIZE; i++)
{
if(scanf("%d", &inputs[i]) == 1) /* If `scanf` was successful in scanning an `int` */
count++; /* Increment `count` */
else /* If `scanf` failed */
break; /* Get out of the loop */
}
printf("You entered the following values:\n");
for(i = 0; i < count; i++) /* Note the change here */
printf("%4d", inputs[i]);
printf("\n");
return 0;
}
If you want the user to enter numbers having decimals, you should use:
#include <stdio.h>
#define SIZE 20
int main(void)
{
int i, count = 0;
float inputs[SIZE]; /* For storing numbers having decimal part */
printf("Enter real numbers, up to %d, q to quit\n", SIZE);
for(i = 0; i < SIZE; i++)
{
if(scanf("%f", &inputs[i]) == 1) /* If `scanf` was successful in scanning an `float` */
count++; /* Increment `count` */
else /* If `scanf` failed */
break; /* Get out of the loop */
}
printf("You entered the following values:\n");
for(i = 0; i < count; i++)
printf("%.1f \n", inputs[i]); /* Print the number with one digit after the decimal, followed by a newline */
printf("\n");
return 0;
}
Note that both the above approaches leaves q (or whatever non-integer the user typed) in the stdin. You can clean this from the stdin by using
int c;
while((c = getchar()) != '\n' && c != EOF);
after the first for loop.