Infinite for loop? ()in c - c

the value of i resets after it reachers 7
#include <stdio.h>
int main(){
char marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
output

Problem is here:
scanf("%d", &marks[i]);
Specifier "%d" expects a pointer to int, not char. Usually it will write 4 bytes what is a typical size of int.
Therefore on 8th iteration the elements of marks at index from 7 to 10 are touched. However, marks[10] is outside of marks array (only indices 0-9) are valid. Undefined Behaviour is invoked and the program can do anything, from crashing to infinite looping or conjuring nasal deamons.
To fix the program change the type of marks to int:
int marks[10];
Note:
UB is invoked even on the first iteration because "%d" expects a pointer to int while type of &marks[0] is char*. This operation is undefined by C standard because int* and char* may differ in size and/or representation and/or alignment. However it is a unlikely case for modern CPUs.

You have declared the marks as a character array and tried to get input from user using %d which asks asks for an integer,
#include <stdio.h>
int main(){
int marks[10];
int i;
printf("enter the numbers:\n");
printf("-------------------\n");
for (i=0;i<10;i++)
{
printf("%d\n",i);
printf("element %d-",i);
scanf("%d", &marks[i]);
}
printf("\n all %d",marks);
printf("\n second %d\n",marks[1]);
return 0;
}
Also I didn't understand the use of all so I couldn't find a solution for it. If you want to print a specific number then you have to specify it like you have done it for second or if you want to display the total you want to add a furthermore code to calculate the sum of elements in the array.

Related

How do I determine if a value is within a range?

I am relatively new to C, I have to do it for school unfortunately and I am having issues with it at the easiest exercises.
Here I have to check if a number is in a certain interval, for example between 4 and 6. I made it like this.
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%s", i);
if (i>4 && i<6){
printf("%s Value is in first interval\n", i);
}
}
The scanf to enter the number and check if it is in the interval. But even if I enter a number that is part of it, for example 5, the printf doesn't do anything. I tried also to add an else statement for numbers outside the interval, but also there the printf did not change anything.
It is because you have declared i variable as int and you are taking input as string so when it is checking condition it is getting null value in i variable and not able to enter if block check below code
#include <stdio.h>
int main(){
int i;
printf("Value to check Interval \n");
scanf("%d",&i);
if (i>4 && i<6){
printf("%d Value is in first interval\n", i);
}
}
try compiling your code without if condition i variable will return a null value

Sorting Strings in a static array based on their length crashes? |wrong allocation/access|

I wanted to make an array of strings and sort them in order based on their length (smallest -> biggest) but the program crashes after all inputs.
And also it bypasses Element 0 (starts directly from element 1 during input)
#include <stdio.h>
#include <stdlib.h>
main()
{
int i,j,N;
printf("\nInput amount of alphanumericals: ");
scanf("%d",&N);
{
int min;
char *swap=(char*)malloc(sizeof(char)*150);
char *A[N],**temp;
for(i=0;i<N;i++)
*(A+i)=malloc(sizeof(char)*N);//Error Here
temp=A;
for(i=0;i<N;i++){
printf("\nInput %d element:",i+1);
fgets(temp+i,150,stdin);//And Here
}
printf("\n\nData [");
for(i=0;i<N;i++)
printf(" %s",A[i]);
printf(" ]\n\n");
//insertion sort
for(i=0;i<N;i++){
min=i;
for(j=i+1;j<N;j++){
if(strcmp(A[j],A[min])<0){
min=j;
}
}
if(min!=i){
swap=A[i];
A[i]=A[min];
A[min]=swap;
}
}
free(swap);
printf("\n\nInsertion Sorted Data [");
for(i=0;i<N;i++)
printf(" %s",A[i]);
printf(" ]");
}
return 0;
}
This error :
for(i=0;i<N;i++)
*(A+i)=malloc(sizeof(char)*N);//Error Here
i reproduced with g++ compiler, if this is your case also i.e. you also compiling with g++ add casting to char* :
*(A+i)= (char*) malloc(sizeof(char)*N);//Error Here
The second issue is because you trying to pass char** instead of char*
fix :
fgets(*(temp+i),150,stdin);//And Here
Also brackets after scanf("%d",&N); limits scope of variables min and swap , so later should not be visible at all.
First, what happens with element 0: after you enter the number of elements which is read by scanf("%d"), you press Enter so that your input reaches the program. But the scanf calls only reads the number, not the newline character. So the first call to fgets gets what remains of the line — an empty line.
See Get scanf to quit when it reads a newline? for several approaches to solve this problem. The most robust way is to call fgets to read a line (which is expected to call the number), then call sscanf to parse the number in the string in memory.
The second problem is in the call fgets(temp+i,150,stdin). A good compiler would produce a warning like this:
a.c:17:9: warning: passing argument 1 of ‘fgets’ from incompatible pointer type [enabled by default]
You're passing a pointer to a pointer to char (the address of a location containing the address of a string buffer), but fgets expects a pointer to char (the address of a string buffer). Since temp+i is a pointer to the entry in the array A (which is an array of pointers), what you need to pass to fgets is the value that this pointer points to: *(temp+i), which is more commonly written temp[i]. Given what you do with the variable temp, just drop it and use A.
fgets(A[i], 150, stdin);
After that, your sort routing doesn't always return the correct result, but that's another story.

Adding numbers until a negative is encountered

I'm trying to create a program that lets the user enter numbers(maximum entries>10^6) until a negative is encountered. I've tried a lot of version but they either don't register that a negative value is entered or they crash.
This is where I'm currently at:
#include <stdio.h>
#define HIGHEST 999999
int main(){
int i=0, entry, sum=0;
while(i<HIGHEST){
scanf("%i", entry);
if(entry>0){
sum+=entry;
}
else{
i=HIGHEST;
}
i++;
}
printf("Sum: %i", sum);
system("pause");
}
Your problem is on this line:
scanf("%i", entry);
Which should be:
scanf("%i", &entry);
You need to pass in the address of the integer variable that will store the scanned value. Since
entry was never initialized, it is just filled with garbage/whatever is in memory and not the entered value. See this reference, which states,
"Depending on the format string, the function may expect a sequence of additional arguments,
each containing a pointer to allocated storage where the interpretation of the extracted
characters is stored with the appropriate type"
You provide a way to leave if the entered number is too big:
while(i<HIGHEST){
But nothing to leave if it is less than 0; Try this:
while((i<HIGHEST)&&(i>=0)){
Additionally, #OldProgrammer is correct, your scanf() should be as he has pointed out.

how to convert char to int

I'm trying to write a short program were:
#include <stdio.h>
void main()
{
char=a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
}
The exercise I'm trying to solve is how to change the char to int so if I write in a the number 3, I will get the number 3 Printed.
at this point I'm only getting the value.
I would appreciate any help.
The answer depends somewhat on what you can assume about the character set. If it's something like ASCII (or really, any character set that includes the digits in sequential order), you just need to offset the character value by the value of the character 0:
int aValue = a - '0';
I'm sure that C# provides better ways to do what you're trying to do, though. For example, see this question for some examples of converting strings to integer values.
First of all your syntax need some checking
You should know that you declare a variable this way (a char in this example):
char a;
If you want to declare multiple variables of the same type in a row you do :
char a, b, c;
If you want to assign a value to a declared variable :
a = '3';
Now to print a char using printf (man printf is a must read, more infos are in coreutils) :
printf("%c", a);
If you want to get the char from the command line, I recommand you to use getchar() (man getchar) instead of scanf because if suits better what you are trying to achieve and doesn't require you to use a syntax in scanf that I am sure you don't fully understand yet.
Your question is incredibly light on details, so here are several options:
#include <stdio.h>
int main()
{
char a,b,c;
printf("please place 3 numbers:\n");
scanf("%c%c%c", &a,&b,&c);
printf("Printing ints (auto-promotion): %d %d %d\n", a, b, c);
printf("Printing ints (explicit-promotion): %d %d %d\n", (int)a, (int)b, (int)c);
printf("Printing digits: %d %d %d\n", a-0x30, b-0x30, c-0x30);
return 0;
}
If the input is 123,
I expect the output to be:
Printing ints (auto-promotion): 49 50 51
Printing ints (explicit-promotion): 49 50 51
Printing digits: 1 2 3
Some things I fixed along the way.
main should return an int, not be void.
char=a,b,c; is a syntax error. You meant char a,b,c;
added a return 0; at the end of main.
You question is not quite understandable. Still I'll try to help. I think that what you want is to store an integer value in the char variable. You can do so by using the following code:
#include<stdio.h>
void main()
{
char a,b,c;
printf("Enter three numbers:\n");
scanf(" %c %c %c",&a,&b,&c); //notice the spaces between %c
}
Or if you want to enter a character and print its ASCII value, you can use the following code:
#include<stdio.h>
#include<conio.h>
void main()
{
char a,b,c;
printf("Enter three characters:\n");
scanf(" %c %c %c",&a,&b,&c);
printf("Entered values: %d %d %d",a,b,c);
getch();
}

failing to display array entered from keyboard in c

I'm new to c and I'm trying to write a c program that get 10 integer values entered from keyboard using scanf and then print them using printf but the result is not correct. Here is the code:
#include<stdio.h>
#include<conio.h>
main(){
int x[10];
printf("\n\n\t\t PRGRAM THAT CAPTURES AND PRINTS 10 SCORES");
for(int i=1;i<=10;i++){
printf("\n\tEnter Score %d", i);
scanf("%d",x);
}
printf("\n\t The entered scores are: %d",x[i]);
return(0);
}
the output given is a four digit number like 8731 yet I expect something like 1234567890. some help please
You need to make a new for loop to display the values, just like you do when reading them.
PS: format your code better, you'll thank it later.
PS2: try to avoid conio.h, it's not standard, and you don't even need it for your code.
PS3: also your code is wrong. Should be for(int i=0;i<10;i++). Arrays go from 0 to size-1, not from 1 to size. The C compiler will not warn you that i[10] is an invalid index for your array.
Try this:
#include<stdio.h>
#include<conio.h>
int main(){
int x[10];
printf("\n\n\t\t PRGRAM THAT CAPTURES AND PRINTS 10 SCORES");
for(int i=0;i<10;i++){ //Change 1
printf("\n\tEnter Score %d", i);
scanf("%d",&x[i]); //Change 2
}
//Change 3
for (int i=0; i<10; i++)
printf("\n\t The entered scores are: %d",x[i]);
return(0);
}
#include<stdio.h>
#include<conio.h>
The header <conio.h> is not standard. You get better portability if you don't use it. Anyway, your program doesn't use anything from it.
main(){
The function main() returns an int. Get into the habit of saying so explicitly (and you might also get into the habit of objectively specifying it takes no parameters).
int x[10];
printf("\n\n\t\t PRGRAM THAT CAPTURES AND PRINTS 10 SCORES");
For better working of printf() in all implementation, end each one with a '\n'. Otherwise the output might appear out of order.
for(int i=1;i<=10;i++){
printf("\n\tEnter Score %d", i);
scanf("%d",x);
Trying to always read to the same position in the array in a loop?
}
printf("\n\t The entered scores are: %d",x[i]);
The element x[i] does not exist. At this point in the code, i is larger than the largest legal array index.
return(0);
}

Resources