Issue with C program (maybe solved with use of arrays) - c

I have written the following code. But it doesn't run until the final printf. Plus if the validation I have set fails to pass, it prints a result I can't explain.
#include <stdio.h>
int main(void)
{
int k, j, z, i, n;
int l[30];
// Setting initial values 0 (0=off 1=on)
for (n=0; n<30; n++)
{
l[n] = 0;
}
// Employee number
printf("give employee number\n");
scanf("%d", &k);
// Validation of k
if (k<0 || k>30)
{
printf("wrong input");
}
else
// Lamp status change
for (i=1; i=k; i=i+1)
{
for (z=i; z=30; z=2*z)
{
if (l[z] = 0)
l[z] = 1;
else
l[z] = 0;
}
}
for (j=0; j<30; j++);
{
printf("lamp[%d] is: %d\n", j+1, l[j]);
}
return(0);
}

I suggest that you go work a little more your C basis...
First advice: As reported by halfer you should take care of your indentation code, it allows you (and us) to read it more easily.
First error, also pointed out by halfer: You probably forgot to declare a
block of code with {}, tips for your research to know when to put
it here.
Second error: You should take a look at the for loop syntax: for (j=0; j<30; j++);will basically do nothing due to ;at the end.
You confuse assignment and condition test, if (l[z]=0), for (i=1; i=k; i=i+1) and for (z=i; z=30; z=2*z) haven't condition test, but assignment (just = and not == or <=, etc.) so they are always true...
Also, you don't explain what you want your code to do... It seems like you want to turn on some lights, but the double statement loop with the wrong for is confusing. I don't know if you want to turn on 2^N bulbs or just the one selected by the user... Here is my correction of your code:
int main(void) {
int k, j, z, i, n;
int l[30];
// Setting initial values 0 (0=off 1=on)
for (n=0; n<30; n++) {
l[n] = 0;
}
// Employee number
printf("give employee number\n");
scanf("%d", &k);
// Validation of k
if (k<0 || k>30) {
printf("wrong input");
} else { // New block
// Lamp status change
/*
i = k is an assignment not a test, maybe i == k ?
but still false, for do while the condition is true
so use <= and why use i = i+1 here and not i++ like for n++ L6 ?
Ok for this loop, but with the other you gonna reswitch again and
again. If you want only switch the one selected, consider to use
an if instead of the 2nd for loop.
*/
for (i=1; i <= k; i=i+1) {
/*
Same test / assignment misunderstanding.
personally except 15, I don't know a lot of intergers
mutiplied by 2 that give 30. Example: if I set 1 in
my keyboard, k = 1, then i = 1, z = 1, z = 2,z = 4,
z = 8,z = 16, z = 32, z = 64, etc. to overflow.
So z = 30 (ouch z == 30) is never true.
If you tried to switch only the lamp selected by the user
I don't see the point of the second for loop.
But if you wanted to switch 1 light each 2^N bulbs you
should set z <= 30.
*/
for (z=i; z<=30; z=2*z) {
if (l[z] == 0) // = is an assignment, == instead?
l[z] = 1; // A block with {} is not needed here because there is only 1 instruction
else
l[z] = 0; // Same as above, {} are not needed here too
}
}
for (j=0; j<30; j++) { // No; here, see the 'for' loop syntax
printf("lamp[%d] is: %d\n", j+1, l[j]);
}
} // End of the else block
return(0);
}

Related

Why isn't this program showing any number above 3?

Wrote this to find the prime numbers between 2 to 1000. But it stops after showing that 2 and 3 are prime numbers. I know I can find how to write a code for finding out prime numbers on the internet. But I really need to know what's going wrong here.
#include <stdio.h>
main() {
int i, j;
int ifPrime = 1;
for (i = 2; i < 1000; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
ifPrime = 0;
break;
}
}
if (ifPrime == 1) {
printf("%d is prime\n", i);
}
}
}
The line
int ifPrime=1;
must be inside the outer for loop. There it will be initialized for every i. This corresponds to the natural language words "to check whether a number i is prime, first assume it is. Then check if it is divisible". The code you had before said "to check whether the numbers 2 to 1000 are prime, first assume they are", and this wording was too broad.
The code should be:
int main()
{
for (int i = 2; i < 1000; i++)
{
int ifPrime = 1;
for (int j = 2; j < i; j++)
I replaced main with int main since that is required since 20 years. (You should not learn programming from such old books.)
I moved the int i and the int j into the for loops so that you cannot accidentally use these variables outside the scope where they have defined values.
To avoid this bug in the future, it's a good idea to extract the is_prime calculation into a separate function. Then you would have been forced to initialize the ifPrime in the correct place.
Another way of finding the cause of this bug is to step through the code using a debugger and ask yourself at every step: does it still make sense what the program is doing?
You are not setting ifPrime back to 1 after checking for the single number. So once you get a number that is non_prime, ifPrime is now 0 and hence if(ifPrime == 1) would never return true post that and hence you only see 2, 3 as prime
#include <stdio.h>
int main(void) {
for( int i=2;i<1000;i++)
{
int ifPrime = 1;
for(int j=2;j<i;j++)
{
if(i%j==0)
{
ifPrime=0;
break;
}
}
if(ifPrime==1)
{
printf("%d is prime\n",i);
}
}
return 0;
}

Changing and updating values with arrays in C

I am having issues with my c program. I am new to C programming and I have to write a program for class involving arrays. I have to use two sets of arrays and allow the user to remove a location and add a new value into that spot. I created a max array of 20 but we have to use 1 thru 5 and allow the user to remove the value in either data set. Here is what I have currently and I am getting a lot of errors saying I have ; and { in the wrong spots but it doesn't seem wrong when I go back to my text book and slides about arrays. I created constant values under myarr1 and myarr2 and SIZE is set to 20. Any and all help is appreciated I don't understand why i am getting all these errors.
int display_arr(int * count);
int remove_arr();
int myarr1[SIZE];
int main() {
printf("Data confirmation and update program written in C.\n");
int display_arr[6];
// display_arr[0]=NULLL;
int counter = 6;
my_identity();
for (i = 0, i < SIZE; i++) {
myarr1[i] = counter;
}
for (i = 0, i < SIZE; i++)
printf("Array[%d] is %d.\n", i, myarr1[i];
return EXIT_SUCCESS;
}
// deleting entry from data
int remove_arr() {
int position;
printf("Enter the location where you wish to delete element\n");
scanf("%d", & position);
}
int display_arr(int * count) {
int i;
for (i = 0; i < * count; i++)
printf("%d", myarr1[i]);
return 0;
}
//add an entry to data set
// int myarr()
}
// int input;
// printf("Enter the value you would like to add to the end of the arry:");
// scanf("%d", &input);
// if (array_select == 1){ // adds value to data set 1
// myarr1[*counter] == input;
// else
// myarr2[counter] == input; // adds value to data set 2
//return 0;
}
}
Computer programming is about being precise. This means also following the rules exactly to the point, not more, not less.
In this case, I see two things
Parenthesis/braces/brackets must be balanced:
printf("Array[%d] is %d.\n", i, myarr1[i];
Do you see the missing parenthesis at the end?
Comma and semicolon are not the same:
for (i = 0, i < SIZE; i++) {
Do you see the first comma?
For the other problems, look at the compiler error messages.

I need to input 20 numbers and to output only double location

try to input 20 numbers with array and to output
the numbers in the double location only but somehow it's print
also the 0 location... please help.
#include<stdio.h>
#define n 20
int main()
{
int num[n]={0},i=0,order=1,double_locaion=0;
for(i=0;i<n;i++)
{
printf("please enter %d number\n",order);
scanf("%d",&num[i]);
order++;
}
for(i=0;i<n;i++)
{
if (i%2==0 && i!=1 && i!=0)
{
printf("%d\n",num[i]);
}
}
}
Try this, start with 2 and increase by 2 every time, the you don't have to deal with 0th element and odd element.
for (i = 2; i < n; i += 2)
{
printf("%d\n",num[i]);
}
First of all there is no way that your code is printing the 0-th location of the array. That's impossible given the condition of the if statement.
Secondly n- you don;t need to use macro expansion for that name.
/* This program takes 20 integer number from input.
* Prints the numbers entered in odd positions.(First,Third,..etc).
*/
#include<stdio.h>
#include<stdlib.h>
#define NUM 20
int main(void)
{
int numArr[NUM];
for(size_t i = 0; i < NUM; i++) {
printf("please enter %zu number\n",i+1);
if( scanf("%d",&numArr[i]) != 1){
fprintf(stderr, "%s\n","Error in input" );
exit(1);
}
}
for(size_t i = 0; i < n; i++)
{
if( i%2 == 0 )// if you want to omit the first number put the
// the condition (i%2 == 0 && i)
{
printf("%d\n",numArr[i]);
}
}
return 0;
}
What you did wrong that your code skipped 0th element?
if (i%2==0 && i!=1 && i!=0)
^^^^
i when 0 makes this condition false - and you never get to print it.
i!=1 ?
If i=1 then i%2 will be 1, so you will not even check the second conditions, the whole conditional expression will become false. So you can safely omit this logic.
Is there a better way?
Sure,
for(size_t i = 0; i < n; i += 2){
printf("%d\n",num[i]);
}
Explanation
If you consider that every time you check the modular arithmetic of 2 the elements which results to 0 remained are
0,2,4,6,8,10,...18
See the pattern? Starts with 0 and increments by 2 each time and when does it stop? Yes before reaching 20 coding it we get
for(size_t i = 0; i < n; i += 2){
/* Initialize with i=0 as first number is 0 (i=0)
* Increments by 2 (i+=2)
* Runs when less than 20 (i<n)
*/
printf("%d\n",num[i]);
}
If you want to omit the 0-th index do initialize properly
for(size_t i = 2; i < n; i += 2){
If you mean you want the numbers from array that are present at even position than you can do like this:
for (i = 2; i < n; i=i + 2) //Initialize i = 0 if 0 is consider as even
{
printf("%d\n",arr[i]);
}
I above code i is initialized to 2 and the increment in each iteration is 2 so it will access elements only at even position (2,4,6...).

arithmetic mean of numbers divisible by 3

I understand this is not the best piece of code and I'm not looking to improve it - only to understand it.
I'm not sure about the s=i=k=0 expression and the integer k and of course then if (k) s/=k; is totally dubious.
Thank you.
main()
{
int a[100], i,k,n;
double s;
while (1)
{
printf ("Enter the number of elements:");
scanf ("%d", &n);
if (n<0 || n>100) break;
for (i=0; i<n; i++)
{
printf("a[%d]:", i);
scanf("%d", &a[i]);
}
for (s=i=k=0; i<n; i++)
if (a[i]%3 == 0)
{
s+=a[i];
k++;
}
if (k) s/=k;
printf("s=%.2f\n", s);
}
}
s=i=k=0
is same as
s = 0;
i = 0;
k = 0;
Remember that multiple assignment on one line is done right to left
s=(i=(k=0))
k = 0 // first
i = k // second
s = i // third
! double variables should be initialized with 0.0 instead of 0.
s /= k;
is same as
s = s / k;
You can do this shortening with a lot of operator, like *,+,-,%,&,|,...
if ( k ) equals if ( k!=0 )
and
if ( !k ) equals if ( k==0 )
But its better to use (k) and (!k) just for boolean variables for better reading / understandong of code.
arithmetic mean of numbers divisible by 3
if (a[i]%3 == 0)
{
s+=a[i];
k++;
}
Checking if variable a[i] is multiple of three. If it is, execute body of condition.

Why does this generate an infinite loop (C, While Loop)

I am doing a program for my class, and I need to set all the values of the array 'decade' into -1 before I begin. I tried this (And the version in a for loop) and it just puts me in an infinite loop! Can someone explain why this is happening, and how I can fix it?
Code:
int decade[9][9], i = 0, k = 0;
while (i<10) {
while (k<10) {
printf("i is %d, k is %d\n",i,k);
decade[i][k] = -1;
k++;
}
k=0;
i++;
}
Thanks in advanced!
It prints out this:
For anyone who needs the answer in the future, declare decade as 'decade[10][10]' instead of 'decade[9][9]', or however yours is defined.
When you declare an array of size 9 it has the indexes from 0 to 8. You go to 9 which will overwrite the memory. This is undefined behavior and can cause any number of subtle but faulty behavior.
I don't know how "decade" is defined - but if it is defined incorrectly, and/or the wrong size you could get a buffer overrun which could result in the wrong memory getting set to "-1" - i.e. the "i" or "k" variables could be getting overwritten.
int decade[9][9], i = 0, k = 0;
while (i<10) {
while (k<10) {
printf("i is %d, k is %d\n",i,k);
decade[i][k] = -1;
k++;
}
k=0;
i++;
}
is incorrect, because you are iterationg from 0 to 9 (10 elements)
this code is correct:
int decade[9][9], i = 0, k = 0;
while (i<9) {
k = 0;
while (k<9) {
printf("i is %d, k is %d\n",i,k);
decade[i][k] = -1;
k++;
}
i++;
}
note that you set k to zero before looping again.
There exists also other possibilities to loop for example the for loop, you use while loops actually not for counting.
You loops must be from 0 to 8 (decade array is length 9):
while (i<9) {
while (k<9) {
/* ... */
}
}
The dimension in "9x9" - you are initialzing 10x10. Set it to decade[10][10], use (x<8) or do (x<=9)
Index out of bound exception for your code. Try this one instead.
int dimSize = 10;
int decade[dimSize][dimSize], i = 0, k = 0;
while (i<dimSize) {
while (k<dimSize) {
printf("i is %d, k is %d\n",i,k);
decade[i][k] = -1;
k++;
}
k=0;
i++;
}

Resources