Missing First Character In Printing Array (While Loop) - c

Very simple question. Why is the first letter cutting off? Prints "harles" going down. I see that I can hard code a fix with x = -1 but defeats the purpose of truly understanding what the underlying issue is and knowing solutions. Thanks.
#include <stdio.h>
int main()
{
int x = 0;
char iArray[7] = 'Charles';
while (x < 7) {
x++;
printf("%c\n", iArray[x]);
}
return 0;
}

You are first incrementating the index, then using it to print.
x++;
printf("%c\n", iArray[x]);
Changing to
printf("%c\n", iArray[x]);
x++;
will fix that problem and also avoid UB for accessing beyond the array.
The second mentioned problem occurs when the loop condition is still true for x==6 and the index is then incremented to 7, which accesses iArray[7]. That is beyond the array because the highest legally accessable index in an array of size 7 is index 6.

Try this!
#include <stdio.h>
int main()
{
int x = 0;
char iArray[7] = 'Charles';
while (x < 7) {
printf("%c\n", iArray[x]);
x++;//increment after printing
}
return 0;
}

You have increment x by 1 beforing using it, so x[0] will never print, x[0] contains 'C'. Increment the index 'x' after using it.
#include <stdio.h>
int main()
{
int x = 0;
char iArray[7] = "Charles";
while (x < 7) {
printf("%c\n", iArray[x]);
x++;
}
return 0;
}

Related

Why am I getting some random values after the output?

#include <stdio.h>
int main()
{
int k;
scanf("%d",&k);
for(int i=0;i<k;i++)
{
char num[10];
scanf("%s",&num);
int x = num[0]-'0';
int sum;
int y;
for(int i=0;i<10;i++)
{
if(num[i]=='\0')
{
y = num[i-1]-'0';
sum = x+y;
printf("%d\n",sum);
}
}
}
return 0;
}
This program is to obtain the sum of first and last digit of a given number. I am getting some random values after the output. Can anyone please explain me this and how do I eliminate it?enter image description here
You have an inner loop that looks for the terminating null byte in the array. You find it, but then you keep looping through the array looking for more null bytes. If you happen to find one, it takes whatever the prior byte is and treats it as the last digit.
You can fix this by breaking out of the loop when you find the null terminator:
for(int i=0;i<10;i++)
{
if(num[i]=='\0')
{
y = num[i-1]-'0';
sum = x+y;
printf("%d\n",sum);
break;
}
}
Or by simply using strlen to find the end of the string.
y = num[strlen(num)-1]-'0';
sum = x+y;
printf("%d\n",sum);
The code also doesn't handle reading too many characters, which can overflow the buffer, or reading an empty string, in which case num[strlen(num)-1] is off the start of the array. You can address the former by putting a field width in the scanf format, and the latter with an explicit check:
char num[10];
scanf("%9s",num);
int sum;
if (num[0] == 0) {
sum = 0;
} else {
int x = num[0]-'0';
int y = num[strlen(num)-1]-'0';
sum = x + y;
}
printf("%d\n",sum);
The problem is that you don't stop the inner loop once you print the sum. You continue and use the indeterminate elements in the array num beyond the string terminator. That leads to undefined behavior.
You could solve it either by not having the inner loop (by using index 0 and strlen(num) - 1), or by using break to break out of the loop once you printed the sum.

C function to print 2D array of chars

Im trying to learn C, surely using the hard way and cant figure out this one error, could someone help? :-)
#include<stdio.h>
#include <stdlib.h>
#define max_X 15
#define max_Y 15
int x, y;
char Array[max_Y][max_X];
void displayArray(void){
for (y = 0; y < max_Y; y++) {
for (x = 0; x < max_X; x++) {
printf("%c",Array[y][x]);
}
printf("\n");
}
}
int main(void){
for (y = 0; y < max_Y; y++) {
for (x = 0; x < max_X; x++) {
Array[y][x] = '.';
}
}
displayArray;
getchar;
return(0);
}
Im trying to print out char array containing just dot characters using function. When i run it, there is just blank cmd and return value 0. I keep getting warnings about statements with no effect on these two lines:
displayArray;
getchar;
Can someone help? or give me a link to similar one where i can find answer to my problem? I was looking around but couldn't find anything i could compare to mine and understand at least a little.
You need to use parentheses even when the function you're using takes no arguments. So,
displayArray;
getchar;
should be:
displayArray();
getchar();
Also, return isn't a function. It's a keyword, so you can do:
return 0;
Use displayArray();
You should not call function like this displayArray;you can use this while providing address of function to function pointer.

Passing an array to a pointer

I'm trying to learn C Language using pointers and arrays etc... but my code won't work. Whats is wrong with this code?
#include <stdio.h>
#include <conio.h>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
int main(){
int *number = 0;
int i = 0;
int *random = 0;
int randomTry[100];
int *getRandomTry = 0;
int randomGenerator[100];
int *getRandomGenerator = 0;
srand (time(NULL));
*getRandomTry = randomTry[100];
*getRandomGenerator = randomGenerator[100];
do{
*random = rand() % 10;
getRandomGenerator = random;
printf("Choosing a number:\n\r");
for(i = 0; i < 30; i++){
printf("*");
Sleep(50);
}
printf("\n\r\n\rWell done, your time.");
printf("\n\r------------------------------");
printf("\n\rPick a number ( 0 to 10): ");
scanf("%d", number);
getRandomTry = number;
if(*number > 10){
printf("\n\rRemember, number only from (0 to 10)\n\r");
}
else{
if(number == random){
printf("\n\rYou choose right!");
printf("You entered theses numbers till the right answer");
for(i = 0; i < randomTry[i]; i++){
printf("%i", getRandomTry);
}
}
else{
printf("\n\rYou choose wrong, number: %d - random: %d\n\r", number, random);
Sleep(700);
system("cls");
}
}
}while(number != random);
getch();
return 0;
}
When i compile the program stop working, no warnings or comments show in console.
I'm using the notepad++ with MinGw to compile this code.
Assigning a value to a NULL pointer is undefined behaviour, such as (in your code).
int *getRandomTry = 0;
*getRandomTry = randomTry[100];
gives undefined behaviour on two counts. The second statement tries to retrieve the value of randomTry[100], which doesn't exist (since array indexing starts at zero, and randomTry only has 100 elements). Second, it tries to store that value into a location addressed by the NULL pointer.
With undefined behaviour, anything can happen. Program crashes are pretty common, but not the only possible result.
So you need to understand how array indexing works (it starts at zero, not one). And you need to ensure all pointers point at something valid before trying to set or retrieve values via the pointer.
For example;
int x = 5;
int *getRandomTry = &x;
*getRandomTry = 42; // will change x
The following is a correct declaration of a pointer to an integer, with initial value zero:
int *random = 0;
The following statement will try to place the result of the calculation to the address in memory where the pointer 'random' is pointing:
*random = rand() % 10;
Since 'random' was assigned the value of 0, it is pointing at memory location zero, and the second statement will result in 'undefined behavior', meaning that what happens next in your program is not easily predictable. In practice, it will most likely crash in one way or another, since you cannot write to memory location 0.
if the code was like this:
int random = 0;
...
random = rand() % 10;
then everything would work fine. It would also work if code was like this:
int random_variable;
int *random = 0;
...
random = &random_variable;
...
*random = rand() % 10;
In this last case, 'random_variable' would end up with the result of the calculation.
Hope this helps.

Segmentation Fault 11 with recursive function in C

I keep receiving a Segmentation Fault 11 for the following code. I believe it has something to do with recursion but I'm not entirely sure how. The method should take in an array, skip the odd values, and keep repeating until it has an array with only value left and returns that value.
Thanks!
#include <stdio.h>
int callTable(int table[], int size)
{
int i = 0;
int j = 0;
int cHeight = size / 2;
int cTable[cHeight];
while (i < size)
{
if (table[i] % 2 == 0)
{
cTable[j] = table[i];
j++;
}
i++;
}
if (size > 1)
return callTable(cTable, cHeight);
else
return cTable[0];
}
int main()
{
int tPass[100];
int i, answer;
for (i = 0; i < 100; i++)
tPass[i] = i + 1;
answer = callTable(tPass, sizeof(tPass) / sizeof(tPass[0]));
printf("%d\n", answer);
}
Do you want to skip the odd values or the odd indexes? You are currently skipping the odd values, so after you call callTable once, there are only even values left. Then, on the second call, you try to use an array of half the size to store the even values (which are all of them), so you try to store the entire array on another with half the size.
If you intended to skip the odd indexes, then change this line:
if (table[i]%2==0)
for this one:
if (i%2==0)
That runs fine and returns 1 (which is the number with index 0).

Can't subtract in a for loop in C/Objective-C

I'm going through the Big Nerd Ranch book on Objective-C, which takes you through some early C stuff. I've played with C before, and am pretty experienced in PHP.
Anyhow, I'm doing the challenges and this one is not working the way I think it should. It's pretty simple - start at 99, loop through and subtract three until you get to zero, and every time you get a number that is divisible by 5 print "Found one." Pretty straightforward. However, subtracting by three in the for loop is not working
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i;
for(i = 99; i > 0; i-3){
printf("%d\n", i);
if(i % 5 == 0) {
printf("Found one!\n");
}
}
return 0;
}
It creates and endless loop at 99, and I'm not sure why.
i-3 doesn't modify the variable i. Do something like -
for( i=99; i>0; )
{
// ....
i -= 3;
}
It should be i-=3 instead of i-3.
#include <stdio.h>
int main (int argc, const char * argv[])
{
int i;
for(i = 99; i > 0; i-=3){
printf("%d\n", i);
if(i % 5 == 0) {
printf("Found one!\n");
}
}
return 0;
}
i-3 does not change the value of i.
i-=3 does.
Your loop statement doesn't modify the value of i. Just doing i - 3 doesn't change i, it just returns the value of i - 3.
Use: for(i = 99; i > 0; i = i - 3)
In the for loop, it should be i=i-3.
You are just subtracting 3 from i, but you are not assigning it to i.
Use i = i - 3 instead of just i - 3.
Change your for statement like this:
for(i = 99; i > 0; i = i - 3) {
// Write your code here.
}
The Last Term in the For loop is the increment of decrement operation. While i-3 is none. If you want the Value of i to get reduced by 3, then you should store that value in i itself.
To do that Following code should be written: i = i-3 or shorthand i-=3.

Resources