while loop has terminating sign still works well - c

I was implementing Newton Raphson method in C. The code work well. There is no error in the code.
#include<stdio.h>
#include<math.h>
#define f(x)(x * sin(x)+cos(x))
#define df(x)(x*cos(x))
int main()
{
float x,h,e;
e=0.0001;
printf("Enter the initial value of x:\n");
scanf("%f",&x);
do
{
h=-f(x)/df(x);
x=x+h;
}
while(fabs(h)>e);
printf("The value of the root is=%f",x);
return(0);
}
/*
Output:
Enter the initial value of x: 3
The value of the root is = 2.798386
However, I was surprised I mean how did this code work? As per c rule while statement does not have any terminating semicolon. However, in my code while(fabs(h)>e); has a semicolon yet it run well.
Can anyone tells me how does it work?

What you mean is putting
while(...);
{
//some code
}
that will be interpreted as
while(...){
//looping without any instruction (probably an infinite loop)
}
{
//some code that will be executed once if the loop exits
}
do-while loop has the code executed before the condition (so at least once differently from simple while loop). The correct syntax has a semicolumn:
do{
//your code to be executed at least once
}while(...);

So the answer to your question is that :
do
{
h=-f(x)/df(x);
x=x+h;
}
while(fabs(h)>e);
is not a while statement, it's a do-while statement.

Related

How to code Caesar Cipher encryption using file in C

For Caesar cipher encryption, I have this code. This program uses text written by the user. But I want this to be read from a text file and run.
#include<stdio.h>
#include <conio.h>
#include<string.h>
void main()
{
int key,i;
char [30];
clrscr();
printf("\n enter plain text : ");
gets(data);
printf("\ enter key value : ");
scanf("%d",&key);
{
for (i=o;i<strlen(data);i++) {
if (data[i]==' ') {}
else
{
if (data[i]>='x')
{
data[i]=data[i]-26;
}
data[i]=data[i]+key;
}
}
}
printf("your cipher text is : %s",data);
getch();
}
Did you just copy and paste this code from somewhere?
As everyone else has already pointed out, there are some pretty big problems with your code, so I'll try and touch on the ones they haven't mentioned throughout. To start though, you should declare main as an int. The return value tells you if the program exited correctly, it's not just convention.
Here is your original code, formatted. I removed conio.h because it's been deprecated for years and moreover you don't need it here. All it was doing was clearing the screen for you, which you can do with System("CLS");, although here is a great article that's been shared many times here on SO that explains why you should refrain from using it.
#include<stdio.h>
#include<string.h>
int main()
{
int key,i;
// original: char [30];
// I'm guess you copied and pasted wrong?
char plainText[30];
printf("\n enter plain text : ");
gets(data);
printf("\nenter key value : ");
scanf("%d",&key);
// You had brackets here, essentially creating an unnecessary
// block of code.
for(i=o;i<strlen(data);i++)
{
// Where did the "data" variable come from? You haven't declared it
// and you're trying to get its length in this for loop
if (data[i]==' ')
{
// ?
}
else
{
if (data[i]>='x')
{
// Instead of this approach I would go with a modulus operation
// If you're not familiar with modular arithmetic I really recommend you look
// it up. It's absolutely essential in cryptography. It's central to both
// symmetric and asymmetric key cryptography.
data[i]=data[i]-26;
}
// This is the heart of the Caesar cipher right here. This is where you're actually
// shifting the characters, so it's a literal Caesar cipher
data[i]=data[i]+key;
}
}
// Again, you haven't declared "data" so you can't call it. I'm guessing you didn't
// try to compile this program because it is teeming with errors GCC, Clang, and VC++
// would have caught immediately
printf("your cipher text is : %s",data);
getch();
// Remember to make your "main" function return an <code>int</code>. This value is
// very important, especially when your program gets called by another program because
// it's how your program communicates that it ran successfully, or something went
// wrong. In that case you could set a specific error code to know exactly
// what went wrong and were
// Example:
int x = 1;
if (x == 1)
exit(4);
// This program would now exit with a status of 4, which you would then know was due
// to this function. This was a contrived example, but hopefully you get the gist
return 0;
}

Something strange with if() in c

This is for a school project I'm working on, it's just a small part of the code but for some reason the program doesn't seem to go inside the if() no matter what the input is. I've tried anything and everything I know of (also used the isalpha() function) but it just won't run the commands inside the if().
do
{
flag=1;
gets(input.number);
printf("\n%s\n",input.number);
for(i=0;i<strlen(input.number);i++)
{
printf("yolo1\n"); //debug
if(input.number[i]<48 || input.number[i]>57) //PROBLEM HERE
{
printf("\nyolo2\n"); //debug
flag=-1;
break;
}
}
if(strlen(input.number)<1000 || strlen(input.number)>9999 || flag==-1) printf("\nINVALID INPUT\n\nARI8MOS: ");
}while(strlen(input.number)<1000 || strlen(input.number)>9999 || flag==-1);
Can you guys help me out here??? I've been staring and the code for the better part of 3 days now....
I presume you declared char input.number[].
Your condition in if says that you only want to get into its body if the character is NOT a digit. This is somehow contradictory to the name input.number of the variable (but perhaps you are just checking for incorrect characters here...)
To better see what is happening with the condition, you can choose to print the values of its components, like this:
printf("%c[%d]", input.number[i], input.number[i]);
printf("%d, %d, %d\n", input.number[i]<48 , input.number[i]>57, input.number[i]<48 || input.number[i]>57);
(you will se a 0 for false and 1 for true)
BTW: You could write the same condition in a more readable manner, using char constants like this:
input.number[i]<'0' || input.number[i]>'9')

Why is the modulus operand not working on inputted variables in my C code?

I'm not new to C or anything, I was just doing a couple of exercises when...
for (i=0;i<no_1;i++)
{
if (no_1%i==0)
{
number_1=i;
}
This program is meant to display the highest common factor of two inputted numbers. The problem is, my code keeps stopping after the user inputs the second number, and I get this option to send an error report to Microsoft (I'm using Windows XP)
I've stripped all my code and realized that it was the modulus operator that was causing my program to stop, but I honestly don't see why. I tried using the modulus operator in a program by itself where I test if 10%2==0. That worked fine. So by deduction,my problem must be because the numbers I'm using are variables inputted by the user. But then why would it still not work? Am I missing some golden rule or something?
The problem is in the following:
for (i=0;i<no_1;i++)
Start the counter from 1:
for (i=1;i<no_1;i++)
You are currently causing a divide-by-zero error.
Change your code to:
int main()
{
int no_1,no_2,number_1=0,number_2=0,i,j;
printf("Enter a number: ");
scanf("%d",&no_1);
printf("\nEnter another number: ");
scanf("%d",&no_2);
for (i=1;i<no_1;i++)
{
if (no_1%i==0)
{
number_1=i;
}
}
for ( j=1;j<no_2;j++)
{
if (no_2%j==0)
{
number_2=j;
}
}
if (number_1==number_2)
printf("The HCF is %d",number_1);
else
printf("The HCF is 1");
return 0;
}
It's happening because you've start your counter from 0, it causes the division by zero error. Start the counter from 1 for both of your loop.

Window instantly closing when opening compiled .exe in C

I have tried so many things. Running from command line, running from cmd, running with /K, putting system("pause"); getchar(); getch(); before return 0 and I simply can't get it to run. I'm writing in Notepad++, compiling in Cygwin and the window appears blank for the split second it appears (according to my screenshot, it could have been taken too early). Basically I've tried anything I could Google myself to. So I figured it must be something wrong with my code that the debugger doesn't show.
#include <stdio.h>
int main()
{
float lt1, lt2, dmg, x;
lt1=10;
lt2=30;
while(lt2>dmg)
{
while(x>0 || lt2>dmg)
{
dmg=dmg+x*lt1;
x--;
return (dmg);
}
x=x+0.01;
return (x);
}
printf("Horde factor is: %f", x);
return 0;
}
I would appreciate any help I can get, and I hope you will bear over with my inexperience.
You have undefined behavior in your code.
When you declare a local variable without assigning anything to it, its value is indeterminate. Usage of this variable will be undefined behavior until you assign a value to it.
In this case it's the dmg and x variables that causes this problem.
Its because of these statement :
return (dmg); //this ends the code execution .. because you have returned something from main()
x=x+0.01;
return (x); // even this one is wrong
you are exiting the code there and never getting to the printf ..
there should only be one return in main() .. and at the end.
More problems with your code:
you don't initialise dmg and x , but you use them as parameters for while loop
float lt1, lt2, dmg, x; // dmg,x uninitialized
In the outer while loop .. its an infinite loop as you don't do anything to the parameters of that loop to get out of it.
Like I said above .. there should be only 1 return in main()
Maybe instead of returning you should look into break; ( i don't know if thats what you want or not as I don't understand your code )

What does for(;;) mean?

I am confused by the for(;;) construct. I think it is a form of shorthand for an unlimited for loop but I can't be sure.
Here is the code:
for(;;)
{
//whatever statements
}
Your guess is correct; it's an infinite loop.* This is a common C idiom, although many people (including me) believe the following to be less cryptic:
while (1) { whatever statements; }
* It's infinite assuming there are no break/return/etc. statements inside the loop body.
It's an un-terminated loop. It is sometimes written with a while:
while (1)
or even better:
while (true)
I would expect to see a break or return inside any such loop, no matter whether it is written with for or while. There has to be some abnormal control flow or it really will be an infinite loop.
Yes, that's the for C syntax with blank fields for initialization expression, loop condition and increment expression.
The for statement can also use more than one value, like this sample :
for (i=0, j=100, k=1000; j < 500 || i<50 || k==5000; i++, j+=2, k*=6) {};
Maybe one step beyond in for understanding ? =)
Yes, the expressions in the for loop are just optional. if you omit them, you will get an infinite loop. The way to get out is break or exit or so.
This statement is basically equal to:
while(1) {}
There is no start, no condition and no step statement.
As I understand it, for(;;) creates a deliberate non-exiting loop. Your code is expected to exit the loop based on one or more conditions. It was once provided to me as a purer way to have a do while false loop, which was not considered good syntax. Based on the exit condition, it is easier to dispatch to a function to handle the result, failure, warning, or success, for example.
My explanation may not be the reason someone used that construct, but I'll explain in greater detail what it means to me. This construct may be someone's "Pure C" way of having a loop in which you can serially perform multiple steps, whose completion mean something like your application has performed all steps of initialization.
#define GEN_FAILURE -99
#define SUCCESS 0
/* perform_init_step1() and perform_init_step2() are dummy
place-holder functions that provide a complete example.
You could at least have one of them return non-zero
for testing. */
int perform_init_step1();
int perform_init_step2();
int perform_init_step1()
{
return 0;
}
int perform_init_step2()
{
return 0;
}
int ret_code = GEN_FAILURE;
for(;;)
{
if(SUCCESS != perform_init_step1())
{
ret_code = -1;
break;
}
if(SUCCESS != perform_init_step2())
{
ret_code = -2;
break;
}
break;
}
If part of the initialization fails, the loop bails out with a specific error code.
I arrived at using C having done a lot of firmware work, writing in assembly language. Good assembly language programmers taught me to have a single entry point and single exit. I took their advice to heart, because their creed helped them and me immensely when debugging.
Personally, I never liked the for(;;) construct, because you can have an infinite loop if you forget to break; out at the end.
Someone I worked with came up with do..until(FALSE), but the amount of proper C furvor this caused was not to be believed.
#define GEN_FAILURE -99
#define SUCCESS 0
/* perform_init_step1() and perform_init_step2() are dummy
place-holder functions that provide a complete example.
You could at least have one of them return non-zero
for testing. */
int perform_init_step1();
int perform_init_step2();
int perform_init_step1()
{
return 0;
}
int perform_init_step2()
{
return 0;
}
int ret_code = GEN_FAILURE;
do
{
if(SUCCESS != perform_init_step1())
{
ret_code = -1;
break;
}
if(SUCCESS != perform_init_step2())
{
ret_code = -2;
break;
}
}
until (FALSE);
This runs once, no matter what.

Resources