I have already done the sorting part and the copy but I am really struggling to put it together.
Here is only the sorting part because i am not so familiar with it. My main problem is when I start copying the array it only copies the first 2 number then stops and I think its a small problem in the for loop somewhere but i cant find it.
int main ()
{
int number[30];
int number2[30];
int i, j, a, n;
printf("Enter the value of N\n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] < number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The array is copied and sorted like:\n");
for (i = 0; i < n; ++i)
{
printf("%d\n", number[i]);
}
system("Pause");
}
I compiled (MinGW) and ran this exact code and got the following output:
Enter the value of N
10
Enter the numbers
9
1
0
2
8
3
7
5
4
6
The array is copied and sorted like:
9
8
7
6
5
4
3
2
1
0
Press any key to continue . . .
It looks like it is correctly reverse-sorting the input values. Note that this is a fairly common sorting algorithm (https://www.geeksforgeeks.org/bubble-sort/).
Based on this I would argue that the for loop works as is, assuming that you are looking for a reverse sort.
I am not sure what exactly is meant by "copying the array". Array number2 is unused and there are no operations that appear to copy the array number, just operations for loading it, sorting it and printing it.
I'm currently going through CS50 through edx and doing problem set 1, Mario.
The objective is to create a print out using pound signs. With the help of some videos I got the code for the first one but I don't understand fundamentally how the math works/ what the computer is understanding.
So I figure if I don't learn I'm crippling myself later.
if n= 5
Then i has 1 added to it until it is not less than 5 which means 5 times yes?
Take a look at this line for the space loop >
for (int j = 0; j < n -1 - i; j++)
If n is 5, then it ends up being j(0) < 3...
So why on the first line are there four spaces and not three spaces?
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int n;
do
{
n = get_int("Pyramid Height: ");
}
while (n < 0 || n >= 24);
//print out this many rows
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n -1 - i; j++)
{
printf(" ");
}
// print out this many columns
for (int j = 0; j < i + 2; j++)
{
printf("#");
}
printf("\n");
}
}
I get the correct pyramid yet i don't understand the logic behind the spacing and prints
if n=5 then n-1-j would be equal 5-1-0 i.e. 4 for the first time executing the loop that is the reason why you are seeing four spaces. The first loop condition should be n-2-j if you want the number of spaces to be three because total no of columns is 5 and the pounds expected in the first row are 2, therefore you should be subtracting 2 from n.
That looks way too complicated.
Here's a simple version I whipped up:
#include <stdio.h>
int main(void) {
int height = 5;
char blocks[height];
memset(blocks,'#',height);
for(int i=0; i<height; ++i)
{
printf("%*.*s\n", height, i+1, blocks );
}
return 0;
}
Output:
Success #stdin #stdout 0s 9424KB
#
##
###
####
#####
Let us try to figure out the pattern here. Like for the left pyramid if the height of the pyramid is 8, check the pattern of spaces and hashes from top to bottom. In this case we need 8 lines, every line has same characters and no of spaces decreases and no of hashes increases from top to bottom.
Now we have the pattern for the left half, the right half is the same, mirror image. So now we can write down the loop as we know the no of spaces and hashes from top to bottom. In programming we need to understand the underlying principle. Plug in the code afterwards becomes easy.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int h;
do
{
h = get_int("Pyramid height: ");
}
while (h<1 || h>8);
int n = 8, i, j;
for (i=0; i<h;++i)
{
// left half
for (j=0;j<h-1-i;++j)
printf(" ");
for (j=0;j<i+1;++j)
printf("#");
// two spaces in middle
printf(" ");
// right half, we have omitted the space code as it is not required.
for (j=0;j<i+1;++j)
printf("#");
printf("\n");
}
return 0;
So, I have a File full of numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
The case is, I don't know the exact number of numbers in this file, so I don't know the exact size of array I will need to write this file info in to this array.
I just gave array much bigger size than I need and I will show you the output, partially it does its job.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#define ARR_SIZE 30
int main(void){
FILE *fp;
int array[ARR_SIZE];
fp = fopen("C:/project/project.txt", "r");
printf("Numbers: ");
for(int i = 0; i < ARR_SIZE; i++){
fscanf(fp, "%d", &array[i]);
}
for(int j = 0; j < ARR_SIZE; j++){
printf("\n%d", array[j]);
}
fclose(fp);
return 0;
}
I am just trying to do standard things, opening file, reading file with for loop, writing all this info to array and outputting array.
Here is the output I get, I understand it is because of the size, but can you tell me how to limit all of these? Easiest way?
Output:
Numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
4199136
0
4200896
6422240
6422296
6422476
1998244384
592257989
-2
1998220218
1998220461
4200896
6422368
4200987
4200896
I have array size 30 and numbers in the file 15, first 15 is okay, it is exactly what I need, but I don't need those number after it...
You need a stop-condition for the loop that reads from the file. One option is to stop when you can't scan an item. Use the return value from fscanf to detect that.
When you do the printing only print the number of items actual scan'ed.
Try
for(int i = 0; i < ARR_SIZE; i++){
if (fscanf(fp, "%d", &array[i]) != 1) break; // Stop if the scan fails
}
for(int j = 0; j < i; j++){ // ARR_SIZE replaced by i
printf("\n%d", array[j]);
}
BTW: You should check that fp is valid just after the file open.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I want to obtain the following output:
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
The code am running is as follows:
#include <stdio.h>
int main(void) {
int i=1,flag=0,lines=0; //0 for forward, 1 for reverse
while(i!=0 && lines<3){
if(!flag){
printf("%d ",i);
if(i==10){
flag=1;
printf("\n");
lines++;
}
else
i++;
}
else if(flag){
printf("%d ",i);
if(i==1){
lines++;
flag=0;
printf("\n");
}
else
i--;
}
}
return 0;
}
Am getting the desired output from the above code but not sure if it's an optimal code. Any other method/suggestion? Considering unlimited space but time complexity should be kept minimum.
Condition: Use only one loop
Use forloops, minimize code that is repeated
#include <stdio.h>
int main(void) {
int lines, flag=1, val;
for(lines=0;lines<3;lines++)
{
if(flag == 1)
for(val=1;val<=10;val++)
printf("%d ", val);
else
for(val=10;val>0;val--)
printf("%d ", val);
printf("\n");
flag = -flag;
}
return 0;
}
Hint: you can use for loops to iterate in either direction:
for (int i = 1; i <= 10; ++i)
or
for (int i = 10; i >= 1; --i)
Also, a for loop is better than a while here because it really shows to the reader "I am iterating i from this to that."
Use an array and iterate it normally at first iteration, vice versa in the second iteration and then normally again.
Sample code:
#include <stdio.h>
#define SIZE 10
void print_arr(int* array, int size);
void print_rev_arr(int* array, int size);
int main(void)
{
int array[SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int iter = 3;
for(int i = 0; i < iter; ++i)
if(i % 2)
print_arr(array, SIZE);
else
print_rev_arr(array, SIZE);
return 0;
}
void print_arr(int* array, int size)
{
for(int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
void print_rev_arr(int* array, int size)
{
for(int i = size - 1; i >= 0; --i)
printf("%d ", array[i]);
printf("\n");
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
IO completely dominates this problem.
But the fastest way to iterate forwards is
for(i=0;i<N;i++)
and the fastest and most elegant way to iterate backwards is
int i = N;
while(N--)
You can do this:
Use a for loop that will start from 1 and reach 10. Print its
counter.
Use a for loop that will start from 10 and stop at 1. Print its
counter.
Use a for loop that will start from 1 and reach 10. Print its
counter.
Sample code:
#include <stdio.h>
#define LEN 10
#define ITER 3
int main(void)
{
for(int i = 0; i < ITER; ++i)
{
if(i % 2)
for(int j = 1; j <= LEN; ++j)
printf("%d ", j);
else
for(int j = LEN; j >0; --j)
printf("%d ", j);
printf("\n");
}
return 0;
}
Output:
Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
There are 2 things to consider.
First is whether the program is optimal or not. Is is quite easy to prove that your program is optimal (at least asymptotically optimal). You need to display 3n numbers, so you need at least 3n iterations. You have 3n iterations, so it's fine. You might be able to further optimize the iterations themselves, but that will arise as an implicit result of the second paragraph.
The second is readability. Your code is a bit verbose and unflexible. Consider the following:
int pattern[] = {1,2,3,4,5,6,7,8,9,10};
int patternSize = sizeof(pattern)/sizeof(int);
for (int i=0; i < 3; i++)
for (int j=0; j<patternSize; j++) {
if (i % 2)
printf("%d", pattern[patternSize - j - 1]);
else
printf("%d", pattern[i])
}
The code is shorter and clearer. Also, it is more maintable. It is clear what you have to do to chanelge the pattern. I could hardcode the pattern size as 10, but that would requite 2 changes when you change the pattern. I could generate the pattern, from the value of j, but that would limit the number of patterns that could be shown.
But what if the pattern is all the numbers from 1 to 200? Of course I'm not going to write them by hand. Just replace the array with a for loop that fills up the array. You don't have to change the code that displays the array. This is a small example of separation of concerns - one part of thr code does pattern generation, another part does the display, and they can be modified independently.
While this is asymptotically optimal, there are optimizations that can be made. For examples, using that array to store the pattern is not as efficient as generating the pattern from j. But in practice, unless more efficiency is needed, the advantages of this method outweigh the small performance penalty.
Okay, here's my take, I think it's more pleasant than most:
#include <stdio.h>
int main(void)
{
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 10; ++j)
{
const int v = (i % 2) ? 10 - j : j + 1;
printf("%d ", v);
}
putchar('\n');
}
return 0;
}
Some points:
Doesn't use an array, instead just generates the very simple pattern from the line number (i) and position (j).
Not designed for "pluggable" patterns by using an array, since the pattern was very simplistic and repeating, that is exploited to simplify the code.
Re-use the inner loop, rather than duplicating it.
Prints a linefeed in the proper place, to actually get separate lines (not all posted solutions to that).
The inner loop's body could be shortened to a single line by folding v into the printf() of course, but I aimed for readability and clarity, there.
I don't know what's happening with this code.
#include<stdio.h>
int main()
{
int ii[5], i;
for (i=1; i<=5; i++)
{
scanf("%d", &ii[i]);
}
printf("----------------------\n");
for(i=1; i<=5; i++)
printf("%d\n", ii[i]);
return 0;
}
After compiling when I provide input as
1 2 3 4 5
then it prints as it is,
but when I provide input in reverse order:
5 4 3 2 1
it keeps on asking up to some more digits and after that it prints out some random digits from given set of input.
How can I fix this?
c uses 0 indexing that means that array indexes start at 0 not 1. A for loop over an array should look like this:
int array[ARRAY_LENGTH], i;
for (i = 0; i < ARRAY_LENGTH; ++i) {
This will ensure that i will go from 0 to ARRAY_LENGTH - 1 and will not go outside the bounds of your array.
These lines:
for(i=1; i<=5; i++)
printf("%d\n", ii[i]);
will Access element 5 of ii where the maximum index is 4. This will cause Undefined Behavior which is likely why you are seeing random numbers appear.