How does a program run in c? - c

I'm just learning programming with c.
I wrote a program in c that had a bug in the body of the while loop
I did not put {}.
The program is as follows, but the question that came to me later is how to run the program in c? Why does error 2 not print while it is before the start of the while loop? If the c language is a compiler, why is it that the error of the whole program is not specified first, and up to line 15 the program is executed without any problems?
int main()
{
int n ,k;
float d ;
printf("please write your arithmetic sequence sentences ");
scanf("%d",&n);
printf("\n");
printf("please write your common differences");
scanf("%d",&k);
printf("\n");
printf("please write your initial element ");
scanf("%f",&d);
printf("error 1");
printf("\n");
printf("error 2");
printf("number \t sum");
printf("erorr 3");
int i = 0;
int j = 0;
int sum = 0;
while (i < n)
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
return 0;
}

Firstly, the program enters an infinite loop:
while (i < n)
j = d + i*k;
Since the values of i and n do not change, the condition never becomes false.
Secondly, the printing sequence:
printf("error 2");
printf("number \t sum");
printf("erorr 3");
does not display a line break at the end. The output is buffered (stored internally) waiting for the line break to be printed, which, naturally, never happens. Add \n at the end of "erorr 3" to see the difference.

#include <stdio.h>
int main()
{
int n ,k;
int i = 0;
int j = 0;
int sum = 0;
float d ;
// If the given values are not an integer, it wouldn't continue the sequence and end as an "error"
printf("please write your arithmetic sequence sentences ");
if(scanf("%d",&n)){
printf("please write your common differences");
if(scanf("%d",&k)){
printf("please write your initial element ");
if(scanf("%f",&d)){
printf("Number \tSum\n");
} else {
printf("error");
}
} else{
printf("error");
}
} else{
printf("error");
}
// This is where the values get solved
// You also forgot to add {} in your while statement
while (i < n){
j = d + i*k;
sum += j;
printf("%d\t%d",j,sum);
i++;
}
return 0;
}

Related

C: why does my program not continue after while loop? (scanf)

I'm currently learning C and wanted to write a program that takes a number ganzeZahl to determine array length.
Then you have to input the numbers being stored in that array of size n and after that it's supposed to do a selection sort (which I cut out here, because my program doesn't even reach to that part).
I can't get past the while loop whenever I try to run it. It compiles fine.
It never reaches the printf("!!!--------!!!"); //this part isn't reached for some reason? test5.
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}
Your program does execute correctly, and eventually reaches the last printf call.
When, it enters the whileloop, it keeps on calling scanf, what causes it to stop and wait until you enter a value every iteration. If you provide ganzeZahl inputs (enter a number and press 'enter'), it will complete the loop and proceed. I guess that if you add a printf before scanf within the loop, it should be more intuitive.
for(int z = 0; z < ganzeZahl; z++){
printf("%d\n", array[z]);
The array is not initialized and so you can't print the array yet.
Actually you messed up with the order of code.The while loop should come first and then the for loop. I have corrected your code below. Happy coding!
#include<stdio.h>
int main() {
int ganzeZahl;
scanf("%d", &ganzeZahl);
//printf("ganze Zahl ist: %d\n", ganzeZahl); //test
int array[ganzeZahl];
int i = 0;
while(i<ganzeZahl) {
//printf("!!!hier!!!\n"); //test2
scanf("%d", &array[i]);
//printf("zahl gescannt!\n"); //test 3
i++;
//printf("i erhöht!\n"); //test 4
}
for(int z = 0; z < ganzeZahl; z++) {
printf("%d\n", array[z]);
}
printf("!!!--------!!!"); //this part isn't reached for some reason? test5
//selection sort here
//[...]
return 0;
}

segmentation fault (core dumped) gcc ubuntu

I was trying to make a simple function to make a group of number that user enters them, using pointer of pointer but i keep getting this error and its hard to tell where the problem is, if there any other option to use something else that tells me where the problem is instead of this weird error.
#include <stdio.h>
void BuildGroub(int** group,int* count){
int i=0;
int j;
printf("Enter the size of the group \n");
scanf("%d", &*count);
while(*count != 0){
printf("Enter the %d number of the group:\n", i);
j=0;
scanf("%d", &**(group+i));
while(**(group+i)!=**(group+j)){
j++;
}
if(j==i){
i++;
count--;
} else{
printf("you have already entered this number please try again: \n");
}
}
}
int main(){
int count;
int group[100];
int *groupptr = &group;
BuildGroub(&groupptr,&count);
for(int i=0;i<count;i++){
printf("%d, ", group[i]);
}
return 0;
}
With this question, you do not need to use double pointer. If you want to learn how to use the double pointer, you can google then there are a ton of examples for you, for example, Double Pointer (Pointer to Pointer) in C.
In BuildGroub you decrease the count pointer
if(j==i){
i++;
count--;
}
, but in the condition of while loop, you compare the value that count pointer points to. it seems strange.
while(*count != 0)
Even if you change count-- to (*count)--, it will decrease the number of elements that you enter to 0 when you get out of the while loop, then in main function:
for(int i=0;i<count;i++){} // count is equal to 0 after calling BuildGroub function if you use (*count--) in while loop.
You should use a temp value for while loop function, for example:
int size = *count;
while(size != 0){
...
if (i == j) {
i++;
size--;
}
}
You should use, for example, group[i] instead of *(group+i). It will be easier to read your code.
The code complete:
#include <stdio.h>
void BuildGroub(int* group,int* count){
int i=0;
int j;
printf("Enter the size of the group \n");
scanf("%d", count);
int size = *count;
while(size != 0){
printf("Enter the %d_th number of the group:\n", i);
j=0;
scanf("%d", &group[i]);
while(group[i] != group[j]) {
j++;
}
if(j==i){
i++;
size--;
} else{
printf("you have already entered this number please try again: \n");
}
}
}
int main(){
int count;
int group[100];
int *groupptr = group;
BuildGroub(groupptr,&count);
for(int i=0;i<count;i++){
printf("%d, ", group[i]);
}
return 0;
}
The test:
./test
Enter the size of the group
5
Enter the 0_th number of the group:
1
Enter the 1_th number of the group:
2
Enter the 2_th number of the group:
2
you have already entered this number please try again:
Enter the 2_th number of the group:
3
Enter the 3_th number of the group:
3
you have already entered this number please try again:
Enter the 3_th number of the group:
4
Enter the 4_th number of the group:
5
1, 2, 3, 4, 5,
If you want to use a double pointer, you need to change your function like this:
void BuildGroub(int** group, int* count) {
int i = 0;
int j;
printf("Enter the size of the group \n");
scanf("%d", &*count); //I think this is redundant but works.
while (*count != 0) {
printf("Enter the %d number of the group:\n", i);
j = 0;
scanf("%d", (*group + i)); //The content of group + i
while ( *( *group + i) != *(*group + j)) { //the content of the content
j++;
}
if (j == i) {
i++;
(*count)--; //The content decrement
} else {
printf("you have already entered this number please try again: \n");
}
}
}
But you have a big problem in main and it is because you are using the parameter count to decrement until zero inside the function. So when the function finish, count value is zero and you don't print anything... You need to change this, using a internal variable to make the count, and finaly, setting the parameter to be using in main.

Printing out dynamically allocated memory in C

I'm a total beginner in programming and got an assignment about dynamically allocated memory. One of the expected outputs was a printf statement where all the entered inputs(integers) are printed in a single line, in a row. I have managed to printf in a for-loop, but thats not enought. How do I printf them in a single code-line? Here's the code:
int main()
{
int how_many_integers, count, entered_integers, i, *pSize;
printf("\nHow many integers are you going to type?\n");
scanf("%i", &how_many_integers);
getchar();
// Allocates memory for the integers.
pSize = malloc (how_many_integers * sizeof(int));
// Checks if the integer is 0, and/or reads in all the integers.
if (how_many_integers == 0)
{
printf("No numbers were given.\n");
exit(0);
}
printf("Please enter your integers.\n");
for (int i = 0; i < how_many_integers; i++)
{
scanf("%i", &entered_integers);
count++;
pSize[i] = entered_integers;
}
for (int i = 0; i < how_many_integers; i++)
{
printf("Number: %i\n", *(pSize+i));
}
free(pSize);
printf("Count: %i", count);
return 0;
}
Try this:
printf("Numbers:");
for (int i = 0; i < how_many_integers; i++)
{
printf(" %i", *(pSize+i)); // No \n
}
printf("\n"); // if you want a new line at the end
This should result in an output like
Numbers: 1 2 3 4 5
And as others mentioned, your count variable is never initialized. Initialize it to 0.

Undefined reference error to function that is actually defined in C

I wrote this program to build a number diamond. The issue is that when I compile the program, it throws the error
build2.c:(.text+0x5): undefined reference to `get_input'
collect2: error: ld returned 1 exit status
I've tried for hours to figure out what exactly the problem is (e.g. if there is a spelling mistake or something similar), but the function call looks identical. I have attempted to rename it, write it as both a prototype and as an implementation, and nothing seems to work. Is there an issue that I'm not seeing?
//Define prior to main
int is_valid(int);
int get_input(void);
void print_pattern(int);
//Main
int main(void){
int diamond_size;
//diamond_size = get_input();
//value from get imput method used for diamond size
print_pattern(get_input());
return 0;
}
void print_pattern(int size){
int length, num, i, j;
//beginning of new diamond
printf("\n");
//Define each integer to work in layout of diamond
//First for loop fans out
for(i=1; i <= size; i += 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
//second for loop fans in
for(i=size-2; i >= 1; i -= 2){
length = size-i+1;
num = 1;
printf("%*s", length," ");
for(j = 0; j < i; j++){
printf("%d ", num);
num++;
}
printf("\n");
}
int is_valid(int value){
int rem;
//uses remainder to determine if it is odd or even; an even number will not have a reaminder in this case
rem = value % 2;
if (rem == 0){
printf("You've entered a even number. Please try again.\n");
return (0);
}
//greater than 9 cnd
if (value > 9){
printf("You have entered a number greater than 9. Please try again.\n");
return (0);
}
//less than 1 cnd
if (value < 1){
printf("You have entered a number less than 1. Please try again.\n");
return (0);
}
return (1);
}
int get_input()
{
int cont, number, valid;
cont = 1;
while (cont = 1)
{
printf("Enter an odd number less than 9 and greater than 0 < ");
scanf("%d", &number);
valid = is_valid(number);
if (valid == 1)
{
cont = 0;
}
}
return number;
}
}
You seem to have nested functions; this is (a) a non-standard GCC extension, and (b) I presume the scope of the nested get_input() function is the enclosing function, not the file scope. The solution is to move get_input() to file scope. At the end of print_pattern() add an extra }, and delete the final } at the end of the file.
Also, please format your code - most IDEs these days have options to tidy it up, and with correct indentation you may have seen your problem earlier.
Oh, and as a bonus bug fix, you also have in get_input():
while (cont = 1)
This will always be true - use this instead:
while (cont == 1)
The function print_pattern is not terminated at proper place but instead at the very end of the file:
void print_pattern(int size){
...
... end of the loop
}
... more functions
...
... end of print_pattern
}
This results into defining nested functions instead of global level.
It's generally good habit to indent the blocks, in which case you would realized the mistake very quickly.

C skip a "while" loop?

I have a problem, I tried to write a program to show the whole sum from 1 to 22 and after that, to do 2 while loops. The first one is supposed to perform the sum of some numbers given by the user, as an example: you type 10, 30 and 40 then as you enter a 0 the program sums the first three numbers. Unfortunetly the first while loop is not working. It goes directly to the last while loop where it is supposed to type a decimal numbers like (10.20 30.50 40.55) and after you type 0 again it sum those numbers and add and multipli every entry with 1.19. So far the last loop is working properly, unfortunately the second loop does not, if I move printf and scanf over the while it let me write but just start writing w/o stopping the number I wrote . Thank You in advance!
Here is the code :
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b;
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
return 0;
}
You don't initialise i to any value before entering the loop with
while(i != 0)
i might very well be zero at this point, so your loop won't be entered even once. Initialising i to a non-zero value should fix this particular problem. The same holds for the variable b.
You should turn on warnings in your compiler, so it can show you problems like this one.
The first time the condition of the second while is evaluated, b has undefined value, since it wasn't initialized. The same applies to the third while.
Whether or not both loops are executed is only a question of chance.
Initialize both variables with non-zero values to ensure both whiles are entering. Or use a do-while:
do {
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
} while (b != 0);
Don't test b with while, test it after the user enters the number. Then you can use break to exit the loop.
while (1) {
printf("type a number:");
scanf("%i", &b);
if (b == 0) {
break;
}
sum += b;
printf("%i\n", b);
}
while(1) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
if (i == 0.0) {
break;
}
sum1 += i*1.19;
printf("%lf\n", i);
}
Your only issues are initialization: see edits in the code below. (it compiles and runs)
Did you get any compiler warnings for these? If not, you should change your settings so you do.
#include <stdio.h>
int main()
{
int sum = 0;
int a;
int b=-1; //initialize (any non-zero value will work)
double i;
double sum1 = 0;
for (a= 0; a <= 22; a++) {//a initialized in for(...) statement, (this is good)
sum = sum + a;
printf("the sum from 1 till 22 : %i\n ", sum);
}
while (b != 0) { //b Needs to be initialized before using (done above)
printf("type a number:");
scanf("%i", &b);
sum += b;
printf("%i\n", b);
}
printf("the sum is : %i\n", sum);
i=-1; //initialize i to any non-zero value
while(i !=0) {
printf ("Type a decimal number:");
scanf ("%lf",&i);
sum1 += i*1.19;
printf("%lf\n", i);
}
printf("The decimal summ is: %lf\n",sum1);
getchar();
return 0;
}

Resources