Text formatting in for loop - c

I have a very basic idea that I want to implement but somehow my logic for this isn't the best one since the code is not working as I want it to.
I want to have numbers written on screen/in text file in such way that after 20 iterrations there's new line which separates them.
Please take a look.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * File = fopen("NUMBERS.txt", "w");
int *a;
int n;
int i;
int j;
int r;
printf("How many numbers do you wish to enter?\n");
scanf("%d", &n);
a = malloc(n*sizeof(int*));
time_t t;
srand((unsigned)time(&t));
fprintf(File, "%d\n", n);
for(i = 0 ; i < n; i++)
{
r = rand() % 100;
a[i]= r;
printf("%d ", r);
fprintf(File, "%d ", r);
if(a[i] % 20 == 0)
{
printf("\n");
fprintf(File, "\n");
}
}
system("pause");
return 0;
}
Lets say that the user enters (21 or any higher number) the output should be:
21
67 24 8 10 27 83 7 89 99 40 69 5 69 12 66 92 99 16 37 22
42

If you want to add a line break after 20 iterations you need to check the i variable used in the iteration instead of the value of the i'th item in the array, so replace
if(a[i] % 20 == 0) with if(i % 20 == 0)
Also, the memory allocation is incorrect as pointed out in another answer (and comment).

Related

I don't know why it pops up "runtime error". Is there any steps I missed :(

To scan two files which only include numbers. Combining and sorting all of the numbers. I have tried so many times but it still pops up an error message.
Please tell me if anyone knows where the problem is. Thank you so much!!!
#include<stdio.h>
#include<stdlib.h>
#define N 128
int main(){
int i, j, temp, count=0;
int data1[N];
char fname1[N], fname2[N];
scanf("%s", fname1);
FILE *f1 = fopen(fname1, "r");
while(1){
fscanf(f1, "%d", &data1[i]);
i++;
if(feof(f1)){
break;
}
count++;
}
fclose(f1);
scanf("%s", fname2);
FILE *f2 = fopen(fname2, "r");
while(1){
fscanf(f2, "%d", &data1[i]);
i++;
if(feof(f2)){
break;
}
count++;
}
fclose(f2);
for(j=count; j>1; j--){
for(i=0; i<j-1; i++){
if(data1[i]>data1[i+1]){
temp = data1[i];
data1[i] = data1[i+1];
data1[i+1] = temp;
}
}
}
for(i=0; i<count; i++){
printf("%d ", data1[i]);
}
return 0;
}
The inputs:
2 5 9 10 15 18 18 20 30 58
1 3 10 12 19 22 25 28 40
The output:
1 2 3 5 9 10 10 12 15 18 18 19 20 20 22 25 28 30 58

How to reverse the position of a nested loop output?

I'm a beginner C programmer and a college freshman.
I need a little help here with a test i'm working on here.
I want to make a nested loop that shows a sorted number. Sorta like this:
1
3 2
4 5 6
10 9 8 7
11 12 13 14 15
21 20 19 18 17 16
22 23 24 25 26 27 28
... ... ... and so on, depending the limit of rows you input
I already tried to make a crude trial-and-error test code:
int i;
int j;
int limit;
int number1 = 1;
int number2 = 3;
int spesial = 0;
printf("Input limit : ");
scanf("%d", &limit);
for (i=1;i<=limit;i++)
{
for(j=1;j<=i;j++)
{
if (i%2==0)
{
printf("%d ", number2);
number2--;
}
else
{
printf("%d ", number1);
}
number1++;
}
if (i%2==0)
{
number2=(i*6)-i+(spesial*1);
spesial+=1;
}
printf("\n");
}
I managed to make it sorted to the 7th rows, but the rest are not..
help please...
I want to know if we could actually control the position of the output without sorta crude our way like this.
Also, sorry for my English... I'm not really from an English speaking country and this is my first time posting/question in this site.
Thank you for reading this lengthy question and I hope you have a good day and good night.
https://ideone.com/yCxpHo:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int rows;
int i, j;
int n = 0;
printf ("How many rows do you want? ");
if (scanf("%d", & rows) != 1 || rows < 1) return EXIT_FAILURE;
printf ("\n");
for (i = 1; i <= rows; ++ i) {
for (j = 0; j < i; ++ j) {
printf ("%4d", n + (i % 2 == 0 ? i - j : j + 1));
}
printf ("\n");
n = n + i;
}
return EXIT_SUCCESS;
}
It can be more convenient to create another function that will calculate the biggest number of a row (I called it lineMax).
int lineMax(int num){
int cnt=0;
for (int i=1;i<=num;i++)
cnt+=i;
return cnt;
}
void main(){
int i,j,limit;
printf("Input limit : ");
scanf("%d", &limit);
for(i=1;i<=limit;i++){
if(i%2==0){ //right to left
for(j=lineMax(i);j>=lineMax(i-1)+1;j--)
printf("%d ",j);
}
else{ //left to right
for(j=lineMax(i-1)+1;j<=lineMax(i);j++)
printf("%d ",j);
}
printf("\n");
}
}
You are making a lot of special cases with number1, number2 and special. This will not work for bigger numbers.
One way is to calculate count which will give you the value to start from in each loop of j. count += i and then every time print count -j
count = 0;
for (i=1;i<=limit;i++)
{
count += i;
for(j=0;j< i;j++)
{
printf ("%d ",count-j);
}
printf("\n");
}

C: Can't get the correct output I need

EDIT: New Problem, now I get a totally different output than the one I need. The following is how I have it written, assignment instruction is on the bottom, please and thank you all!
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE * ifp = NULL;
char filename[20];
printf("What is the name of the input file?\n");
scanf(" %s", &filename);
while (ifp == NULL){
/*PROMPT USER FOR INPUT FILENAME*/
printf("What is the name of the input file?\n");
scanf(" %s", &filename);
/*OPEN INPUT FILE*/
ifp = fopen(filename, "r");
}
int totalSize = 0;
fscanf(ifp, "%d", &totalSize);
int id[totalSize];
char category[totalSize];
int handCombatPt[totalSize];
int distCombatPt[totalSize];
int observationPt[totalSize];
int concealPt[totalSize];
int agilityPt[totalSize];
float ranking[totalSize];
int row=0;
for (row=0; row<totalSize; row++) {
fscanf(ifp, "%d %c %d %d %d %d %d\n", id+row, category+row, handCombatPt+row, distCombatPt+row, observationPt+row, concealPt+row, agilityPt+row);
}
for (row=0; row<totalSize; row++) {
if (category[row] == 'A') {
ranking[row] = (handCombatPt[row] + distCombatPt[row]*2 + observationPt[row]*2 + concealPt[row] + agilityPt[row]*5)/10.0;
}
if (category[row] == 'C') {
ranking[row] = (handCombatPt[row]*5 + distCombatPt[row]*5 + observationPt[row] + concealPt[row] + agilityPt[row]*2)/10.0;
}
if (category[row] == 'S') {
ranking[row] = (handCombatPt[row] + distCombatPt[row] + observationPt[row]*5 + concealPt[row]*5 + agilityPt[row]*2)/10.0;
}
}
int firstA, firstS, secondS, firstC, secondC;
for (row=0; row<totalSize; row++) {
if (category[row]=='A' && ranking[firstA] < ranking[row]) {
firstA = row;
}
if (category[row]=='S' && ranking[firstS] < ranking[row]) {
secondS = firstS;
firstS = row;
}
else if (category[row]=='S' && ranking[secondS] < ranking[row]) {
secondS = row;
}
if (category[row]=='C' && ranking[firstC] < ranking[row]) {
secondC = firstC;
firstC = row;
}
else if (category[row]=='C' && ranking[secondC] < ranking[row]) {
secondC = row;
}
}
printf("A : %d %f \n", id[firstA], ranking[firstA]);
printf("C : %d %f \n", id[firstC], ranking[firstC]);
printf("C : %d %f \n", id[secondC], ranking[secondC]);
printf("S : %d %f \n", id[firstS], ranking[firstS]);
printf("S : %d %f \n", id[secondS], ranking[secondS]);
return 0;
}
And here's the input.txt file:
10
14 A 447 252 68 34 978
2 C 230 299 597 180 9
27 A 318 220 97 28 1317
32 C 563 450 547 112 28
8 C 669 260 200 36 171
11 S 179 45 1342 732 174
19 S 74 249 861 1165 6
21 A 757 240 97 119 2032
15 S 275 177 588 577 52
6 C 886 401 327 109 48
The program needs to output the follow:
A: 21 1171.00
C: 6 696.70
C: 32 578.00
S: 11 1094.20
S: 19 1046.50
Any help would be greatly appreciated!
EDIT: Here is the assignment in case it helps anyone understand what I'm trying to do
Problem: Mentorship
It is time for your friend to select their ninja mentors! Ninja students are able to select several mentorsfrom the class of higher level students to learn special skills from. Skills are categorized as Stealth (S),Combat (C), and Agility (A). Your friend will be provided with a file of older students that has their nameand rankings for the different skills. They can then choose 5 mentors to learn from. To assist, your program should read in all of the student’s information and print out the two bestcombat mentors, the two best stealth mentors, and the best agility mentor. If your friend has been adiligent student, they will be able to select these best options! If not, they will need to go down the listand select other mentors.Combat Skills are split into Hand to Hand and Distance. Stealth skills are split into Observation andConcealment. Agility is a singular category.
Input File Format
The first line of the input file will contain a single integer n (5 ≤ n ≤ 100), denoting the number ofpotential mentors, for which information is listed in the file. The following n lines will have all theinformation for all the mentors with one mentor's information on a single line. Each line will have thefollowing format:ID Category HandCombatPts DistanceCombatPts ObservationPts ConcealPts AgilityPtsID will be a positive integer representing the potential mentor.
Category will be a single character, either 'C', 'S' or 'A', for combat, stealth or agility, respectively.HandCombatPts will be an integer representing the number of points that student was given last year bytheir hand to hand combat instructor. DistanceCombatPts will be an integer representing the number of points that student was given lastyear by their distance combat instructor.ObservationPts will be an integer representing the number of points that student was given last year by
their observation and spying skills instructor.
ConcealPts will be an integer representing the number of points that student was given last year by their
concealment and disguise instructor.
AgilityPts will be an integer representing the number of points that student was given last year by theiragility and acrobatics instructor.
How to Compute a Ranking
For each potential mentor, their ranking will be a summation weighted by their category. If they are a potential combat mentor their ranking should be:(HandCombatPts*5 + DistanceCombatPts*5 + ObservationPts + ConcealPts + AgilityPts*2)/10If they are a potential stealth mentor their ranking should be:(HandCombatPts + DistanceCombatPts + ObservationPts*5 + ConcealPts*5 + AgilityPts*2)/10If they are a potential agility mentor their ranking should be:(HandCombatPts + DistanceCombatPts*2 + ObservationPts*2 + ConcealPts + AgilityPts*5)/10
Program Specification
You must use arrays to solve the problem.
Your program should first prompt the user for the name of the input file. Then, your programshould process the input file and write the five best mentors for your friend. Each line shouldlist the category, the ID, and the ranking of the mentor, respectively, separated by spaces.Round the ranking to two decimal places. The mentors must be listed according to category asfollows: agility, followed by the two combat, followed by the two stealth. Both the combat andthe stealth mentors must be listed in descending order of ranking.
First:
'Program compiles but then “program.exe has stopped working'
I'm sorry to have to inform you that this is the usual behaviour. Writing code and getting it to compile is trivial compared with the effort and skill required to get it to do what you want. Testing and debugging is 99% of software development skill. That is why debuggers exist.
Next:
ALWAYS check the result of ALL system calls. In your case, specifically fopen().
...............
[sigh] 'after I set the uninitialized variables to 0, but now I get a completely different output then the one I need'
See above, especially the hint: 'That is why debuggers exist'. It is really MUCH easier for you to fix your problems than to use SO contributors remote-debug by text exchange. You have the actual code, (ie. not what you originally posetd), the environment, test files etc. We have what you are drip-feeding us, both in terms of what you are doing and what you are getting:(
You must learn to debug now, before you write even one more line of code. If you cannot debug, you cannot develop programs and should not try:(
#include<stdio.h>
#include<stdlib.h>
int main() {
FILE * ifp = NULL;
char filename[20];
while (ifp == NULL){
printf("What is the name of the input file?\n");
scanf(" %s", &filename);
ifp = fopen(filename, "r");
}
int totalSize = 0;
fscanf(ifp, "%d", &totalSize);
int id[totalSize];
char category[totalSize];
int handCombatPt[totalSize];
int distCombatPt[totalSize];
int observationPt[totalSize];
int concealPt[totalSize];
int agilityPt[totalSize];
float ranking[totalSize];
int row=0;
for (row=0; row<totalSize; row++) {
fscanf(ifp, "%d %c %d %d %d %d %d\n", id+row, category+row, handCombatPt+row, distCombatPt+row, observationPt+row, concealPt+row, agilityPt+row);
}
for (row=0; row<totalSize; row++) {
if (category[row] == 'A') {
ranking[row] = (handCombatPt[row] + distCombatPt[row]*2 + observationPt[row]*2 + concealPt[row] + agilityPt[row]*5)/10.0;
}
if (category[row] == 'C') {
ranking[row] = (handCombatPt[row]*5 + distCombatPt[row]*5 + observationPt[row] + concealPt[row] + agilityPt[row]*2)/10.0;
}
if (category[row] == 'S') {
ranking[row] = (handCombatPt[row] + distCombatPt[row] + observationPt[row]*5 + concealPt[row]*5 + agilityPt[row]*2)/10.0;
}
}
int firstA=0, firstS=0, secondS=0, firstC=0, secondC=0;
for (row=0; row<totalSize; row++) {
if (category[row]=='A' && ranking[firstA] < ranking[row]) {
firstA = row;
}
if (category[row]=='S' && ranking[firstS] < ranking[row]) {
secondS = firstS;
firstS = row;
}
else if (category[row]=='S' && ranking[secondS] < ranking[row]) {
secondS = row;
}
if (category[row]=='C' && ranking[firstC] < ranking[row]) {
secondC = firstC;
firstC = row;
}
else if (category[row]=='C' && ranking[secondC] < ranking[row]) {
secondC = row;
}
}
printf("A : %d %f \n", id[firstA], ranking[firstA]);
printf("C : %d %f \n", id[firstC], ranking[firstC]);
printf("C : %d %f \n", id[secondC], ranking[secondC]);
printf("S : %d %f \n", id[firstS], ranking[firstS]);
printf("S : %d %f \n", id[secondS], ranking[secondS]);
return 0;
}
This worked, I initialized everything to 0 and made a while loop for the file name, now it outputs corerctly, though more numbers after the decimal than I need but I think i can fix it with a .lf in the variable print part. If anyone can check that and let me know if they see any thing wrong with it please. Thank you all for the help!

Reading numbers from a text file to an array in user defined function in C

I'm having trouble scanning values from a text file, I've never really used file i/o before and I'm still very shaky with user-defined functions so I'm almost positive that the error is in the first function, I don't know how to fix it however, I'm pretty new at programming so please bear with me.
my code so far is
#include <stdio.h>
#include <stdlib.h>
int read_temps(void)
{
int i;
int num;
int fileArray[25];
FILE *file;
file=fopen("temperatures.txt", "r");
if (file == NULL)
{
printf("Error Reading File\n");
exit(0);
}
for (i=0; i<25; i++)
{
fscanf(file,"%d", &fileArray[i]);
}
fclose(file);
return fileArray[i];
}
int calc_results (int a[], int n)
{
int i, j, maximum, minimum, average,sum;
float avg;
printf ("Temperature conditions on October 26th, 2015:\n");
printf("Time Temperature in Degrees F \n");
for(i = 0; i<25;i++)
{
printf("%d\t%d\n", i, a[i]);
if(maximum < a[i])
maximum = a[i];
if(minimum > a[i])
minimum = a[i];
sum+=a[i];
}
printf("Maximum Temperature for the day: %d\n", maximum);
printf("Minimum Temperature for the day: %d\n", minimum);
avg=(float)sum/25;
printf("Average Temperature for the day: %f\n", avg);
return 0;
}
int main ()
{
int average,i;
int temp[25];
for (i=0;i<25;i++)
temp[i]= read_temps(); //calling user function for file input
calc_results(temp,i); //calling user function
return 0;
}
the program is supposed to read the values from the .txt file in read_temps, calculate the max, min, and average value in calc_results. It does all this and compiles, but it doesnt read the values correctly. The .txt file contains numbers like 87, 65, 92 and when I run my program the output is the same large number like 19863578 repeated for almost all the values, expect for max, min and avg. I don't know what to do :(
these are the values on the textfil
67
67
69
71
77
79
80
80
82
85
87
88
91
93
94
95
95
96
94
90
85
82
81
77
74
the output should be
Temperature Conditions on October 9, 2015:
Time of Day Temperature in degrees F
0 85
1 80
2 97
3 90
4 73
........
25 68
One mistake in your code is that You are calling
for (i=0;i<25;i++)
temp[i]= read_temps();
in your main function. And performing
for (i=0; i<25; i++)
{
fscanf(file,"%d", &fileArray[i]);
}
in your read_temps function which will iterate 25 times all the time and return you the garbage value after the last integer in the file always.
It's because you return fileArray[i]; after for loop, when i = 25, and there is no such value in array
write instead:
int* read_temps(void)
{
int i;
int num;
int fileArray[25];
FILE *file;
file=fopen("temperatures.txt", "r");
if (file == NULL)
{
printf("Error Reading File\n");
exit(0);
}
for (i=0; i<25; i++)
{
fscanf(file,"%d", &fileArray[i]);
}
fclose(file);
return fileArray;
}
and
int* temp;
temp = read_temps();

Using Scanf for Storing Input in 2d Arrays

I want to scan input and save it in a square 2d array.
The first two digits are saved in seperate variables, the first digit is a target number (irrelevant here), the second digit gets saved in variable m, i.e. m = 5 in this case. m is the number of rows/colums of the square matrix. The rest of the input should be saved in the array.
For this particular input, I get a segmentation-fault and random numbers are printed on the screen.
I used some printf statements to trace where things go wrong, and I noticed that the index i in the first loop jumped from 2 to 11 in one scenario, for other input it jumped to 33.
Thanks for your help! I hope I am not missing an obvious mistake.
Input: (each row is seperated by the previous by pressing enter.)
42 5
0 3 7 9 10
9 13 20 5 20
12 11 33 0 12
17 39 22 3 18
My code:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char* arv[]){
int target; // for later processing, irrelevant here
int m; // m = #rows and #columns of array
int array[m][m];
scanf("%d %d", &target, &m);
int i, k;
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
scanf("%d", &(array[i][k])); // save value in array.
}
}
// the problem occurs before this point.
for(i = 0; i < m; i++){
for(k = 0; k < m; k++){
printf("%2d", array[i][k]); // print array.
}
printf("\n");
}
return 0;
}
You have not initialized the value of m before creating array[m][m]. Without initializing, the value of m can be anything.
Change:
int array[m][m];
scanf("%d %d", &target, &m);
to
scanf("%d %d", &target, &m);
int array[m][m];
This is the place where you messed up.
int m;
int array[m][m];
Here ,m is uninitialized and you are creating an array of m*m elements. You need m initialized before the declaration of the array. So move the array declaration after the scanf just after it so that m gets initialized before you declare the array.
#innclude <stdio.h>
int i, j;
int t[5][5];
i=0;
j=0;
while(i < 5)
{
j = 0;
while (j < 5)
{
scanf("%d", &(t[i][j++]));
}
i++;
}

Resources