c program to decrement a large number with minimum execution time [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
#include <stdio.h>
#include <time.h>
unsigned int decrement(unsigned int value);
main()
{
clock_t start, end;
double cpu_time_used;
register unsigned int value;
value = 4294967;
start = clock();
decrement(value);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("cpu_time_used %lf\n",cpu_time_used);
}
unsigned int decrement(register unsigned int value)
{
int i;
for(;value;value--)
{
printf("loop value %u\n",value);
}
return 0;
}
I have tried to decrement a large integer value with less execution time, to achieve that i am declaring a variable with register keyword like register unsigned int value from this i have not received any optimization results while run this program with/without using this register keyword. please correct me if i am wrong. and please share if we have any other method to decrement a larger number with minimum execution time.
program mentioned here is just for example with register keyword(one of the optimization method to reduce execution time) main agenda of this question is how to decrement a larger number with minimum execution time.

Without the understanding of the logic telling me the decrement(x) should be always zero, there is another problem:
value = value--; is invoking an undefined behaviour, as value-- is a post decrement operation having side effects. You want either value--; or value -=1. But not both.

When you're calling the decrement function, value is being passed in by value. This means that the value you're modifying in the decrement function isn't the one with the register keyword associated with it. You would would need to the decrementing in the same function that the register variable is define.
Even then, I question whether this is something you really need to do. Seems like a classic case of premature optimization to me.

register is commonly ignored by compilers... Anyway if something should be qualified register it is the variable value of the decrement function not the value of main. If you want to accelerate, why inserting an if inside the for loop? You may rewrite your code as :
unsigned int decrement(register unsigned int value)
{
for(;value;value--)
{
printf("loop value %u\n",value);
}
return 0;
}
Write slightly better code and let the compiler optimize...

I would modify the decrement funtion like this:
unsigned int decrement(unsigned int value)
{
for(value; value > 0; value--)
{
printf("loop value %u\n",value);
}
return value;
}
You dont need to say i >= 0 when you need that i is only > 0(see the if with the break when i == 0 ), you don't even need "i" just do the operation with the variable value, since that's what you want to return( That's what I understand from your code) Sorry for my bad English!

Sorry for my formatting as I am new here.
Please change value = value-- to just --value
Unless you are using it in a definite way/statement, post-increment operator is usually slower than pre-increment operator. Same goes for decrement as well.
Also, you do not need to do an explicit check for i>=0
Try this:
unsigned int decrement(register unsigned int value)
{
while(value>=0)
printf("loop value %u\n",value--);
return 0;
}

Related

Variable Initialization in Function

I'm fairly new to coding and am currently learning C. In my C programming class, my instructor gave us the assignment of writing a program that uses a function which inputs five integers and prints the largest. The program is fairly simple even for me, but I'm facing some problems and was hoping to get some advice.
#include <stdio.h>
int largest(int x);
int main(void) {
int integer1;
largest(integer1);
return 0;
}
int largest(int x) {
int i;
for (i = 0; i < 5; i++) {
printf("Enter an integer: ");
scanf_s("%d", &x);
}
return x;
}
This is the code that I have written. The main problem that I am having is that in my main method, the IDE tells me to initialize the value of integer1. However, I'm not really sure how to do that because I'm supposed to input the value within the largest() method via the scanf_s function. How may I solve this?
The problem is here, the warning message is to warn you about the potential pitfall of using the value of an uninitialized automatic local variable. You made the call like
largest(integer1);
but you ignore the return value, so the integer1 remains uninitialized.
Remember, in view of largest(), x is a local copy of the actual argument passed to that function, any changes made to x won't be reflecting to the caller.
That said, your code is nowhere near your requirement, sorry to say. A brief idea to get there would be
Create a function.
Create a variable (say, result) and initialize with minimum possible integer value, INT_MIN
Loop over 5 times, take user input, compare to the result value, if entered value found greater, store that into result, continue otherwise.
return result.
I know that normally help for assignments shouldn't be given but I have to say that you might need to rethink what you want to do.
You are inputting an integer to the function named largest. But why are you only inputting a single integer to a function that should return the largest value. You can't do much with a single number in that case.
You should instead be inputting say an array of 5 values(as said in your assignment) to the function and let it return the largest.
The order would then be:
Read 5 values and save to an array
Call the function largest with the array as input
Let the function do it's work and return the largest value
Do what ever you want with the largest value
But if you only want to remove the warning simply type
int integer1 = 0;

Unused Variable Error

I am new to programming and I am currently learning the C language. This is my code. I have tried different fixes, such as making sure I have my semicolons. However, when I go to check my code in the online compiler, I always get unused variable and data definition has no type or storage class. Any information would help me, I assure you, so please let me know what you think a possible solution could be.
//C code
//This program will calculate the average speed of passing cars using a WHILE-END loop
//Developer: Jasmine Tucker
//Date: 7 Sept 2014
#include <stdio.h>
Int main ()
{
/* define variable */
int average_speed;
int car_count;
int car_speed;
};
/* set variable values */
average_speed= 0;
car_count=0;
car_speed=0;
/*WHILE-END loop */
WHILE (car_count > 0)
{
printf (“Enter the car’s speed %s:”, car_count);
scanf (“%d”, & car_speed);
average_speed= car_speed/ car_count
car_count++;
}
printf (“\n The average speed is %d miles per hour. \n”, (average_speed));
return 0;
}
A Few Things:
Int main()
should be
int main()
This is perhaps an easy typo, or the unfortunate side effect of a grammar check.
You could probably do well by studying the standard types in C.
Modifiers aside, there are not very many, and except for special types, _Bool, _Complex, _Imaginary, they are lowercase. (The same holds true for keywords).
Storage class refers to something less commonly used, or at least out of the scope of this program (auto,register,static,extern).
The following definitions use the int type as well, so I will reproduce them here [sic].
/* define variable */
int average_speed;
int car_count;
int car_speed;
};
/* set variable values */
average_speed= 0;
car_count=0;
car_speed=0;
As others have mentioned, there is an extraneous curly brace after the three variables are declared. };
(Notice how sad he looks.)
If you are coming from a language that requires semi-colons after curly braces, you have some hard habits to break.
In any case, commenting that out should remove several errors:
/* }; */
as this is effectively closing the block for main().
As user haini pointed out, you could actually pull the variable definitions outside of main(), allowing them to be accessible to any function. (Use across source files would bring up the aforementioned extern).
Some programmers use special varaible [pre|suf]fixes to distinguish global from local variables.
int g_average_speed;
int g_car_count;
int g_car_speed;
As these variables need to be initialized before use, you can do this in the definition:
int g_average_speed = 0;
int g_car_count = 0;
int g_car_speed = 0;
Often, the use of global variables is discouraged, preferring instead parameter-based sharing of variables, which makes more sense once you introduce multiple functions.
As mentioned, 'WHILE' is not a keyword, while while is. As with the variable types, the list of keywords is very short, and mostly lowercase. It is good to know the keywords so as to avoid using them for variable/function naming.
As far as logic is concerned, your while-loop will never begin, as the expression car_count > 0 will not be satisfied as you've initialised car_count to 0.
While it's easy to hard-code a value, you may probably want to set another variable such as max_cars to an upper limit and check for car_count < max_cars. (Don't forget you're counting from 0).
/* define variable */
int max_cars = 10;
/* rest of variables, init */
while( car_count < max_cars )
Now, aside from the interesting quotations '“' which will give you trouble, and the missing semicolon at average_speed = car_speed / car_count as pointed out again by haini, you should try to step through your loop mentally. Don't ever forget that users are inherently evil and will attempt possibly unforseen values when allowed to interact with the program (scanf()). Negative values and 0 are not out of the question with int and %d, though you may expect some cars to be 'parked' and thus speed 0. Down the line, the unsigned modifier and %u may be of use.
In any case, it's good to get in the habit of sanitizing user input, and/or giving the user an option to opt-out (i.e. "TYPE -1 to break..." ), and checking for invalid or exit codes with an if. (break may be the keyword to pursue in this case)
Your average_speed calculation doesn't quite seem right. Don't forget you're storing values into integers, so you're gonna have some rounding errors.
First think about what happens when your initial case arrives -- what is car_count, and what happens when you divide by that value?
Then, think about the final case, (assuming your upper boundary is 10) in which car_count == 9. You will be assigning car_speed / car_count to average_speed. Is this really what you want?
You can minimize rounding errors and more difficult calculation by maybe 'keeping track' of the total of the speeds, and only one average calculation.
/* define variable */
int total_speed = 0;
In your while loop:
total_speed += car_speed;
or
total_speed = total_speed + car_speed;
And then outside of the loop:
average_speed = total_speed / (car_count - 1);
(The adjustment to car_count is necessary because the value increments after the final loop.)
NOTE: in this limited example, the average_speed variable may not be necessary, unless used outside of the printf().
There are a few issues in your code that I see.
The code will never get in the while loop. If you initialize it to 0, it will never be greater than 0, so will never enter the loop.
Even if it gets into the loop, this is an infinite loop. Keep adding one to a variable would make it so the variable is always greater than 0, so will never exit the loop.
MAJOR ONE: your variables are inside main, but you are using them outside of main!
#include <stdio.h>
Int main ()
{
/* define variable */
int average_speed;
int car_count;
int car_speed;
**};**
(Not sure about this one) but you have an uppercase I in the word int in your method declaration, and uppercase WHILE, should be while.
Code that is not within the main() function causes your errors.
//C code
//This program will calculate the average speed of passing cars using a WHILE-END loop
//Developer: Jasmine Tucker
//Date: 7 Sept 2014
#include <stdio.h>
/* define variable */
//You Can define global variables or local variables. If you want to use them outside your
//function you Need to declare them globally as done here
int average_speed;
int car_count;
int car_speed;
//This is where the Magic happens. If you execute your program it will jump to the main
//function and execute whatever is in there
int main ()
{
/* set variable values */
average_speed= 0;
car_count=0;
car_speed=0;
/*WHILE-END loop */
//The while Loop is not a function, you Need to put it in main() so it gets executed
while(car_count > 0)
{
//You did use very strange signs here. The correct ones are These: ""
printf("Enter the car’s speed %s:", car_count);
scanf("%d", &car_speed);
average_speed= car_speed / car_count; //You Forget a semicolon indeed ;-)
car_count++;
}
printf("\n The average speed is %d miles per hour. \n", average_speed);
return 0;
} //semicolons at the end of a function are not used in C. They are used if you want to define a structure.
I strongly suggest that you start off with basic books / a wiki to C programming. Here is a good (at least it was for me) start into that: http://en.wikibooks.org/wiki/C_Programming/Intro_exercise

Can anyone help me understand what's wrong with this code? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
int m[1000]; //declaring global array
int added(int input){
for(int i=1;i<= input; i++){
if(i>0 && input % 2) // checking if the numbers are even...
m[i]= input; //array implementation
return m[i];
}
}
int main()
{
for(int j=2;j<54;j++){
printf("%d",m[i]);
putchar('\n');
}
return 0;
}
I'm trying to return array from a function. why isn't it working?
Implemented array in for loop.
Your main function has a for loop iterating on a variable called j, but the body of the loop is trying to use an undefined variable called i.
Your main function also never even calls your added() function.
Moreover, your added() function is kind of problematic too.
int added(int input){
for(int i=1;i<= input; i++){
if(i>0 && input % 2) // checking if the numbers are even...
m[i]= input; //array implementation
return m[i];
}
}
I code in several different languages, so I'm not sure if this is actually an issue here or not, but your return statement is within a for loop. In many languages, this won't compile because your added() function doesn't have a return statement for every possible execution path. What happens if you send added() an argument <1? added(0) or any negative int will never enter the for loop, so added() gets to the end of the function without a return statement.
Moreover, with your return within the for loop and outside the if statement, you're guaranteed to only return the result of the first for loop, so you may as well just do a nested if statement or something.
Then there's your if statement. if(i>0 && input % 2). The && returns true when both halves also return true (and that's the only time your if statement is executed). In this case, i>0 returns true every time i is a non-zero positive integer. No problem here. Meanwhile, input % 2 doesn't return a boolean. It will return an int, and in this case, it will return 0 or 1. It will return 0 on even numbers and 1 on odd numbers. And as it turns out, the integer 0 is evaluated as a boolean false here and non-zero integers are evaluated as boolean true so this is probably doing the opposite of what you want. You need to change input % 2 to ((input % 2) == 0) probably.
And finally, if m[] is declared globably, you don't actually need to return anything. main() and added() can both see the variable perfectly fine. You can modify your function to look like this:
void added(int input){
for(int i=1;i<= input; i++){
if(/*i will always be >0 in this for loop*/(input % 2) == 0)
m[i]= input;
}
return;
}
Then all you have to do is actually call added() from main and it will correctly modify the array.
You use i in main but you meant to use j, I suspect.
You are not returning an array from added(), you are returning an element m[1] from the array. The function will return m[1] at the first iteration of the for loop.
At the first iteration of the for loop i = 1, so m[1] will be whatever the input is and the function will return m[1] at return m[1].
Another problem in main(), you are using m[i] but i is not defined in main().
You never called added, you never initialized int m[1000]; hence by default the entire array has 0 - you are indexing with i in main instead of j. Return is inside the for loop.

Test result of assignment against original value without introducing extra variable in ANSI C

I wonder if I can at the same time assign a value and check if it changed in a C conditional expression without introducing new examples. Consider the function test as fixed in the following example (I don't want to change its parameters or return values). I search for a variation of the conditional in the main routine which prints "works" because the value of n is incremented by 1 by the test routine. I.e. I want a comparison with the old value of nsing. At the same time it should print "works not" if n would not be incremented by test. I wonder if this could be possible exploiting rules for the order of evaluation or something, i.e. without introducing new variables which store the value of n.
#include <stdlib.h>
#include <stdio.h>
int test(int n)
{
return n + 1;
}
int main()
{
int n;
if ((n = test(n)) == n) {
printf("works not\n");
} else {
printf("works\n");
}
return 0;
}
short answer: no you cannot. For a longer explanation have a look at sequence points
No, you can't do that and that's undefined behaviour, because there's no sequence point between the assignment and the comparison.

Which variable should be optimize in following C code

If your compiler actually optimizes access time of only two registers variables per function, which two variable in the following program are the best one to be made into register variables?
void main(void)
{
int i,j,k,m;
do
{
printf("enter value");
scanf(“%d”,&i);
m=0;
for(k=0;k<100;k++)
m=k+m;
}
while(i>0);
}
Please ignore if any mistake is there...
Trick question? In a smart compiler, none of the variables are registerized. i has its address taken, so it can't be in a register all the time. j, k and m should be optimized away.
Certainly not j, since it is never used. Not i either, as you are using the address-of operator to write to it, which means it needs to be read back from memory after it's been written by the scanf. That only leaves k and m.
Good compiler will optimize this part of code:
m=0;
for(k=0;k<100;k++)
m=k+m;
And replaced it with m = 4950; :)
The better one will optimize m = 4950; and put nothing in place). j also will be optimized. And i can't be register because in scanf its address is needed. So final answer is "NO ONE".
I'd guess the compiler would pick k and m
Since the result of the computation is never used the compiler can optimize out almost all of your code. The only things that must remain are equivalent to
int main(void) {
int i;
do {
printf("enter value");
scanf(“%d”,&i);
} while(i>0);
return 0;
}
As others have already said the only remaining variable i can't be of register storage class since its address is taken.

Resources