Why is this code printing "123" instead just 3? - c

I've got some code here:
int n = 0;
for(n = 1;n<4;n++)
printf("%d",n);
return 0;
Why does it return '123' instead of just '3'?
I tried to Google for this issue, but I couldn't find anything useful.

After asking my question, I think I see what you are getting at.
What you have with
int n = 0;
for(n = 1;n<4;n++)
printf("%d",n);
return 0;
is functionally the same as
int n = 0;
for(n = 1;n<4;n++)
{
printf("%d",n);
}
return 0;
Since the for loop expects a statement, either a block of statements enclosed in braces, or a single one terminated with a semicolon as you have in your example. If you wanted it to just print 3 and for whatever reason wanted to use a loop just in increment a number, you would want to provide it with an empty statement as such:
int n = 0;
for(n = 1;n<3;n++);
printf("%d",n);
return 0;
or
int n = 0;
for(n = 1;n<3;n++){}
printf("%d",n);
return 0;
Both of which will only print 3.
Please note that because the variable n gets incremented and then checked, using your original bounds n < 4, the loop would end when n = 4 and thus 4 would be printed. I changed this in my last two examples. Also note the incorrect use of the term return, as some comments pointed out.

Related

C: Printing INT Values on array - How to stop printing on NULL values?

I need to print values stored in an int array, stopping when a NULL character is encountered ('\0').
So I have this code:
const int display[10] = {1,4,8,2,0,9,2};
int main(){
int i = 0;
for (i = 0; i < 10; i++){
if (display[i] == '\0'){
break;
}
printf("%d\n", display[i]);
}
exit(0);
}
I expected to print all the values of display[10] OR break when a '\0' was encountered but my code breaks on display[4] (0) instead of continuing until display[6].
Any advice on how to achieve this, avoiding printing the null characters at the end of my array?
The null character, '\0', is equal to 0. That's why your loop is only printing the first four elements. It breaks when it encounters 0.
In C, '\0'==0. If you want to print only the initialized fields, put a sentinel (say, a negative number) right after the last initialized field and break the loop when you either encounter the sentinel or count to 10.
const int display[10] = {1,4,8,2,0,9,2,-1 /* a sentinel */};
for (i = 0; i < 10 && display[i] >= 0; i++) {
You do not need to check whether null is exist or not. First declare the array without total number initialization. Then You can just run the loop by checking the total number of array element. Now the question is how you get the number of element? It is easy.
const int arr[]= { 1, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
printf("%d", arr[i]);
}

Using printf( ) in a for loop

When attempting this (code below), the console doesn't even request an input value, then spits out a random number (likely from a number previously stored at the location).
Why does this not work and how can i fix it?
int main( ) {
int arr[3];
for(int i = sizeof(arr); i <= 0; i--) {
scanf("%d", &arr[i]);
}
printf("%d", arr[2]);
return 0;
}
There are two things that are wrong.
Assuming you want the number of elements in the array, it is done, using:
size_t len = sizeof(arr) / sizeof(*arr)
sizeof gives the actual size (number of bytes allocated for arr.
You should start with len - 1 and not len.
NOTE: Array indexing is 0 based not 1 based, so the array elements are indexed from 0 to 2 But you would have tried to access arr[3], which can result in undefined behaviour.
You wrote i <= 0. So, i starts from let's say 2, is 2 <= 0 ? NO!
Hence it will never go inside the loop. The correct condition is i >= 0
int len = sizeof(arr) / sizeof(*arr);
for(int i = len - 1; i >= 0; i--)
Well, I don't know why you are taking reverse order input, but a general convention is to take input using:
size_t len = sizeof(arr)/sizeof(*arr);
for (i = 0; i < len; i++)
{
// take input
}
EDIT:
From other comments it seems that you don't understand the for loop.
Have a look in this answer
Please comment for any further clarification.
i <= 0
the code can never enter the loop since the initial value of i is greater than zero.
It is important to note that in C, other than languages like Java/Python, you must explicitly know the length of the array, sizeof will NOT give you the amount of items in the array.
int main() {
int arr[3];
int itemsInArray = 3;
for(int i = itemsInArray-1; i >= 0; i--) {
scanf("%d", &arr[i]);
}
printf("%d", arr[2]);
return 0;
};
Since i-- will decrease the value of i , and the condition for loop is i <=0 to start the loop the i must be 0 or negative.Since arr[3] will return 12(3 elements and each has 4 bytes(int has 4 bytes)), the value will be posivite,greater than 0 so we need to change the loop condition to check if i is positive
#include <stdio.h>
int main( ) {
int arr[3]={0};
int i = sizeof(arr)/sizeof(arr[0]) -1;
for(; i >= 0; i--) {
scanf("%d", &arr[i]);
}
printf("%d", arr[2]);
return 0;
}
There are a couple of issues with your code: first of all, sizeof(arr) won't return "3" as you probably thought; "arr" is a pointer to arr[0], so you are requesting the size of an int pointer.
Secondly, i <= 0 prevent the loop to even be executed.
Finally, please set array to zero while declarating, as best practice, ie:
int arr[3] = {0};
EDIT: i wrong-spelled my thoughts: you are requesting the size of the whole memory area allocated for the array.
Comments below are corrected though.

Break a number down int array and get factorial of each number - C programming

I apologize in advance for the length of the code and how tedious it may be to follow. I am trying to break a number down into individual digits and get the factorial of each one. I have successfully done that (with the help of paxdiablo) but I want to do this all the way from 99999 to 0. In order to do that I have placed all of the code in a loop starting indx at 99999 and decreasing value until it reaches 1. The reason I am trying to do this is because I need to compare the sum of the factorial of each individual digit to the number and if they are equal then I have a match. The program runs and the first run for the number 99999 works perfectly fine but the next loop SHOULD be 99998 and do the exact same thing but instead the next number is 4. I have no idea why it would do this. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
int indx;
int fact = 1;
int individualDigit[50];
int length;
for(indx = 99999; indx > 0; indx--)
{
num = indx;
for (length = 0; num > 0; length++, num /= 10)
{
individualDigit[length] = num % 10;
}
printf ("Digit count = %d, digits =", length);
for (indx = length - 1; indx >= 0; indx--)
{
printf (" %d", individualDigit[indx]);
}
for (indx = 0; indx < length; indx++)
{
while (individualDigit[indx] > 0)
{
fact = fact * individualDigit[indx];
individualDigit[indx]--;
}
printf("\n%d ", fact);
fact = 1;
}
printf("\n");
}
return 0;
}
The value in "indx" is being used by multiple for loops. The line
for (indx = 0; indx < length; indx++)
increments indx back up to 4, which is the value used by your outer loop. Just use some new variables to count the different loops
This seems like a homework question and your code quality seems to confirm that so I'm hesitant to write you actual code but I'll give you a few pointers.
As #Cody Braun said above your index variable is getting overwritten in line 23 where you calculate the factorial.
There is a much more efficient way to calculate factorials using dynamic programming
I don't know if you just didn't want to do it in the post but learning how to properly format your code will help you catch these errors quicker and keep yourself form making them. As well as make it easier for others to read your code.
Cheers

Test 2 stings for same words (C)

i am working on algorithm, that would compare two sentences and find if they are made of same words.
Basically the input of this function are 2 strings, i cut them by " " and each word put in array. So i have something like this:
sent1[0]="one"
sent1[1]="two"
sent1[2]="three"
sent1[3]="four"
sent2[0]="four"
sent2[1]="two"
sent2[2]="one"
sent2[3]="three"
My algoritm works that for each word from sent1 it compares each word in sent2.If the sentences are equal it return 1 , otherwise it return 0;
//n = max index of sent1 and m is max index of sent2
int equal =0;
for (i = 0; i < (n); i++){
for (x = 0; x < (m); x++){
if(strcmp(sent1[i],sent2[x])==0){
equal =1;
}
}
if(equal==0){
return 0;
}
equal=0;
}
return 1;
Problem of this algoritm is that it is very uneffective and slow, in order to make it faster it would be best to somehow delete index of array i already found equal word so every time i do new search it would search smaller array.Problem is that i dont know how to implement this in C because my every try ended with memory problems.
Thank you for any help.
In C language you cannot delete an element from its array, because an C array a contiguous block of memory.
But you can shift left the elements after you "delete" an item.
However an another suggestion about your code:
When the 'strcmp' function success (found equal) then you no need continue the actual loop, you can terminate that with 'break' command.
int equal =0;
for (i = 0; i < (n); i++){
for (x = 0; x < (m); x++){
if(strcmp(sent1[i],sent2[x])==0){
equal =1;
break;
}
}
if(equal==0){
return 0;
}
equal=0;
}
return 1;

Trying to find if the element of an int array is equal to a number entered in C

I'm trying to use a for loop to iterate over the elements of an integer array and find out if a particular element in that array is equal to some other integer.
Here's what I've got, and it doesn't seem to work:
int squaresArray[1000];
int numberOfSquares = 1000;
int i = 0;
for (i; i<=numberOfSquares; i++)
{
squaresArray[i] = i*i;
if (number == squaresArray[i]){
printf("%d is a perfect square\n", number);}
break;
}
According to what I know about for loops this should work, but it prints nothing even when the number should be equal to some element of the array.
You're breaking on the first iteration due to misplaced brackets (i.e. break is not in the scope of the if-statement). Change it to:
if (number == squaresArray[i]) {
printf("%d is a perfect square\n", number); // no closing bracket here
break;
} // <--
Also, your loop condition should probably be i < numberOfSquares. After all, numberOfSquares (1000) is an out of bounds index for an array of length 1000. Moreover, you don't need a loop initialization statement if you've already declared/initialized i in the loop's enclosing scope. Hence, we're left with
int i = 0;
for (; i < numberOfSquares; i++)
If you're using C99 and above, you can limit the scope of i to only the loop, which should be preferred:
for (int i = 0; i < numberOfSquares; i++)

Resources