arithmetic mean of numbers divisible by 3 - c

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.

Related

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...).

Find symmetry in Array

Hi i need to check if the array is symmetry or not. i have a function that takes in a two-dimensional array of integer numbers M and the array sizes for rows and columns as parameters, and returns 1 if M is symmetric or 0 otherwise. I tried many times but the output will be either yes to non-symmetric array or no to symmetric array
Here is my code:
#include <stdio.h>
#define SIZE 10
#define INIT_VALUE -1
int symmetry2D(int M[][SIZE], int rowSize, int colSize);
int main()
{
int M[SIZE][SIZE], i, j, result = INIT_VALUE;
int rowSize, colSize;
printf("Enter the array size (rowSize, colSize): \n");
scanf("%d %d", &rowSize, &colSize);
printf("Enter the matrix (%dx%d): \n", rowSize, colSize);
for (i = 0; i < rowSize; i++)
for (j = 0; j < colSize; j++)
scanf("%d", &M[i][j]);
result = symmetry2D(M, rowSize, colSize);
if (result == 1)
printf("symmetry2D(): No\n");
else if (result == 0)
printf("symmetry2D(): Yes\n");
else
printf("Error\n");
return 0;
}
int symmetry2D(int M[][SIZE], int rowSize, int colSize)
{
int h, k, temp;
int result;
for (h = 0; h < rowSize; h++)
{
for (k = 0; k < colSize; k++)
{
M[h][k] = M[k][h];
}
}
result = 0;
for (h = 0; h < rowSize && result; h++)
{
for (k = 0; k < colSize; k++)
{
//if it is not equal to its transpose
if (M[h][k] != M[h][k])
{
result = 1;
break;
}
}
}
if (result == 0)
{
for (h = 0; h < rowSize; h++)
{
for (k = 0; k < colSize; k++)
{
return result = 0;
}
}
}
else
return result = 1;
}
Several issues:
By your definition, a matrix is symmetric if and only if it is equal to its transpose. That can be the case only for square matrices, yet you accommodate non-square matrices as well, for no apparent reason.
Your symmetry2D() function contains serious logical flaws:
It makes the input symmetric via the loop that performs M[h][k] = M[k][h]
Even if it did not do so, it would never find the input non-symmetric, because its test for that is if (M[h][k] != M[h][k]), which must always fail.
It's unclear what you think the if/else and loop nest at the end of symmetry2D() are achieving for you, but provided that rowSize and colSize are both greater than zero, the actual effect of the whole construct is the same as a simple return result;.
It looks like the idea might have been to create an array containing the transpose of the input, and then compare the input to that. That would have worked, despite being rather grotesquely inefficient, but you never in fact create that separate array for the transpose. If you're going to test without creating the transpose -- which you should -- then
Do not modify the input array (so remove the first loop nest altogether).
Get your indexing right for the symmetry comparisons: M[h][k] != M[k][h]
For best efficiency, avoid redundant and needless comparisons. For example, if you have already tested the M[1][2] == M[2][1] then you do not need to test whether M[2][1] == M[1][2]. And you never need to test elements on the main diagonal. You could achieve this efficiency pretty easily with a better choice of loop bounds.
Also, if indeed the symmetry2D() function is supposed to avoid modifying the input array, consider declaring the element type for its first argument to be const int instead of plain int (but do not modify the type of the corresponding variable in main()). If you had written it that way in the first place then the compiler would have noticed the function's logically erroneous attempt to modify the array elements, and rejected the code.

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

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);
}

How do I print a cross to the console in C?

I've just started studying information technologies and I am currently stuck on a programming assignment.
I have to write a code in C which displays a cross to the console, the size of the cross being determined by an initial input.
So the console output should look like this:
size?: 5(user input)
xooox
oxoxo
ooxoo
oxoxo
xooox
(replace the os with blank space)
I've now come as far as this:
#include <stdio.h>
int main(void)
{
int n;
printf("size?: ");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if( (i==j) )
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
But this only displays one diagonal of the cross, I'm thinking that the opposite diagonal can be created by another condition after the if however I am lost as to what that condition might be.
You're definitely on the right track! Don't give up.
The way to think about this is to think about the loop counters. You've figured out one half of it. If the row and column are the same, you need to output a *. So what's the other condition? Well, think about counting backwards. If the row is the same as the column counted backwards, we also want a *.
I don't want to do your homework for you, so I'll hold off on writing the code, but hopefully that gives you a hint as to what you need to do.
Replace if( (i==j) ) with if( (i==j)||(i+j)==n+1 ), That is,:
#include <stdio.h>
int main(void)
{
int n;
printf("size?: ");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if( (i==j)||(i+j)==n+1 )
printf("*");
else
printf(" ");
}
printf("\n");
}
return 0;
}
Should you need some help, you have to check the column from the other side as well:
#include <stdio.h>
int n;
int main(void) {
printf("size?: ");
scanf("%d",&n);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
if (i == j || i == n - j + 1) printf("*");
else printf(" ");
}
printf("\n");
}
return 0;
}
Edit: There are suggestions to do i + j == n + 1, but I believe i == n - j + 1 makes more sense, since:
i is your current row
j is your current column
n is the size of your square (max row / max column)
i == n - j + 1 means draw * at max - current + 1 column
First thing's first, C compilers don't like
for (int i = 0; i < n; i++)
They like
int i = 0;
for (i = 0; i < n; i++)
But if you're using a C++ compiler, you probably won't get that problem.
Now; back to solving the problem at hand!
On the line:
if( (i==j) )
With this conditional, you're plotting points at (1, 1), (2, 2), (3, 3) ...
You want to also plot points at (1, n), (2, n - 1), (3, n - 2) ...
So you need to add a second conditional to this if statement:
if ( (i==j) || (i == (n - j) + 1 ) )
Then you can simplify this up a bit if you want...
if ( (i==j) || (i == n - j + 1 ) )
And there you go! It now prints a cross, like you described in your question.

How to use exponents using a for loop

I am working on a functions HW for my programming class and Im trying to write a function that will allow me to do exponent math (in a simple form). (Oh and I can't use the actual exponent function, I have to write my own function using for loops, if statements or other things like that.)
EX: user enters base and then enters the power to raise it by. So the user enters:
5
3
it should be 5 to the 3rd power, so it should output 125 (5x5x5). However my for loop is not working properly. How should I structure my for loop to properly handle exponent math?
code:
int main(){
int base, pow;
scanf("%d", &base);
scanf("%d", &pow);
int i;
for (i=0; i<=pow; i++) {
i *= base;
printf("%d\n", i);
}
printf("%d", i);
Well you're using the same variable for the loop and the result. You don't want to do that.
int j = 1;
for(i = 0; i < pow; i++)
{
j*= base;
}
Is what you want. You're also off by one on the loop count. With i <= pow you have
i=0, j * 5 = 5, i=1
i=1, j * 5 = 25,i=2
i=2, j * 5 = 125,i=3. This is where you want to stop but 3 <= 3 so it goes again.
i=3, j *5 = 625,i=4. 4 is not <= 3 so it will then stop here.
The loop is obviously wrong:
for (i=0; i<=pow; i++) {
i *= base;
printf("%d\n", i);
}
You are multiplying the loop counter by base for some reason, which will not yield any good.
The right one would be:
int result = 1;
for (i=0; i < pow; i++) {
result *= base;
}
You want an accumulator that starts at 1 and is multiplied by the base each time. This accumulator should also not be i (since this will change at each step of the for loop).
Try
int base, pow;
scanf("%d", &base);
scanf("%d", &pow);
int i, accumulator;
accumulator = 1
for (i=0; i<pow; i++) {
accumulator *= base;
printf("%d\n", accumulator);
}
printf("%d", accumulator);

Resources